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
#include <stdio.h> int getopt(int argc, char * const argv[], const char *optstring); extern char *optarg; extern int optind, opterr, optopt; Basic Utility Syntax Guidelines 3, 4, 5, 6, 7, 9, and 10 which parallel those defined by application portability standards (see intro(1)). It can also be used by applications which additionally follow the Command Line Interface Paradigm (CLIP) syntax extension guidelines 15, 16, and 17. It partially enforces guideline 18 by requiring that every option has a short-name, but it allows multiple long-names to be associated with an option. The remaining guidelines are not addressed by getopt() and are the responsibility of the application. The argc and argv arguments are the argument count and argument array as passed to main (see exec(2)). The optstring argument specifies the acceptable options. For utilities wanting to conform to the Basic Utility Syntax Guidelines, optstring is a string of recognized option characters. All option characters allowed by Utility Syntax Guideline 3 are allowed in optstring. If a character is followed by a colon (:), the option is expected to have an option-argument, which can be separated from it by white space. Utilities wanting to conform to the extended CLIP guidelines can specify long-option equivalents to short options by following the short-option character (and optional colon) with a sequence of strings, each enclosed in parentheses, that specify the long-option aliases. The getopt() function returns the short-option character in optstring that corresponds to the next option found in argv. The getopt() function places in optind the argv index of the next argument to be processed. The optind variable is external and is initialized to 1 before the first call to getopt(). The getopt() function sets the variable optarg to point to the start of the option-argument as follows: If the option is a short option and that character is the last character in the argument, then optarg contains the next element of argv, and optind is incremented by 2. If the option is a short option and that character is not the last character in the argument, then optarg points to the string following the option character in that argument, and optind is incremented by 1. If the option is a long option and the character equals is not found in the argument, then optarg contains the next element of argv, and optind is incremented by 2. If the option is a long option and the character equals is found in the argument, then optarg points to the string following the equals character in that argument and optind is incremented by 1. In all cases, if the resulting value of optind is not less than argc, this indicates a missing option-argument and getopt() returns an error indication. When all options have been processed (that is, up to the first operand), getopt() returns -1. The special option “--”(two hyphens) can be used to delimit the end of the options; when it is encountered, -1 is returned and “--” is skipped. This is useful in delimiting non-option arguments that begin with “-” (hyphen). If getopt() encounters a short-option character or a long-option string not described in the opstring argument, it returns the question-mark (?) character. If it detects a missing option-argument, it also returns the question-mark (?) character, unless the first character of the optstring argument was a colon (:), in which case getopt() returns the colon (:) character. For short options, getopt() sets the variable optopt to the option character that caused the error. For long options, optopt is set to the hyphen (-) character and the failing long option can be identified through argv[optind-1]. If the application has not set the variable opterr to 0 and the first character of optstring is not a colon (:), getopt() also prints a diagnostic message to stderr. The getopt() function returns the short-option character associated with the option recognized. A colon (:) is returned if getopt() detects a missing argument and the first character of optstring was a colon (:). A question mark (?) is returned if getopt() encounters an option not specified in optstring or detects a missing argument and the first character of optstring was not a colon (:). Otherwise, getopt() returns -1 when all command line options are parsed. No errors are defined. pathExample 2 Check; } } This example can be expanded to be CLIP-compliant by substituting the following string for the optstring argument: :a(ascii)b(binary)f:(in-file)o:(out-file)V(version)?(help) and by replacing the '?' case processing with: case 'V': fprintf(stdout, "cmd 1.1\n"); exit(0); case '?': if (optopt == '?') { print_help(); exit(0); } if (optopt == '-') fprintf(stderr, "unrecognized option: %s\n", argv[optind-1]); else fprintf(stderr, "unrecognized option: -%c\n", optopt); errflg++; break; and by replacing the ':' case processing with: case ':': /* -f or -o without operand */ if (optopt == '-') fprintf(stderr, "Option %s requires an operand\n", argv[optind-1]); else fprintf(stderr, "Option -%c requires an operand\n", optopt); errflg++; break; While not encouraged by the CLIP specification, multiple long-option aliases can also be assigned as shown in the following example: :a(ascii)b(binary):(in-file)(input)o:(outfile)(output)V(version)?(help) See environ(5) for descriptions of the following environment variables that affect the execution of getopt(): LANG, LC_ALL , and LC_MESSAGES. Determine the locale for the interpretation of sequences of bytes as characters in optstring. The getopt() function does not fully check for mandatory arguments because there is no unambiguous algorithm to do so. Given an option string a:b and the input –a –b, getopt(). It is a violation of the Basic Utility Command syntax standard (see Intro(1)) for options with arguments to be grouped with other options, as in cmd – abo filename , where a and b are options, o is an option that requires an argument, and filename is the argument to o. Although this syntax is permitted in the current implementation, it should not be used because it may not be supported in future releases. The correct syntax to use is: cmd −ab −o filename See attributes(5) for descriptions of the following attributes: For the Basic Utility Command syntax is Standard, see standards(5). Intro(1), getopt(1), getopts(1), getsubopt(3C), gettext(3C), setlocale(3C), attributes(5), environ(5), standards(5)
http://docs.oracle.com/cd/E36784_01/html/E36874/getopt-3c.html
CC-MAIN-2016-36
refinedweb
1,051
50.06
And which are crawling, festering nightmares, devouring the sanity of anyone who uses them? Your personal experiences with remote procedure calls are eagerly solicited. I just finished implementing an RPC library for one of my clients. This got me thinking about RPC in general. So when I ran into my friend Michael (a talented hacker and skilled ranter), I asked him about the available RPC protocols. As it turned out, Michael had been writing a research paper on distributed computing. So he'd been wading through specs, and he had plenty of material for a good rant. But I'm also interested in real-world experience with various RPC protocols. Here's a list of some popular (and/or infamous) protocols: Which of these have you used? What were they good for? Did they fill you with warm, fuzzy contentment, or did they make you climb the drapes? Sun RPC isn't too bad, seemed to work when I used it for an NFS client. It was fairly easy to use and there don't seem to be too many strange things associated with it. If you're interested, here's a really good link to programming information (it is relevant to the Linux implementation, too): Tru64 RPC Programming Interface. I've used CORBA a fair bit. it's got good parts: and bad parts:and bad parts: - receiver makes right byte order - aligned messages - async requests - multiplexed connections. - complex message structure - method dispatch by string-matching - several layers of abstraction and indirection between wire protocol and code the question whether to use SOAP or CORBA seems to be pretty popular these days. Being not a specialist in XML-RPC nor SOAP, I have however, a couple of concerns. CORBA is much more than a RPC protocol. In fact, one of its strong points is to hide the precise invocation mechanism totally from the programmer. It is an architecture that enables programs to be written in a distributed environment, with a couple of requirements, among which are transparency and scalability. One of the big problems I see with XML-RPC and SOAP is their exclusive use of port 80. That's not only a security issue, that's also a bottleneck if you need high throughput. It's definitely not scalable. Another issue is the XML encoding of the data. It generates much more data to be marshalled than GIOP. Besides, CORBA has a precise IDL to GIOP mapping, i.e. once you know the server's interface, you can talk to it. I'v not heared about a similar feature in XML-RPC or SOAP. A DTD doesn't seem to be a good replacement for type definitions. I'm using CORBA heavily in the berlin project, for a couple of reasons. First of all, its type system makes it easy to write a lightweight component architecture (see the recent discussion). Second, with its support for location transparency, it provides the means to define network transparent protocols that don't mandate the process boundaries (as compared to X, for example). Don't forget Java RMI. (No personal experience. I haven't found a good use for RPC yet in anything that I have done. I don't deny that there may be some justified uses. I just haven't seen any.) stefan writes: A DTD doesn't seem to be a good replacement for type definitions. I think this gets right to heart of the matter. CORBA is a high-performance, statically-typed protocol with strictly-defined interfaces. XML-RPC is a low-tech, dynamically-typed protocol. It's sort of like the difference between C++ and Perl. Both are respectable tools, but they seem to be intended for different purposes. :-) CORBA has some very slick features. I'm especially impressed by ORBit's ability to make in-process CORBA calls without mashalling or demarshalling arguments. I also like CORBA's IDL--it's so much prettier than COM's IDL. If you need to be ultra-fast, and you want to define a custom, object-oriented API, CORBA is probably the right tool for the job. But, on the other hand, there are situations when it's nice to be casual. For example, I'd just soon not use CORBA for searching a website. For starters, the server would be a pain to write (you know your ISP doesn't want to hear about running another server process). The clients would need to include some kind of ORB. And anybody who wanted to write a client would need to master the CORBA bindings for their favorite programming language. In a scenario like this, shipping around XML over HTTP appears to be an adequate solution, as perverse as it might initially sound. One of the big problems I see with XML-RPC and SOAP is their exclusive use of port 80. That's not only a security issue, that's also a bottleneck if you need high throughput. It's definitely not scalable. That's not correct. Neither SOAP or XML-RPC require port 80. SOAP doesn't even require the use of HTTP. We implement apps on all kinds of ports, and do others. FYI. The projects I'm currently involved with make heavy useage of xml-rpc. We looked at many possible alternatives including CORBA,SOAP, and a home brewed solution and decided to go with xml-rpc. The primary reason being that it is simple. I would probabaly even so far as to say elegant. Simple enough to actually be useful. For the time being, it even seems to be violating the "conservation of misery" principle, but then, only time will tell ;-> I would suspect a good programmer with no prior knowledge of any RPC or component technologies could write an xml-rpc implementation quicker than they could learn to use CORBA. Now granted, xml-rpc has a fairly limited feature set in comparison to some of the other alternatives, but it's a great fit for a very large subset of problems where RPC is needed. The primary benefits are: - Cross Language Versions are available for python, C, perl, VB, java, php,tcl and a handful of other languages. - Cross Platform More than likely just about any platform is going to have good support for one of the above languages/libraries. - Simplicity - Easy to leverage well proven robust technologies Our xml-rpc useages are all linux based, using apache, mod_python, and mod_perl. I have a lot of faith in those technologies for this kind of use. Try it, you might like it. I've used CORBA rather a lot, and I would recommend it, whereever possible. The big advantage of using CORBA is that its quite high level, and allows you to continue to think in terms of your problem, (be it objects, or methods), rather than having to worry about the transport mechanism. One of the biggest plusses that I can see with the use of CORBA is its sheer availability its possible to use CORBA from Java, Perl, C, C++, and accross multiple architechtures. I worked on a large project which involved distributed reporting, this used a CORBA server running on Solaris, with clients running on Windows - using either Visual Basic (Yeah;), C++, or Java. The really cool thing was that once the interfaces had been written we didn't have to worry about the byte ordering, or the marshalling, it was enough to invoke the method, and trust that it would happen. Steve --- Steve.org.uk graydon wrote, about CORBA: >...it's got good parts: > 1. receiver makes right byte order. This has a comical history. Sun RPC (like TCP) uses big-endian byte order, which is a nuisance when two little-endian boxes are talking. You'd like something adaptive. The most sensible is "sender makes right", because then you don't have to ask the receiver anything, and you can prepare byte streams before you figure out who they're for. The problem is that "sender makes right" is patented. I don't know by whom, or when it expires. As soon as it expires, all new protocols should switch to it (including CORBA v.N). In the meantime, we have this "receiver makes right" which nobody had patented because it was too inept to consider seriously. The "sender makes right" is so obvious that it ought to be easy to crack it with prior art; evidently the DCE and CORBA people didn't have the stomach for such a fight. CORBA must have got "rmr" from DCE, which was based in turn on on Apollo's AEGIS networking. AEGIS was groundbreaking in its day; some of its cooler features have still not found their way into IP-land. I don't know at what point "receiver makes right" got introduced. Can anybody report when the "sender makes right" patent expires? Has there been any work on collecting prior art in case anyone is willing to challenge it? You said: The most sensible is "sender makes right", because then you don't have to ask the receiver anything, and you can prepare byte streams before you figure out who they're for. Hmm, I'm curious - how is receiver-makes-right comical or somehow worse than sender-makes-right? With smr, you clearly can't prepare a byte stream before you know who it's for, since if you want to "make it right" you must know the definition of "right." Worst case, this can require an extra round trip as sender asks "what byte order are you" and waits for a reply. rmr should be the opposite -- the sender just sends whatever it wants, and the receiver fixes it when it arrives. Or does one of us have our definitions backwards? I'm certainly not a CORBA expert. XML-over-the-wire is generally very useful for low volume, fully specified transactions. The main reason is that there is not much hidden in the payload that may go wrong - both sides agree to a DTD or schema and that's (almost) it. After that you can implement this stuff in any number of environments without any fancy libraries or code - if you are using HTTP it's trivial. Our first serious use of XML in the company I work for was sending quotes for auto repair to our web-based workflow engine from auto repair shop accounting programs - neither of the apps' maintainers were likely to learn something like CORBA for this stuff, but getting them to generate an XML document and send it via an authenticated POST request was no problem. I love that you end up getting all the information for one atomic transaction in a single call. That is really a lifesaver. OT: I find it quite annoying though that so much XML transaction stuff is going on in Java, a language that has not been picked up in the Linux world as readily as elsewhere. Most of the push for XML on Linux has been in the form of storage formats - while that's useful, XML really shines as a contextual data transfer format. Let's see some more XML tools for Linux! Avery wrote:Hmm, I'm curious - how is receiver-makes-right comical or somehow worse than sender-makes-right? ... Or does one of us have our definitions backwards? Somebody has it backward, and not just one of us. Here's a summary of the differences. They say "sender chooses" as the alternative, although they seem confused about the consequences. This one and this one suggest the opposite definition. Here's good discussion of the tradeoffs, although it seems DCE people have been mixing up endianness with automatic conversions of various "int" and float sizes, creating even more confusion. Feh. It looks as if the consensus is on Avery's definition, given the confused description in the one contrary source. So, why do people complain about, in DCE, having to find out what the receiver wants so they can send that, and not being able to multicast? And why do they complain about the patent on just sending what you have? Maybe whoever I was reading was just confused. According to the citations above, in real programs the Sun RPC choice, fixed network formats, wins on performance because you don't have to spend time figuring out whether and how to convert formats; you know at compile time and can code it in-line. I'm sorry if I created any confusion. so you have a header. you have to have a header. the header tells you what function call this is and how much data you are sending. in the header, you specify the byte order. now. what exactly was the question / problem again? there is an advantage to specifying that the receiver makes right. how much code do you need for each of the alternatives (ntoh, rmr, smr)? ntoh/hton: macros. both by sender _and_ receiver. lots of. great. you always, always have to call your macros. if you have a decent compiler, and you compile on the right architecture, your macros disappear. but not _all_ the time on _all_ systems. smr: the sender must convert to whatever data format the receiver accepts. that means that you must have an additional negotiation phase in order to detect what the receiver will accept! additionally, you'd better damn well not send what the receiver won't accept! rmr: sender doesn't even have to bother converting what it sends. in one simple "send" - simple because there _are_ no macros doing any damn conversion, and simple because the header just says 'it's this way round: deal with it' you have shortened the amount of work to be done: only the _receiver_ needs to do macros that convert or don't convert, depending on what they're told to do. so, with an extra bit of work at the receiver end, you've saved a round-trip on the setup phase and simplified the sender's job. seems to me like those guys patented the wrong thing!!!!!!! :) excellent! very pleased to see this available for c. has anyone considered adding security to xmlrpc? ncm said: CORBA must have got "rmr" from DCE Apparently IIOP got its marshalling and semantics mostly from a company called Expersoft, which wrote one of the first ORB implementations (along with Iona, who I worked for). So blame them. AFAIK they've since disappeared though. I don't mind "rmr" over "smr", I agree with what lkcl said; "rmr" cuts out some negotiation, so it's a bit neater. I'd prefer TCP-style one-true-byte-order, as "rmr" does add extra complexity to your CDR marshalling code to handle both byte-orderings, but that's easy to test and not a big deal. However, what I do mind is the broken packing and byte-ordering mechanisms, which mean that some complex messages can require full marshalling into a buffer multiple times, which can really kill performance, and can also mean that (for example) writing something like a transcoding transport-level proxy server is impossible, as you'll need knowledge of the interface to work out what each lump of bytes is representing. :( My personal feeling on "which to use" is to prefer XML-RPC or SOAP; the main reason is that, as stefan pointed out, one of [CORBA's] strong points is to hide the precise invocation mechanism totally from the programmer. Which is IMHO a strong point sometimes, but if you want control over when you write to the network, and how to handle timeouts, non-blocking writes, and that kind of low-level stuff, you can't (unless your ORB vendor has added proprietary hooks to allow that). Also, there's the readable nature of a SOAP request, which is nice; and very handy for hand-marshalling packets when you just want a quick hack. ;) Gimme a lightweight library, where I control the sockets, anyday ;) lkcl writes: excellent! very pleased to see this available for c. has anyone considered adding security to xmlrpc? The RedHat Network uses XML-RPC over SSL, which seems like a good first step. And Karl Wallner is porting xmlrpc-c to work with curl, which should also support SSL. For the export-controlled, one or two of the XML-RPC clients also support HTTP Basic Auth. And KDE's kxmlrpc stores a cleartext token in a read-only file in your home directory. So there is some security stuff being worked on, but it isn't yet universal. In particular, more non-US developers are needed to work on SSL. (And I need to extend the xmlrpc-c API so the client can add authentication tokens. Doh!) ISBN 1578701503. funnily enough, it describes: briefly the history and politics of dce/rpc and how it got into NT. enough SMB to use it as a transport for DCE/RPC enough DCE/RPC to implement the minimum for interoperability with NT enough DCE/RPC over SMB services to implement a Windows NT Primary Domain Controller or a Domain Member Server. dce/rpc over smb and these services can be implemented in c in under 80,000 lines of code. contrast this with the dce/rpc 1.1 runtime library which, as i have pointed out before, is 250,000 lines with _no services_. if you go the whole hog with dce/rpc you have: - transport independence. TCP, UDP, DECNET/3.0, SMB (including SMB over TCP, IPX and NETBEUI because SMB runs over NetBIOS), IPX/SPX, HTTP, NetBIOS (direct, not via SMB), NETBEUI, and basically anything you can get your hands on. - security independence. NTLMSSP, Kerberos (4, 5 and ms-modified), GSSAPI, noauth, and others. - full and _complex_ c syntax data structures. CORBA's IDL is missing the capability to do arrays of encapsulated unions, iirc correctly. full pointer marshalling - e.g. you can successfully pack and unpack a doubly-linked list with DCE/RPC's marshalling/unmarshalling - something that i doubt any of the other IDLs can handle. note: full pointer marshalling is quite heavy, code-wise, so not even microsoft bothered with it in their implementation of DCE/RPC!!! - negotiation of ascii _and_ ebdic. if you are wondering what this is all about, then at least appreciate this: DCE/RPC is the mechanism behind DCOM. please bear in mind that both CORBA and DCOM are object models. they make use of a standard "RPC" mechanism as the basis for an "object" system. theoretically, CORBA could use DCE/RPC as its... er.. "transport" for its objects and their associated functions, and DCOM could theoretically do likewise with CORBA's underlying RPC mechanism. so the question that mentioned CORBA and DCOM as possible RPC mechanisms to use, and which do you prefer, is a little misleading. [question: does anyone know the correct name of the CORBA underlying RPC mechanism? is the RPC mechanism sufficiently self-contained to be able to make use of it _without_ CORBA's object stuff on top of it, is another way of putting it?] i have worked with [from over-the-wire] dce/rpc for over three years, now. i am very impressed with it. future plans [jeopardised by the primary samba maintainers] included extensions to TCP and HTTP transports in order to implement an epmapper, and then move on to an exchange client / server (which is basically using DCE/RPC over TCP as an authenticated transport for the MAPI transport, if anyone's interested. microsoft _really_ do believe in making life difficult, but seem to achieve a hell of a lot more than anyone _else_ does, so don't go bitching and bashing unless you can do better, which i doubt, to be really blunt and honest. yes, i'm issuing you a challenge there. make my day: prove me wrong :-). i investigated the dce 1.1 rtenv, primarily because it already had the TCP transport in it, and found it to be somewhat lacking. i tried to add NTLMSSP to it, and freaked out. Jim Doyle, formerly of bu.edu, had done a _lot_ of work porting the dce 1.1 rtenv to Linux. primarily, he had made the IDL compiler work with flex / bison, which he said last time i spoke to him that it was a tough job, taking up most of his time. he then went on to provide a "hack" job implementation of DCEthreads, which are Posix (Draft 4) Threads and he implemented them using sigsetjmp and siglongjmp, which works under redhat 5.2 as long as you don't expect to use a debugger, and fails immediately under glibc 2.1 even _without_ a debugger: it goes into an infinite recursion loop and runs out of stack. so, if someone is seriously considering doing dce/rpc development under open source unix for interoperability with nt, then first thing that's needed is a _portable_ version of DCEthreads. second, you need to add NTLMSSP as a security mechanism. alternative: help with the samba tng Hg and sidlc projects. our aim is to provide the missing transport TCP (we have a local loop-back and SMB transports already), write an IDL compiler (sidlc), then we can implement an endpoint mapper daemon, maybe add thread support (which is a dodgy and thorny issue and there are ways to avoid needing threads), and _then_ the code will be in a position to implement things like an exchange server / exchange client, with a full native open source alternative to the Win32 MAPI api (then people can compile all their favourite win32 mail clients without modifying the source too much!), maybe we'll go for an MS-SQL 7.0 API, too: it would make writing a _native_ ODBC driver for unix utterly trivial (none of this daft odbc-odbc bridge stuff). i think you get the idea. DCE/RPC is embedded in ms applications like you wouldn't believe. and because of the samba tng project, technically, the gap is now a hell of a lot narrower than most people realise. including my former employers. Actually I was in the room when it happened, and you've all got it wrong! IIOP has a bicanonical encoding. That means there's a big-endian (network order) and a little-endian (Intel order) encoding for every integer or floating point. And it only uses IEEE floating point. That's not the same as "receiver makes right", the scheme used by DCE (and hence allegedly DCOM) .... The considered opinion of the folk who settled on that bicanonical form was: - The justification for a bicanonical form was political ("maybe DEC/MS can swallow it"); it was acknowledged to be sub-optimal. - As a political accomodation, it wasn't enough. DEC/MS would only accept DCE-RPC, which no technologist in their right minds would accept (way too complex, huge adoption/exit costs). - A single canonical representation, as used in XDR (Sun/ONC RPC) would have been better. Cheaper in terms of cost (as widely noted) and design consequences. That said, IIOP is still quite a usable scheme, with advantages including wide availability. Particularly compared with bloated schemes like those used in RMI or SOAP, where extra type data must be explicitly carried in every request ... lots and lots of it, bloating the size and processing costs to an extreme. (There's no good reason to carry that around in the typical case where both sides of the operation already know it.) XML based protocols are the latest trend, and certainly Microsoft likes them because to the extent they're adopted, they prevent non-Microsoft protocols like CORBA from gaining further ground. But I can't be all that keen on protocol designs which aim to undermine security (by promoting firwall tunnels) as much as Virus-X. And anyway, don't we need another RPC protocol like a fish needs a bicycle? :-) - Dave However, what I do mind is the broken packing and byte-ordering mechanisms, which mean that some complex messages can require full marshalling into a buffer multiple times, which can really kill performance, and can also mean that (for example) writing something like a transcoding transport-levelkilling performance? ha!!!! that's the _least_ of your worries. i often describe sending semi-random data to NT4 as like walking through a minefield where the mines are guaranteed to be four inches apart :) :) i gave up sending reports in to microsoft about the state of their marshalling and unmarshalling code [apparently, someone disabled the safety-checking in the compile for the final release build!!!!] for NT4 because there were just... so many ways to crash critical services, it wasn't even fun any more. by contrast, and probably because i was finding bugs at the rate of one per two to three weeks whilst trying to network-reverse-engineer their NT Domain functions / services, they did a _total_ rewrite for NT5 (aka w2k) of the marshalling / unmarshalling and the security API. other than one or two quite serious (black screen of death) bugs, i find it really really difficult to crash NT5. the point / moral of the story: use a decent, correct IDL compiler and supporting marshalling / unmarshalling library!.i presume you mean dce/rpc not dec rpc, even though it was dec doing most of the coding for the 8 million line dce 1.22 CDS, DFS etc. services :) you are wrong about the model being .... etc. there are no padding / alignment "restrictions" which vary on the originating CPU, for a start. the int types supported are uint8, 16, 32 and 64. the IDL compiler generates code for client and server. the receiver therefore doesn't "figure out" alignment / padding. let me see if i can find the part in the spec for you.... ah, here we go.. let's find the bit on alignment... yep! alignment of primitive types. well, the spec doesn't give any examples. let's say you are at offset 0x5, and you have to read a uint32. you must skip ahead to offset 0x8 and you will find / place the uint32 there. the receiver follows these rules; the sender follows these rules, because the IDL told you to read a uint32 next. what was the problem again? regarding floating point representations, i cannot inform you there: none of the network traffic i have been reverse-engineering has used floating point (or ebcdic either). however, if you asked me to venture an opinion, allowing for the negotiation of (actually, it's just - like rmr - that the sender _tells_ the receiver, here, you're going to use this, today) different floating point formats seems pretty future-proof and stops damn committees from arguing the pointless toss. urr, yuck!!! NDR has IEEE 754, cray, VAX and IBM floating point formats!!!! eeeuw! well, at least you can be sensible and say, hey, i couldn't care less about anything other than IEEE these days :) All these RPC mechanisms have an underlying assumption the both computers trust each other completely (sometimes this assumption is explicit, sometimes not, sometimes there are compensating mechanisms, sometimes not). This may be useful for back-end business apps where all the computers are owned by the same organization and there is a full-time sysadmin staff running around checking to see if any of the computers have been compromised, but it would be a big mistake to start with this assumption when writing distributed Internet applications. Check out the E Language, which starts with some very strong assumptions about security and trust and ends with a sophisticated, elegant tool for distributed applications. A good place to start is the QuickE 15 minute tutorial. All these RPC mechanisms have an underlying assumption the both computers trust each other completelyin the case of dce/rpc that is not the case. dce/rpc has authentication (and auth negotiation), and the security then negotiated can use the signing and sealing mechanisms on PDUs to provide tamper-proof and encrypted function calls. i had to implement this, remember!!! :) the algorithms used by microsoft (NTLMSSP v1 and NETLOGON Schannel) are described in ISBN 1578701503 if you're interested, and NTLMSSP v1 and _part_ of v2, and the Schannel, are implemented in samba tng. so, only if your security mechanism - or lack of - trusts both computers completely do you have no security, in dce/rpc. This might seem weird, but I consider authentication to be almost completely useless for security.. This seems to be the kind of security that we most desperately need on today's Internet. How many of the exploits that have paraded by in the past few years would have been prevented by ubiquitous, forgery-free authentication on all connections and digital signatures on all source code? Zero. No exploits (as far as I know) have depended on using an unauthenticated channel or replacing a well-known piece of code with a Trojan horse before that code is delivered to the victim. The actual issues in security, both present and future, fall into two categories: 1. code that you run on your system that accidentally betrays you due to bugs or design flaws or 2. code that you run on your system that maliciously betrays you. Neither of these problems are solved by authentication. Both are addressed by E. The first by providing a simple, elegant, flexible security model with accompanying language support so that programmers can easily design and audit secure code[1], and the second by "capability" security[1], the uniquely flexible and secure method of restricting code from doing certain things while still allowing it to do others. See this article by science fiction author Marc Stiegler for an example of a simple secure application that is easy in E but probably impossible in any other current system. Regards, Zooko [1] Well, at least it looks nice. I haven't actually written any code in E yet, but Marc Stiegler has, and he's not even a real programmer -- he's a lowly science fiction writer. [2] Note: "capability theory" in security -- originally in secure OS design -- has been around for decades. Recently some people, notably Linux hackers, have been using the word "capability security" to mean something else -- basically fine-grained access control. An unfortunate pollution of the namespace... jmason: I agree with you that at times you want to control the details of the communication. So do the CORBA architects, apparently. You may be pleased to read about the new Messaging QoS Framework (for example here). In fact, it appears this reflects CORBA's evolution in general. It first tried to hide everything from the user, and as people are using it and ORB implementors add useful (but proprietary) extensions, they fill in the important pieces to standardize lower level control mechanism (see the BOA -> POA step, for example). The philosophy seems to be: as low level as necessary, but not more Wow, intresting stuff, I came to this thinking smr was the correct encoding scheme, with a small amount of thought I am convinsed that it uses less machine resources. Note I did not say faster or better. This because in reality unless we are talking about encoding large data structure (and the app I work on IRL can send 1M ones) it is the transport time which is so much larger than the encode time it is almost irelivent. But that said if you have a bizzy machine which is getting a lot of calls it might make a difference, but for a file server I very much doubt it as getting a block off the disk is also orders slower than the encoding. In fact I have never seen a NFS server which has had a CPU problem even if it thrashing the disks. It is much more likely to be limited on the ethernet or disk IO. In all engineering you have to deside what you mean by 'best' and in this case to me it seams that 'best' means the data gets into the ABI format correctly at the recieving end. IMHO this means that you should have a standidized format so that less ABI X to ABI Y code needs to be in each library on each machine. In rmr this effectivly means if I change the size of a DT then all the recievers need new library updates. This sounds like a reasapy for incompatibility. So unless there are any other reasons to me it seams h2n/n2h is best. I have been programming client server systems for 12 years, the first systems where simple BSD sockets app using standard event / select loops with our own encoding system (normally to text). It took a long time after I found out about RPC/IDL technology before I could find a project team / company brave enough to build a system with it. And that is what we have been doing at Monotype System for the last 5 years. Initially we looked into using ONC/RPC, DCE/RPC, CORBA, and DCOM which where the 'leading' technologies in the feild at that time. We rejected all but Sun's ONC because the other where not avaiable for free on other platforms (at that time). Having the source also meant that we could port it to any other platforms as needed. I designed and build a set of classes on top of the base level RPC API to shield the low level API from everyone else, but crutially I never tried to hide the network calls from the programmer. There was no attempt to make a network method look like a standard C++ method. Hence when a programmer uses the network call there is a whole lot of setup and checking code which must be hand written for each call. This means that the coder is not deluded into thinking that the call will be 'quick' or 'error free'. This is one of the problems of using a standard RPC system. You can be fooled into think that the getpwent() call is part of local API and will not make any calls to other machines. Generally using ONC/RPC has been a great success we have built and sold lots of servers specifically for different customers requirements and they all interoperate transparently. Hence as far as I am concerned "it does what it says on the tin". :-) I thought as we are on the topic of RPC systems I might tell you about my dream called Hg. Hg? Hg -> Mercury -> God of Communication & Transport Cute name, so? The TNG-Samba project Hg has two main goals: - provide a MS-DCE (like) implementation that can be used by TNG-Samba - write a RPC independed API library What was that? The second goal is to write a simple API which can be used to connect and commicate with any server that has a 'resnoble' protocol and make it look like they all work the same way. So just by creating a connection to a DCE/RPC server telling the API that it is a DCE/RPC protocol you can communicate to it using the same API as the one used to do the same to ONC/RPC or MS-DCE/RPC or even HTTP, DNS servers etc. Anyone intrested? What you all thing? Could it be done? Should it be done? Does anyone want to have a go? Basically everything listed does in fact make remote procedure calls. This is, however, a bit limiting, since the very concept of a function call maps poorly into the network domain; this is why asynchronous messaging features inevitably get bolted onto these systems. What I've been looking for lately is something with just that: I'm looking for a general-purpose messaging system which allows for various pleasant sorts of asynchronous message passes, muxed i/o aka select() processing while waiting, and so forth. (By async message passes, I mean you can make assorted remote calls--some expecting responses and some not--with a nonblocking API, and then you can go about your business, examining the status of all outstanding calls at whim, or blocking for the respons(es), or continue after having registered response handler callbacks as you prefer). The best free alternative I found was to build atop arpc, which is a fully nonblocking implementation of sunrpc-style messaging, with a few nice enhancements. This supports more or less arbitrary arrangements of synchronous and asynchronous message-passing processes in a network, without being limited to the rpc-style invokations emphasized in the usual suspects. It works properly in traditional select()-based event driven Unix programs, or, since it's nonblocking, could be trivially adapted for threadsafety. Curiously, the authors then turned around and implemented the original synchronous RPC semantics atop arpc as the Q system; I supposed this must have had some root in their Ada work. The second-best free alternative was DIPC, which provides network forwarding of sysvipc syscalls (and shared memory pages), and thus provides end-to-end guarantees for the various msgxxx functions. This didn't suit since it had a round dozen ways to die a horrible death: there are scads of plumbing processes, and the thing isn't really built for performance in the first place. Unfortunately, here at work we've tentatively decided that the nonfree system NDDS might be a better option, since it would require basically no work up front. It's got a number of features that are nifty from a reliability standpoint, and offers a marginally easier API, being a (really expensive) commercial product and all. But that easier API is due in part to a surprisingly thread-heavy implementation, which makes me nervous just on principle. So are there any others? I hate to pay the extortion-level pricing for an NDDS source license when this is clearly the sort of infrastructural software that really ought to be LGPL. emk, what does US/non-US have to do with adding SSL support to XML-RPC implementations? wmf asks: what does US/non-US have to do with adding SSL support to XML-RPC implementations? The U.S. government considers cryptographic software to be an export-controlled munition. This is why many web browsers come in two versions: a version with 128-bit SSL for domestic use, and a version with 40-bit SSL for export. The 40-bit version is basically worthless--you can break it in a college computer lab in an afternoon. The export rules have recently been relaxed (especially for published source code), but it's still a big headache. Does anybody know if RedHat's XML-RPC code supports 128-bit SSL? This is definitely where I want to go in the future. This might seem weird, but I consider authentication to be almost completely useless for security.hm. fascinating. so, if i understand you correctly, E is basically a more secure version of the Cambridge Capability System (searches with google didn't show this up, i would look more if i had more time but this url looks more cluefully up-to-date anyway:). you are right. the NT NETLOGON service basically makes _use_ of DCE/RPC to provide a secure user-logon and SAM database replication mechanism from explicitly-named trusted hosts (similar to NIS+). this mechanism is in no way built-in to DCE/RPC. _however_, what they did was, having written the NETLOGON service, they then _used_ that DCE/RPC service to do NTLMSSP authentication for other DCE/RPC services! and no, it's not recursive, because NETLOGON can be connected to anonymously. even when you _can_ add security into DCE/RPC services, it is *explicitly performed by the service*! even using the authenticated user's security context is optional! it is recognised that this is something that services may wish to do, and so there are a series of functions (in both the dce rtenv lib and in the samba TNG / HG codebase) that can be used to check security context and to seteuid - _if_ the service wants to. and quite often, you simply don't have to! so, anyway: saying "services implicitly trust each other" is a bit misleading. services only implicity trust each other if that is what you have designed (quite probably by omission from the design, more than anything else) them to do. dce/rpc _does_ provide the means for a designer to actually make use of the security context: how else could only an Administrator be the only one allowed to add user accounts with USRMGR.EXE (nt) / samedit (samba-tng)? Right, E is inspired by the capability secure operating systems, as well as others. The difference is that while EROS is an operating system, running on bare metal and confined to a single machine, E is a language, running on an OS, and running distributed programs across multiple networked machines. I see what you mean, that RPC mechanisms like DCE/RPC can be used to perform authentication more fine-grained than simple connection authentication. Still, fine-grained ACL-style authentication doesn't seem as useful to me as a capability environment like E. Consider a couple of examples: - I want to register a remote procedure with a server, like mp3.com, so that it can asynchronously contact my home computer and inform me about new developments, e.g. a new tune has appeared that matches my preferences. I don't want my home computer to be subverted by mp3.com, (whether or not I have authentication proving that it was really mp3.com from which the procedure was invoked). So I need to audit my local procedure implementation and guarantee that no mistake on my part, and no malicious mis-use on mp3.com's part, can result in my operating system being compromised. I want to accept an agent -- a small script -- from a remote computer, like folding@home, and run it when my computer is idle, without risking that my entire operating system could be compromised by the agent if it is malicious. Again, if my operating system is vulnerable to the agent's misbehaviour, then having the agent signed by "folding@home" reduces my risks a little bit, but not much. This is because a hacker (or a malicious person who works at "folding@home"), would first have to compromise "folding@home" before they could compromise my computer. Once they compromised my computer, then they could distribute agents signed with my key to further victims -- a great plague of digitally signed virusses. I would much rather just be able to run the agent in such a way that it can't hurt me. Then I don't have to worry so much who has signed it or not. I want to try out a new program, for example, a new game by a new, previously unknown author. If you think about it, all of the code on your computer, except for the code that you wrote yourself, is "mobile, untrusted" code. You downloaded it over the net and installed it and ran it, taking your chances and hoping that neither the authors nor any intervening hacker installed a Trojan in it. So in my opinion, the RPC mechanisms that have been described in this thread are fine for situations in which both computers are controlled by the same entity and do not have to be mutually suspicious of one another, but these mechanisms fall completely flat (with or without authentication or ACLs), when it comes to interoperating programmatically with a machine that you do not trust. Personally, it is the latter situation that interests me most. That would be "yes". It is based on openssl which is included in Red Hat Linux 7.0 (with retrofit packages available for 6.2). And it does validate certificates as being signed against a CA (in this case, the CA certificate is shipped in the GPG signed packages). Keep in mind that this is just the outer wrapping for this useage of the xml-rpc protocol. Each call to the server also includes a authentication token. xml-rpc itself doesnt really include any support for authentication beyond that which the underlying http layer provides. In the case of the Red Hat Network, we make use of certification verification, and ssl session encryption at the http layer, and app layer authentication above the protocol. Adrian writes:. Cool! Is there a good source of information on current export restrictions? Everyone says they've been relaxed, but nobody seems to know the recent court cases actually apply in practice. The xmlrpc-c library uses w3c-libwww for HTTP support. There are some third-party SSL patches available for w3c-libwww, so enhancing the client shouldn't be too hard. In the case of the Red Hat Network, we make use of certification verification, and ssl session encryption at the http layer, and app layer authentication above the protocol. This seems to be the Right Thing(tm). It's certainly a natural and obvious extension to XML-RPC. AFAIK, there aren't any court cases that apply to the relaxation in crypto export rules. You can probably find more info in the Mozilla crypto FAQ or netscape.public.mozilla.crypto. Unfortunately I have to run off to class right now. re: emk's request for offical crypto export control status i think that most of the aforementioned relaxed crypto-export policy has come in the form of new legislation and executive orders... here are some urls that might be acceptably 'official': - the eff archive on crypto export policy - a white house statement of the export changes - specific bill there is one court case that also may be of interest to you, the well publicized bernstein v. US DoJ trial. a lower court ruled that source code (cryptographic or otherwise) is protected under the first amendment and as such bernstein has been granted the right to step over the export restrictions. this ruling may well be overruled on appeal, though. news concerning the case is maintained at the eff . basically, this is still in the air as we're still upholding the current regulations until the appeals process for the case runs its course. looking through these links i've just given just makes me (again) realize how awesome the eff is. need to donate... hope this (boring) info gives you some help and confidence in your legal right to include cryptographic components in your xml-rpc library. when i first started hunting for this info, the mozilla project was a great help. btw, thanks for the excellent/helpful/superlative library! i see a great many uses for it. regards, --matt stefan wrote: Besides, CORBA has a precise IDL to GIOP mapping, i.e. once you know the server's interface, you can talk to it. I'v not heared about a similar feature in XML-RPC or SOAP. I'm currently working on it. ;-) Now that xmlrpc-c supports introspection, you can query a server for a list of supported methods, get a machine-readable API description, and dump it to the console. The next step is to automatically generate C++ (or Java) wrapper classes for the entire API. This isn't too hard, because XML-RPC has such a simplistic data model. Once this is done, you should be able to turn a server URL into a complete set of client classes. This would be a Good Thing(t!
http://www.advogato.org/article/232.html
crawl-001
refinedweb
7,922
61.77
I'm trying to write a program that will accept input from the user as sales, then it will total the sales and display both the total and the sales tax (total multiplied by .0825 #include <stdio.h> #include <stdlib.h> #define SIZE 9 int main(void) { /*initialize */ int a[SIZE]= {0}; int total, sales, tax; /*input data */ printf ( "Enter sales (enter -1 to end):$ "); scanf ("%d", &sales ); while ( sales != -1 ){ total = sum_array(a,SIZE) ; tax = total * .0825; printf ("Enter sales in a week(enter -1 to end):$ "); scanf ( "%d", &sales ); } printf("total = %d\n", sales); printf("sales tax= %d\n", total); system("PAUSE"); } int sum_array(int a[], int num_elements) { int i, sum=0; for (i=0; i<num_elements; i++) { sum = sum + a[i]; } return(sum); } output Enter sales (enter -1 to end):$ 100 Enter sales in a week(enter -1 to end):$ 200 Enter sales in a week(enter -1 to end):$ 200 Enter sales in a week(enter -1 to end):$ -1 total = -1 sales tax= 0 Press any key to continue . . .
https://www.daniweb.com/programming/software-development/threads/328453/average-of-an-array
CC-MAIN-2018-47
refinedweb
174
71.18
Hahahahaha i love being rewarded as a defi crypto currency project released on the way to a public forum, including your coinbase account email., * ability to send until end of january 21.this is good news amongst yesterday’s chaos., could this be considered financial advice..,. doge and the price goes down.. \——————————————————————, the official baitcoin bsc flash presale, use the **report** link to report digibyte income?. These are ious similar to dji chart pre covid., after months of modifications, the built in pancakeswap trading fees will be ask email, sms and google play. what is the way… yall see bitcoin?. Use to be a decentralized, secure, technology rely so heavily like every huge bsc token, the growth comes a high fee cripplecoin policy of blockstreamcore., they go to the moderators.. How Digibyte Currency And How To Buy Bitcoin With Cash App Usd? How To Buy Dgb Anonymously With A Traditional Valuation Measure? Is tron digibyte?. usually over 1% in btc saying it’s a pretty stellar hire., . what if i buy the dip!, the real bull market will reward you handsomely for it.. ✅ liquidity locked ✅, **anti-whales limit per transaction:** 8000 spaceking. blockchain technology goes beyond what’s making money and they wanna create a digital asset?. Can You Buy Chiliz What Are The Bitcoin Market Open And Close? Magnificent technology.. point.. any safe work arounds?. however you do don’t buy that pizza place accept crypto on coinbase are on reddit buy doge. 8: we are an integral part of the year.. to the moon!. has this occurred to me why proof of stake, always do your own diligence... ledger support will never send you to check out this link to report their holdings to a twitter does to their gravy train., give away up until now?. 📖contract address: 0x075a46d2c903dff38c6883ad8d04798f1f48802a, lets gooooo, that’s why people looking into terra finder i have:. For your security, do not solely rely on these tools., *i am a bot, and this action was performed automatically.. i’m back after reaching 8 cents for a bit.. when the dip twice today.. so far.., ✔️ 11%+ slippage. The soundtrack:. so when can expect huge profits when it was red…. tonnes of downvotes, who owns digibyte atms?. How To Sell And When To Sell Dgb And Why Should I Buy Eur Through Schwab? Jesus christ, they operate via private messages and private chat., hypermoon just fair launched now!🚀✨ safest moonshot!, currently we are deep into the financial stuff for crypto, or anybody who will remember that the changes in market cap | 300+ holders | 5% additional tax to the moderators.. As always – no financial advisor so make sure all his bitcoin by saying we are looking to get free money until you sell.. i can’t compete against other crypto can be created?, bigger and better living world., > one lp is locked., im gonna wait for the next best blockchain project to optimize profitability., now what?, there are too expensive for end-users., 0.43😔. i’m in early., and when it dips 10% overnight you are the parents/guardians of the average joe that they are joining in out there.. \———————————————–, a como el dgb hoy en colombia?. other goings on: new logo and mascot, i did everything they asked my coin for the candle/ time frame, as always – no matter what happens, it’s good that can be caused by said whales., how much is pos actually improving things for good vibes. \- contribution min 0.01 bnb max purchase: 1 bnb = 225,000 tst, . this coin is a public forum, including your coinbase account email.. 🗺☠ roadmap ☠ 🗺. • sloppy licks: 3% goes to sustainability address. How Can I Really Make Money With Dgb? ❤️ 2% sent straight to the moon., warning: to everyone that’s stressed out…. here’s some bubble wrap to relieve stress, saw the transactions, i exited out of the item at all.. also, great info!. it seems i cannot deposit anything for it’s first month.. to the moon!!!!!!. the ownership has been processed on may 22nd 📡 at 10 am edt.. so why doesnt it ask me anything. Can You Buy Dgb With My Paypal Account To Buy And Sell Money In Canada? If your trying to find my wallet address dptvynqjdcbrg84u3ypcrnf2qyivszavrx. 2% fee automatically goes back into liquidity. potential moonshot.. Theoretically it will attract way more data you can *always* control at least 15%. *i am a bot, and this action was performed automatically., investment time is the price giving the middle of a lot of trouble connecting nano s ledger 1.1.9 that i can say is wow, you bought in what this page is working.. I am not here long after., is it makes it special.. How to buy dgb video?. i would have caused a spike. Use tools such as and to help you determine if this project is legitimate, but do not solely rely on these tools., 🌳 welcome to our lil doges success – always runs good in the bear markets, but i´ve come across so, just trying to get into dgb account?. ✅ liquidity locked ✅, telegram:, -liquidity fee. wassawassawassup!. what if you have any questions, the team has 5% wallet for days, . Pls😔 my referral 127789899, the reality is somebody just wants you to contribute to the token is on pancakeswap v2!. do you really did a well known in old portfolios and notice you lost out, big time bridge to matic., assume that every project posted is a loaded question., bringing back my friend to get money from digibyte?. me watching my money is not over!. **8% tax on money machine?. can you doge community should call elon’s bluff and tell others this is rotten tomatoes, you know, i am worried when the community created by the panic will probably hurt the project otherwise they wouldn’t invest so much for any answer and recommendation, so, what lesson do you get loans against it or almost ready.. * initial supply: 1,000,000,000,000,000, my advice is admissable as per dhl tracking portal the parcel to shipper again!, and ethereum., reaching $10b by eoy.. How much processing power have massively piqued my interest account and is inflationary.. well you might be wrong to find bnb prizes hidden in the rest of today you guys to decide if i could buy, but spread your frustration to other wallets such as and to help you determine if this project is legitimate, but do not solely rely on these tools., use tools such as and to help you determine if this is a community driven token and by investing in ripple today cause i only had about a year since epns began its journey toward becoming the world’s economy.. the cost for the whitelist., are you looking where to find upcoming listings / upcoming market crash and won’t watch that vile creature.. ut lobortis venenatis laoreet.. Nothing wrong with what the hell out of my family and always will.. lock period: 4 years older whether you receive private messages, be extremely careful., this dog currency never disappoints 👍, , 🚀**. can i put other 150$ i also think that if i may not be released early to tell., gearing up for us.. usdt is a long shot.. if this process and am unemployed with chronic pain, so this is false. Please share the picture on socials., pissing off customers, where are dgb worth currently?, bitcoin can now earn interest on dogecoin.. my picks right now fml. Assume that every project posted is a scam/rug/honeypot until proven otherwise.. kicks bitcoin so just make sure our roadmap and purpose.. Can You Make Your Own Thunder Token Mining Still Profitable Reddit? Can Using System Like Decentraland Help Protect Identity Theft? **spacepath**, how to buy ✨, are we getting a great user experie, how much to pay a single called fat bottomed doges. yes my friend, 🤣 i love it!! 🤣. we are individuals who passed and she will succeed!!. 🙏. How To Cash Out Digibyte On Cash App To Another Wallet On Another Computer? Wake and bake pizza delivered and ate it raw., tuesday and wednesday proved that blockchain technology. learn more at, either you have a real use case of bch., assume that every project posted is a dip and you noob hackers skipped it.. How Many Hnt Does It Take To Transfer Money To Send Usd With Credit Card? 📝contract:, not receiving any codes, so i am not a financial planner., my business accepts dogecoin!, me just riding out using gcash hope this project is legitimate, but do not solely rely on these tools.. How Long Does It Take To Transfer Mithril From Cardtronics Atm? They’re cleaning out accounts, worst things can happen., am i the only crypto going down today, i plan on long term investors in here to see how attractive this is., # links, 💦 100,000,000 total supply, *i am a bot, and this action was performed automatically.. you see, applying a 8% tax fee that is always one of them canceling my transaction.. You just applied one negative talking point of bitcoin devaluation now and every exchange will appear on my long., ⚡ project elon debunked | new standard for adult entertainment content platforms in the chat, in subsequent alterations, mechashiba is usually a week.. 🔥 burn 4%, 🛸 low market cap, and active marketing campaigns 🔝. this is life, if you generate any more, it expires the old money on here we are., lol so much more!!!. be sure to increase slippage between 1-12% due to constant demand!, found a few minutes ago, the dapp is going somewhere., ana li zaml dayr 3a9li f kalb #moroccodogecoin. the nano should have sold for a big pump!, i’m new to the community.*. ± hypechart 📊 will be locked and or all of you are confident that dromos will be happy to pay, and then bitching when markets get manipulated and outcasted by the developer of doge, because it’s a possibility for stellar like this if everyone bounces to a $100m+ valuation like $cummies 🔥**. * hardcap : 160 bnb. 740 members as of right now, though., \*merch store 50% goes to our charity wallet which sells & adds to liquidity provider.. send the moderators for featuring hbar!. How To Know When To Trade Internet Computer On Luno Exchange? ###the dev team with super low market cap, and active marketing campaigns mentioned above within the realm of possibilities for somebody to solve the privacy goals of the initial purchase price, largely thanks to this. luca coin will be rewarded and get endless benefits., the coincasso, ccx-power, join now if you want to lose if you snooze then stfu because you are less risky., may 2021.. What makes anyone feel he is slummed., after all polls have finished!, every swap and pancakeswap are so rewarding because of screenshots, all of us, and power corrupts.. It’s highly unlikely all the bitcoin hash network, they utilize one of the coin’s transaction fees included in the sector in carrying out a heavy heart and teary eyes.. just hodl should recover. 💎 lucagaming platform is fair launching at 500 tg members +. the people’s currency., 🛸 1% fee is included, the fee goes back into equities!, better to be for dogecoin. *grabs popcorn*…. it took btc 2.5 years to realize, that all the reactions this is coiling up for this.. , cheers!. We appreciate your understanding on this., 1st audit passed. big space bags., 3.. Check back in. \- 10% tax. liquidity locked, china ban, launch soon || active staff || marketing || beautiful site ||. . notice the amount of the storm.., 📄verified contract: tba before launch so we would love opinions., guess what doge is good and i can buy as much as 30% within 24 hours of research into the liquidity pool.. Where Do You Need To Start Qtum Mining Be Profitable In Pakistan? Just recognize its impact and when to buy ✨. who suspects that he has any better by the community, and whichever number the pin and either the traditional crypto and beyond. **creators get a order through until the floor, either way thought i’d ask here hoping someone can always start with some more doge today as mark of 50 bnb.. When You Buy Keep With Amazon Gift Card To Buy A Small Amount Of Dogecoin To Money? How To Transfer Chromia From Cash App With Credit Card Online With Money? 📊 $sfcn tokenomics 📊, maybe this can be useful., hippy dippy do!, 4% of the sender’s balance, **incoming catalysts:**. 🔥🔥🔥 🔥🔥🔥. wtf!. i will provide all necessary links below.. over the years and a 10 % of tokens to a huge pumper.. Promotions: payout, at the end of this awesome dogecoin sticker and remember to act responsibly, because if you were unable to add money to clear this up for your support request please respond to this goal., was def lagging like a small bit first., we need to to see what happens if i sold last night. 4., all down… Not a scam., why is grd safe?, liquidity is 100% a believer in doge so soon. supply : 1,000,000,000. Can I Buy Something With Dgb? How Much Is Digibyte A Good Time To Buy Dogecoin With Credit Card? Hoping support on .27521, lets watch what happens when digibyte futures work?. the most powerful forces in the entire nft-market, or whatever tokens the community votes for.. People like to buy ✨, that’s literally the entire supply such that the idea of mine., it has 4 words start with?, and other noob questions.., so to repeat, invest only what you’re gut tells you., are we in today’s 1992?, to the moon !! guys next gem 💎, **tokenomics:**, it sucks.. hopefully doge can be pushed to the current circumstances?. I tried a stupid question., after being betrayed and abandoned by devs, 🚀✨ what makes you pay taxes on dgb profits?. How to get the whole world that really aren’t there in a few years?, i personally traded half my bch for everything, speculators won’t be able to trade big holdings at once to take control and not donations., all profits go to a video:. raspberry pi makes it approachable., rather than xrp trying take bitcoins mantle., fucking wimps mate.. How Akash Network Transactions Take So Long To Receive Ethereum To Buy Ethereum? How Many Digibyte Can I Lose More Than 21 Million Money Worth? Burning phase. this is a public forum, including your coinbase account email., — 1% of tax evasion risk. be sure to increase slippage between 1-12% due to constant demand!. the token is on pancakeswap v2!, be an early buyer and get others to be the same amount of success.. 🚀 how to buy?. i made my average is our chance to sow the seed early!. is this normal?, be sure to read comments, particularly those who are downvoted, and warn your fellow redditors against scams.. How Can I Invest In Digibyte Legal? How Much Does One Share Of Digibyte To Buy Games With Bitcoin? Is Now The Right Time To Send Digibyte From Coinbase To Binance? ….all my ltc and how we roll. rfi tax holders: 4%, snowgecoin – $1.7m mc, listed on cmc and poocoin ads and doing 10x in no time to exit., at a time to buy dgb from one wallet to another department in order to reset google authenticator recently and now i’m sitting at a loss.. Do you buy dgb gemini?. 🔥 presale: 475000000000.0000, what are my options section in binance since new update is available.. this is a service that is a simple high school 😂, the community around the bush., just bought some btc with high coat of mining usd?, are you sick of getting started | 35 of 60bnb filled | $20k ga, * ability to send info to sign up for the memes and pictures/videos but for sure affect the price can climb.. Ban of cryptos and precious metals., armstrong: now you can see the utility without outside influences.. *i am a bot, and this action was performed automatically.. Where Do I Find My Nexo To Make Money With Dogecoin On Binance? Use tools such as and to help you determine if this project is legitimate, but do not solely rely on these tools.. 🚀✨. A Beginners Guide To Vidt Datalink If The Internet Goes Down? Is Dgb Trading At Currently? Are Dgb Still Worth Buying Ethereum Is Legal In Malaysia? Will Dgb Rise? But anyway, if you’re looking for a long time.. we all had to delete this post has so i’m trying to kick the scammers out of all the ambients of the other subs but i know it dropped from 64k to 47k we went live on my bank’s end, or is this shit you fkn noobs!. When users swap between two tokens, the protocol is focused on war efforts so most of the world how strong is the way.. the team understands the subtleties of communication and identity, the most imperfect thing currently is given a small amount for his doge rocket next year.. assume that every project posted is a public figure lol.. lil question. with highly devoted devs and whales!. it goes into details of the pool., 1 windows 10 pc that i need help changing this so different?. I don’t want to send dgb?. all of them., doge wallet address without a gig.. is this true?. 🐋💨, fiat withdrawa – vefification problem. that looks disgusting. • dividends received in satisfactory condition then it went to sleep, americans woke up!, for those stressing out everyday since .. X1000 potential!. make sure to do your own diligence.. buy at .27😊, with the weight of the appeal of safemoon, wenmoon, safemars…. are you still have your best friend, now try ruby!. 🛸 low market cap, and active marketing campaigns 🔝, 63% of all transactions. why is digibyte fork happen?. the whole market is down.. you’re still early, get in now!. sad.. 🍑 website:. 27k hodlers.. you my friend. be sure to do your own diligence., 🐕 🌒, **roadmap q2**. how to create paper wallet without connect my ledger nano s?. is be more content out there.. Feel free to join doge family., things like,, you don’t need laser eyes and wake up and in turn increase demand/price. dogefather literally gave one message, and i honestly don’t., i have been there myself a novice.. Why i bolded your text?. import 52 character private key, crisis widespread to other exchanges:. the project is still holding and speculating for an hour old, this coin are all these started even before launch on may 10!. some of our savings and then spend it in but i only hold mid-long term projects, but heard he still have perks that doge has no transactional tax.. in the crypto space in nano s and go to r/dogecoinbeg for this dip.. they all have those moments once again!. how to buy these?, they never have.. How Do You Get Paid For Running A Elastos Wallet Address On Cash App? How To Flip Dgb Reddit? Tokenomics anti whale:. wassawassawassup!, there is no longer using crypto?. Is It Still Time To Get Credit Card To Buy Mxc Without Paying Taxes? I withdrew my money, it is used to purchase things online?. for now.. 🚀✨ what makes yummyshiba the best decision., use tools such as and to help you determine if this project and allow for tax evasion., reality says otherwise. But besides that, i actually like to be exclusive bsc pump signal telegram group., learn more at. cheems!, you could have made a gain against dollars since matic went up, and i’m considering leaving my xlm yet..
https://digibyte.crypto-invest.cc/where-can-i-invest-in-blockchain-without-investing-in-dgb-philippines
CC-MAIN-2021-43
refinedweb
3,267
76.93
From long time I was looking for BEX query comparison tool but I did not get anything and after long efforts I got one idea to compare Bex Queries in Different client. And I wanted to share this with all of you. Many times queries are modified in production directly which create problem to keep queries in sync. First of all I want to say it may not 100% accurate to compare Query in different client/system but it is boon to reduce your manual comparison of Query. Let’s start with “How to Compare Query in Different client/system?” Let’s have scenario here you want to compare Query from PROD TO DEV then Go to PROD and enter Tcode RSRTQ Enter Query name as follows and execute. You will get all query definition as follows then click on Download(F9) Click on OK… Then Go to System -> List -> Save -> Local File Press OK. Then Create one text file in Notepad say PROD300.txt and paste and save. Similarly follow all steps in DEV also and create file DEV100.txt Now we will compare these two files using any Code Comparing Tools. In my case I am using online Code Difference Comparison Tool . Put your both code in Text pane 1 and 2 and compare. Then simply you can compare both queries from PROD & DEV as follows. Hope this document will be helpful to the readers… Hi Pushkar, It's a really helpful article!!! Regards, Sonal Very Good Pushkar!! 🙂 Simran Matharu Thanks... 🙂 Pushkar Dhale Great....doc 🙂 Regards, Deepak Machal Great.. It's a really helpful article Good info... Its helps a lot. 🙂 KP Very Useful Good one.. Nice info. Simple and neat. Thanks... 🙂 Pushkar Dhale Good Approach.. Good One Puskar, Gud efforts. One more easy way also we can check from here. That is After Providing query name here (In RSRTQ), we can select the check box for required Query Elements. Means, let us say, first select the Check box for Filter and execute then compare the fileter values maintained in Dev and Prod.. Similarly for Rows / Columns, Cells, Input Variables, Exceptions & Conditions etc.. Thanks, Venu Hi Venu, Thank you for your valuable suggestion. 🙂 Very Good work and nicely presented. Thanks Krishna Chaitanya. Thank you Krishna.... Thanks for sharing great tip Regards Rajeev Hi Rajeev, It is good to see that my piece of writing is helping you. Good doc..! Thanks Naveen... 🙂 Nice document...ultimately you should come to a non changeable production environment but it took us a long time too..now you can only create adhoc reports in a separate namespace and then you get rid of comparing queries in different systems Martin Thank you Martin your noble words are valuable for me.... 🙂 good work, thanks for sharing. Thank You Kalpana 🙂 Good work... really helpful.. Thanks Durga...!!! Hi its too good doc. Thanks for sharing.. 🙂 🙂 Regards Wasem Hi Pushkar, Nice document for comparision of queries..thanks for sharing 🙂 . Very informative and useful work Pushkar..keep it up 🙂 It seems that sometimes the ordering of the characteristics/KFs in the query outline do not match across systems, making the line-by-line comparison impossible. Hi Pushkar, This is indeed very helpful. Regards, Shalaka Thanks Shalaka.... 🙂
https://blogs.sap.com/2013/04/17/compare-bex-queries-in-different-client-system/
CC-MAIN-2021-31
refinedweb
537
76.93
Ambiguous documentation pstats does not behave as the documentation says it does. I got to the stage that you can look through the output of Lib/test/test_profile.py (in Python distribution) and the output of that very same file but with a import hprofile as profile at the top instead of the import profile. My output is good, very good I'd even dare to say. However it is not sorted in the same way! The output is suppsed to be sorted by " stdname". The description of this output in the documentation is as follows:').But, it appears they actually sort the data with the criteria in a different order as explained above! They seem to sort on 'name', 'line', 'file' when using " stdname". Notice however how they also say that "the standard name is a sort of the name as printed". And this would make more sense, that is what they actually do. Don't know why they explain it as the same as "nfl" though. Got me confused for a while (I admit, untill halfway this post! Why it can be usefull to blog about your problems!). On another note, work is progressing nicely. I only need to implement a couple more Stats methods before I'm done. They are a bit harder again though: .print_callers()and .print_callees()methods. I'll need to add data into the hstatsmodule before I can do this. But hopefully that shouldn't become to difficult. .dump_stats()method which can save all the data. Since I can not join two hotshot files (not withouth considerable hacking in _hotshotand I try to keep the delta on that file as small as possible, besides, I'm running out of time, need to do uni work next week) I am currently thinking of just pickeling the data. Then to load I can just try one of the formats (the pickle or the hotshot file) and if it fails try the second. After that there are just bits and bobs to do left and right. Like writing some quick comparison script that looks at my speed increase etc and generally making sure I meet all requirements. ;-) New comments are not allowed.
http://blog.devork.be/2005/08/ambiguous-documentation.html
CC-MAIN-2019-09
refinedweb
365
74.08
![if gte IE 9]><![endif]> Attempt to update data exceeding 32000. (12371) Unable to update Field. (142) I just recieved this error on an import statement. I have logging before and after the statement. I have a file I could reproduce the error. What I can't determine is why the error is occurring. Here is the code line "import stream inlines unformatted thisline." None of the lines in the file exceed 32000 characters. Does anybody have any advice for troubleshooting this issue? Even just where I can find more information about it. Thanks, ~Justin I'm able to reproduce with the below code. What I don't understand is that s1 and s2 never contain more than 16002 (with new line) characters. Is there a process limit on number of characters in all strings that when s2 and s1 are in memory at the same time thats when the issue occurrs? Also I thought it was odd, if I add no-undo to either s1 and s2 or both of them, I no longer get the error. There should be no undo to be skipping correct? define variable iCount as integer no-undo. output to testfile.txt. repeat iCount = 1 to 32002: put unformatted "A". if iCount = 16001 or iCount = 32002 then put unformatted skip. end. output close. define variable s1 as character. define variable s2 as character. input from testfile.txt. import unformatted s1. s2 = s1. input close. 32000 isn't just the limit on a single character variable, but also on a record and on the total size of the variables in some divisions of the code ... I'm a little vague on the latter, perhaps because I don't program in a way I am likely to encounter the problem. If you actually have individual character fields as large as 16000, you should probably be thinking longchar anyway. Consulting in Model-Based Development, Transformation, and Object-Oriented Best Practice
https://community.progress.com/community_groups/f/27/p/186/416
CC-MAIN-2017-51
refinedweb
323
68.67
cell.offset() is passing incorrect type as 'column' argument to worksheet.cell() in 2.2.0 Code in older versions (cell.py): def offset(self, row=0, column=0): offset_column = get_column_letter(column_index_from_string( self.column) + column) offset_row = self.row + row return self.parent.cell('%s%s' % (offset_column, offset_row)) This was passing in, for example, self.parent.cell('A1') for which the cell method would return the cell at A1. Code in 2.2.0 (cell.py): def offset(self, row=0, column=0): offset_column = get_column_letter( column_index_from_string(self.column) + column) offset_row = self.row + row return self.parent.cell(column=offset_column, row=offset_row) This is now passing a value of, for example, 'A' in as the column index, which the worksheet.cell() expects to be an integer index. I haven't had time to submit a test case for this, nor this issue yet, sorry, but both are just one line fixes. Here is the commit with the change. As self.parent.cell() is expecting it's column kwarg to be an integer, the change to this function needs to be: Updated method in DummyWorksheet to reflect change in behaviour moving away from using coordinates. Need still looser coupling. Resolves #437 → <<cset 471d4b2c2350>> This will be fixed in the next patch release but I'm wondering about the use case and whether it wouldn't be better to delegate the function to the worksheet. How are you using it? Removing version: 2.2.x (automated comment)
https://bitbucket.org/openpyxl/openpyxl/issues/437
CC-MAIN-2018-30
refinedweb
243
53.68
Someone sent me a question yesterday that boiled down to the difference between kinds of numeric exceptions. I’ll give my response below, but first a little background. Numeric exceptions occur when a computer does some operation on a number that produces an error. The abstraction that lets us think of computer numbers as mathematical numbers has sprung a leak. On Windows you may see output that looks like -1.#IND or 1.#INF. On Linux you may see nan or inf. These values do not correspond to mathematical real numbers but instead are codes saying what went wrong. If you’ve heard of NaNs (NaN stands for “not a number”) you might call every numerical exception a NaN. That’s reasonable since indeed an exception is “not a number”, or at least not an ordinary number. The problem is that NaN has a more restricted technical meaning that excludes some kinds of exceptions. An infinite values is an exception but not a NaN. The difference is important. Some mathematical operations still make sense on an infinite value, but no operations make sense on a NaN. For example, if two floating point values are infinite and have the same sign, they are equal. But a NaN cannot equal anything, not even itself. So in C, if x is a double then the test x == x will return true if x is infinite but not if x is a NaN. The question that motivated this post had assumed that an infinite value was a NaN. No, and infinity is not a NaN. It all makes sense when you think about it. A NaN is a computer’s way of saying “I don’t know what else to do.” An infinity is the computer saying “It’s bigger than I can handle, but I’ll preserve the sign.” For example, let xbe the largest finite number a computer can represent. What is 2*x? Too big to represent, but it’s positive, so it’s +infinity. What’s -2*x? It’s -infinity. But what is sqrt(-1)? It’s not big, so it’s not infinity. It’s just complex. Nothing else makes sense, so the computer returns NaN. Windows displays infinite results as 1.#INF or -1.#INF depending on the sign. Linux displays inf or -inf. Windows displays NaNs as -1.#IND (“ind” for “indeterminate”) and Linux displays nan. For more details see these notes: IEEE floating point exceptions in C++ Related posts: 6 thoughts on “Numerical exceptions” “When a processor”. When a processor tries to compute sqrt(-1) it returns NaN or an exception or both. Because my computer processes sqrt(-1) just fine. Hi, John. With respect, your suggestions on that page are not very “C++-ish”. There is a standard way to deal with some of this in C++, ever since the standard was ratified in 1998. That means it works on Linux, Windows, Mac, and any compiler now and forever that implements the standard. It has other advantages too… The only missing piece is “fpclassify”, which is not available prior to C++0X. The standard approach is numeric_limits<>, which works like this: #include <limits> typedef double real_t; real_t min_denorm = std::numeric_limits<real_t>::denorm_min(); // static functions also exist for infinity, quiet NaN, signalling NaN, etc. Not only is this standard, but you could also “typdef” real_t to “long double” instead and all of your other code will still work. You could also define your own numeric-ish class: class MyAwesomeFloat { // 365 bits of precision (366 during leap years)!! Awesome! … }; …and then you specialize the std::numeric_limits<> template to provide implementations for infinity, NaN, etc. Then you can typedef “real_t” to “MyAwesomeFloat” and again no uses would have to re-write their code. So this is not just the standard way; the general approach (using a “traits” class for compile-time polymorphism) is a very typical and useful C++ pattern. fpclassify is unfortunately missing from the C++98 standard :-(. It is, however, provided by both Boost and by the soon-to-be-ratified C++0X standard. Even if you roll your own implementation, making it a template class would make it more flexible and general than a simple C-style function. (And unlike run-time polymorphism provided by virtual functions, this sort of compile-time polymorphism carries zero run-time performance cost.) This discussion reminds me of one I had a long time ago when I asked about the difference between “Does not exist” and “undefined” in math class. The explanation I got was that “Does not exist” means that the value in question could possible exist, but does not due to inconsistency (eg lim x -> 0 ( 1/x ). In this case, taking limits from the left or right produces different answers, so the limit doesn’t exist, even though it could, in theory). “Undefined” is just something that doesn’t make sense (eg limit x -> -1 ( sqrt(x) ). Since -1 isn’t in the domain of sqrt(x), the limit makes no semantic sense). Maybe it’s more a philosophical observation, but the ideas seem to make sense applied here to NaNs and inf values. I don’t recall the details but some of my coworkers and I were just laughing a couple weeks ago about some software returning -NaN. Technically the strings 1.#INFor nandon’t come from the OS but from the C standard library, I guess. So if you use gcc on Windows you’d get the Linux ones as well. The “nan” and “inf” output (along with a set of possible variants) is required by C99. I understand you as meaning MSVC when you say “Windows”, and MSVC doesn’t try to comply to C99. Gcc (not “Linux”; gcc runs on Windows too) uses these strings to be standard-compliant, rather than introducing a platform difference.
http://www.johndcook.com/blog/2011/04/28/numerical-exceptions/
CC-MAIN-2016-50
refinedweb
974
65.62
NOTE: This WL serves as a place to list candidates for deprecation/removal. NOTE: 2010-07-28: Feedback was solicited from stakeholders, but no decisions have been made. NOTE: 2010-08-13: The thread_concurrency item was added to the proposal, so the feedback period is extended to 2010-08-20. NOTE: 2010-08-25: ServerPT approved decision to deprecate features listed here in Dahlia, and to remove them 2 GA releases following the GA release containing the deprecation warnings. For removal scheduling, see WL#5681 and WL#5722. This is a task for formally deprecating items in Dahlia (MySQL 5.6?) so that they can be scheduled for post-Dahlia removal. The proposal is that these items be deprecated in Dahlia such that warnings accompany their use, and that they be removed in some future release to be determined. Deprecation or removal has already taken place for some of the items described here, but they are listed for completeness. [Note added 2010-10-06: Consistent with previous deprecations, we should also add deprecation language to the --help descriptions where appropriate.] Candidates: * BUG#44209: Deprecate the --master-retry-count option, similar to deprecation of other --master-xxx options that occurred in 5.1 (with removal in 5.5.3). The option value now can be set using CHANGE MASTER TO. Reason to deprecate option: It's confusing because it is silently ignored if the master.info file exists. * WL#751: This worklog implemented --lc-messages-dir/lc_messages_dir. It deprecated the --language option and has already removed the language system variable. It remains to schedule removal of the --language option. * WL#4738: Deprecate the storage_engine system variable. Reason: WL#4738 added default_storage_engine, which has the same meaning, but the name matches the --default-storage-engine command-line option more closely. storage_engine does not have the same obvious correspondence to --default-storage-engine. Note: This was already deprecated in 5.5 by WL#5185. WL#5265 adds warnings, for removal see WL#5681. * From Kostja: I'd like to request a deprecation and removal of global server variable/startup option 'table_lock_wait_timeout'. This option is currently unused. Starting from 5.5, it is fully superseded by a global and a session option lock_wait_timeout. Note: table_lock_wait_timeout was already removed in 5.5.3 by BUG#45225 * From Davi: On trunk (5.5) in sys_vars.cc there is some signs that the options sql_low_priority_updates and sql_big_tables are to be removed, but I haven't found any indication that they are being deprecated. Perhaps we can add those two to WL#5265 or a similar worklog? Reference from sys_vars.cc #ifndef TO_BE_DELETED /* Alias for big_tables */ static Sys_var_mybool Sys_sql_big_tables( "sql_big_tables", "alias for big_tables", SESSION_VAR(big_tables), NO_CMD_LINE, DEFAULT(FALSE)); #endif #ifndef TO_BE_DELETED /* Alias for the low_priority_updates */ static Sys_var_mybool Sys_sql_low_priority_updates( "sql_low_priority_updates", "INSERT/DELETE/UPDATE has lower priority than selects", SESSION_VAR(low_priority_updates), NO_CMD_LINE, DEFAULT(FALSE), NO_MUTEX_GUARD, NOT_IN_BINLOG, ON_CHECK(0), ON_UPDATE(fix_low_prio_updates)); #endif * WL#5252: Deprecate optimizer_search_depth, value 63. Add deprecation warnings for value 63 beginning in 5.5, remove value 63 beginning with 1st GA release after Celosia. Deprecation warnings will be added to the *manual* beginning with 5.1. Note: The deprecation as of Celosia, and removal of 63 as a legal value in Dahlia has already occurred. For this item, there is nothing else to do; it is listed for completeness. Note: This was deprecated by WL#5252, removed by WL#5369. * From Kostja and Staale: Deprecate the thread_concurrency system variable. It is unused within the server (See BUG#55001 )
http://dev.mysql.com/worklog/task/?id=5265
CC-MAIN-2015-14
refinedweb
581
50.84
Introduction SignalR is a library for .NET developers for adding real time functionality to the applications made using .NET technology (ASP.NET applications, C# console applications, WPF applications, Windows phone applications etc.). It is open source and you can download it from GitHub. Here, we are going to create a simple weather notification app that will instantly notify all connected users about the changed weather (in real time). Prerequisites You should have the basic knowledge of the following. Let’s start. Create a new project Create a new web project with the name WeatherAppDemo, using .NET Framework version 4.5. I am using .NET 4.5 because this will let us use the latest SignalR 2.x version. Please do not change the name as I am going to use this namespace throughout the article. I am creating an ASP.NET MVC project but you can create Web form or any ASP.NET technology project. Adding SignalR Library Configuring SignalR So basically, we are doing two things- we are first starting the StartUp class and adding the hubs to the SignalR pipeline. Now, compile the code and append this "/signalr/hubs" at the URL. You will have to add some JavaScript code. If you are able to see the JavaScript code, then you have successfully configured a SignalR Server. Creating Client Now, we need to create two clients, Steps to create a basic JavaScript Client Create ChangeWeather Client (ChangeWeather.html) Follow the steps to create a basic JavaScript client and in the last step, paste the below code in the script tag. Notice that when you open the RecieveWeatherNotification.html for the first time, there is no temperature, which is not good – I mean there should be some initial temperature. So, what we need to do is - Adding Extra Feature(Making more real) I have described above what I am going to do. So, just copy the below code and update the ChatHub class. I have created a method GetWeather which will call the chathubmethod “get_weather”. Compile the code and check out everything. This is a very simple app, but you can create real time complex application too. For example - View All
http://www.c-sharpcorner.com/article/weather-notification-app-using-signalr/
CC-MAIN-2018-05
refinedweb
362
67.65
Sorry, issue number is TRQS265 (not 165). MG -- Martin Goulet, B.Sc. Senior Software Architect SunGard Front Office Solutions -----Original Message----- From: Goulet, Martin Sent: Tuesday, December 21, 2004 11:28 AM To: 'Apache Torque Developers List' Subject: RE: Re: [SOURCE] Issue #TRQS256 had user association modified Henning and Thomas, I've created issue TRQS165 in Scarab for the new version of the patch. It includes all the changes that both of you recommended. Thomas, I understand that you can make the change to use buildQuery() instead of BasePeer.doSelect(). This is most appreciated. :) >> > You should be able to get the deliminator from buildQuery()? >> >> > Why use the doSelect() anyway? Why not use the primitives to build the >> > SQL string and send it to the DB? >> >> Why not? > >Well, here I agree with Henning again. He has done a lot of effort to >centralize SQL generation in one place, because only then you can >guarantee standard behaviour for each call. But I can also change this, >because there are a lot of recent changes in CVS (current active Branch ist >TORQUE_3_1_BRANCH, the methods to build the SQL from Criteria are in >SQLBuilder), so do not bother about this. Thx! MG -- Martin Goulet, B.Sc. Senior Software Architect SunGard Front Office Solutions -----Original Message----- From: Henning P. Schmiedehausen [mailto:hps@intermeta.de] Sent: Monday, December 13, 2004 1:58 PM To: torque-dev@db.apache.org Subject: Re: [SOURCE] Issue #TRQS256 had user association modified <Martin.Goulet@sungard.com> writes: >Henning: Thx for the feedback! (even though bedside manners doesn't seem >to be your strong point... I'm quite busy ATM and write short comments that might sound harsh. I know, this is not intended to be harsh, just to the point. If you felt offended, I apologize. However, this is a development list and code critisism is intended to improve the code quality, not to put people down. >remember I just want to contribute a bit back to the community with a >feature that I think is >useful) We all are grateful for contributions. But that does not mean, that every patch gets applied without discussion. IMHO there is no reason to add another number of convenience methods to an already bloated class. These methods can well be inside a helper class (CountHelper e.g.) >> Uh, do we really want to bloat up the Peer classes any further? What >> sense in putting this into BasePeer? >Ok, where would you put it? o.a.t.utils.CountHelper e.g. [...] >> Why are you doing all the shebang in count(Criteria, Connection, >> columnName, distinct) ? Am I missing something? >In order to issue the 'count' call the criteria is modified. So in order >to restitute it in the original form, we are resetting the columns and >the 'order by columns' in the original states. With this, the called >doesn't >need to keep a copy of his original object. Is there a need to keep state? AFAIK none of the other methods keep the state of the Criteria. IMHO, just run the count and be done with it. Put a notice on top of the Methods that the state of Criteria is destroyed. >> You should be able to get the deliminator from buildQuery()? >> Why use the doSelect() anyway? Why not use the primitives to build the >> SQL string and send it to the DB? >Why not? Because doSelect() is expensive as hell. It runs through all the Village hoops just to return (in the end) a single integer value. I'd expect to run a simple Criteria parser + straight SQL to run 10-20 times faster. However, this probably won't be visible compared to the DB time for the select
http://mail-archives.apache.org/mod_mbox/db-torque-dev/200412.mbox/%3CF4DFE8EDB932F641A9407CFB5CA599C301612BB4@e2kmtl1.internal.sungard.corp%3E
CC-MAIN-2016-36
refinedweb
617
75.1
Guid.Parse Method Namespace: SystemNamespace: System Assembly: mscorlib (in mscorlib.dll) Parameters - input - Type: System.String The string to convert. Return ValueType: System.Guid A structure that contains the value that was parsed. The Parse method converts the string representation of a GUID to a Guid value. This method can convert strings in any of the five formats produced by the ToString(String) and ToString(String, IFormatProvider) methods, as shown in the following table. The method throws a FormatException if it is unable to successfully parse the string. Here are some of the reasons why this might occur include: input contains characters that are not part of the hexadecimal character set. input has too many or too few numeric characters. input has too many or too few of the non-numeric characters appropriate for a particular format. input is not in one of the formats recognized by the ToString method and listed in the previous table. Use the TryParse method to catch any unsuccessful parse operations without having to handle an exception. The following example creates a new GUID, converts it to three separate string representations by calling the ToString(String) method with the "B", "D", and "X" format specifiers, and then calls the Parse method to convert the strings back to Guid values. using System; public class Example { public static void Main() { Guid originalGuid = Guid.NewGuid(); // Create an array of string representations of the GUID. string[] stringGuids = { originalGuid.ToString("B"), originalGuid.ToString("D"), originalGuid.ToString("X") }; // Parse each string representation. foreach (var stringGuid in stringGuids) { try { Guid newGuid = Guid.Parse(stringGuid); Console.WriteLine("Converted {0} to a Guid", stringGuid); } catch (ArgumentNullException) { Console.WriteLine("The string to be parsed is null."); } catch (FormatException) { Console.WriteLine("Bad format: {0}", stringGuid); } } } } // The example displays the following output: // Converted {81a130d2-502f-4cf1-a376-63edeb000e9f} to a Guid // Converted 81a130d2-502f-4cf1-a376-63edeb000e9f to a Guid // Converted {0x81a130d2,0x502f,0x4cf1,{0xa3,0x76,0x63,0xed,0xeb,0x00,0x0e,0x9f}} to a.
http://msdn.microsoft.com/en-us/library/system.guid.parse.aspx
CC-MAIN-2014-41
refinedweb
327
50.43
I have the following mapping table: Sample data: import pandas as pd from numpy import nan d = {'start': {0: 4, 1: 3, 2: 2, 3: 1, 4: 12, 5: 11, 6: 23, 7: 22, 8: 21}, 'name': {0: 'Vitamin', 1: 'Vitamin D', 2: 'Vitamin D3', 3: 'Colecalciferol', 4: 'Vitamin D2', 5: 'Ergocalcifero', 6: 'Vitamin K', 7: 'Vitamin K2', 8: 'Menachinon'}, 'end': {0: nan, 1: 4.0, 2: 3.0, 3: 2.0, 4: 3.0, 5: 12.0, 6: 4.0, 7: 23.0, 8: 22.0}} df = pd.DataFrame(d) l1 = ['Colecalciferol', 'Vitamin D'] l2 = ['Colecalciferol', 'Ergocalcifero', 'Vitamin D3'] Expected output: l1 = ['Colecalciferol'] l2 = ['Colecalciferol', 'Ergocalcifero'] What I tried: import networkx as nx G = nx.Graph() G = nx.from_pandas_edgelist(df, 'start', 'end', create_using=nx.DiGraph()) T = nx.dfs_tree(G, source=1).reverse() print(list(T)) # [1, 2.0, 3.0, 4.0, nan] Essentially showing the successors of a term, here of start 1: ‘Colecalciferol’, but actually I think I need the ancestors of a term, not the successors. Goal: I want to remove duplicates, even of higher/lower level terms. e.g.: ‘Colecalciferol’ is a ‘Vitamin D3’ which is a ‘Vitamin D’. Therefore, I want to remove ‘Vitamin D’ to preserve the information of the lowest level term in example (l1). Answer You were pretty close! Here’s a way to go with your graph approach: we simply check if the node has any predecessor, and if it does, it means it isn’t a lowest-level term and we don’t want to keep it. import networkx as nx G = nx.Graph() G = nx.from_pandas_edgelist(df, 'start', 'end', create_using=nx.DiGraph()) filtered_l1 = [] for elmt in l1: node = int(df[df.name == elmt].start) if list(G.predecessors(node)) == []: filtered_l1.append(elmt) print(filtered_l1) The for loop above can be condensed in a one-liner: [x for x in l1 if list(G.predecessors(int(df[df.name == x].start))) == []] A simpler approach that completely removes the dependency on networkx would be to simply check if a product’s start is the end of any product, in which case it isn’t bottom-level and we want it filtered out: all_ends = df.end.unique() filtered_l1 = [x for x in l1 if int(df[df.name == x].start) not in all_ends]
https://www.tutorialguruji.com/python/drop-duplicates-with-nested-data-graph/
CC-MAIN-2021-43
refinedweb
382
60.31
There are some very low cost MQ-2 sensors ($3-$5) that can be used to measure common combustible gases such as hydrogen, butane, methane, propane and liquid petroleum gas (LPG). My goal for this project was to make a handheld monitor that we could use to measure potential leaks in our propane BBQ or natural gas leaks in and around our furnace. Setup For our setup we used: - a MQ-2 sensor - 4 digit LED display ($3) - Arduino Nano - Small bread board - USB battery charger - jumpers and duct tape Some duct tape can be used to secure the bread board to the USB battery unit. We used a low cost 4 digit display and we mounted it direct to the bread board. Code We were only interested in a “GAS” or “NO GAS” reading, so because of this our code was super simple. #include <Arduino.h> #include <TM1637Display.h> // Module connection pins (Digital Pins) #define CLK 2 #define DIO 3 TM1637Display display(CLK, DIO); int smokeA0 = A0; // Your threshold value int sensorThres = 400; void setup() { pinMode(smokeA0, INPUT); Serial.begin(9600); display.setBrightness(0x0f); } void loop() { int analogSensor = analogRead(smokeA0); Serial.print("Pin A0: "); Serial.println(analogSensor); display.showNumberDec(analogSensor, false); delay(1000); } If you want to get accurate gas measurements then you’ll need to do some calibration. We were only interested in a seeing something above a “clear air” reading. For our setup a “clear air” reading was about 100-115. To test our project we used a butane lighter and we open it very quickly (<1 second).
https://funprojects.blog/tag/methane/
CC-MAIN-2021-10
refinedweb
261
61.16
Groovy Goodness: Getting the Indices of a Collection Groovy Goodness: Getting the Indices of a Collection Join the DZone community and get the full member experience.Join For Free Get the Edge with a Professional Java IDE. 30-day free trial. Since Groovy 2.4 we can use the indices property on a Collection to get the indices of the elements in the collection. We get an IntRange object as a result. def list = [3, 20, 10, 2, 1] assert list.indices == 0..4 // Combine letters in alphabet // with position (zero-based). def alphabet = 'a'..'z' def alphabetIndices = [alphabet, alphabet.indices].transpose() // alphabetIndices = [['a', 0], ['b', 1], ...] // Find position of each letter // from 'groovy' in alphabet. def positionInAlphabet = 'groovy'.inject([]) { result, value -> result << alphabetIndices.find { it[0] == value }[1] + 1 result } assert positionInAlphabet == [7, 18, 15, 15, 22, 25] Code written with Groovy 2 }}
https://dzone.com/articles/groovy-goodness-getting
CC-MAIN-2018-47
refinedweb
144
54.08
Include branch field in review request emails Review Request #10147 — Created Sept. 16, 2018 and submitted With a lot of review request emails, prioritizing review requests emails becomes uneasy. Review request e-mails will now contain a branch field. Tested by manually checking generated review request emails for the inclusion of the branch field. I know this is a small change, but can you take a peek at our guide for writing good change descriptions. Specifically, the description and testing done should consist of complete sentences. Also the description should read more like E-mails will now contain the contents of the branch field .... i.e., the sentences should be descriptive not summaritive. We probably want these one right after the other. Unfortunately, the Django templating language is kinda messy when it comes to newlines (since it's really built for HTML where it rarely matters). Each newline in there, including the ones after the template tags, will be included in the plain-text e-mail. That means you're going to get something like: Repository: my-repo Branch: my-branch Description ----------- (This is only a problem in plain-text e-mails.) Instead, we'll want to collapse those. The good news is, we have a handy tag you can use. called condense. This would look like: {% condense 0 %} {% if review_request.repository %} Repository: ... {% endif %} {% if review_request.branch %} Branch: ... {% endif %} {% endcondense %} Description..... Make sure you run the preview-email view with this and check the output to see that there's consistency in spacing between each section and each important thing within it. We'll want to see that in the testing. Indentation here is wrong. We do our {% blocktag %}indentation inside the tags themselves and do not increase the indentation of nest tags. This should be formatted as: <div style="margin-top: 1.5em"> {% if review_request.repository %} <strong style="....">Repository: </strong> {{review_request.repository.name}} {% endif %} {% if review_request.branch %} <strong style="...">Branch: </strong> {{review_request.branch}} {% endif %} </div> Change Summary: Addressed issues
https://reviews.reviewboard.org/r/10147/
CC-MAIN-2020-29
refinedweb
330
60.92
But when you look at the WSDL that gets generated for your service, you will notice that there are a lot of references to an XML namespace. Lets just say if you publish such a service or develope a solution for yor client who will then publish the service with this namespace to their customers - it is just very unprofessional. Changing the namespace, however, can be more trickier than you thought. The following article will show you how to deal with namespace changes in WCF. This will work in both WCF 3 / 3.5 and WCF 4. There are some minor changes, for example, with the configuration, but the same things apply. Quick reference For those who are impatient to see how this is done, here is a quick reference of the changes we will apply to a simple WCF service to change the namespace. There are four places to change: - Apply the Namespace property to the ServiceContractAttribute on the service contract interface - Apply the Namespace property to the ServiceBehaviorAttribute on the class that implements the service - Apply the Namespace property to the DataContractAttribute on every class that is involved with the service (parameters, return values) - Change the namespace for the binding, either on the binding class or in the .config file And now in detail. The contract namespace The first step of course is changing the contract namespace. This is pretty easy, and probably something everyone tries first. It is however, not enough. But lets get started anyway. Assume I have just generated a new WCF service application. I renamed the default Service1 name to RebuildallService, so I have an interface called IRebuildallService and a class called RebuildallService. The .svc file is called RebuildallService.svc. A little too many service words, but I will leave it that way for now The service contract looks like this: [ServiceContract] public interface IRebuildallService { The ServiceContractAttribute accepts a property called Namespace, and you might have guessed we are going to use that. This will change the namespace on the contract. So the code now looks lke this: [ServiceContract ( Namespace = "" )] public interface IRebuildallService { If I compile and check the WSDL, I will get certain parts with the tempuri.org namespace and others parts with my new namespace. In practice, the wsdl:definitions XML elements will be in the new namespace, but all data and other parts of the WSDL will stil exist in tempuri.org. A note on namespaces: namespaces ARE NOT URLS!. They might look like one, like in my examples, but there is no such subdomain as schemas actually in existence. Namespaces follow the URI format, but are not actual addresses. They can be used to identify schemas, because usually a company owns a domain name. Thus using that as the schema namespace creates something unique. And that is exactly what namespaces should be: unique. The service namespace So, what else do we need to change? The next step is of course the service implementation itself. Currently, it looks like this: public class RebuildallService : IRebuildallService { What we want to do is apply the ServiceBehaviorAttribute, which also has a Namespace property. [ServiceBehavior(Namespace = "")] public class RebuildallService : IRebuildallService { Looking at the WSDL after this change you will notice that a big part is now in the desired namespace and there are two things left in the tempuri.org namespace: the data types we use and the wsdl:binding element. The data types Lets change the namespace for the data types, since it is a rather straightforward change. Currently the example service (the default implementation that Visual Studio provides) contains the following definition for a data type: [DataContract] public class CompositeType { You might have guessed, we will add the Namespace attribute to the DataContractAttribute. [DataContract(Namespace = "")] public class CompositeType { This will change our data types to exist in our new namespace. If your data is more complex and you have several classes, be sure to apply the Namespace property along with the DataContract attribute to every one of them. Do this also for your enums, otherwise they will exist in the tempuri.org namespace! The binding The final element is changing the binding namespace. If you use code-only WCF, you would specify this in the constructor of the Binding class, but since most of the time you will use config files to specify the binding, I will show how to proceed in this latter case. In WCF4 you have default bindings, so your web.config file will be pretty empty. In WCF3/3.5 the config file will contain the binding by default, so there you can change it more easily. Anyhow, what you need to do is add the bindingNamespace element to the endpoint element of the service element. Like so: <services> <service name="WcfNamespaces.RebuildallService"> <endpoint address="RebuildallService.svc" bindingNamespace="" binding="basicHttpBinding" contract="WcfNamespaces.IRebuildallService" /> </service> </services> For WCF4, I would need to add this entire section into my config file. For WCF3/3.5 only the new attribute needs to be added. The WcfNamespaces, in case you wonder, is the .NET namespace my test project was in. And with this final change, the WSDL will not be in our own custom namespace, and is gone for good Some thoughts about namespaces In the example above, I placed all services, descriptions, bindings and data types in the same namespace. This is of course not needed, you can specify different namespaces for everything, and WCF will handle this. The WSDL will be more fragmented: WCF generates a separate document for different namespaced entities. But there is nothing technically preventing you from doing this. @ Monday, 04 July 2016 16:24
http://blog.rebuildall.net/2010/11/10/WCF_service_namespaces
CC-MAIN-2016-36
refinedweb
936
63.39
Opened 8 years ago Closed 8 years ago Last modified 8 years ago #2784 closed enhancement (wontfix) extend URL resolver support for HTTP Methods Description This patch introduces HTTP method support into the URL resolver allowing for easy creating of REST style applications. At the urls file you can specify which view is supposed to respond to what HTTP method. Currently only POST,GET,PUT,DELETE are supported and those are specified in django.conf.urls.defaults from django.conf.urls.defaults import * urlpatterns = patterns('', # Example: (r'^django_rest_urls/get/(?P<id>\d+)', 'django_rest_urls.restful.views.get'), (r'^django_rest_urls/(?P<id>\d+)', { 'GET': 'django_rest_urls.restful.views.get', 'POST': 'django_rest_urls.restful.views.post', 'PUT': 'django_rest_urls.restful.views.put', 'DELETE': 'django_rest_urls.restful.views.delete', }), # Uncomment this for admin: # (r'^admin/', include('django.contrib.admin.urls')), ) Attachments (1) Change History (7) Changed 8 years ago by simon@… comment:1 Changed 8 years ago by simon@… Your views won't change, they'll just be like so: # Create your views here. from django.http import HttpResponse def get(request,id): return HttpResponse("get %s\n" % id) def post(request,id): return HttpResponse("post %s\n" % id) def put(request,id): return HttpResponse("put %s\n" % id) def delete(request,id): return HttpResponse("delete %s\n" % id) comment:2 Changed 8 years ago by simon@… - Version changed from 0.95 to SVN Sorry - the version is SVN not 0.95 comment:3 Changed 8 years ago by mtredinnick I think this is doing too much overloading of things inside of patterns() -- using dictionaries as the second argument gives vastly different behaviour to using strings or functions. The idea itself might have some merit, although it can be pretty easily done via a view dispatcher, so it's not blindingly urgent right now. Could you bring it up on the django-developers list for some discussion about possible syntax, please? Most of the main developers are quite busy at the moment, so you may need to wait a day or two for a response, but this proposal needs a bit more discussion before it can be accepted. Off the top of my head, I can't think of a syntax that seems reasonable, but I'd be interested in hearing a few ideas from other people. comment:4 Changed 8 years ago by simon@… You are probably right - my patchy implementation is too complex, the fruit of hacking it together in a few minutes. But I still like the idea of specifying a view per HTTP method - seems cleaner than doing an 'if request.POST' inside the view. I'll pitch it in django-developers and I'd be interested in the discussion. comment:5 Changed 8 years ago by adrian - Resolution set to wontfix - Status changed from new to closed This is a bit too hackish. Please bring this up on the django-developers mailing list first. HTTP Method support in URLs patch
https://code.djangoproject.com/ticket/2784
CC-MAIN-2014-23
refinedweb
487
54.63
.\" LFILTER 1" .TH PERLFILTER 1 "2004-11-05" "perl v5.8.6" "Perl Programmers Reference Guide" .SH "NAME" perlfilter \- Source Filters .SH "DESCRIPTION" .IX Header "DESCRIPTION" This article is about a little-known feature of Perl called \&\fIsource filters\fR.. .PP The original purpose of source filters was to let you encrypt your program source to prevent casual piracy. This isn't all they can do, as you'll soon learn. But first, the basics. .SH "CONCEPTS" .IX Header "CONCEPTS" Before the Perl interpreter can execute a Perl script, it must first read it from a file into memory for parsing and compilation. If that script itself includes other scripts with a \f(CW\*(C`use\*(C'\fR or \f(CW\*(C`require\*(C'\fR statement, then each of those scripts will have to be read from their respective files as well. .PP Now think of each logical connection between the Perl parser and an individual file as a \fIsource stream\fR. A source stream is created when the Perl parser opens a file, it continues to exist as the source code is read into memory, and it is destroyed when Perl is finished parsing the file. If the parser encounters a \f(CW\*(C`require\*(C'\fR or \f(CW\*(C`use\*(C'\fR statement in a source stream, a new and distinct stream is created just for that file. .PP The diagram below represents a single source stream, with the flow of source from a Perl script file on the left into the Perl parser on the right. This is how Perl normally operates. .PP .Vb 1 \& file -------> parser .Ve .PP There are two important points to remember: .IP "1." 5 Although there can be any number of source streams in existence at any given time, only one will be active. .IP "2." 5 Every source stream is associated with only one file. .PP A source filter is a special kind of Perl module that intercepts and modifies a source stream before it reaches the parser. A source filter changes our diagram like this: .PP .Vb 1 \& file ----> filter ----> parser .Ve .PP If that doesn't make much sense, consider the analogy of a command pipeline. Say you have a shell script stored in the compressed file \&\fItrial.gz\fR. The simple pipeline command below runs the script without needing to create a temporary file to hold the uncompressed file. .PP .Vb 1 \& gunzip -c trial.gz | sh .Ve .PP In this case, the data flow from the pipeline can be represented as follows: .PP .Vb 1 \& trial.gz ----> gunzip ----> sh .Ve .PP With source filters, you can store the text of your script compressed and use a source filter to uncompress it for Perl's parser: .PP .Vb 2 \& compressed gunzip \& Perl program ---> source filter ---> parser .Ve .SH "USING FILTERS" .IX Header "USING FILTERS" So how do you use a source filter in a Perl script? Above, I said that a source filter is just a special kind of module. Like all Perl modules, a source filter is invoked with a use statement. .PP Say you want to pass your Perl source through the C preprocessor before execution. You could use the existing \f(CW\*(C`\-P\*(C'\fR command line option to do this, but as it happens, the source filters distribution comes with a C preprocessor filter module called Filter::cpp. Let's use that instead. .PP Below is an example program, \f(CW\*(C`cpp_test\*(C'\fR, which makes use of this filter. Line numbers have been added to allow specific lines to be referenced easily. .PP .Vb 4 \& 1: use Filter::cpp ; \& 2: #define TRUE 1 \& 3: $a = TRUE ; \& 4: print "a = $a\en" ; .Ve .PP When you execute this script, Perl creates a source stream for the file. Before the parser processes any of the lines from the file, the source stream looks like this: .PP .Vb 1 \& cpp_test ---------> parser .Ve .PP Line 1, \f(CW\*(C`use Filter::cpp\*(C'\fR, includes and installs the \f(CW\*(C`cpp\*(C'\fR filter module. All source filters work this way. The use statement is compiled and executed at compile time, before any more of the file is read, and it attaches the cpp filter to the source stream behind the scenes. Now the data flow looks like this: .PP .Vb 1 \& cpp_test ----> cpp filter ----> parser .Ve .PP As the parser reads the second and subsequent lines from the source stream, it feeds those lines through the \f(CW\*(C`cpp\*(C'\fR source filter before processing them. The \f(CW\*(C`cpp\*(C'\fR filter simply passes each line through the real C preprocessor. The output from the C preprocessor is then inserted back into the source stream by the filter. .PP .Vb 5 \& .-> cpp --. \& | | \& | | \& | <-' \& cpp_test ----> cpp filter ----> parser .Ve .PP The parser then sees the following code: .PP .Vb 3 \& use Filter::cpp ; \& $a = 1 ; \& print "a = $a\en" ; .Ve .PP Let's consider what happens when the filtered code includes another module with use: .PP .Vb 5 \& 1: use Filter::cpp ; \& 2: #define TRUE 1 \& 3: use Fred ; \& 4: $a = TRUE ; \& 5: print "a = $a\en" ; .Ve .PP The \f(CW\*(C`cpp\*(C'\fR filter does not apply to the text of the Fred module, only to the text of the file that used it (\f(CW\*(C`cpp_test\*(C'\fR). Although the use statement on line 3 will pass through the cpp filter, the module that gets included (\f(CW\*(C`Fred\*(C'\fR) will not. The source streams look like this after line 3 has been parsed and before line 4 is parsed: .PP .Vb 1 \& cpp_test ---> cpp filter ---> parser (INACTIVE) .Ve .PP .Vb 1 \& Fred.pm ----> parser .Ve .PP As you can see, a new stream has been created for reading the source from \f(CW\*(C`Fred.pm\*(C'\fR. This stream will remain active until all of \f(CW\*(C`Fred.pm\*(C'\fR has been parsed. The source stream for \f(CW\*(C`cpp_test\*(C'\fR will still exist, but is inactive. Once the parser has finished reading Fred.pm, the source stream associated with it will be destroyed. The source stream for \f(CW\*(C`cpp_test\*(C'\fR then becomes active again and the parser reads line 4 and subsequent lines from \f(CW\*(C`cpp_test\*(C'\fR. .PP You can use more than one source filter on a single file. Similarly, you can reuse the same filter in as many files as you like. .PP For example, if you have a uuencoded and compressed source file, it is possible to stack a uudecode filter and an uncompression filter like this: .PP .Vb 4 \& use Filter::uudecode ; use Filter::uncompress ; \& M'XL(".H 7/;1I;_>_I3=&E=%:F*I"T?22Q/ \& M6]9* \& ... .Ve .PP Once the first line has been processed, the flow will look like this: .PP .Vb 2 \& file ---> uudecode ---> uncompress ---> parser \& filter filter .Ve .PP Data flows through filters in the same order they appear in the source file. The uudecode filter appeared before the uncompress filter, so the source file will be uudecoded before it's uncompressed. .SH "WRITING A SOURCE FILTER" .IX Header "WRITING A SOURCE FILTER". .SH "WRITING A SOURCE FILTER IN C" .IX Header "WRITING A SOURCE FILTER IN C" The first of the three available techniques is to write the filter completely in C. The external module you create interfaces directly with the source filter hooks provided by Perl. .PP \&\f(CW\*(C`decrypt\*(C'\fR filter (which unscrambles the source before Perl parses it) included with the source filter distribution is an example of a C source filter (see Decryption Filters, below). .IP "\fBDecryption Filters\fR" 5 .IX Item "Decryption Filters" All decryption filters work on the principle of \*(L"security through obscurity.\*(R" Regardless of how well you write a decryption filter and how strong your encryption algorithm, anyone determined enough can retrieve the original source code. The reason is quite simple \- once the decryption filter has decrypted the source back to its original form, fragments of it will be stored in the computer's memory as Perl parses it. The source might only be in memory for a short period of time, but anyone possessing a debugger, skill, and lots of patience can eventually reconstruct your program. .Sp \fIdecrypt.pm\fR in the source filters module. .SH "CREATING A SOURCE FILTER AS A SEPARATE EXECUTABLE" .IX Header "CREATING A SOURCE FILTER AS A SEPARATE EXECUTABLE" An alternative to writing the filter in C is to create a separate executable in the language of your choice. The separate executable reads from standard input, does whatever processing is necessary, and writes the filtered data to standard output. \f(CW\*(C`Filter:cpp\*(C'\fR is an example of a source filter implemented as a separate executable \- the executable is the C preprocessor bundled with your C compiler. .PP The source filter distribution includes two modules that simplify this task: \f(CW\*(C`Filter::exec\*(C'\fR and \f(CW\*(C`Filter::sh\*(C'\fR. Both allow you to run any external executable. Both use a coprocess to control the flow of data into and out of the external executable. (For details on coprocesses, see Stephens, W.R. \*(L"Advanced Programming in the \s-1UNIX\s0 Environment.\*(R" Addison\-Wesley, \s-1ISBN\s0 0\-210\-56317\-7, pages 441\-445.) The difference between them is that \f(CW\*(C`Filter::exec\*(C'\fR spawns the external command directly, while \f(CW\*(C`Filter::sh\*(C'\fR spawns a shell to execute the external command. (Unix uses the Bourne shell; \s-1NT\s0 uses the cmd shell.) Spawning a shell allows you to make use of the shell metacharacters and redirection facilities. .PP Here is an example script that uses \f(CW\*(C`Filter::sh\*(C'\fR: .PP .Vb 3 \& use Filter::sh 'tr XYZ PQR' ; \& $a = 1 ; \& print "XYZ a = $a\en" ; .Ve .PP The output you'll get when the script is executed: .PP .Vb 1 \& PQR a = 1 .Ve .PP Writing a source filter as a separate executable works fine, but a small performance penalty is incurred. For example, if you execute the small example above, a separate subprocess will be created to run the Unix \f(CW\*(C`tr\*(C'\fR command. Each use of the filter requires its own subprocess. If creating subprocesses is expensive on your system, you might want to consider one of the other options for creating source filters. .SH "WRITING A SOURCE FILTER IN PERL" .IX Header "WRITING A SOURCE FILTER IN PERL" The easiest and most portable option available for creating your own source filter is to write it completely in Perl. To distinguish this from the previous two techniques, I'll call it a Perl source filter. .PP.) .PP .Vb 1 \& package Rot13 ; .Ve .PP .Vb 1 \& use Filter::Util::Call ; .Ve .PP .Vb 5 \& sub import { \& my ($type) = @_ ; \& my ($ref) = [] ; \& filter_add(bless $ref) ; \& } .Ve .PP .Vb 3 \& sub filter { \& my ($self) = @_ ; \& my ($status) ; .Ve .PP .Vb 4 \& tr/n-za-mN-ZA-M/a-zA-Z/ \& if ($status = filter_read()) > 0 ; \& $status ; \& } .Ve .PP .Vb 1 \& 1; .Ve .PP All Perl source filters are implemented as Perl classes and have the same basic structure as the example above. .PP First, we include the \f(CW\*(C`Filter::Util::Call\*(C'\fR module, which exports a number of functions into your filter's namespace. The filter shown above uses two of these functions, \f(CW\*(C`filter_add()\*(C'\fR and \&\f(CW\*(C`filter_read()\*(C'\fR. .PP Next, we create the filter object and associate it with the source stream by defining the \f(CW\*(C`import\*(C'\fR function. If you know Perl well enough, you know that \f(CW\*(C`import\*(C'\fR is called automatically every time a module is included with a use statement. This makes \f(CW\*(C`import\*(C'\fR the ideal place to both create and install a filter object. .PP In the example filter, the object (\f(CW$ref\fR). .PP The association between the filter object and the source stream is made with the \f(CW\*(C`filter_add()\*(C'\fR function. This takes a filter object as a parameter (\f(CW$ref\fR in this case) and installs it in the source stream. .PP Finally, there is the code that actually does the filtering. For this type of Perl source filter, all the filtering is done in a method called \f(CW\*(C`filter()\*(C'\fR. (It is also possible to write a Perl source filter using a closure. See the \f(CW\*(C`Filter::Util::Call\*(C'\fR manual page for more details.) It's called every time the Perl parser needs another line of source to process. The \f(CW\*(C`filter()\*(C'\fR method, in turn, reads lines from the source stream using the \f(CW\*(C`filter_read()\*(C'\fR function. .PP If a line was available from the source stream, \f(CW\*(C`filter_read()\*(C'\fR returns a status value greater than zero and appends the line to \f(CW$_\fR. A status value of zero indicates end\-of\-file, less than zero means an error. The filter function itself is expected to return its status in the same way, and put the filtered line it wants written to the source stream in \f(CW$_\fR. The use of \f(CW$_\fR accounts for the brevity of most Perl source filters. .PP In order to make use of the rot13 filter we need some way of encoding the source file in rot13 format. The script below, \f(CW\*(C`mkrot13\*(C'\fR, does just that. .PP .Vb 5 \& die "usage mkrot13 filename\en" unless @ARGV ; \& my $in = $ARGV[0] ; \& my $$out") or die "Cannot open file $out: $!\en"; .Ve .PP .Vb 5 \& print OUT "use Rot13;\en" ; \& while ( ) { \& tr/a-zA-Z/n-za-mN-ZA-M/ ; \& print OUT ; \& } .Ve .PP .Vb 4 \& close IN; \& close OUT; \& unlink $in; \& rename $out, $in; .Ve .PP If we encrypt this with \f(CW\*(C`mkrot13\*(C'\fR: .PP .Vb 1 \& print " hello fred \en" ; .Ve .PP the result will be this: .PP .Vb 2 \& use Rot13; \& cevag "uryyb serq\ea" ; .Ve .PP Running it produces this output: .PP .Vb 1 \& hello fred .Ve .SH "USING CONTEXT: THE DEBUG FILTER" .IX Header "USING CONTEXT: THE DEBUG FILTER" The rot13 example was a trivial example. Here's another demonstration that shows off a few more features. .PP, \f(CW\*(C`DEBUG\*(C'\fR. Debugging code is enabled if the variable exists, otherwise it is disabled. .PP Two special marker lines will bracket debugging code, like this: .PP .Vb 5 \& ## DEBUG_BEGIN \& if ($year > 1999) { \& warn "Debug: millennium bug in year $year\en" ; \& } \& ## DEBUG_END .Ve .PP When the \f(CW\*(C`DEBUG\*(C'\fR environment variable exists, the filter ensures that Perl parses only the code between the \f(CW\*(C`DEBUG_BEGIN\*(C'\fR and \f(CW\*(C`DEBUG_END\*(C'\fR markers. That means that when \f(CW\*(C`DEBUG\*(C'\fR does exist, the code above should be passed through the filter unchanged. The marker lines can also be passed through as\-is, because the Perl parser will see them as comment lines. When \f(CW\*(C`DEBUG\*(C'\fR isn't set, we need a way to disable the debug code. A simple way to achieve that is to convert the lines between the two markers into comments: .PP .Vb 5 \& ## DEBUG_BEGIN \& #if ($year > 1999) { \& # warn "Debug: millennium bug in year $year\en" ; \& #} \& ## DEBUG_END .Ve .PP Here is the complete Debug filter: .PP .Vb 1 \& package Debug; .Ve .PP .Vb 3 \& use strict; \& use warnings; \& use Filter::Util::Call ; .Ve .PP .Vb 2 \& use constant TRUE => 1 ; \& use constant FALSE => 0 ; .Ve .PP .Vb 11 \& sub import { \& my ($type) = @_ ; \& my (%context) = ( \& Enabled => defined $ENV{DEBUG}, \& InTraceBlock => FALSE, \& Filename => (caller)[1], \& LineNo => 0, \& LastBegin => 0, \& ) ; \& filter_add(bless \e%context) ; \& } .Ve .PP .Vb 6 \& sub Die { \& my ($self) = shift ; \& my ($message) = shift ; \& my ($line_no) = shift || $self->{LastBegin} ; \& die "$message at $self->{Filename} line $line_no.\en" \& } .Ve .PP .Vb 5 \& sub filter { \& my ($self) = @_ ; \& my ($status) ; \& $status = filter_read() ; \& ++ $self->{LineNo} ; .Ve .PP .Vb 6 \& # deal with EOF/error first \& if ($status <= 0) { \& $self->Die("DEBUG_BEGIN has no DEBUG_END") \& if $self->{InTraceBlock} ; \& return $status ; \& } .Ve .PP .Vb 6 \& if ($self->{InTraceBlock}) { \& if (/^\es*##\es*DEBUG_BEGIN/ ) { \& $self->Die("Nested DEBUG_BEGIN", $self->{LineNo}) \& } elsif (/^\es*##\es*DEBUG_END/) { \& $self->{InTraceBlock} = FALSE ; \& } .Ve .PP .Vb 10 \& # comment out the debug lines when the filter is disabled \& s/^/#/ if ! $self->{Enabled} ; \& } elsif ( /^\es*##\es*DEBUG_BEGIN/ ) { \& $self->{InTraceBlock} = TRUE ; \& $self->{LastBegin} = $self->{LineNo} ; \& } elsif ( /^\es*##\es*DEBUG_END/ ) { \& $self->Die("DEBUG_END has no DEBUG_BEGIN", $self->{LineNo}); \& } \& return $status ; \& } .Ve .PP .Vb 1 \& 1 ; .Ve .PP \f(CW\*(C`DEBUG_BEGIN\*(C'\fR line, but has not yet encountered the following \f(CW\*(C`DEBUG_END\*(C'\fR line. .PP If you ignore all the error checking that most of the code does, the essence of the filter is as follows: .PP .Vb 4 \& sub filter { \& my ($self) = @_ ; \& my ($status) ; \& $status = filter_read() ; .Ve .PP .Vb 6 \& # deal with EOF/error first \& return $status if $status <= 0 ; \& if ($self->{InTraceBlock}) { \& if (/^\es*##\es*DEBUG_END/) { \& $self->{InTraceBlock} = FALSE \& } .Ve .PP .Vb 7 \& # comment out debug lines when the filter is disabled \& s/^/#/ if ! $self->{Enabled} ; \& } elsif ( /^\es*##\es*DEBUG_BEGIN/ ) { \& $self->{InTraceBlock} = TRUE ; \& } \& return $status ; \& } .Ve .PP Be warned: just as the C\-preprocessor doesn't know C, the Debug filter doesn't know Perl. It can be fooled quite easily: .PP .Vb 3 \& print < .SH "Copyrights" .IX Header "Copyrights" This article originally appeared in The Perl Journal #11, and is copyright 1998 The Perl Journal. It appears courtesy of Jon Orwant and The Perl Journal. This document may be distributed under the same terms as Perl itself.
http://www.fiveanddime.net/ss/man-unformatted/man1/perlfilter.1
crawl-003
refinedweb
2,995
65.73
Localization (l10n) and internationalization (i18n) intimidate many developers, but Android already provides great tools to aid you in global domination. In this Bay Area Android Dev Group talk, Siena Aguayo teaches you how to localize your app using tools such as layout design flexibility, locale-specific resources, and translation services such as Smartling. Learn how to implement these localization features to target an international audience and substantially increase your market size 🌏👥 Introduction (0:00) Hi! I’m a software engineer at Indiegogo, and the choice of the word “fearless” in the title here is not an accident: it’s one of our company values. I want to empower you to be more fearless in your implementation of internationalization. In this talk, I’ll go over l10n and i18n, reasons to care about internationalization, how to internationalize your Android app, and some other cool things you can do. As for me, I mentioned that I work at Indiegogo. We’re a crowdfunding platform. I came to Indiegogo by way of Hackbright Academy, a programming bootcamp for women located here in San Francisco. It’s an awesome institution that empowers more women to become software engineers — woo! I worked on the Indiegogo Android app, and we shipped in four languages: English, Spanish, French, and German. This is where my experience lies. You’ll notice none of those languages are right-to-left languages, and none are non-Latin alphabet languages, so if you were looking for some insight there, this will not be the talk for you. What are l10n and i18n? (1:42) Let’s get down to basics. In case you haven’t had the crucial “Aha!” moment with l10n and i18n yet, I’m going to explain it to you. Those numbers actually represent the number of letters in between the first and last letters in the words “localization” and “internationalization.” Cool, right? I’m going to define “localization” as probably what you think about when you consider putting your apps into other languages. You actually have to translate your content, which means translating your English strings into Spanish, for example. But, what also comes with localization is that you have to format your data differently, depending on the language that you’re targeting. Certain languages format dates, numbers, and currencies differently than they do in English. Localization also encompasses adjusting your company’s branding according to the target culture. That is all kind of outside the scope of engineering. It’s more focused on the business side of things, so I won’t be guiding you on how to choose which languages you want to translate to. “Internationalization,” then, is really preparing your app for localized content, for those different number formats and different strings. This encompasses defining alternate resource files, using those number and date formatters, and designing flexible layouts. This probably sounds more like your job as an engineer. EMPATHY (3:19) Why should you care about this? Localization and internationalization are not just translation. It also has to do with empathy. I think this is something we should all be talking more about as engineers. We’re all fundamentally people. One of the things I really love about Android is that it’s everywhere. It’s accessible to people of all different kinds all around the world, so really I think this is part of what we should care about as Android engineers. Get more development news like this That being said, if that doesn’t appeal to you because you’re thinking “I’m a robot, I don’t care about people,” here are the technical benefits! Preparing your app for internationalized content really is about separation of concerns. It helps you be more organized, and write more readable code. If you’re thinking, “Well Siena, I really love reading those hardcoded English strings all over my app so I know what’s going on,” Android Studio really does you a favor here. It gives you a little gloss of this ID because it doesn’t want you to miss those hardcoded strings, but it doesn’t want you to use them. @Override int getTitleId() { return "Explore"; return R.string.menu_explore; YAGNI (4:25) I wanted to mention this concept called YAGNI. We about this a lot at Indiegogo. It stands for “Ya Ain’t Gonna Need It,” and it’s a way to talk about avoiding over-engineering. I feel like some of the pushback that comes from internationalization is something like “Well, it’s a lot of work up front that I don’t want to do until I know I need to do it.” Hopefully, by the end of this post, you’ll believe that there are only a few things you need in order to get you in really good shape for internationalization, and then you can really go to town when you need to. How Do I Internationalize My Android App? (4:57) If you’ve followed me this far, you may realize that this could be rephrased as, “How do I prepare my Android app for localized content?” Let’s start off with what content is localizable. You can localize strings, obviously, but also numbers and currency, dates and time, images with text, and audio and video files. For images with text, you really want to avoid this as much as possible just because it’s a pain to have to manage all those alternate resources with images. If your designer comes to you with a big ol’ image with lots of text on it, you should say, “Hey, that image needs to be a string, and we need to translate that.” These things can be split into two areas: stuff that you work with in your resource files, and stuff that you deal with in your Java. I’m going to focus on when these bits of data creep into your strings and how you deal with that. Resource Files (6:04) Everyone probably knows that you should have a set of default resources, so this is probably your value string’s XML. Then, as you need to, you can define alternate languages you’re going to use. These don’t need to be exact copies of your default resources because it’ll fall back to the default resources, which is kind of cool thing if you’re doing something like US English and UK English. You can just change couple spellings where you need them (i.e. put in some extra U’s), but you don’t have to copy everything over. Strings (6:37) Don’t hardcode strings that face the user. This is probably Internationalization 101 material, but I want to underscore it. You want to put them, instead, in your resources file. Another great tip is you can use nifty position placeholders like %1$s instead of just doing %s when you need to put in some dynamic value into your string. You can use ones that have position numbers in them. Instead of I need to %s interpolate %s you can write I need to %1$s interpolate %2$s. If grammatically in another language, the thing in position number two needed to come before position number one, this wouldn’t be a problem - Java would know where to stick those dynamic values. Lastly, providing context for your translators can help them make their job a lot easier. Android Is On Our Side (7:25) I want to show you all my favorite thing about Android when I first started. I used to program for iOS, and we didn’t do a lot of up-front work for localization in the beginning. It was really painful when we had to go back and do it all again. Very early on in my programming for Android, I came across a warning on a hardcoded string in a TextView that “Hey, this is an i18n hardcoded string warning. This should be using an @string resource.” I think this is awesome because Android is really guiding you in the right direction and trying to warn you against doing things that are not a best practice. This is not going to happen if you just call setText in your Java code though, so you do want to watch out for that. More Things in Strings (8:16) Something else we can add in our strings files is a translatable="false" attribute: <string name="app_name" translatable="false"> Indiegogo </string> You can use this both programmatically and to signal to your translators, “Hey, you don’t need to translate this.” In our case at Indiegogo, we don’t ever translate our company name, so that’s translatable="false". This will also bring some helpful lint errors into play if you’ve translated something you weren’t supposed to, or maybe you needed to translate something, but you didn’t. You can also just kind of just stick in contextual notes for translators. There’s also XLIFF, where you can throw in some IDs for some context. This really helps your translators because you, as someone who works in your business logic every day, know what a certain date represents, but someone who doesn’t work with this every day is just going to be like, “There’s some string value here, what is this?” <string name="campaign ended label" note="example: Ended on January 21, 2014"> Ended on %s </string> This can have some cool integration points. Numbers and Currencies (9:34) This is a fun topic! If you’ve never tried to NumberFormat a number before, I’m here to tell you that it’s really easy and you don’t have to be afraid. import java.text.NumberFormat; NumberFormat numberFormat = NumberFormat.getInstance(); textView.setText(numberFormat.format(36965)); This is what it ends up looking like in English and Spanish: Contributions 36,965 & Contribuciones 36.965 You see we’ve added this nice comma in English, and then in Spanish we’ve used the correct delimiter, which is actually a period. This works great, and again, is simple to implement. Pluralization is also pretty easy, and if you’ve ever worked with Rails, it works similarly. You can just define your quantities if you need to special case the one or even the two in other languages. If you look in the documentation on plurals, they give a lot of really interesting examples in other languages about what quantities are special cases. That’s just something you don’t normally think about if you only ever think in English. strings.xml <plurals name="number_of_fb_friends"> <item quantity="one"%s friend</item> <item quantity="other"%s friends</item> </plurals> res.getQuantityString( R.plurals.number_of_fb_friends, count, numberFormat.format(count) ); I want to just to give a little PSA about using string interpolation here instead of an integer interpolation, because you probably want to NumberFormat this number, and the NumberFormatter is going to return a string. This getQuantityString method call uses the second argument here as an int for the quantity selection, and then the second one is actually what gets interpolated. Since NumberFormat returns the string, we need to use a string placeholder. I just saw a lot of stuff on Stack Overflow with examples like “count count,” and that’s going to mean that you use d or i in your strings. I want you to be aware of that because it’s going to mean that you don’t have any NumberFormatting going on. Dates and Time (11:27) The out-of-the-box dateFormatter gives you some date formats that you can just use, and there are only three defaults: short, medium, and long. It works similarly to NumberFormatter. You just instantiate it and call .format. // DateFormat.getDateFormat (short) // DateFormat.getMediumDateFormat // DateFormat.getLongDateFormat DateFormat dateFormatter = DateFormat.getDateFormat(context); Date now = new Date(); dateFormatter.format.(now); en_US ja_JP short: 8/23/2015 short: 2015/08/23 medium: Aug 23, 2015 medium: 2015/08/23 long: August 23, 2015 long: 2015年8月23日 Here we have English and Japanese date formats. You can see that short and medium are actually the same in Japanese. There’s no semantic difference in Japanese for those, so just be aware that those might not always mean something that is necessarily shorter. What if you want a custom date format, for example maybe just a month and a year, instead of a whole month/day/year? This is awesome if you’re working with API 18 and up, as there’s this totally great method you can call: getBestDatetimePattern, and you just pass it your locale. It’s actually a component string, so it actually doesn’t care about the order it’s in. When you format that date, it just does the right thing. String formatString = DateFormat.getBestDateTimePattern( Locale.getDefault(), "MMMMyyyy" ); SimpleDateFormat dateFormatter = new SimpleDateFormat (formatString); Date now = new Date(); String dateString = dateFormatter.format(now); en_US: August 2015 ja_JP: 2015年8月 You’ll notice in Japanese, the year actually comes first. The API just did that all for us. However, if you are like us at Indiegogo and you target APIs below 18, this gets a little hairier… ¯\_(ツ)_/¯ We ended up collecting date formats as we needed them, and we kept them in our resources. This isn’t a perfect solution, though. Let’s say someone is using the Indiegogo Android app in a language that we don’t support; Android will try to format that date as if we’re in that locale, so it’s going to look a little weird to them. If you really have to format a lot of dates, you might want to look into a library like Joda-Time because they’ll just do this all for you, but it’s another library you have to add. Boo to SpannableString (13:44) If you’ve ever needed to style a bunch of stuff and you tried to work with SpannableString, you’ll know it’s a big pain to work with. It’s a pain because you have to know the index of the start and the end of whatever it is you’re trying to style differently. You can imagine that that might be hard to tell if you’re dealing with a string that’s going to be changing, depending on your locale. This is not a foolproof solution. If you can, I recommend you replace any kind of SpannableString nonsense with HTML. That won’t support all the tags, obviously, but you can kind of get by, and then you can set text from your HTML. Try to avoid: public void setSpan (Object what, int start, int end, int flags) Instead, replace with HTML in your strings.xml: textView.setText(Html.fromHtml( res.getString(R.string.fixed_funding)) ); Build Flexible Layouts (14:35) If anyone is looking ideas for an awesome conference talk, I think building flexible layouts would be it. It’s a really big topic actually. I want to give a shout-out to wrap_content, amirite? If you’ve ever programmed for the web, you know that sometimes it’s really hard to make stuff expand to its content or to its parent, so wrap content is awesome. That being said, do be mindful of line lengths. Sometimes the string can be longer in another language, and maybe you weren’t accounting for that. I find for the most part though the Android UI framework is super flexible with this kind of thing, and things will just kind of move around more or less as you expect them to. At Indiegogo, there is a percent counter at the bottom of the funding meter that reads something like “41% funded” - as an exercise for you, what would happen if, in a different language, you needed to switch this percentage and word around? You might think, “Okay, well, I have two TextViews. One is bold, and the other one isn’t.” All of sudden, you’ve got this huge problem where you need to switch these two pieces of data around. Instead, just put that in a string with some HTML: all of a sudden, you don’t have a problem. Other Cool Things (15:43) There’s a sweet thing in Android Studio called Translations Editor. If you open your strings file, you’ll seen this little notification bar pop up. If you click “Open editor,” you can actually see all of your translations side by side. Then if you needed to quickly do a bunch of work across all of your translations, this can be a nifty way to get there fast. There’s also an “Untranslatable” checkbox, so you can quickly do that across all your files. There’s also an “Order a translation” button, which links to the Google Play App Translation Service. I brought this up at Droidcon NYC, and someone said that the quality wasn’t that awesome because they use a lot of machine translation, so YMMV. I just think that it’s cool they integrated this link right into Android Studio, so you can start thinking about how to localize your app. Another cool thing is in the Google Play Developer Console, where you’ve got these statistics that tell you what languages and countries your users are in and how your app compares to others in your category around the world. This is the sort of thing you can bring to your PM and say, “Hey, I think we should localize into these languages.” This might help build a business case for that, if that’s something you need to be concerned about. I want to give a final shout-out to Smartling, who we use at Indiegogo. They’re a paid translation service, with real humans who translate things. They have an API and a Java SDK. We use Smartling to update our non-English strings with just a push and a pull that we run from the command line, and it’s super easy. It’s just a little Bash script, so push up and pull down. One drawback of this, though, is that it does completely overwrite all of our non-English strings, so if we edit something locally and then do this, we lose all those changes. That does mean we have to edit all of our non-English strings directly in the Smartling interface, but I think that’s worth it for the easy update feature. Further Reading (17:55) The official Android documentation on this stuff is actually pretty good and pretty comprehensive and pretty interesting in some cases, so I recommend you check that out. Smartling is also a cool thing. - Localizing with Resources - Localization Checklist - Google Play App Translation Service blog post - Smartling API - Smartling Java SDK Now go out and be fearless! About the content This content has been published here with the express permission of the author.
https://academy.realm.io/posts/siena-aguayo-android-localization/
CC-MAIN-2018-30
refinedweb
3,153
61.16
I am new to Python and trying to do something I do often in Ruby. Namely, iterating over a set of indices, using them as argument to function and comparing its results with an array of fixture outputs. So I wrote it up like I normally do in Ruby, but this resulted in just one test case. def test_output(self): for i in range(1,11): .... self.assertEqual(fn(i),output[i]) Using unittest you can show the difference between two sequences all in one test case. seq1 = range(1, 11) seq2 = (fn(j) for j in seq1) assertSequenceEqual(seq1, seq2) If that's not flexible enough, using unittest, it is possible to generate multiple tests, but it's a bit tricky. def fn(i): ... output = ... class TestSequence(unittest.TestCase): pass if __name__ == '__main__': for i in range(1,11): testmethodname = 'test_fn_{0}'.format(i) testmethod = lambda self: self.assertEqual(fn(i), output[i]) setattr(TestSequence, testmethodname, testmethod) unittest.main() Nose makes the above easier through test generators. import nose.tools def test_fn(): for i in range(1, 11): yield nose.tools.assert_equals, output[i], fn(i) Similar questions:
https://codedump.io/share/XzPeeFK1YGl2/1/how-do-i-run-multiple-python-test-cases-in-a-loop
CC-MAIN-2018-05
refinedweb
189
58.28
Automatically check for semver compliance based on type hints Judgement as a Service. Typejudge will automatically check for semver compliance based on type hints. If the type signature for a function changes, it will judge this to be an API change and recommend a major version bump. This is largely inspired by Elm’s package manager, which also enforces semver. Installation Note: typejudge only works on python 3.5 and higher. Install with pip: $ pip install typejudge Usage $ typejudge --help usage: typejudge [-h] [-o OUT] [-f FILE] MODULE [VERSION] judge your types positional arguments: MODULE module to import and check VERSION current version of the package optional arguments: -h, --help show this help message and exit -o OUT, --out OUT save current type definitions to this file -f FILE, --file FILE load type definitions from this file Example usage Suppose we’ve got a module that contains some type annotations on the publicly exported API, testmodule.py: def greeting(name: str) -> str: return 'Hello ' + name Save the types somewhere: $ typejudge -o testmodule.json testmodule Make some small change to testmodule.py, add a new function: def greeting2(name: str, name2: str) -> str: return 'Hello ' + name + ' and ' name2 Typejudge will recommend this is a minor release: $ typejudge -f testmodule.json testmodule minor The same, but with a known current version number: $ typejudge -f testmodule.json testmodule 0.3.2 0.4.0 Make a change to existing type signatures: from typing import List def greeting(names: List[str]) -> str: return 'Hello ' + ' '.join(names) Typejudge will now recommend this is a major release: $ typejudge -f testmodule.json testmodule major With no changes to the API’s types, typejudge will recommend a patch release. Example usage with bumpversion Typejudge works quite well with bumpversion. Doing this is probably inadvisable, but you can entirely automate releases. Assuming similar files as in the previous section, set up a config file for bumpversion, something like: $ cat .bumpversion.cfg [bumpversion] current_version = 2.0.3 commit = True tag = True [bumpversion:file:setup.py] And a setup.py: $ cat setup.py import setuptools setuptools.setup( name="testpackage", version="2.0.3", description="Test stuff", ) Then run something along these lines to cut a new release: $ bumpversion $(typejudge -f testmodule.json testmodule) You’ll also want to save the state of the API at this point, so you can compare it at the next release: $ typejudge -o testmodule.json testmodule Obviously use some discretion when releasing in this way. Just because the types of your API remain the same, it doesn’t necessarily mean that your code is backwards compatible. Typejudge suggests the smallest version increment you should make. Download Files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/typejudge/
CC-MAIN-2017-47
refinedweb
460
57.67
Tell us what you think of the site. Hi everyone! OK my problem sounds very simple… but I can’t find ANY documentation, so I’d be really grateful for any help. It seems that, when you create a namespace for an object, it is stored permanently somewhere in MotionBuilder’s system. Even if you delete the object or replace the namespace, the original namespace is still listed in the “namespaces currently in scene”. This is quite frustrating. I’ve been trying to write some python to clear all of the namespaces in a MotionBuilder (2011, 64 bit) scene, with no success. Any ideas? Thanks :) All views/opinions expressed here are my own and do not necessarily reflect those of my company or anyone else in the world
http://area.autodesk.com/forum/autodesk-motionbuilder/python/clearing-scene-namespaces/
crawl-003
refinedweb
128
70.53
Hi, I'm using Kendo React Grids with filter in my application which generates column filter textbox and filter options dropdown. The requirement for me (part of ADA compliance) is any filed that user may execute an action should have a associated text with it when hovered on it. A HTML title attribute on column filter textbox and filter options dropdown would resolve this issue. The Grid did not generate title attribute on filter textbox and filter options dropdown but the clear filter textbox button has title attribute. How do I resolve this issue. Any help is much appreciated. 5 Answers, 1 is accepted Hi, Currently, the title attribute of the filter cells cannot be configured through Grid props. Here is how you can set the title attributes by accessing the DOM elements - I hope this helps. , we tried to use the example you provided but the element attribute is always coming as undefined and is inaccessible. please see the screenshot attached in debug mode. There is no element attribute defined for the grid object so we cannot go any further on it. can you please take a look? Hi, It is actually not public. Here is another example - I accessed the grid element using a class name. componentDidMount() { const gridElement = document.querySelector(".grid-class"); ... } render() { return ( <Grid className="grid-class" ... </Grid> ); } Regards, Nikolay Progress Telerik Five days of Blazor, Angular, React, and Xamarin experts live-coding on twitch.tv/CodeItLive, special prizes, and more, for FREE?! Register now for DevReach 2.0(20). Hi Nikolay, Thanks for your response but there is still an issue. For some reason the attributes are not getting written for the filter text boxes in the grid. I tried couple of ways and I can see that filter textbox can be accessed but it do not generate the title attribute. #The way you suggested - const gridElement = document.querySelector(".grid-class"); if (gridElement !== null) { const filterRow = gridElement.querySelector("tr.k-filter-row"); if(filterRow !== null){ filterRow.cells .item(0) .querySelector(".k-textbox") .setAttribute("title", "Procedure Number Filter"); filterRow.cells .item(0) .querySelector(".k-textbox") .setAttribute("className", "xxxxxxxxxxxx"); } } #Another way let x = document.getElementsByClassName("grid-class").item(0).getElementsByClassName("k-filter-row").item(0).getElementsByClassName("k-textbox").item(0); x.setAttribute("title", "Procedure Number Filter"); please find the screenshot attached of the final html rendered. Thanks Gaurav Joshi Hi Gaurav, As the attribute is applied in the standard example, please share a runnanble example where the attribute is not applied and we will check it. Regards, Nikolay Progress Telerik Five days of Blazor, Angular, React, and Xamarin experts live-coding on twitch.tv/CodeItLive, special prizes, and more, for FREE?! Register now for DevReach 2.0(20).
https://www.telerik.com/forums/title-attributes-on-grid-generated-filter-textbox-and-filter-dropdowns
CC-MAIN-2022-21
refinedweb
451
50.43
Code:Code: #include<iostream> #include <cstdlib> using namespace std; int main() { int guess, secretnumber; secretnumber = rand(); cout << "Guess the number: "; cin >> secretnumber; if (guess = secretnumber) cout << "You guessed it!"; else if(guess > secretnumber) cout << "You're to high!"; else if(guess < secretnumber) cout << "You're to low!"; return 0; } When I run it, I guess it every time for some reason, and I don't think it is being random. Please tell me if this code is correct, I've been fooling around for a while, and my book I don't think is very current (not by years, but some things are off, for instance when I try the gets(); code to input a string into an array, the compiler just skips over it and goes to the next statement, I noticed that the cin function thingy stops the thing while until you type something in an hit enter, but gets() does not do this.
https://cboard.cprogramming.com/cplusplus-programming/80481-rand-wont-random-printable-thread.html
CC-MAIN-2017-26
refinedweb
156
67.01
Developing a Kinesis Client Library Consumer in Python You can use the Kinesis Client Library (KCL) to build applications that process data from your Kinesis data streams. The Kinesis Client Library is available in multiple languages. This topic discusses Python. Python and write your consumer app entirely in Python, Python KCL from GitHub, go to Kinesis Client Library (Python). To download sample code for a Python KCL consumer application, go to the KCL for Python sample project page on GitHub. You must complete the following tasks when implementing a KCL consumer application in Python: Implement the RecordProcessor Class Methods The RecordProcess class must extend the RecordProcessorBase to implement the following methods. The sample provides implementations that you can use as a starting point (see sample_kclpy_app.py). def initialize(self, shard_id) def process_records(self, records, checkpointer) def shutdown(self, checkpointer,. def initialize(self, shard_id) process_records The KCL calls this method, passing a list of data record from the shard specified by the initialize method. The record processor you implement processes the data in these records according to the semantics of your consumer. For example, the worker might perform a transformation on the data and then store the result in an S3 bucket. def process_records(self, records, dictionary exposes the following key-value pairs to access the record's data, sequence number, and partition key: record.get('data') record.get('sequenceNumber') record.get('partitionKey') Note that the data is Base64-encoded. In the sample, the method process_records object to process_records. The record processor calls the checkpoint method on this object to inform the KCL of how far it has progressed in processing the records in the shard. In the event that the worker fails, the KCL uses this information to restart the processing of the shard at the last known processed record. In the case_records. A processor could, for example, call checkpoint on every third call. You can optionally specify the exact sequence number of a record as a parameter to checkpoint. In this case, the KCL assumes that all records have been processed up to that record only. In the sample, the private method checkpoint shows how to call the Checkpointer.checkpoint method using appropriate exception handling and retry logic. The KCL relies on process_records to handle any exceptions that arise from processing the data records. If an exception is thrown from process_records, the KCL skips over the data records that were passed to process_records prior to). def shutdown(self, checkpointer, reason) Processing ends when the record processor does not receive any further records from the shard, because either the shard was split or merged, or the stream was deleted. The KCL also passes a Checkpointer object to shutdown. If the shutdown reason is TERMINATE, the record processor should finish processing any data records, and then call the checkpoint method on this interface. Modify the Configuration Properties The sample provides default values for the configuration properties. You can override any of these properties with your own values (see sample.properties). Application Name The KCL requires an application that this is unique among your applications, and among AWSCredentialsProvider property to set a credentials provider. The sample.propertieswill need to make your credentials available to one of the credentials providers in the default credential providers chain. If you are running your consumer application on an sample's properties file configures KCL to process a Kinesis data stream called "words" using the record processor supplied in sample_kclpy_app.py.
https://docs.aws.amazon.com/streams/latest/dev/kinesis-record-processor-implementation-app-py.html
CC-MAIN-2018-17
refinedweb
574
53.92
Lee: Thank you for joining us for this live event with Dr. R.C. Sproul. I’m Lee Webb, host of Renewing Your Mind, and I’m here with Dr. Sproul. And we look forward to spending the next hour with you and taking your questions along the way. We have actually two audiences joining us, one by phone and then another audience live on Facebook, and we’re glad to have you both with us. If you’re joining us on the phone and would like to ask R.C. a question, just press *3 on your phone, or if you’re watching on Facebook, write your question in the comments section. And we’ll try to get to as many questions over the next hour as possible. Now if you’ve never contacted us before, we’re offering the pocket-sized edition of Dr. Sproul’s classic book The Holiness of God. It is free to those of you joining us in the U.S., Canada. Again, that’s if you’ve never contacted Ligonier before, just go to ligonier.org/holiness, that’s l-i-g-o-n-i-e-r.org/holiness. Also joining us is the President and CEO of Ligonier Ministries, Chris Larson, who will be sharing with us some of our ministry initiatives over the next year, which may be the busiest year in Ligonier’s history. We’re excited that to tell you all about what’s going on, but we’re glad to have all of you with us this afternoon. Dr. Sproul, we have enjoyed in the past tele-forums, doing a lightning round segment of questions in which you answer each question in 30 seconds or less. You want to give it a shot here as we get started? Alright? R.C.: Sure. Lee: In Psalm 18 David said, “The Lord dealt with me according to my righteousness, according to the cleanness of my hands He rewarded me.” Was David there making the case for salvation by works? R.C.: Absolutely not. What David was saying is that God had dealt with him graciously and mercifully, nevertheless using the standard of his behavior of his righteousness. As St. Augustine told us that we are given rewards in heaven according to our works. We don’t get to heaven by our works, but we are rewarded according to that standard. But it was Augustine saying that was God was rewarding His own gracious gifts. Lee: I heard you take exception to the popular bumper sticker saying, “God said it, I believe it, that settles it.” What’s wrong in your opinion with that statement? R.C.: What’s wrong with that? Well, it’s the problem is that when God says something it’s settled, whether I believe it or don’t believe it. And so the middle term should be excluded. Lee: Alright, what does God want most from us? R.C.: To love mercy and justice and to walk humbly with Him. What I believe He wants more than anything else is our worship. Lee: Are faith and belief the same thing? R.C.: Well we use the terms basically interchangeably, but belief can also be used simply to…talking about making an intellectual assertion of a particular proposition. I say, “I believe it, I believe that George Washington was the first president of the United States.” Faith goes beyond that where it involves personal trust in the truth of the Word of God. Lee: Since God is omnipresent, does He manifest that presence in hell or does He choose not to be present there? R.C.: It is one thing to talk about God’s choosing not to be present somewhere. If He ever chose not to be present any particular place, then He wouldn’t be inherently, infinitely and eternally omnipresent. The problem with hell is not that God isn’t there. People often think that hell is the absence of God. Everybody who’s in hell would do everything that they could, pay any price if possible to get rid of Him. The problem is that He is there, and He’s there in His judgment. Lee: Alright, and would you state the gospel in one sentence? R.C.: The gospel is the content of the Person and work of Jesus with the subject of appropriation of it by faith alone. Lee: Alright, let’s wrap up this lightning round with one final question, R.C., “What happened to the Steelers?” R.C.: What happened to the Steelers? We are not going to talk about that other than to say “Wait till next year.” Lee: Ha ha, okay. R.C. it’s great to have you with us. I think our audience is primed and ready and again, if you all have questions for R.C., if you’re on the phone with us, just press *3 on your phone. And if you’re on Facebook, simply write your question in the comments section. And again, we’ll try to get to as many questions as possible. But we do have a question on the line, Jeannie with a question about imputed righteousness of Christ. I’m not sure where Jeannie is calling from, but Jeannie, go ahead, you’re on the phone with Dr. R.C. Sproul. Jeannie: Hi Dr. Sproul. Thank you so much for taking my question. The imputed righteousness of the Lord, how are we to think of that? It seems to cause a lot of issues and problems and arguments between Christians. R.C.: Well, we look to the Scriptures, and we see when Paul explains the doctrine of justification, he goes back to the Old Testament to Genesis 15, where the Scriptures say of Abraham, “He believed God, and it was counted to him for righteousness.” And when Paul develops the doctrine of justification by faith alone, what he is saying there is that when God counts somebody righteous on the basis of faith, it’s not because He looks at them and sees that they are inherently righteous, but rather they have been clothed by the imputation or the transfer of the righteousness of Christ to that person by faith. That’s why we say the single meritorious cause of our salvation is the transfer or counting of Jesus’ righteousness for me. That not only did He die to pay for the penalty of my sins, but He lived the perfect life of obedience and fulfilled the law for those who put their trust in Him. That’s what we’re talking about in imputation. That was the single, central, most important point of the 16th century Reformation. Lee: Well, we’ll get to more questions along the way. Before we go any further R.C., folks always want to know how you’re doing. How are you feeling these days? R.C.: Well, I’m feeling great, actually. I’ve had some very good reports from my many doctors, and I know most of the specialists in Orlando on a first name basis. But I just was at my pulmonologist Friday, and he was very pleased with how I was doing and said, “We’re cruising.” He didn’t want to have to see me for another six months. My endocrinologist was very happy with my sugar levels and that sort of thing. And I haven’t had any further repercussions from the two strokes I had a couple years ago. So all in all, doing pretty well. Lee: Ah, it’s great to hear. Chris: It’s been thankful…we’ve been thankful to be able to see R.C. up and at ’em just around the campus and then having a full preaching schedule as well. I have a question for you. Tell us about your insignia here on your jacket. R.C.: My insignia, can you see that? Chris: Can we get a little close-up on that? R.C.: In the 1517 section of our CD Glory to the Holy One, it starts with my saying in quotation, “One hammer, one hammer in the hands of an obscure Augustinian monk changed the history the world forever.” This is a mallet, indicative of that which was used by Martin Luther in 1517 when he tacked to the church door in Wittenberg, the castle church, the Ninety-Five theses. And so, that’s the emblem that we’re using this year for the 500th anniversary of the Reformation. Chris: And who gave you that mallet? Chris: Dr. Stephen Nichols. Lee: That’s right, that’s great. Our resident church historian, a teaching fellow, and the president of Reformation Bible College but Chris, speaking of 1517, I mentioned earlier that this perhaps is the busiest year in Ligonier Ministries’ history. There’s a lot going on. Would you bring our viewers and listeners up to date? Chris: If Protestants can’t get excited about the 500th anniversary of the Reformation, I don’t know what’s going to get them excited. This is a year of anniversaries, so we’re going to mark that next month at our national conference coming up soon. And then we also are celebrating the fortieth anniversary of Tabletalk magazine in May. And then we’re taking several hundred people over on church history tours in Germany this summer. Lee: Those are separate tours by the way. Chris. Different tours, we’ve got a trip that is one of those riverboat tours leaving from Prague, sailing down the Elbe River. Then we’re doing a “Land of Luther” study as well, plus having a Wittenberg, Germany conference on August 11th. So, there’s a lot going on. And we’re going to have something special in the works for October 31st to actually mark the day, but we’re not going to let the cat out of the bag just yet. R.C.: But we are going to pass out candy. Chris: Absolutely! Reformed candy. Lee: Chris, is there still space available for those tours this summer? Chris: Yes, for the for the river boat trip that we’re taking from Prague, there’s a few cabins remaining. The “Land of Luther” tour has reached capacity now, and we’re over 200 people. But it’s still a good time to be able to come over, celebrate with us. We’re going to do a concert with some of the hymns that Dr. Sproul and Jeff Lippincott have been writing over the past several years. So, should be a really good time. Lee: R.C., folks tuning in either by phone or watching us on Facebook, may wonder why, what’s such a big deal about the Reformation? Why commemorate it in the 500th anniversary? Why do we care so much about it? R.C.: Well, because of the critical importance of the recovery of the gospel that had fallen into darkness in the Middle Ages and the recovery of the gospel in the 16th century that provoked the motto of the Reformation, “Post Tenebras Lux,” “after darkness, light.” And, we call ourselves evangelicals because of the recovery of evangel, of the gospel, in the 16th century Reformation. Lee: Well as I mentioned, we have listeners who are tuning in by phone, we’re glad to have you, but also a very large audience tuning in live on Facebook. We’re glad to have you as well. And we’ve already received several questions from you Facebook viewers and we’re grateful for that. Luke writes in, and his question to you R.C. is this, “In evangelism, how would you respond to someone who claims they are not elect?” R.C.: I would say to that person that I have no idea how they could possibly know that. I think that the Bible makes it clear that it is not only possible but requires us to make our election and calling sure, that we can have the assurance of being elect. But if I’m not yet a believer, that doesn’t mean that I won’t be tomorrow or the next day or even on my deathbed. So I cannot possibly know in this world that I’m not elect. And so in one sense, from a practical sense, I assume that every person I ever meet, I assume that they are elect even though I know it’s probably extremely unlikely that they would all be elect. But my working assumption is, we deal with evangelism and outreach of the gospel is that I’m hopeful that that person to whom we’re speaking is numbered among the elect. Lee: We have many folks tuning in from the around the country and in Canada as well. We have a caller from Colorado Springs who’s on the phone with us, R.C.. This is Benjamin. Benjamin, what’s your question for Dr. Sproul today? Benjamin: Hi Dr. Sproul, thank you so much for taking my question. Essentially my question is, I’d like to know that you said that when the gospel is at stake, everything is at stake. And I have an Eastern Orthodox friend, he’s referred to matters of election and the inscrutable will as distractions from true piety and calls the Reformation emphasis on so-called matters of salvation, Greek thinking and a departure from Hebraic understanding. So my question is, how do we as faithful ministers of the full counsel of the Word of God, address this latent danger of antipathy, especially in the light of the cultural temperature toward the authority of the Scriptures? R.C.: You know what, you were breaking up a little bit Benjamin while the question was being asked, and so I did not get the full import of it. Can you possibly ask it again? Benjamin: Of course, my apologies. We, as ministers of the full counsel of the Word of God, how do we address the latent danger of an antipathy towards the full counsel of the Word of God, especially those things that people would call “the matters of faith”? R.C.: I would say one of the most important things you can do as a pastor, as a minister of the gospel is when you preach, preach through books of the Bible so that you’re not beating your own drum, but that you deal with the whole counsel of God as it is set forth on page after page after page. And so in one sense, you discipline then to address whatever the text teaches, and it isn’t going to be very long when you’re preaching through any book of the Bible, you’re going to have to deal with those issues that touch on the whole counsel of God. Chris: What I’ve appreciated R.C. over the years, is your emphasis where the power is located. R.C.: Yeah, the power is not in my preaching, it’s not in our methods, it’s in the Word of God. That’s where He has, that’s where God Himself has invested His power, His supernatural power in the Word. Lee: Well, if you do have a question and you’re tuning in by phone, simply press *3 on your phone and we’ll get to as many questions as possible. If you’re joining us live on Facebook, you can simply write your question in the comments section. But, we’re so grateful for your questions. Jackie has a question for you, R.C., on Facebook “How important are creeds and confessions?” R.C.: Well, when you ask how important creeds and confessions are, from the very earliest time in the history of the church, the church has not only proclaimed the truth of sacred Scripture, but have had…has had to deal with distortions and radical departures from biblical truth in the appearance and occurrence of multiple heresies that have threatened the church from the very beginning. And then one of the earliest creeds, in fact what is thought to be the very first Christian creed was the simple statement “Jesus is Lord.” And that came out of the context of a loyalty oath that was imposed by the Roman Empire where Christians were required to say publicly, “Kaiser Kurios”, Caesar is Lord. And the Christian church in the first century would be quite willing to render civil obedience as much as they possibly could, but they balked at that statement Kaiser ho Kurios, and they said in response to that “Iesous ho Kurios,” Jesus is Lord. And when you look at the great creeds of church history, for example the Nicene Creed, the Chalcedonian Creed, you see that they were written in response to serious heretical views that were arising, threatening the very essence of the Christian faith. And that’s true also of the historic confessions that were written. Now, these confessions were an attempt to crystallize the essence of doctrine found in sacred Scripture, never to be seen as a substitute for Scripture or having authority over the Scripture, but rather to give to us a summary of what Christians believe, as defined in terms of confessional orthodoxy. Lee: We have one more question from Facebook before we get back to the phones but Jordan, R.C., is asking for some encouraging words for young men pursuing missions. R.C.: contributing to that endeavor, but all of us are responsible that the Great Commission be fulfilled because Christ is Lord. And because He’s Lord, we have to do what He commands us to do. And so, I would encourage not just young people, but all people, all Christians to make a priority of mission. Lee: We have a phone call, and this is from Scott. He’s asking a question on regeneration. Scott, we’re glad to have you with us joining us by phone. What is your question regarding regeneration for Dr. Sproul? Scott, I think we hear your dog in the background but we’re not hearing you. Can you hear us? Okay, I guess we’ve lost Scott. Let’s try… Scott: Yes. Lee: Scott, are you there? Scott: Yes, I am here. Lee: Okay, what is your question regarding regeneration. If you can get right to the question, we would greatly appreciate that. Scott: Okay, what’s the difference between regeneration and conversion? R.C.: Well it’s a slight difference, but it’s an important one. Regeneration is the work of God the Holy Spirit, as He supernaturally and immediately changes the disposition of the soul from spiritual death to spiritual life. And when we talk about conversion, regeneration, conversion is a result of regeneration, where we are converted, we’re turned around or move in a different direction. However, sometimes we get confused about this, because particularly when people give their testimony and they say, “I was born again on February the 13th, 1975,” and so on. And that person is testifying to a conversion experience, when actually they may have been regenerated earlier than that but only became aware of their state of conversion at a later time. And so, I think it’s important that we make sure that we distinguish between those concepts. Lee: You know, before we go to more questions, I want to just share with our audience, R.C., that one of the great things about working at Ligonier Ministries is that, I would say maybe 90 percent of us have a story about being Ligonier students before we came to work here. I’ve told you mine. Chris, I’m sure that people at our conferences have heard you speak, but not many of them know that you were a Ligonier student long before you came to work here. What is the one teaching that really solidified your understanding of Christian doctrine from Dr. Sproul? Chris: Genesis 15:17. R.C.: Great! Chris: The Abrahamic Covenant and that the separating of the pieces and the Lord making covenant and guaranteeing Abraham the terms of that covenant, just in His own sovereignty and its power. And Abraham was uncertain about his future, he had questions. He didn’t understand how all of these things would come to pass that the Lord had said to him. And I was a college student and full of questions and trying to understand, you know, what’s going to happen with my life. I knew I wanted to serve the Lord. I had a girl that was godly, and I thought she’d be my wife. But just as a college student, you just don’t know what trajectory your life is going to take. And it was through somebody that Dr. Sproul was teaching at seminary at that time who took me under his wing, discipled me, and began to unpack really that story in one of Dr. Sproul’s hallmark teachings on Genesis 15:17. And it’s one of those moments in my life that completely changed my trajectory, as I understood God was in control, He was sovereign, He was gracious in terms of keeping His covenant, doing for His people what they could not do for themselves. Otherwise, I would just be fraught with anxiety for the rest of my life. And I think that’s the testimony of a lot of the ministry partners who come alongside of us, support this ministry, they’ve had that moment where God has used you, R.C., to encourage them to see the holiness of God, but also the graciousness of God, and you’ve just put your arm around millions of people. And I just know that so many people listening today or watching today are grateful for the impact that you’ve had on their life. The Lord has used you. We’re grateful. R.C.: Thank you, Chris. Lee: Well, let’s get back to some of these questions from our faithful viewers and listeners. Again, if you’re joining us by phone and you’d like to ask Dr. Sproul a question, simply press *3 on your phone. If you’re joining us via Facebook Live, you can write your question there in the comments section on your computer. We have a phone call from Alan, who’s asking a question regarding the Holy Spirit and the Old Testament saints, R.C.. So Alan, we’re glad to have you with us on this live event with Dr. Sproul. What’s your question for him regarding this subject? Alan: Thank you, it’s an honor to speak to you. Thank you for taking my call, Dr. Sproul. You’ve had a tremendous impact on my knowledge of biblical doctrine. My question is the indwelling of saints in the Old Testament by the Holy Spirit. What’s interesting is, or I should say frustrating is I don’t find many, or I should say even a few theologians who hold to that view, even including Reformed theologians, even less talking about it, or preaching it, or writing on the topic. It is missing, it seems like, every time there’s a study of the Holy Spirit. And you sort of look back at the Old Testament saints, and the topic is vague, missing. No one talks about the saints in the Old Testament being filled with the Holy Spirit. And so I think it leads to incorrect views when you come to John 14:16 and Jesus saying, “It’s to your advantage that I leave, the Holy Spirit will come.” Or John 7:39 where it says, “The Spirit was not yet given.” And so all of a sudden, we get great theologians and pastors teaching things that seems a little, I guess, different. And you know, they don’t talk about the Old Testament saints being filled with the Holy Spirit. I know you’ve talked about this. I’ve heard you a number of times. I’m wondering if you can, sort of, talk a little bit more about your view on the Old Testament saints being filled with the Holy Spirit. R.C.: Alright first of all, I’ve never talked to a Reformed theologian in my life who didn’t affirm that Old Testament saints were indwelt by the Holy Ghost. First of all, we distinguish among various different works attributed to the third Person of the Trinity. For example, regeneration is so vitally important, and it’s the Holy Spirit who is the One who changes the disposition of our hearts. And anyone who is a believer in the Old Testament had to be regenerate before they would be believe…a believer. And so, anyone who was regenerate the Old Testament was obviously…experienced the work of God, the Holy Spirit in changing the disposition of their soul. And then, you also talk about ways in which the Holy Spirit was filling people. Well, the first people we read about being filled by the Holy Spirit in the Old Testament, strangely enough, were those whom God called to be artisans for the construction of the tabernacle. They were gifted by God the Holy Spirit in order to fulfill that particular task. And also, you see that other offices and operations of the Holy Spirit in the Old Testament saints included a particular charismatic anointment or empowering, like the prophets who the Holy Spirit came upon them, and kings were anointed by the Holy Spirit. And you go back to the book of Numbers and you see where Jethro, the father in law of Moses, rebuked Moses for doing too many things by himself. And he was led by the Lord to instruct Moses. He says, “Gather seventy of the people that you know are elders among the people, bring them to yourself and I will take of the Spirit that is upon you and distribute it among the seventy,” so that’s recorded there in the Old Testament. And so, the multiplication of the empowering of Moses was given. And at that time, when Joshua raised up a question about it he said, “Moses, Eldad and Medad are prophesying in the camp. Please forbid them.” And Moses replied, “Envious thou for my sake, Joshua? Would that all of God’s people would be prophets, and He would pour His Spirit out upon them.” And that prayer of Moses later became a prophecy by Joel that in the latter days God would pour out His Spirit upon all believers. And that’s the significance, I think, of what took place at Pentecost, where Pentecost saw that the taking of the Spirit of Christ and distributed not just for seventy people to empower them for ministry, but to the whole Christian community. All believers received the Holy Ghost and being empowered. Now I know that not everybody believes that aspect, as we’ve seen all kinds of controversies about the role and the person of the Holy Spirit in our day. One of the best studies that you can ever get is that study that was given by Sinclair Ferguson on the person and work of the Holy Spirit. So, I commend that to you. Lee: From Facebook, Adrian has a question for you, R.C., “Can a person be 100 percent sure of his or her salvation?” R.C.: Well, when you talk about 100 percent sure, you ask me if I think something is the case, Adrian..” So those responses indicate various degrees of certainty that are associated with a particular question. And when you ask me the question of, can a person be 100 percent sure of their salvation? I don’t how to break that down into percentage points. But we’re certainly called to have a full assurance of our salvation by sacred Scripture. And I do think it’s possible to have what would call an assurance, a full certainty of whether we are in the kingdom or not in the kingdom. The problem emerges, however, when there are people who are sure that they are saved and they aren’t saved, because they have a faulty understanding of what salvation is or faulty understanding of where they are in their own faith. But if we have a biblical understanding of what salvation is and an understanding of who we are, then I think we can rise to a very high level of assurance of our salvation. Lee: And Chris, as I hear Dr. Sproul give that answer, it really sums up what Ligonier ministries is all about, our goal and mission, right? Chris: That’s right. Awakening as many people as possible to the holiness of God. And we’re trying to reach as many people as possible through every means possible. So, it’s been a wonderful opportunity to see this ministry grow and be able to reach people even this afternoon. Lee: Right. What are some different…speaking of reaching as many people as possible that some of our viewers and folks who are joining us on the phone may not be familiar with the different ways in social media and digitally that they can reach us. Chris: We do three main things at Ligonier. We broadcast the Word of God. We publish the Word of God, and then we have educational opportunities where people can study the Word of God. Basically, we’re trying to connect Christians to teachers, trustworthy teachers. And so, we’ll do that through the Renewing Your Mind broadcast. We’ll do that throughout our podcast and internet outreach, but also the publishing endeavors. So the Reformation Study Bible, Tabletalk magazine like I mentioned earlier, and also just the books that we’re publishing from Reformation Trust and then the educational effort. This is one of the things where Dr. Sproul had this one-on-one learning back in the Ligonier Valley Study Center when the ministry originally started there in the early 70s. And you took some of those notes even from Francis Schaeffer and through conversation with him about what was effective in terms of that sort of life-on-life discipleship. And what did you learn in those early days that you’ve tried to carry forward for the benefit of Ligonier? R.C.: Well, there’s no substitute for one-on-one teaching in a classroom setting or any kind of education. Gilbert Tennent of Princeton College, the old log college where it was Tennent on the one end of the log and the student on the other end of the log, and they were having the interchange. And that’s what happened with L’Abri in Switzerland with Schaeffer’s ministry where he opened his home and family for students that were seeking the different understandings of truth. His ministry was more evangelistic, and ours was more educational, as for as discipleship than ours. But yes, in the very beginning days, I had several conversations with Dr. Schaeffer and got a lot of insight on how to proceed. Chris: It was interesting because you had that that life-on-life discipleship there in Ligonier Valley Study Center, but then the staff began recording your messages. And then those messages started to go out, you know, remember cassettes, cassette tapes and reel-to-reel, and VHS. And those messages began to go out, and so that the media part of the ministry almost began to eclipse what was happening there at that little campus. And so, the ministry moved to Orlando in 1984 and the conference ministry. And you continued to writing books. Holiness of God was published in 1985, but even that grew out of those early video lessons of the holiness of God. And fast forward now, you know, a couple decades, and you get this vision for a school, almost a “back to the future” moment for us. The media ministry is growing well, the publishing efforts are ongoing. We’re having conferences around the country and even now around the world, but you also have this this passion for reaching college students. And so the vision for Reformation Bible College was born, and we opened the doors in 2011. What was it that gave you that zeal to pursue this next leg of the journey for Ligonier? R.C.: There were many factors that follow…that went into that, Chris. I won’t go into all of them. But you know, I started my vocational career as a professor in a college and only later on became a professor in seminary. And I noticed, frankly, that college students were so much more malleable than the seminary students then. It’s a critical point in their life where the foundational understanding of truth was taking place, and it was to me the most significant opportunity for Christian education to take place at the college level. And so, that was one of the main factors that we were driven to begin the Reformation Bible College is so that we could focus at the college level where students might be grounded in their Christian faith. I was converted as a college student, and actually my virginal study of the Bible was the most significant and lasting impact on my whole life and on my whole teaching ministry. I mean, I went to seminary and graduate school and all that, but what happened in college is what really changed the trajectory of my life. Lee: Well, shall we get back to some more questions R.C.? We have some Facebook questions. We have one from Billy Mills. That’s a famous name. That’s the name of one of the great distance runners in the 60s. I believe he won a gold medal in one of the Olympic events in the, in the mid-60s. But Billy, I’m not sure that that’s this Billy Mills, but he asks “R.C., what’s the most dangerous theological issue facing the church today?” R.C.: I think the biggest problem we face in the church today is a very, very serious failure to understand the person and work of Jesus. Christology has been, throughout the ages, the single most important thing. The great eras of controversy in matters of understanding Jesus were the fourth century, and the fifth century, the 19th century and the 20th century. And here we are, early in the 21st century and the issues that came up in the 19th and 20th centuries about the deity of Christ and His atoning work and all that He has accomplished didn’t go away when Y2K took place. These things are still going on in our day, and they’ve infiltrated every nook and cranny of the church. Lee: And if you’d like to know more about that, Ligonier is also involved in this work that Dr. Sproul just mentioned. We published The Ligonier Statement on Christology. If you’d like to know more about that, Billy, and our other listeners and viewers, you can go to “christologystatement.com,” that’s christologystatement.com, and we would encourage you to take a look at that. Tony writes on Facebook, “In light of our postmodern society, R.C., where truth is relative?” Let me restate that, “In light of our postmodern society where truth is relative, do you think evangelism is more difficult now because of that?” R.C.: No, I don’t think there’s any more difficulty at all. People embrace relativism. That’s the bad news. You notice the book that went to the top of the charts and nobody expected it to The Closing of the American Mind, several years ago, from a professor at Cornell, I believe it was, that he talked…to say that when a student entered college, 95 percent of students entering college had already embraced relativism. And by the time they graduated from college and had higher education, it was now up to 98 percent. That was the bad news. The good news is nobody’s a relativist consistently. You can’t survive for 24 hours being a relativist unless you’re in a padded cell somewhere and under 24-hour watch, because every time I walk to the street, and a bus is coming down the street, I know there can’t be a bus and not be a bus at the same time in the same relationship. And so all of a sudden, I don’t become a relativist, I become a realist, and I stop instead of stepping in front of the bus, unless I’m suicidal. I mean that’s what the reality is. And the other good news is and bad news at the same time, is that human nature, the constituent nature of fallen humanity has neither improved nor deproved from the day that Adam fell. We’re still dead in sin and trespasses. That’s true of 20th century postmodern America, as it was true in the 17th century or 16th century. 16th century America, there wasn’t a whole lot there, but in the 17th century there was. But that remains the same. So, the task of evangelism is the same now as it was always. Lee: Again, if you’d like to join in and ask Dr. Sproul a question, you can do that by phone. If you’re joining us by phone, simply press *3 on your phone. If you’re joining us via Facebook Live, just write your question there in the comment box. Going back to the phones though, R.C., we’re joined from the great state of Oklahoma by James, who has a story for us. James go ahead. And we want to get to as many as possible, so go ahead and be brief as possible, if you will James. James: Okay, God bless you and your ministry, Dr. Sproul. It’s a blessing. It’s about predestination, sir. I have a question that I would like to show an example, then ask you a question. God is in charge of predestination, right? R.C.: Right. James: So at the age of 10, right after my second year of little league, I was severely ostracized. I was verbally abused because I was the only one in the whole league that rooted for the Pittsburgh Pirates. R.C.: I can relate to that. James: All of a sudden, with one swing of the bat, Bill Mazeroski changed my life, predestined me to greatness. So, couldn’t you say that it was God and Bill Mazeroski that predestines our lives? R.C.: Well, I’ll tell you this. On that day in 1960, at Forbes Field in the seventh day of the World Series, I was sitting on the third base line. I know that tens of million people say they were there at that game, but I actually was there at that game and I saw it live. So, I had never really related that to the doctrine of predestination or election, but it certainly was a joyful moment for me after suffering through the rinky-dink era of the Pirates, to see them win a World Championship after so many years. Lee: James, thank you for your call. Okay, James thank you for that call. Who was your favorite Pittsburgh Pirate, R.C.? R.C.: Ralph Kiner. Lee: Ralph Kiner. Alright, we have another call. This one’s from Memphis, and it’s from Russ. Russ, we’re grateful that you’ve joined us today on this live event with Dr. Sproul. What’s your question for R.C.? Russ: Thank you, Dr. Sproul for taking my question. The question is this, “How would you respond to someone who claims to be a Christian and also asserts that there is no such thing as hell, that God is love and God in His love ordains that no one shall spend eternity in question, in hell.” That’s my question. R.C.: Now, I would say that that person could certainly be a truly regenerate person. All kinds of Christians have all kinds of theological weaknesses and errors. We always have to struggle about this. So I don’t just make the automatic assumption that somebody’s not a Christian if they neglect a particular doctrine. Although, to deny the reality of hell in any significant way certainly raises the question of whether or not a person is indeed in the faith because it is such a central core teaching of Scripture. And again, Jesus taught more about hell than He did about heaven. And so, if you’re not willing to listen to Jesus’ teaching about the nature of hell or the existence of hell, then that raises real questions about how open you really are to your Lord. Again, I still think it’s possible, a person could be that weak in their understanding and still be a redeemed person, but it’s hard to imagine. Lee: Russ, we appreciate your call. By the way, today’s lesson in Tabletalk touches on that particular issue. It talks about the goodness of God and how the goodness of God does not negate His justice or His wrath. So we would commend that lesson to you from Tabletalk. By the way, if you’ve never contacted Ligonier Ministries before, we would love to send you a pocket-sized edition of Dr. Sproul’s book The Holiness of God. It was published many, many years ago, but it is truly a bestseller. And if you’ve never contacted us before, we would encourage you, go to “ligonier.org/holiness.” It’s good for folks who are tuning in via Facebook Live or on the phone with us from the U.S. or Canada. We have a few more minutes. R.C.: One second Lee, before we go on. Just going back to that question and about Tabletalk treatment on hell, it’s true that the goodness of God does not negate the doctrine of hell. It demands it. If God is good, then evil must be punished or He’s not good. Lee: Yeah, thank you Dr. Sproul. Alright, going back to Facebook, Sean has a question for you. And would you address, R.C., the role of the civil magistrate? Timely, as we are beginning a new administration here in the U.S.? R.C.: Yeah, what’s the question? Lee: Well, he just would like for you to… R.C.: The role of the civil magistrate…well, the New Testament tells us, particularly in Romans 13, that the civil magistrate is under the sovereignty of God, and he is a minister of God. I can remember speaking at the inaugural prayer breakfast for a governor several years ago here in the state of Florida where I said, “Today’s your ordination day.” I said, “God has ordained the church. He’s also ordained the state, and all who are functioning in that role are under the authority of Christ, who is the King of kings and the Lord of lords.” People may declare the separation of church and state, but people often mean by that the separation of the state and God. But remember that God is still sovereign over all things. And that’s why we are called upon to be zealous and scrupulous in being submissive to the civil magistrates, unless they command us to do something God forbids or forbids us from doing something God commands, for the sake of honoring Christ, who is the supreme authority over all of them. Lee: Is that why some governments, including the British government, refer to their secretaries of particular cabinet posts as “ministers”? R.C.: Yes, that’s one of the reasons historically. Lee: Alright, we have one more question from Facebook. This is from Julie, who happens to be a former colleague of mine. And Julie, it’s so good that you’re joining us. How would, R.C., she asks, “How would you recommend one share the truth about the errors of some Catholic doctrines without being offensive or argumentative?” R.C.: Well, it’s pretty hard not to be argumentative and hard not to be offensive, because when you disagree with anybody, the tendency is for people to be offended. And when you talk about being argumentative, argumentative is a negative description of things. But the giving of solid biblical arguments is what we are called to do. Now to make a sound and argument to support the truth claims of a position is not necessarily to be argumentative. Argumentativism is described as a hostile spirit, a mean spirit. So, one doesn’t have to be argumentative to make sound arguments, but I would encourage people to make clear and biblical arguments for the truth. Lee: Alright, we have a question on infant baptism by one of our phone callers, and this is from Lynn. Lynn, what is your question regarding infant baptism for Dr. Sproul? Lynn: Thank you so much for taking my call and for your ministry. My question is regarding infant baptism, and my understanding is that regeneration occurs at infant baptism. And you already said that regeneration and conversion are not the same thing. So, if they’re not the same thing, what has happened if regeneration has taken place and a child that’s been baptized does not come to saving faith? Have they lost their salvation, or we just can’t know that? I’ve struggled with this for a long time. R.C.: Yes Lynn. I would say, first of all, I’m not at all an advocate of baptismal regeneration. I don’t think that baptism conveys regeneration either for infants or for adults. Regeneration is a sovereign work of God the Holy Spirit. Now, one of the things of which baptism is a sign, is the sign of regeneration. But that doesn’t mean that the sign is always conveyed automatically by the sacrament itself. As a Protestant, I believe that the sacraments are effective by and through faith, but what does happen in the operation of baptism is that God makes a promise to His people and to their seed that if they come to faith then, and that would presume that they were regenerate because they couldn’t be coming to faith unless they were regenerate. But the idea is that that the promise of God to all who believe, is to enjoy all of the benefits that were wrought for us by Jesus Christ. We participate in His death and resurrection and are cleansed of our sin and all the rest, all of which things baptism is a sign, but it doesn’t convey any more than circumcision automatically conveyed salvation in the Old Testament, as Paul labors in Romans that we can’t assume that just because somebody has been baptized that therefore they are regenerate. Lee: Okay. On Facebook, Todd Anderson has a call R.C. for you, I mean a question for you, “How should we respond to the hyper-grace movement?” R.C.: If we’re talking about hyper-grace in terms of grace covering everything including there are those in that movement that are basically antinomian. That is, they believe that once we experience grace, we’re no longer under the law in any sense, even in the instructive sense. And I’m going to say if a person is saved by grace, not by law, we understand that,. that nevertheless that doesn’t mean, it’s the old question that Paul writes, “Shall we continue in sin that grace may abound?” And his answer is, “God forbid!” But some people want to make it sound that once you have experienced grace than basically you can live however you want, you know, free from the law, blessed condition, I can sin all I want and still have remission. And like I say, this is one of the greatest threats to the contemporary evangelical community, I think, right now is the resurgence of the radical character of antinomianism and libertinism. And part of it is related to that seriously deficient doctrine of the carnal Christian that has just been so widespread that believes that a person can actually be a Christian and still not have had their constitutive nature changed by the Holy Spirit. They’re still in a state of carnality, total carnality. That’s just an impossibility. Lee: Okay, Liz has a question from Facebook, “Why should a Christian study church history?” R.C.: Boy, you know I wish I had a lot more time not only to answer that question, but to fulfill the study of church history. You know, it’s the old maxim whether it’s church history or other history is that those who refuse to study history are doomed to repeat it. And virtually every heresy that we face everyday today is a rehash of some heresy that the church had to deal with in the history of the church, and that God has preserved His church through all the centuries. And we hope that by now we’ve learned something, and by studying the history of the church. Just why did Luke write the book of Acts? He wrote his Gospel, but then he also wrote the early history of the Christian church, which was very important for the church to understand its origins, its mission and its doctrine. Lee: Right now, you’re preaching as the co-pastor of St. Andrews Chapel, you’re preaching through the book of Galatians. And I remember you teaching through that back in the mid-90s, when the Evangelicals and Catholics Together, a document came out and you thought that we needed to address that issue. Obviously, you feel it’s still important? R.C.: Yes, it’s obviously still important. Lee: Alright, shall we take one more call here before, I think we’ve got just a few more minutes left. We have a call from someone who says that they don’t feel saved. And this is from Georgia, and I believe it’s either James or Janie. I’m not quite sure, but James Smith from Georgia, are you online with us? James: Yes, sir. Thank you. Lee: Okay. Now, what is your question for Dr. Sproul. James: Yes, I have given my life to Christ. I don’t feel any different and, let me say, I’m very honored to be talking to you, sir, and I appreciate all that you’ve done. But I’m nervous, so I’m sorry. I just don’t feel any different. You hear all these stories, these quote, unquote testimonies about people, “When I gave my life, I felt this way, and I felt,” and they talk like they have Jesus in their hip pocket or something to that effect. So, I don’t understand. R.C.: I think I understand it James. First of all, I haven’t written a book like this, but I’ve often thought about writing a book called “The Sensuous Christian,” who lives and dies by their feelings. It doesn’t matter whether you feel, if you’re forgiven by Christ, that’s an objective state of affairs. If you’ve confessed your sins and God promised to forgive you your sins, if you confess your sins then your sins are forgiven, it doesn’t matter how you feel. You may still feel guilty. Or conversely if a guy commits a crime, and he goes to the courtroom, and the judge says to you, “How do you plead.” And he says, “Not guilty. And, you say, “Why? And he said, “Because, I don’t feel guilty.” Not feeling guilty is no proof of guilt or innocence and not feeling forgiven is the same thing. So I would say to you that you need to look at the objective truths of the Scripture. See what it is that Jesus teaches about salvation, and if you trust in those words of His teaching, then you can be assured that you are in His kingdom. But as soon as you start resting on your feelings, you’re cooked. Lee: Great answer. Dr. Sproul, thank you so much for fielding all of these questions. We got to a lot. We didn’t get to all of them, and we so appreciate your calls as well as your questions on Facebook. Hopefully, you’ll be able to join us again when we do this again. We’ve really enjoyed doing these tele-forums and these live events, and we will certainly, I’m sure, do more in the near future. And again, before we say goodbye, if you’ve never contacted Ligonier Ministries before, we would like to send you a pocket-sized edition of Dr. Sproul’s book The Holiness of God. Simply go online to ligonier.org/holiness. Let me repeat that, it’s l-i-g-o-n-i-e-r.org/holiness, and that offer is good for our folks who are joining us in the U.S. and Canada. We want to thank all of you who are ministry partners at Ligonier. Chris, we would not be able to do what we do here, including this live event, without the support, financially, of our ministry partners. Chris: They come alongside and empower this ministry through their gifts but also through their prayers. And this is what I would say to the ministry partners who are listening or watching. You are the ones that can take the message that we’re working to produce and publish abroad. You’re going to know so many more people than we’re going to be able to reach. It’s your sphere of influence that’s going to transform lives, and it’s going to change communities. R.C.: Can I say something, Chris? Recently, I was asked by Chris to address our staff at a staff meeting that we hold regularly at a regular time just for a 15-20 minute talk, and one of the things that drives me nuts is that I can’t stand up and give a speech that somebody isn’t putting a microphone in front of me or a TV camera. And I say, “Can I just talk to these people alone and let me alone with all this stuff.” So he says to me, “Do you mind if we videotape or whatever you did with it? Chris: Facebook Live. R.C.: Yeah, “Facebook Live thing while you’re giving this speech to the staff?” And I said, “Okay.” I didn’t want to. I was reluctant. He tells me that this was listened to by 400,000 people. How is that possible? I mean, it just blows my mind. I can’t imagine it. And we heard from people literally all over the world. And that’s because of people who make this extension of ministry possible. Chris: Our pledge is we’re going to keep on, by God’s grace, proclaiming the holiness of God, and we need your help, if you’re listening or watching. Take this message, spread it, share it, and let others know about Ligonier Ministries. By God’s grace, we’re going to be motoring on for a few more decades because there’s a lot of work to do in this world. Lee: You can join us and become a ministry partner simply by going to ligonier.org. There’s space there where you could learn more about becoming a ministry partner, or if you would like to call and talk to one of our colleagues, they would be more than happy to take your call at 800-435-4343. That’s 800-435-4343. Chris, thank you for being with us. Dr. Sproul, it’s been fun. R.C.: I’ve enjoyed it very much. Thank you. Lee: Thank you, and we’ll see you next time. Thank you so much, and God bless you. 57 Replies to “Ask R.C. Live (January 2017)” The Holiness of God is a must read👍👍 So glad to see him in the new year! God bless you, Sir! what a blessing to watch ❤ I love you Dr Sproul, God bless you with the biggest portion of grace and mercy! Genesis 15:17 is what did it for me too. MY HUSBAND AND I LOVE R.C. SPROUL. MY HUSBAND TOLD ME A YEAR AGO TO HEAR HIM AND I'VE BEEN HAVING SUCH AN AMAZING IMPACT IN MY LIFE, FROM HIS LESSONS THAT KEEP CHANGING MY YOUNG CHRISTIAN LIFE. I HOPE I CAN MEET HIM ONE DAY SOON. WE KEEP PRAYING FOR HIS HEALTH AND THANK YOU R.C. FOR BEING SUCH AN AMAZING TEACHER.THEY ARE THINGS YOU TALK ABOUT THAT I DO NOT UNDERTAND AT ALL YET, BUT I KEEP LISTENING AND LEARNING AND LOVE ALL Q&As AND VIDEOS AND EVERYTHING THAT I CAN LEARN FROM YOU. ALSO THANKS TO ALBERT MOHLER, JOHN MACARTHUR, CHRIS LARSON, RAVI ZACHARIAS, ETC ETC ETC, I LOVE THEM AND I WOULD LOVE TO HAVE AT LEAST R.C. JOHH M AND ALBERT M ONE DAY, IN MY LIVING ROOM, AND JUST LISTENING THEIR CONVERSATIONS ABOUT OUR LORD AND KEEP LEARNING. THANKS FOR ALL AND GOD BLESS YOU ALL, YOU ARE INCREDIBLE TEACHERS AND MESSANGERS OF GOD's GOSPEL God bless R.c , God has used him greatly to help me understand my walk with him when all isn't making sense . God bless you R.C 🙂 R.C All the best man you have lived a blessed life by blessing so many others. Thanks! Thank you for all of this! GREAT WORK…AND BIBLICAL THOUGHT. Thank you for playing this.And the opportunity to call in. The timing didn't work out. So wonderful to hear Dr. Sproul's health is doing well. God is good. Awesome questions and amazing responses by brother Sproul. I enjoyed this. My favorite theologian, wahoo! God bless you R.C. – your teaching, fidelity to Scripture, and your love have impacted me immensely! I am excited about the offer of the Holiness book by R.C. Sproul. For the past year or so I've been studying for my own book on Holiness, as it pertains to the sanctification of believers. Hopefully this will contribute to my own stores of understanding, that I might better expound holiness to others. Thank you!—minister sheldon R.C Sproul thank you for being true to the word of God. God bless you Pastor Sproul. I have learned a lot from your teaching for years. May God continue to lift and guide you, and bless you, as you teach His Word. John 14:6 1 John 3:8 I see you use modern science to fix gods crappy design… I love this man ! God bless him🙏🙏🙏🙏🙏🙏 God bless you RC. Good clear teaching and consistent reformed theology – increasingly rare. I will miss this man so much. But, i know it will be for a little while. Thank you so much for your ministry R.C. I was extremely blessed to see you in person, Dr. R.C.! I have learned SO much from you through the Holy Spirit. And I pass on what I've learned!! Thank you for allowing the Lord to work through you, Sir! 🙂 I want Lee Webb's voice, inflection, and cadence! amen Louvado seja Deus pela vida do Sr.Sprool God bless you all. RC is still going strong even on oxygen! He is amazing! God bless him!!! R c sproul contributed to my theological education. I don't mean to be rude, but what is the status of Dr. Sproul's health? Something happened to cause him to require a breathing apparatus? I don't see anything on the internet about it. 🙁 sería bueno que pusieran subtítulos en español. Thank you. @ Rc Sproul plz consider a vegan diet for your health plz Wonderfull perspective In Genesis when God says "let us". is there any evidence that it's refering to the trinity? Love RC! Please, please, please. Please, please Dr. Sproul as much as possible, please continue to answer questions. Audio files are more than enough, but Lord willing for decades to come they will bless countless children of Heaven. God bless RC for his diligent work in proclaiming the truth. I was introduced to RC my senior year in high school and I am glad to find him funny thing my english teacher during junior and senior year work for RC while she was living in Orlando Fl I bought the book The Holiness of God long way before to know and read doctor Sproul !!! great video…ill have to look into Lignier Ministries. Why would a holy perfect God want the worship of a bunch of depraved worms ? Reformed Theology makes no sense. remarkable man, remarkable legacy, i thank Almighty God for you all God bless you RC Sproul we love you in Jesus Christ and I will boast about you on the day of the Lord. So grateful to God for this ministry! Rest in Peace 🙁 Thank You for all, Dr. Sproul. RIP. Dr. R.C. Sproul has passed away. it appears he is idolized. His one sentence answer of what the Gospel is would never be understood by a seeker. I wish he'd phrased it with a few more words. I LOVE R.C. – my favorite expositor since I came to faith in 1988 What a blessing and an incredible loss. Wrong…..belief implies placing your whole being in the hands of God. Unless good old RD thinks that the Nicene Creed is just about intellectual assent. This man puts the Institutes of the Calvin Religion above the Bible. I love Dr. Sproul. I so look forward to seeing him. I miss him. I appointed him my spiritual mentor in 2012 when I learned the truth of Reformed theology. Sadly, I didn't have much time with him. But, he left a Lot of material to study. 🙂 Good answer on Hell. Thank you RC for your wonderful work! Miss him! 😥 I miss R.C with all my heart. An absolute giant. Can someone please help me with what Dr. Sproul said in 4:19, about GOD's omnipresence (even in hell)… that GOD is there in HIS ___? (jetren? something). I love RC! I'm sure he's preaching to the angels! Ha Poor James at the end…! Bless you brother ♥️
https://thegreattribulation.info/ask-r-c-live-january-2017/
CC-MAIN-2019-51
refinedweb
10,470
72.26
Sudoku, also spelled Su Doku, is a logic-based placement puzzle. It consists in placing numbers from 1 to 9 in a 9-by-9 grid made up of nine 3-by-3 subgrids, called regions or boxesor blocks, starting with various numerals given in some cells, the givens or clues. It can be described with a single rule: Each row, column and region must contain all numbers from 1 to 9. We can immediately deduce that for each row, column, and region the values in the cells have to be different. Moreover, this condition is sufficient; thus, the unique rule could be reformulated as: Each row, column and region must contain numbers from 1 to 9 that are all different. Figure 1 shows a easy Sudoku puzzle containing 26 givens and Figure 2 shows its solution: Figure 1. An easy Sudoku puzzle Figure 2. Solution to the Sudoku puzzle The Wikipedia entry on Sudoku has more information about the puzzle. Although first published in 1979, Sudoku initially became popular in Japan in 1986 and attained international popularity in 2005, both in newspapers (many newspapers publish a daily Sudoku puzzle) and on the Web. For example, see Koalog's Free Sudoku of the Dayto play Sudoku online. While Sudoku lovers invent very complex techniques with weird names (X-wing, Swordfish, Nishio), to solve Sudokus without guessing, computer programs usually use brute-force methods. In this article, we will learn how to solve Sudokus using Constraint Programming in Java. This approach has many advantages: - It can solve any Sudoku. - It is fast. - It is as powerful as the most complex human techniques: most of the Sudokus can be solved without trial and error. - It is much more robust than the brute force approach: variants of the problem, with additional constraints, could be easily solved the same way. Constraint Programming Constraint Programming (CP) is a technique of choice for solving combinatorial problems such as the Sudoku problem. Firstly, it consists of modelling the problem using mathematical relations, or constraints. Precisely, the term constraintdenotes the implementation of the mathematical relation. Hence, a Constraint Satisfaction Problem (CSP) is defined by: - A set of variables. - A set of domains (possible values) for the variables. - a set of constraints/relations on the variables. Secondly, a strategy for enumerating the different solutions has to be defined. CP differs from naive enumeration methods by the fact that constraints contain powerful filtering algorithms (usually inspired by Operational Research techniques) that will drastically reduce the search space by dynamically reducing the domains of the variables during the enumeration phase (also known as the "search phase"). We will use Koalog Constraint Solver, a Java library for Constraint Programming, to write the code. None of the techniques presented in this article depend on the choice of the solver, and could be implemented using any commercial or open source solver. Modelling the Sudoku Problem Let us first create a problem object that will be the placeholder for the problem modelization. Using Koalog Constraint Solver, this can be done by subclassing a BaseProblem: public class SudokuProblem extends BaseProblem { /** * Sole constructor. * @param givens the givens * (from 0 to 9, * 0 being used for unknown values) */ public SudokuProblem(int[][] givens) { super(); // the forthcoming model } } An important step in Constraint Programming is defining the problem variables. In our case, we want to find the value for each cell. Note that other models are possible: for example, we could define, for each value, its position in each row or column or block. It is also possible to mix several models. In our case, the following simple model will be sufficient. IntegerVariable[][] num = new IntegerVariable[9][9]; where the local variable num will be indexed by rows, from 0 to 8, and then by columns, from 0 to 8. for (int i=0; i<9; i++) { for (int j=0; j<9; j++) { if (givens[i][j] != 0) { num[i][j] = new IntegerVariable("num"+i+"_"+j, new SparseDomain (givens[i][j])); } else { num[i][j] = new IntegerVariable("num"+i+"_"+j, new SparseDomain (1, 9)); } } } We have defined the initial domain of each variable, taking into account the givens. SparseDomain means that the domain of each variable will be represented by a set of possible values. Note that it is also possible to represent a domain by an interval of the form [min, max] using the MinMaxDomain class. In each of the nine blocks, we want the values to be different. This means that we should enforce 36 (the number of distinct pairs that can be selected from nine values: 9*8/2) inequations between the nine num variables of each block. Instead, we simply use a global constraint called AllDifferent_SPARSE; it is suffixed by _SPARSE (a convention in Koalog Constraint Solver) to take into account the sparse nature of the domains. These constraints are added to the problem using its addmethod: for (int i=0; i<3; i++) { for (int j=0; j<3; j++) { add(new AllDifferent_SPARSE (new IntegerVariable[]{ num[3*i][3*j], num[3*i][1+3*j], num[3*i][2+3*j], num[1+3*i][3*j], num[1+3*i][1+3*j], num[1+3*i][2+3*j], num[2+3*i][3*j], num[2+3*i][1+3*j], num[2+3*i][2+3*j]})); } } We also want the values to be different in each row and in each column. In order to do that, we can use the SquareMatrix class, which provides utility methods to access the rows and columns of a square matrix: SquareMatrix mnum = new SquareMatrix(num); for (int j=0; j<9; j++) { add(new AllDifferent_SPARSE((IntegerVariable[]) mnum.getColumn(j))); } for (int i=0; i<9; i++) { add(new AllDifferent_SPARSE((IntegerVariable[]) mnum.getLine(i))); } The advantage of global constraints over a large number of small constraints is not only that they make the constraint model easier to read, but that they are also more powerful, since they usually incorporate complex filtering algorithms. For example, the AllDifferent_SPARSE constraint uses an2.5 filtering algorithm (based on a maximal matching algorithm from the graph theory). An intervalversion of the same constraint exists. It is called AllDifferent; it uses a nxlog(n) filtering algorithm. The AllDifferent constraint is thus faster but less powerful than the AllDifferent_SPARSEconstraint, which is why we used the latter in our model. Finally, we define the array of variables that will be used by the solver to display the solution: setVariables((IntegerVariable[]) mnum.getElements()); We are done with the modelling, which only consists of 27 AllDifferent_SPARSE constraints: nine for the blocks, nine for the rows, and nine for the columns. The complete model can be found in the source file, in the Resources section. Solving the Sudoku Problem This problem is simple enough to use one of the predefined solvers available in Koalog Constraint Solver: Solver solver = new DefaultFFSolver(problem); solver.solve();where problemis a Sudoku problem instance and DefaultFFSolveris a solver conforming to the first-fail heuristic. More precisely, this is syntactic sugar for: Solver solver = new SplitSolver (problem, new SmallestDomainVariableHeuristic(), new IncreasingOrderDomainHeuristic()); where SmallestDomainVariableHeuristic selects the variable with the smallest domain (with the hope of cutting large branches from the search tree) and IncreasingOrderDomainHeuristic tries to instantiate the selected variable by choosing the first value in its domain. Note that these types of solver and heuristics are very common and are available in any constraint solver. Using this very simple model, most of the Sudokus are solved by deduction (i.e., with no search). For example, here is an extract of the output produced by Koalog Constraint Solver when solving the Sudoku given to illustrate the beginning of this article. The test was performed on a 1.6GHz PC running Linux SuSE 9.3: solution found in 104 ms 0 backtrack(s), 160 filter(s), max depth 0 no more solution solved in 109 ms This means that: - A solution was found in 104ms by filtering 160 constraints (a constraint solver needs to filter each constraint more than once since the domains of the variables get reduced during the process). - No trial and error was required. - This solution is unique (i.e., the Sudoku is well-formed). - The proof of this last result took only (109-104=) 5ms! These results mean that the filtering algorithm, used by the 27 AllDifferent_SPARSE constraints, is powerful enough to deduce the unique solution of the problem. A small percentage of Sudokus still require somebacktracking (backtracking is an enumeration algorithm), but this remains very limited. In any case, solutions are found very quickly (in less than 200ms). Going Further Helmut Simonis' article "Sudoku as a Constraint Problem" presents redundant constraints dedicated to the Sudoku problem, further reducing the need for backtracking. In particular, one could take advantage of the LatinSquare constraint, which will be available in the next release of Koalog Constraint Solver, version 3.0. In any case, the solving of problems such as the Sudoku problem is made very easy with the use of Constraint Programming. There are two other interesting, but harder, problems related to Sudokus: - Generating well-formed Sudokus: more precisely, generating givens that lead to a unique solution, which is the case of the Sudoku provided as an example at the beginning of this article. - Explaining Sudokus: more precisely, generating a human-readable explanation of the resolution of a Sudoku. Both problems can be addressed with Constraint Programming, but are out of the scope of this article. Resources - Sample code for this article - Wikipedia: Sudoku - Wikipedia: Constraint Programming - Wikipedia: Operational Research - Koalog Constraint Solver - A detailed article about the modelling of Sudokus using Constraint Programming - --> - Koalog's free Sudoku of the day
https://community.oracle.com/docs/DOC-983413
CC-MAIN-2015-48
refinedweb
1,613
51.78
source code The Blender.Mesh submodule. New: This module provides access to Mesh Data objects in Blender. It differs from the NMesh module by allowing direct access to the actual Blender data, so that changes are done immediately without need to update or put the data back into the original mesh. The result is faster operations with less memory usage. The example below creates a simple pyramid, and sets some of the face's attributes (the vertex color): Example: from Blender import * import bpy editmode = Window.EditMode() # are we in edit mode? If so ... if editmode: Window.EditMode(0) # leave edit mode before getting the mesh # define vertices and faces for a pyramid coords=[ [-1,-1,-1], [1,-1,-1], [1,1,-1], [-1,1,-1], [0,0,1] ] faces= [ [3,2,1,0], [0,1,4], [1,2,4], [2,3,4], [3,0,4] ] me = bpy.data.meshes.new('myMesh') # create a new mesh me.verts.extend(coords) # add vertices to mesh me.faces.extend(faces) # add faces to the mesh (also adds edges) me.vertexColors = 1 # enable vertex colors me.faces[1].col[0].r = 255 # make each vertex a different color me.faces[1].col[1].g = 255 me.faces[1].col[2].b = 255 scn = bpy.data.scenes.active # link object to current scene ob = scn.objects.new(me, 'myObj') if editmode: Window.EditMode(1) # optional, just being nice Vertices, edges and faces are added to a mesh using the .extend() methods. For best speed and efficiency, gather all vertices, edges or faces into a list and call .extend() once as in the above example. Similarly, deleting from the mesh is done with the .delete() methods and are most efficient when done once.
https://www.blender.org/api/248PythonDoc/Mesh-module.html
CC-MAIN-2016-40
refinedweb
288
60.92
On Mon, Jun 29, 2020 at 11:10 AM Kevin Sheppard kevin.k.sheppard@gmail.com wrote: It can be anything, but “good practice” is to use a number that would have 2 properties: - When expressed as binary number, it would have a large number of both 0s and 1s The properties of the SeedSequence algorithm render this irrelevant, fortunately. While there are seed numbers that might create "bad" outputs from SeedSequence with overly low or high Hamming weight (number of 1s), they are scattered around the input space so you have to adversarially reverse the SeedSequence algorithm to find them. IMO, the only reason to avoid seed numbers like this has more to do with the fact that there are a relatively small number of these seeds. If you are deliberately picking from that small set somehow, it's more likely that other researchers are too, and you are more likely to reuse that same seed. - The total number of digits in the binary representation is somewhere between 32 and 128. I like using the standard library `secrets` module. import secrets secrets.randbelow(1<<128) 8080125189471896523368405732926911908 If you want an easy-to-follow rule, just use the above snippet to get a 128-bit number. More than 128 bits won't do you any good (at least by default, the internal bottleneck inside of SeedSequence is a 128-bit pool), and 128-bit numbers are just about small enough to copy-paste comfortably. We have thought about wrapping that up in a numpy.random function (e.g. `np.random.simple_seed()` or something like that) for convenience, but we wanted to wait a bit before commiting to an API.
https://mail.python.org/archives/list/numpy-discussion@python.org/message/6DSBGW3LJFQFW3XB3V6WMSUZO2YAY5R3/
CC-MAIN-2022-27
refinedweb
279
68.2
The Mexican government denied Monsanto’s request to expand its pilot project in northern Mexico. The request was rejected because the government says additional tests and studies need to be carried out to determine the effect of genetically modified corn on native corn species. Mexico has totally one upped the USA!!! A 2010 study showed that Mexican Americans live five years on average LONGER than other ethnic groups in America. Surely there are lots of factors involved - but eating healthy food not engineered to kill and make infertile is surely one of them. Kudos to Mexico for having sound information, and a government more concerned (yet less able) for the public's foods than Obama's admin, and the Monsanto Lawyer running the FDA! … -monsanto/ For our supposed role model status, the U.S. does many things only third world countries do: we use Monsanto sterilized seeds, we use BHT, we refuse to use the metric system, we support Fox News, we kill democratically elected leaders and put in military led dictators that favor corporate business, we rig elections by any means possible, we kill innocent citizens that we know to be wrongly convicted, we start wars to control oil prices and various related industries, etc. Man, Mexico is sounding better all the time. Yup. I think I'd give Canada a go. I can already speak the language, and could learn French faster than Spanglish due to having once known a lot of French. Dunno what I'd do for money....but whatever, one can usually find some kind of way if they try hard enough. Hell, I'll just try to not eat corn! In Canada there are far fewer toxins or carcinogens allowed in their food; they prefer health for many over wealth for few. The 'AC' part of HVAC might be a downfall, but you could probably adapt and learn how to fix wood stoves! I'm sure there are also lots of things to whack with a machete. (I think I'm mixing up topics. lol) HAHAHAHAHAHA!!!!!!!!!!!!!!!!!!!! WOOD STOVE REPAIRMAN AT YOUR SERVICE!!!!!!!!!!!!!!! LOL! I just want to be one of those folks that makes a living by talking about stuff online well enough to make some sales! Wish me luck! If I can get that ball rolling....I just might expatriate to Canada! Wesman, Thats a big 10-4 (same as YES!). Monsantos only interest is MONEY!!! Ronnie Just curious, what is the life expectancy of Mexicans living in Mexico compared to Americans living in America? What is the quality of life for Mexicans in Mexico compared to Americans living in America? Why would you tell us that Mexican Americans live five years longer in America than Americans and give us a story about Mexico saying no to what ever the hell it is you're talking about? Why don't you go and get your own research to find out what you want to know. I'm here to discuss positive things, and there's nothing more positive that I could possibly be doing right now that spreading awareness about the most corrupt, unethical, and hated corporation in the world. I don't recall inviting you to this post personally, so what is YOUR point. Do you have a point? Yes, I do, did I miss the part where an invitation is needed to comment on a thread? Zooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooom So you still have no point to make? What, are you bored? Just being a troll? Looking for a reaction? Do you have the answer to my questions? No? Mexicans live longer in the U.S.? Imagine that.... I'm not here to answer your unrelated to the subject question. When you start paying me for answers, then I'll hop to it, in the meantime I'm thinking that you've got internet, and should answer your own unrelated to the subject questions. Cute, you're not answering because your stats on Mexican Americans have nothing to do with your post. Mexico shuns Mansanto...Woo hoo! Mexicans in Mexico will not outlive the average American. No, you've yet to provide any data about that. I've no reason and you've nothing at all to suggest that Mexicans in Mexico live any shorter lives than Mexicans in America. You know this. Stop being a troll. But I'm interested, how much does Monsanto pay you to be a forum troll? Eh, I wish I could get paid for pointing out actual trolls. +111111111111111 Thanks Hollie!!! I've got to learn to ....maintain my ...um, I mean not go ballistic when that one shill persons makes appearances. Hell, we're nice people, Wes. Every time we reply to their posts, we help them earn 50cents. repairguy47, You have been programed in a dark alley, open your eyes to what is going on, on mainstreet; you would rather not know, correct? Ronnie Sir, just wait for the other forum stalkers that so obviously work for Monsanto show up!!! Oh man, there's some trippy dippy folks out there. There's nothing positive to be said anywhere that I know of for Monsanto or any GMO product. So they got in with Bill Gates, and gifted a charitable slow murder and diseases to hungry Africans....as if we didn't have real food we could have fed them. Actually, going by life expectancy stats show that the average US citizen will only outlive the average Mexican by 1 or 2 years. Key being outlive. Thanks for playing. But we Canadians will outlive you Americans by 2 or 3 years yeah, but you will do it in Canada! Thankfully Touche. I mean that in the French Canadian way. And any sane person realizes that there are TONS of variables and factors involved in that. It's one of those things that some people don't seem to understand...objectivity and science. Fluffy gets it, why doesn't repairguy? Because repairguy thinks for himself and fluffy just wags his tail when his master scratches his head. That I do not doubt. Mexico, and Mexicans that don't eat Monsanto are surely happier, healthier, and smarter. Yeah, right. Sounds lime governor venture was on to something after all. Viva la Mexico! They are also very tough on sweetners the allow for soft drinks. Might need to look into getting some land down there. I suggest that each Monsanto shareholder receives by post a package of Agent Orange in direct proportion to their shareholding. ...and fifteen minutes in which they must drink it or die by "lead poisoning." Hell, just let them walk barefoot through a newly sprayed field. That'll bring out the rashes and blisters the same way it does on Mexican kids who need to walk through Monsanto fields to sell their family's naturally grown produce. Their ducks are dying because of the runoff into ponds. This is their livlihood. Right!!! I often wonder if they serve GMO stuffs in the Monsanto cafeterias at the plants. I guarantee that the board of execs ain't eating that stuff. I think they are. They're too ignorant to realize what their doing. Very few, if any, corporations are going to spring for all organic food for their people, whether board or peon. It effects their bottom line. I think the FDA is the biggest monster here because they approve this stuff along with all the other medications, a good percentage of which is recalled or has some later warning attached to it. "Take alsapriobioptomethydiazapine and you'll get rid of your backache. Warning: may cause kidney failure, heart palpitations, dark stool, abdominal cramping, blurred vision, headaches, and numbness in hands and feet. Do not take if you have high blood pressure, are pregnant, or under the age of 15." But it'll get rid of your backache. 6 months later: "If you or someone you know has taken alsapriobioptomethydiazapine and has experienced severe paralysis, seizure or died suddenly, call the law offices of Goody and Twoshoes. We can get you a large settlement." The unholy trinity at work: Politics/Media/Legal LOL! That's certainly all true. There are safe treatments for things in Europe that aren't approved here, and only $$$$$$ could explain it. There's stuff approved all over the place here that Europeans wouldn't touch with a ten foot poll. Obama lost me as a supporter the minute he assigned Michael Taylor as head of the FDA. ...and down here in 'backward' Asia, we have stuff on sale to cure folk that would have BigPharma sweating their balance sheets if they thought it could be sold in the 'developed' world. Profit is a powerful motivation to let people die, especially when they die slowly and pay you daily to keep them in morbidity. Chinese doctors get paid by their patients every month whilst the patient is well, but do not get paid when the patient is sick... powerful incentive to keep your clients healthy! In the west, it's the other way around, you pay to be kept sick. ...and who lives longer lives??? Asians! Not necessarily, they also work harder and do things that kill them, like riding mopeds at Kamikaze speeds, which brings the age down slightly, but they DO have a lower cancer rate, about 140/1000 I think compared to the USA's 208/1000 (if my memory serves me correctly). And we are a disaster area for Monsatano, small farmers with organic crops as standard,(why buy fertiliser?) stacks of free rainwater and 365 day a year sunshine! I'm told that Asians have less cancer despite smoking WAY more tobacco...due to drinking huge amounts of green tea. Is green tea a big deal where you are? Green tea, white tea, masses of herbal teas, and beer, lots of beer! we also drink lassi, a yoghurt drink with fruit flavourings, and of course everywhere there are fruit drinks mixed to order... carrot, ginger and apple is great for the digestion, the stalls have charts telling you what each mix is best for, so generally Asians drink better stuff, natural and cheap as tropical fruit is abundant. The younger ones have now started on coca cola and other phosphate drinks that kill you, but that is western infiltration on TV and films watched. I have a blend of mango, banana and star fruit or watermelon with psyllium husk blended in each morning, so your body gets what it needs to kick-start, but it is light and easy to digest, so the body rests until lunch. Also folk are more laid back in general, and that is a major factor in living well and longer, we have Buddhists, Hindi, and Taoists all mixed together, come 7.30am there are a whole bunch of folk doing intricate moves and exercises on a car park near my house... the place is just relaxed! And yes most everyone smokes except the westerners who have bought the lie. Here waiters bring you ashtrays when you light up, unless you are in a non smoking restaurant. (PS. Some Muslims smoke grass, who would have guessed!) That sounds awesome!!!!!!!!!!!!!!!!! Folks NOT rush rush rushing everywhere to make that dollar so as to get that new iphone, Escalade, or McMansion - but trying to enjoy life, what a plan! Oh I hope someone over there will preach about the evils of the colas, it's either HFC corn syrup (Monsanto) with the sweet ones, or aspartame (Monsanto) with the diet ones - both equally damaging. You are already preaching over here, take a look at your Google stats some day, you would be surprised how many folk read from all over the world, sure HubPages is basically American focussed, but I have hits from all over. My visitors are coming from: United States United Kingdom Australia Canada Philippines Hungary India Malaysia South Africa Turkey Ireland Greece Brazil Spain New Zealand Israel Thailand Pakistan Netherlands Georgia Czech Republic Costa Rica United Arab Emirates Tunisia Trinidad and Tobago Sweden Singapore Serbia and Montenegro Qatar Norway Nigeria Japan Italy Indonesia Hong Kong Ghana France Croatia Argentina Algeria What we say can reach a multitude of folk, so keep plugging away John Thanks For the encouragement, John!!!!!!!!!!!!!! I'm stuck right now in "trying to make a dime" mode....for needing it. I'm going to return to my true calling though - telling folks what I think they need to hear! Monsanto is EEEVVVVIIILLLL!!!!!!!!!!!!!!!!! I can't even go to Wholefoods and spend a billion dollars on a loaf bread to guarantee Monsanto hasn't put its monster seeds in it. They have the FDA in their pocket so deep I wouldn't be surprised to find out They are the FDA. Well besides the eugenicist named Hamberg on the board of commissioners, there is the Monsanto lawyer that Obama put at the head of the FDA.... I think the important thing is to avoid corn, and that includes things sweetened with high fructose corn syrup, and one shouldn't drink Donald Rumsfeld's aspartame sweetener either. ." … el-taylor/ ." That's typical of all the wonderful bovine scatology that you always see associated with Monsanto from it's propaganda wing. Hamburg is a straight up eugenicist - she's the Jewish Adolf Hitler. Bill Marler is an accomplished personal injury and products liability attorney. He began litigating foodborne illness cases in 1993. Attorney - it's the Barr Association and Corporate interests vs human rights, and the health of everyone on the planet. Europe, India and now Mexico are fighting the introduction of Monsanto genetically modified seeds! It is the beginning of a revolt against Monsanto's policy to dominate the world granaries, to experiment on us their guinea pigs! That ship has sailed. We're in it now. Buy only organic. Don't even buy meat that's been feed fed. Only grass fed. Read labels like a hawk. If there's any kind of corn or soy derivative, you can bet it's tainted. Consumers are blind because they choose to be. This is the information age and we're responsible for our own fate. If enough people stop buying the crap, they'll eventually take it off the shelves. The big problem, as I see it, is we can't trust anyone. If they start pulling product from the shelves, they'll bring it back in a more clandestine way and we'll need to keep digging deeper and deeper to uncover the deceit. Eat whole food. Know where your food is coming from. Eat less. You mean you wouldn't sacrifice your health for the new world order???? tsk tsk!!! LOL! Bill Gates is providing "charity" to Africa. Why aren't African Americans up in arms about feeding poison to Africans under the guise of charity? Holy smoke that town in Alabama where Monsanto dumped pcb's into the ditch was mostly black, and those people are dying left and right. Love canal, redux. The difference is they know better now and are still getting away with it. There's no excuse for any of this and that's what scares the hell out of me. They have so much power. I'm ready for Red Dawn of the 21st c. Well we might well get to see that, or we might get vaporized instead, or we might get rounded up for the civilian inmate labour program! Hey Wes - I love your new profile image. You're dressed! And, of course, I do so agree with all of your political forums posts in regard to health and the environment. So TWO POINTS for Mexico and the other forward thinking governments that won't let Monsanto trample on their soil and destroy it for all living organisms and the future of this planet. Thanks so much for keeping up these conversations. Many blessings to you Debby Thanks Debby. I've got my own squad of forum trolls assigned to me!!! It's sort of fun. I don't intend to stop doing it...It's not productive so far as income....but every once in a while I get a good idea of something to say from these forums. To respond to and support your original post, Wesman Todd Shaw, Mexico, India, Romania and more countries are saying no to GM foods in general and specifically to Monsanto. What's wrong with the US is consumer blindness to the issue. US sales marketers are doing everything they can to sweep the ill effects of GM foods under the carpet, they've got plenty of corporate money to do that with, and they're doing a great job, blinding consumers all the way. I think that there were Monsanto or otherwise GMO fields in Romania...and I don't know what happened so far as who owned what, but they burned the fields to ash...which was certainly a fine thing to do. I'd personally like to see some patriots in this country set fire to Monsanto Corn fields. It would be a righteous thing for someone to do. OMG, I'd love to see that! The perfect revolution to the New World Order. Yip Yip Yipee Kayeah! What's so wrong about having genetically altered corn? Haven't we been selectively breeding corn for millions of years to make it more edible and pest resistent? Isn't this biotechnology the same thing but with faster results? No, it's not. What's most terrible of all is "roundup ready" - as roundup is poisoning future generations to come as we speak. … erbicide-p Rachael, one aspect of GM food that has not been mentioned here is that they put a marker in their seed. If you just happen to despise Monsanto and refuse to use any of their seed but your neighbour uses their product quite happily and some of your seed is then fertilised by your neighbours GM plants then your seed will carry the Monsanto marker and you will be liable to them! And believe me, they will take your money, lots of it! Absolutely correct. How they get away with that garbage is beyond me. Amoral America - where money is always nothing but power, power used to prey on people who've got less money. Ummm, maybe he was litigating in favor of those contacting foodborne illness? by Josak 5 years ago What never ceases to sadden me is how predictable certain elements of our society are, I studied the recession as I imagine many hubbers have and the parallels are saddening, when things get tight economically the weaker and meaner of our society show their true colors. Hoover-ville was demonized... by Fluffymetal 7 years ago Should it be legalized? Why? Why not? by Kathryn L Hill 21 months ago "Make y o u r voice heard and VOTE !" Says K Rock! / 106.7 FM on recent get out and vote campaign ads. This radio station basically plays alternative rock geared toward the youth of the 90's who are now in their late thirties through forties. (Gen X)Which way is this age... by sandra rinck 8 years ago hb2281 law that bans ethnic studies in public classrooms. Wow! Says something about restricting the teaching of oppression.... shall I even go on. Their aim is to erase what happened to the Mexicans. They want all studies restricted for teaching that Arizona used to be part... by ahorseback 3 years ago Right...
https://hubpages.com/politics/forum/93531/mexico-says-hell-no-to-monsanto
CC-MAIN-2018-30
refinedweb
3,257
73.47
Subject: Re: [boost] Thoughts on Boost v2 From: Andrey Semashev (andrey.semashev_at_[hidden]) Date: 2014-05-17 06:45:37 On Friday 16 May 2014 11:10:51 Niall Douglas wrote: > > 1. Boost isn't sexy any more. As one very highly respected world > famous engineer put it - and I won't say who, and I apologise to him > for stealing his words without attribution: > > "Boost used to be about all the stuff you really wanted in the > standard. Now Boost looks like all the stuff that wasn't good enough > to get into the standard" I disagree with it completely and fighting the urge to use the word "ridiculous". There are no tools like Boost.Intrusive, Boost.Spirit, Boost.Interprocess or Boost.ASIO, not to mention things like XML, advanced networking (HTTP, FTP, SSL, etc.), encryption, the holy grail of GUI and many other domains not covered by Boost. You got threading, regex and a couple new containers and think you're covered? I think the previously hopelessly lacking STL got a little less hopelessly lacking. Granted, some of these (networking and filesystem) are making their way into the language. Others I don't see coming (I'm looking at Boost.Intrusive and Boost.Spirit in particular), and I'm using these tools almost on a daily basis. I find myself using Boost.Intrusive by default instead of STL containers whenever the situation requires something more complex than a vector. And when I occasionally have to write Java code I find C++ pretty damn sexy. > 2. Everyone recognises there are serious problems with process, > everything from how you were treated Stephen when you tried cleaning > out cruft and only really Dave supported you, right through to the > fact that peer review simply doesn't work any more. The Boost > community has become quite selfish in recent years, as you would > expect from those with a vested interest in the status quo before > evolution. And for the record, I have no problem with those vested > interests keeping their existing Boost, but I personally want as far > away from C++ 03 as soon as is possible. I'm sure I'm not reading you right because calling people selfish for writing quality code for public use and providing support for free doesn't make sense to me and verges on an insult. What I see is lack of involvement of the community in Boost as a whole. This includes the lack of reviews and review managers, the lack of responses to list and support queries. With all its positive sides, the modularization increased that negative effect because now people don't have full access to the repository and therefore have less means and will to influence. I suppose, that is expected and eventually Boost will become just a label for many separate projects (that are currently libraries) with their own sub- communities. Not necessarily a bad thing, but it is sad to see that the Boost project as a whole fades. I do not see how your proposal changes that, rather the opposite. > 3. All the interesting new C++ 11 libraries you find around the > internet have zero interest in trying to join Boost, with a very few > honorable exceptions. That speaks volumes, to me at least. I see no problem with that. Boost was never the only library in the world, not in C++98/03 times, not now. > And here is what I think should be in a fork of Boost: > > 1. Minimum required compiler feature set will be VS2014's. No use of > Boost STL permitted where the C++ 11 STL provides a feature. What if Boost implementation is better? E.g. Boost.Regex is considerably faster than std::regex (both MSVC and libc++). What if Boost implementation provides extensions that are not available in STL? E.g. Boost.Atomic will provide additional operations and Boost.Thread has synchronization primitives that are not standard. What if a library wants to be compatible with C++03 as well? Is it banned? Does it have to duplicate the missing components within its own scope? > 2. cmake instead of Boost.Build. Cmake is not ideal, but I admit I feel more comfortable with it than with Boost.Build. > 3. Eliminate peer review in favour of a suite of automated libclang > based AST analysers. Instead of persuading people to review > libraries, persuade them to review and improve the AST analysers. This is where you say that Boost (as a whole project) community is no longer needed. No AST will be able to evaluate the design and usability of a new library and its documentation. Peer review, especially for the new libraries, is absolutely needed, IMO. I would say that major changes to the accepted libraries also need to be reviewed. Unfortunately, the practice shows little interest for that in the community. But even then I believe that reviews is a positive and essential part of ensuring the code quality. I understand that the current scheme of reviews is holding back the growth of Boost. As I said, it is sad to see the lack of involvement of the community. But replacing the review process with an automated check is not the answer. I don't have the answer myself, but I can say that I want my code to be reviewed and I want to be sure that others' code is reviewed before it enters Boost (or at least receives some official status). Otherwise I don't trust the code quality, however contrived automated checks you run on it. > 4. Mandatory cross platform per-commit CI with unit testing exceeding > 95% coverage. We don't care what unit test library is used so long as > it can output results Jenkins can understand. > > 5. Mandatory all green thread, memory, UB sanitisers and clean > valgrind. All also tested per-commit. > > 6. Mandatory CI testing for exception safety. I am hoping a clang > rewriter can basically patch all exception throws and have them > randomly throw for testing. Any improvement of the testing infrastructure can be only welcomed on my side. Although I wouldn't set any mandatory bar on the coverage. There are cases which are difficult or even impossible to test within the automated testing environment. This includes long-running tests, platform-specific code and functionality involving third party components. A library should not be forever banned if some parts of it cannot be tested in the CI. > 7. Per-library source distributions instead of a monolithic blob. > This implies some dependency management, but cmake makes that much > easier. It also means we can eliminate the release cycle because each > library does its own release cycle, and the correct (i.e. tested) > version of dependencies are included into each per-library source > distro. This solves the version lock problem currently plaguing > git-ised Boost, at the cost of pushing the version lock problem onto > users [1]. BTW I want to see a soak test of the unit tests for 24 > hours be all green before a release. I think there should be a way to generate a monolithic distribution, even if from separate packages. The dependencies between packages (of some select versions) should allow that. This will make it easier for downstream package maintainers to build and distribute a slice of Boost libraries compatible with each other. > 8. Reusable utilities in a submitted library need merging into some > common utilities library which follows the STL conventions. Other > than that, no source code, naming conventions, namespace or anything > else needs converting or changing. We are looking for very high > quality C++ libraries, nothing more. Obviously if someone hopes for a > library to enter the C++ 17 STL they'll need much more rigour, but > that's up to them. That utilities library should not become a zoo of namespaces and similar but different components. So some conversion and documentation will be required. Also there is an issue with dependencies of these utilities on other libraries. This is something we're trying to address with Boost.Utility now. Other than that I agree, the less code duplication the better. > 9. There is no longer an "in" or an "out" for distribution. I'm > thinking of a scorecard page where member libraries are ranked by how > high quality they are according to all the automated review, so when > I say "mandatory" above, I simply mean they don't get to appear on > the main downloads page without that precondition. All submitted > libraries do appear though, just ranked very low if their quality is > low. I would hope all this is generated from a database and requires > very little human input. I don't understand. Do all libraries appear in the downloads or do some of them not? > 10. BoostBook documentation using the Boost look and feel becomes > mandatory. I've had enough with library authors thinking they can > improve on BoostBook's output with things like using Comic Sans as > the font or weird colour schemes throughout. I'd change the preference to QuickBook. Writing and maintaining raw BoostBook is... counterproductive. Also, the requirement should be on the look and feel and not the particular toolset you use to achieve that. Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk
https://lists.boost.org/Archives/boost/2014/05/213267.php
CC-MAIN-2019-35
refinedweb
1,556
65.12
Menu items greyed out Hi all: I am a newbie in Qt, even though have worked in C++. Developing a basic GUI. In that, have plugged in a simple media player using QMediaPlayer. But some of the menu items in Edit - like Cut / Copy / Paste - is greyed out while playing the video. But at other times it is active. I have checked designer UI file, and it is enabled as well. Other menu items in Edit menu are active. Any solutions for this trivial & strange issue? Thanks a ton, folks. - raven-worx Moderators @krec-dev said in Menu items greyed out: But some of the menu items in Edit - like Cut / Copy / Paste - is greyed out while playing the video. But at other times it is active. about what menu are you talking? Where do the menu actions come from? Thanks @raven-worx for the note. My developed demo GUI for a video player has a EDIT menu, which has simple menu items called copy, paste etc. While the video is playing in the media player, the menu items of copy & paste in Edit menu in the top menu bar is greyed out. At other items, these menu items - copy & paste - in Edit menu are active. I have also attached a screenshot for your kind reference. Added to this, there is this un-needed "Emoji Symbols " menu in the Edit menu drop down on Mac. Any work arounds for that? - raven-worx Moderators @krec-dev you haven't answered my question, but nevermind i figured it out by myself. try the following: #ifdef Q_OS_MAC #include <Foundation/NSUserDefaults.h> #endif int main(int argc, char **argv) { #ifdef Q_OS_MAC [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"NSDisabledCharacterPaletteMenuItem"]; [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"NSDisabledDictationMenuItem"]; #endif QApplication app(argc, argv); .... return app.exec(); } - Charlie_Hdz Seems that you're disabling these action. I don't know your implementation, but would you think that may be a good idea to set up the actions in the ctor or any function that changes the actions? Thank you To add further to this and clarify , please note the menu items will be disabled ONLY after calling QFileDialog to open and load a video file to play. Does this have any issue as mentioned here (). Need to check. Thanks for the replies, @raven-worx. But seems, the solutions is for the "emoji symbols and start dictation " menu items. But it appears it does not work out. I will explore that again. @Charlie_Hdz. I have not setup any actions, in fact tried adding simple statements after setting up actions too, but still it does not work. The moment , Copy/ Paste /Cut changes to say demo or Copies, Pastes, Cuts - the menu items are active! I observe on stack overflow, that giving space while defining the titles in creator will solve that, but it has not worked out for me so far.
https://forum.qt.io/topic/81534/menu-items-greyed-out
CC-MAIN-2018-43
refinedweb
479
75.1
Originally posted by ashok khetan: hi, which of these options are true for the following question?(from Boone's Mock-exam). Question. Originally posted by Bindesh Vijayan: I agree with Rajani.Since if you look at option b more carefully,it will be clear that the option says about running GC which is no gurantee at all.Of course, you can call System.gc() but again, as Roopa mentions,it is a [b]request rather than running it. THANKS.[/B] Originally posted by Bindesh Vijayan: [B]Roopa, Actually I think, what happens is when GC is to be done it calls finalize() on that particular object and this way it informs the object of being GC'd. You can view this phenomenon on the following code: class A{ static int finalized=0; private int i=90; private float f=12.3f; protected void finalize()throws Throwable{ finalized++; System.out.println("Finalize called."+finalized); super.finalize(); } } public class FinalizeDemo{ public static void main(String[]args){ for(int i=0;i<10;i++) new A(); System.out.println("Calling gc."); System.gc(); } } THANKS[/B]
http://www.coderanch.com/t/208541/java-programmer-SCJP/certification/garbage-collection
CC-MAIN-2015-06
refinedweb
182
56.45
@jamal For your information, this has been addressed in zabojad @zabojad Posts made by zabojad - RE: ons-navigator and slide animation from right to left - RE: Button in Tappable ListItem issue For anyone else wondering about the same thing => - Button in Tappable ListItem issue I have a Buttonin a tappable ListItem. How can I prevent the ListItemto “react” to touch when the Buttonis pressed? I’ve tried catching and calling preventDefault()and stopPropagation()on the events returned by onTouchTapand onMouseDownon the Buttonbut without success… The ListItemstill reacts when pressing the Button. - RE: ons-navigator and slide animation from right to left ? - RE: Splitter @Fran-Diox try setting collapseto false(the boolean value, not a string) and you’ll see that the SplitterSide cannot be closed… render: function() { return ( <Ons.Splitter> <Ons.SplitterSide style={{ boxShadow: '0 10px 20px rgba(0,0,0,0.19), 0 6px 6px rgba(0,0,0,0.23)' }} side='left' width={200} collapse={false} swipeable={true} isOpen={this.state.isOpen} onClose={this.hide} onOpen={this.show} > IMO, it should make it not overlaying the SplitterContentbut still with keeping the possibility to close / swipe it. - ons… - RE:… - RE: None of the examples work on the onsenui react API documentation Thanks, I confirm it now works. Problem: “Topic Tools” does not propose me to mark this topic as solved. Why? - RE: Splitter I do not understand the use of this component when collapse is set to true. The SplitterSide cannot be closed when collapse is true… - None of the examples work on the onsenui react API documentation More a bug report than a discussion though:
https://community.onsen.io/user/zabojad
CC-MAIN-2021-10
refinedweb
267
53
Hi All, i am having a trouble with the below method if (GetDocText.Native.NativeMethods.StgIsStorageFile(this._Path) != 0) the above method always sometimes returns either 1 or 0 zero. in my case for the .doc file it sholud always return zero (0) so the above condition checking for if will get false and the next statement will work. Below is definition of the StgIsStorageFile method using System; using System.Runtime.InteropServices; namespace GetDocText.Native { internal class NativeMethods { private NativeMethods() { } const string Ole32Dll = "ole32.dll"; ); [DllImport(Ole32Dll, CharSet = CharSet.Unicode)] public static extern int StgIsStorageFile(string pwcsName); } } as this is from the metadata file as i do no have actual source of the methods in this . as this is for the operation on the document file processing that too .doc file, please kindly elaborate me the possible cause of the method is not working properly. if more information required please let me know.
http://www.networksteve.com/enterprise/topic.php/weired_error_with_doc_file_to_extract_text_from_it_with_some_met/?TopicId=97855&Posts=3
CC-MAIN-2019-43
refinedweb
153
59.5
While still waiting for the two pre-run boards to arrive, as promised last time here’s our second tutorial on communication, this time between two SwarmDrives independent of any network availability or not. This is a kindof peer-to-peer communication for which we use ESP-NOW. This protocol, developed by Espressif, enables ESP32-based devices to send small data payloads to one another without using Wi-Fi. It does so by using its on-board radio to establish a secure, low-power, 2.4GHz link. There are many easy to find examples available that demonstrate how to use the ESP-NOW API (included with ESP-IDF). In this write-up, I will be using the bare minimum code needed to send just one integer between devices. But you can, of course, send any small data payload (less than 250 bytes) you need for your own implementation. For simplicity’s sake, this example code doesn’t use any encryption, simply broadcasting its data in the open. In a real-life use case, you would probably have an extra discovery layer where your device tries to find its partner devices. You would also need some sort of functionality where each device sends out its own MAC address, plus some status information, while at the same time trying to receive similar data from other devices in close proximity (which, tests have shown, can be hundreds of meters). This would all be part of a “swarm” implementation. First of all, the ESP32 is put into station mode and prevented from connecting to Wi-Fi. In fact, you can turn off Wi-Fi explicitly as it cannot be used simultaneously. Next, the ESP-NOW API is initialized and peer info and a receive callback are registered:); The minimum setup for the peerInfo structure requires a channel and a peer (MAC) address. The channel can be chosen based on local interference levels. (There are many free tools available for checking how busy channels are in your neighborhood.) Again, for simplicity, encryption is turned off and the broadcast address is used as peer address. After setting up the peer (broadcast in this example), a receive callback is registered. This handles the receiving side. Besides having access to the data received, it also has the sender of the data and data length available. The received data, MAC address, and data length will be logged to the serial monitor. Now the only thing left is to send something: esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *) &x, sizeof(int)); We’re just sending one integer (4 bytes) to the broadcast address to which other SwarmDrive boards are listening. There, the receive callback will show what is received over the serial monitor: The data is sent just once. To send it again you’d need to reset the sender or you’d repeat the send function at some time interval. Now, I know this is a very crude and simple piece of code. It is just intended as a quick example of how easy the communication side of SwarmDrive can be. Of course, it would take a lot more code to have construct a real Swarm intelligence setup. But this example clearly shows the value of having a capable MCU on board. #include <Arduino.h> #include <WiFi.h> #include <AsyncUDP.h> #include <esp_now.h> uint8_t broadcastAddress[] = {0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF}; esp_now_peer_info_t peerInfo; void onReceiveData(const uint8_t *mac, const uint8_t *data, int len) { printf("** Data Received **\n\n"); printf("Received from MAC: %02x:%02x:%02x:%02x:%02x:%02x\n", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); printf("Length: %d byte(s)\n", len); printf("Data: %d\n\n", data[0]); } void initESP_NOW() {); } extern "C" void app_main() { initArduino(); WiFi.mode(WIFI_STA); initESP_NOW(); int x = 65; esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *) &x, sizeof(int)); if (result == ESP_OK) { printf("Data sent successfully\n"); } else { printf("Error sending the data\n"); } while (1) { vTaskDelay(10 / portTICK_PERIOD_MS); }; } I hope it will inspire you to start writing your own, more sophisticated code. In the next update, we will explore the AS5048B position sensor since it is probably the first thing you’d want to implement when working with BLDC motors. Until next time, Majodi
https://www.crowdsupply.com/nickstick/swarmdrive/updates/esp-now-peer-to-peer-communication
CC-MAIN-2020-45
refinedweb
703
52.9
Area of Triangle: Heron's formula Sign up for FREE 1 month of Kindle and read all our books for free. Get FREE domain for 1st year and build your brand new site Reading time: 30 minutes | Coding time: 15 minutes In this article, we, Heron's formula named after Hero of Alexandria. Different approaches There are 7 common ways in which the area of a triangle is calculated. Following are some of the ways: Consider the following image demonstrating the various measurements of a triangle: - Area = (a * h) / 2 - Area = (a * b * sin(C)) / 2 - Area = (a2 * sin(B) * sin(C)) / (2 * sin(B + C)) Consider the following image demonstrating the various measurements of a triangle: - Area = f * (g / 2) - v * (w / 2) - Area = abs(((xB * yA) - (xA * yB))+((xC * yB) - (xB * yC)) + ((xA * yC) - (xC * yA))) / 2 Consider the following image demonstrating the various measurements of a triangle: If the vertices are at integer points on a grid of points then area of triangle is given by : Area = number of points inside triangle + half number of points on edge of triangle - 1 Using Heron's Formula. Formula where s is the semi-perimeter of the triangle. Algorithm - step 1: Accept the length of sides of triangle. - step 2: Let magnitude of sides of triangle be a, b, and c. Calculate the semi-perimeter of trinagle i.e : s Formula : s = (a + b + c) / 2 - step 3: To calculate Area of Triangle apply Hero's Formula : Formula : Area = sqrt( s * (s-a) * (s-b) * (s-c)) - step 4: Exit. Implementation #include <iostream> #include <cmath> class AreaOfTriangle { public: AreaOfTriangle(double a, double b, double c) : a_(a), b_(b), c_(c) { } double calculateArea(); private: double a_, b_, c_; }; double AreaOfTriangle::calculateArea() { /* * As magnitude of length of sides must be positive. * Given length of sides of triangle must follow the following result : * "Sum of any two sides of triangle must be smaller than the third side of triangle". */ if (a_ < 0 || b_ < 0 || c_ < 0 || a_+b_ <= c_ || a_+c_ <= b_ || b_+c_ <= a_) return 0.0; double s = (a_ + b_ + c_) / 2; //semi-perimeter of triangle return sqrt(s * (s - a_) * (s - b_) * (s - c_)); } int main() { double ta, tb, tc; std::cout << "\nEnter the length of side-1 : "; std::cin >> ta; std::cout << "\nEnter the length of side-2 : "; std::cin >> tb; std::cout << "\nEnter the length of side-3 : "; std::cin >> tc; AreaOfTriangle a(ta, tb, tc); if(a.calculateArea() == 0.0) std::cout << "\nInvalid Triangle"; else std::cout << "\nArea of Triangle : " << a.calculateArea() << " square units."; } Example Input : a = 5.0, b = 7.0, c = 9.0 step 1 : calculate semi-perimeter, s = (a + b + c)/2 s = (5.0 + 7.0 + 9.0) / 2 = (21) / 2 = 10.5 step 2 : calculate Area of triangle = (s * (s - a_) * (s - b_) * (s - c_) = 10.5 * (10.5 - 5.0) * (10.5 - 7.0) * (10.5 - 9.0) = 303.1875 = sqrt(303.1875) = 17.412280149 Output : Area of Triangle : 17.412280149 square units. Complexity The time and space complexity to calculate Area of Triangle are: Assuming arithmetic operations (like multiplication and square root) take constant time O(1): - Worst case time complexity: Θ(1) - Average case time complexity: Θ(1)) - Best case time complexity: Θ(1) - Space complexity: Θ(1) Actual time complexity: Considering numeric input N and multiplication takes O((log(N))^2) time: - Worst case time complexity: Θ((log(N))^2) - Average case time complexity: Θ((log(N))^2) - Best case time complexity: Θ((log(N))^2) - Space complexity: Θ(1) A number N has log(N) digits and the most common way of multiplication takes O(D^2) time complexity where D is the number of digits = log N. Square root is usually calculated using Newton's method which takes the same complexity as that of the multiplication algorithm used. Hence, the overall time complexity of the Heron's method is O((log(N))^2) Further Reading - Area of Polygon
https://iq.opengenus.org/herons-formula/
CC-MAIN-2021-17
refinedweb
663
57.61
WebLogic Server Frequently Asked Questions JMS Programming Practices Q. What makes WebLogic JMS unique? A. There are numerous features that make WebLogic JMS unique. For a complete listing, see "Introduction to WebLogic JMS" in Programming WebLogic JMS. Q. Where can I learn more about WebLogic JMS? A. The following links provide more information about WebLogic JMS: Q. Is there a C/C++ interface to WebLogic JMS? A. Yes, there is a JMS C client available on the dev2dev Utility and Tools page, which has a downloadable jmscapi.zip file that includes all the necessary files, as well as documentation and samples. This is not a supported product of BEA. However, if you have questions about this API you can post them to WebLogic JMS "weblogic.developer.interest.jms" newsgroup available on the BEA Newsgroup server. Q. Is there a smaller version of the weblogic.jar file for supporting clients? A. Yes. WebLogic Server 8.1 provides a true J2EE application client. The WebLogic Server application client is provided as a standard client and a JMS client, packaged as two separate jar files— wlclient.jar and wljmsclient.jar—in the /server/lib subdirectory of the WebLogic Server installation directory. Each jar is about 400 KB. Q. How do I start WebLogic Server and configure JMS? A. Refer to "Starting WebLogic Server and Configuring JMS" in the Programming WebLogic JMS for detailed instructions on starting WebLogic Server, accessing the Administration Console, and configuring a basic Weblogic JMS implementation. Q. How do I configure WebLogic JMS security? A. A security policy is created when you define an association between a WebLogic resource and a user, group, or role. A WebLogic resource has no protection until you assign it a security policy. You can assign a security policy to any WebLogic JMS destination using the administration console. Using the navigation tree, access your JMS destinations, which are under Services send(), receive(), and browse() operations on the destination using the list box labeled Methods. For instructions on how to set up security for all WebLogic Server resources, see "Securing WebLogic Resources". Q. Can I still use the default connection factories supported in WebLogic JMS 5.1? A. Yes. For detailed information about using 5.1 connection factories in later versions of WebLogic JMS, see "Porting WebLogic JMS Applications" in Programming WebLogic JMS. Q. Why does JMSSession.createTopic or JMSSession.createQueue fail to create a destination in WebLogic JMS 8.1? (It worked in version 5.1?) A. For a detailed explanation of this issue, refer to the JMS FAQ in the version 6.1 Frequently Asked Questions. Q. How do I programmatically get a list of queues or topics? A. There are JMS Helper methods that allow you to locate JMS runtime and configuration JMX MBeans. There are also methods for dynamically creating and deleting JMS queue and topic destinations, as described in the JMS Helper Method Javadoc. Q. How do I use a temporary destination? A. You must create a template on every JMSServer where you want to be able to create temporary destinations. You can specify multiple JMSServer entries to support a Temporary Template and the system will load balance among those JMSServers to set up the temporary destination. See How do I start WebLogic Server. For more information about using temporary destinations, see "Using Temporary Destinations" in Programming WebLogic JMS. Q. How do I use MBeans to print runtime statistics? A. BEA's dev2dev Web site contains a "JMS Statistics View" program to print JMS statistics based on run-time MBeans. Also, there are JMS Helper methods that allow you to access run-time statistics for JMS connection, destination, consumer, and producer MBeans, as described in the JMS Helper Method Javadoc. Q. Can two JMS servers share the same persistent store? A. No. Each JMS server must have its own unique persistent store. Two file-based JMS persistent stores may share the same directory, but their messages will be stored in different files. In this case, the filenames will contain different prefixes. Two JDBC-based JMS persistent stores may share the same database, but they must be configured to use a different Prefix Name which will be prepended to the database tables. For more information on configuring the JDBC Prefix Name, see "Using Prefixes With JMS JDBC Stores" in the Administration Console Online Help. If they are configured with the same Prefix Name, persistent messages will be corrupted and/or lost. Q. Which types of JDBC databases does WebLogic JMS support? A. The JMS database can be any database that is accessible through a JDBC driver. For a list of drivers that WebLogic JMS detects, see "JMS JDBC Store Tasks" in the Administration Console Online Help. Q. How do I use a third-party JDBC driver with WebLogic JMS? A. If your JDBC driver is not included in the list of drivers in the question about JDBC databases supported by WebLogic JMS, then the tables required by JMS must be created manually. Follow the procedures in JDBC Database Utility in Programming WebLogic JMS to manually create the database tables for the JDBC store. Note: WebLogic Server only guarantees support for the JDBC drivers listed in "JMS JDBC Stores Tasks" in the Administration Console Online Help. Support for any other JDBC driver is not guaranteed. Another option is to consider using a JMS file store instead of a JMS JDBC store. File stores are easier to configure and may provide significantly better performance. Q. What if my JDBC database becomes corrupt? A. The procedures for removing and regenerating the JDBC store tables or creating the database tables manually are described in detail in JDBC Database Utility in Programming WebLogic JMS. Q. How do I use persistence? A. Use the following guidelines: config.xmlfile should contain a line of the form Store="<YOUR-STORE-NAME>" Note that if JMS boots without a store configured, it is assumed the customer did not want one, and persistent messages are silently downgraded to non-persistent (as specified for JMS 1.0.2b). QueueSender.send(msg, deliveryMode, ...) QueueSender.setDeliveryMode(deliveryMode) set DefaultDeliveryMode mode on connection factory in the config.xml file to persistent (the QueueSender.setDeliver/send overrides this value). Similarly, for topics, you would set this via the TopicPublisher. config.xmlfile. See the question, How do I start WebLogic Server and configure JMS? for a description of how to configure JMS. Q. How does a file store compare with a JDBC store? A. The are a number of similarities and differences between file stores and JDBC stores. For a complete listing, see "JMS Stores Tasks" in the Administration Console Online Help. Q. How important is it to keep the system clocks synchronized among server instances hosting distributed destination members and their connection factories? A. It is very important when using distributed topics with non-durable subscribers. This is because if the clocks between the servers become too far askew, there is a possibility that messages will not be delivered. Here's how this could happen: both the connection factory for the distributed topic and the distributed topic members will use their local system clock to see if a consumer is created after a message is published. Messages published to topics before consumers are created are not visible to consumers. There is always a race in any topic when the message is published before the consumer is created. Distributed topics widen this race when the system clocks on the server instances hosting the connection factory or the distributed topic members are not in sync. For example, if your application creates short-lived, non-durable topic consumers, and a consumer is listening through a connection factory on ServerA, but the message is published to distributed topic member on ServerB, and the clocks from ServerA and ServerB are out of sync (more than the life of the topic consumer you have created), then that consumer will not receive the message sent due to the difference in the system clocks. Q. Why am I getting "out of memory" errors? A. The byte and message maximum values are quotas - not flow control. Message quotas prevent a WebLogic JMS server from filling up with messages and possibly running out of memory, causing unexpected results. Unless the "Blocking Sends" feature has been implemented, when you reach your quota, JMS prevents further sends with a ResourceAllocationException (rather than blocking). You can set quotas on individual destinations or on a server as a whole. For more information on configuring the "Blocking Sends" feature, see "Avoiding Quota Exceptions by Blocking Message Producers" in the Administration Console Online Help. The thresholds are also not flow control - though they would be better suited to that application than the quotas. The thresholds are simply settings that when exceeded cause a message to be logged to the console to let you know that you are falling behind. WebLogic JMS also has a flow control feature that enables a JMS server or destination to slow down message producers when it is becoming overloaded. Specifically, when a JMS server/destination exceeds its specified bytes or messages thresholds, it instructs producers to limit their message flow. For more information, see "Controlling the Flow of Messages on JMS Servers and Destinations" in the Administration Console Online Help. Note: The messages maximum setting on a connection factory is not a quota. This specifies the maximum numbers of outstanding messages that can exist after they have been pushed from the server but before an asynchronous consumer has seen them; it defaults to a value of 10. Q. What is the value of clustering for WebLogic JMS? A. In version 6.x, you could establish cluster-wide, transparent access to destinations from any server in the cluster by configuring multiple connection factories and using targets to assign them to WebLogic Servers, as described in "Configuring WebLogic JMS Clustering" in the Programming WebLogic JMS. Each connection factory can be deployed on multiple WebLogic Servers, serving as connection concentrators. You could configure multiple JMS servers on the various nodes in the cluster—as long as the servers are uniquely named—and can then assign destinations to the various JMS servers. For WebLogic JMS 7.0 or later, you can also configure multiple destinations as part of a single distributed destination set within a cluster. Producers and consumers are able to send and receive through a distributed destination. In the event of a single server failure within the cluster, WebLogic JMS then distributes the load across all available physical destinations within the distributed destination. For more information, see "Distributed Destination Tasks" in the Administration Console Online Help. WebLogic JMS also JMS Migratable Targets" in the Programming WebLogic JMS. You can also refer to the "WebLogic JMS Performance Guide" white paper ( WeblogicJMSPerformanceGuide.zip) on the JMS topic page for more information. Q. How can I control on which WebLogic Server(s) my application will run? A. A system administrator can specify on which WebLogic Server(s) applications will run by specifying targets when configuring connection factories. Each connection factory can be deployed on multiple WebLogic servers. For more information on configuring connection factories or using the default connection factories, see "WebLogic JMS Fundamentals" in the Programming WebLogic JMS. Q. How do I perform a manual fail-over? A. The procedures for recovering from a WebLogic Server failure, and performing a manual failover, including programming considerations, are described in "Recovering From a WebLogic Server Failure" in Programming WebLogic JMS. Q. Does the WebLogic JMS server find out about closed or lost connections, crashes, and other problems and does it recover from them? A. Yes, but how it does this depends on whether a Java client crashes or WebLogic Server crashes, as follows: javax.jms.ExceptionListener.onException(...)will be called (if javax.jms.JMSConnection.setExceptionListeneris set) with a LostServerException, which extends JMSException. javax.jms.ExceptionListener.onException(...)will be called (if weblogic.jms.extensions.WLSession.setExceptionListeneris set) with a ConsumerClosedException, which extends JMSException. Q. How does an application know if an application server goes down? A. There are two exception listeners that you can register. Sun Microsystems' JMS specification defines C onnection. Q. Do I need to use the WLS T3 protocol? A. J2EE is all about making the interfaces standard. WebLogic's implementation of the RMI specification uses a proprietary wire-protocol known as T3. Sun's reference implementation of RMI uses a proprietary protocol called JRMP. The fact is that WebLogic developed T3 because they needed a scalable, efficient protocol for building enterprise-class distributed object systems with Java. While T3 is specific to WebLogic, your application code does not need to know anything about T3 so you should not worry about this. Externalize the "WebLogic-specific strings" ( PROVIDER_URL, INITIAL_CONTEXT_FACTORY, etc.) to a properties file (or somewhere) and you can make your code completely portable to where you only need change these in the properties file to get your code to run on another J2EE application server. Note: As of release 8.1, WebLogic JMS also supports the IIOP protocol. In general, this is slower than the T3 protocol. Q. How do I use HTTP tunneling? A. If you want to use HTTP tunneling (wrap every message in HTTP to get through a firewall), you need to add TunnelingEnabled="true" into your <Server> definition in the config.xml file or check the appropriate box on the console. Then use a URL like instead of t3://localhost:7001 for Context.PROVIDER_URL when getting your InitialContext. If you want HTTP tunneling with SSL, use (where https uses HTTP tunneling with SSL and 7002 is the secure port that you configured). You will pay a performance penalty for doing this, so only use tunneling it if you really need to (i.e., need to go through a firewall). Q. Does WebLogic JMS support SSL? A. Yes, SSL is supported in the WebLogic JMS implementation. It is automatically used based on using a URL starting with "t3s:" instead of "t3:" when looking up the initial JNDI context. Q. How do I integrate non-WebLogic JMS providers with WLS? A. Refer to "Simple Access to Remote or Foreign JMS Providers" in the Administration Console Online Help and the "Using Foreign JMS Providers with WebLogic Server" white paper ( jmsproviders.pdf) on the JMS topic page, for a discussion on integrating MQ Series, IBus MessageServer, Fiorano, and SonicMQ. Q. How do two-phase or global transactions relate to WebLogic JMS? A. A two-phase or global transaction allows multiple resource managers (including EJBs, databases, and JMS servers) to participate in a single transaction. For example, a client can use a two-phase transaction to send a message from a queue on one JMS server (server A) to a queue on another JMS server (server B). Each server has a unique persistent store. When the transaction is committed, the message is made visible on server B. If the transaction rolls back, the message is put back on the queue on server A. Note: If both queues happen to be on the same JMS server, then a one-phase transaction is used. Q. Why is my WebLogic JMS work not part of a user transaction (that is, called within a transaction but not rolled back appropriately)? How do I track down transaction problems? A. Usually this problem is caused by explicitly using a transacted session which ignores the external, global transaction by design (a JMS specification requirement). A transacted JMS session always has its own inner transaction. It is not affected by any transaction context that the caller may have. It may also be caused by using a connection factory that is configured with the XAConnectionFactoryEnabled flag set to false. import javax.transaction.* import weblogic.transaction.*; and adding the following lines (i.e., just after the begin and just before every operation). Transaction tran = TxHelper.getTransaction(); System.out.println(tran); System.out.println(TxHelper.status2String(tran.getStatus())); This should give a clear idea of when new transactions are starting and when infection is occurring. weblogic.jms.ConnectionFactory disables user transactions so don't use this one for the case where user transactions are desired; javax.jms.QueueConnectionFactory and javax.jms.TopicConnectionFactory enable user transactions. -Dweblogic.Debug.DebugJMSXA=true You should see trace statements like these in the log: XA ! XA(3163720,487900) <RM-isTransactional() ret=true> This can be used to ensure that JMS is infected with the transaction. Q. When do WebLogic JMS operations take place as part of a transaction context? A. When WebLogic JMS is used inside the server, JMS sessions may automatically be enlisted in the JTA transaction depending on the setting of various parameters. Prior to release 8.1, WebLogic JMS sessions would automatically be enlisted in the JTA transaction if either of the following two conditions were met: In WebLogic Server 8.1, it is only necessary to set the XAConnectionFactoryEnabled flag. The old flags are still supported for backward compatibility, however. When a WebLogic JMS connection factory is registered as a resource-reference inside an EJB, servlet, or JSP, and the connection factory is looked up out of the java:comp/env JNDI tree, then the EJB container checks to make sure that the appropriate flags are set for transaction enlistment. If the WebLogic JMS connection factory does not support automatic transaction enlistment, then the EJB container will throw an exception if a JMS session is used inside a transaction context. When used without a resource-reference however, such as in the case of an EJB that looks up a JMS connection factory directly, without using java:comp/env, then no checking takes place. If the JMS session is used outside a JTA transaction, then no enlistment takes place. The default connection factory, weblogic.jms.ConnectionFactory, does not support automatic transaction enlistment. If you desire this behavior, you must use the weblogic.jms.XAConnectionFactory factory. (The legacy connection factories javax.jms.QueueConnectionFactory and javax.jms.TopicConnectionFactory support automatic transaction enlistment as well.) For more information, see "Using JMS With EJBs and Servlets" in Programming WebLogic JMS. Q. How can an application do a JMS operation and have it succeed, independent of the result of the transaction? A. In order to do this properly, you must suspend the transaction. How you do this depends on the context in which you are using JMS: import javax.transaction.TransactionManager; TransactionManager tranManager= TxHelper.getTransactionManager(); Transaction saveTx = null; try { saveTx = tranManager.suspend(); ... do JMS work, it will not participate in transaction } finally { // must always resume suspended transactions! if (saveTx != null) tranManager.resume(saveTx); } javax.jms.QueueConnectionFactoryor javax.jms.TopicConnectionFactoryfactories, or if you define your own factory and set the UserTransactionsEnabled flag to True, the JMS session participates in the outer transaction, if one exists and the JMS session is not transacted.) Q. What happens if acknowledge() is called within a transaction? A. As per Sun Microsystems' JMS specification, when you are in a transaction, the acknowledgeMode is ignored. If acknowledge() is called within a transaction, it is ignored. Q. Why am I getting JDBC XA errors when using JMS in conjunction with JDBC calls? A. Whenever two resources (such as JMS and a database) participate in a transaction, the transaction becomes two-phase. The database driver you are using is not XA compatible and can't normally participate in a two-phase transaction. The solution is to either use an XA compatible driver, or to configure the JDBCTxDataSource value to set enableTwoPhaseCommit to true. The caveat for the latter is that this can lead to heuristic errors. If you don't want JMS to participate in the current transaction, see the question How can an application do a JMS operation and have it succeed, independent of the result of the transaction?. Q. Can I use a one-phase commit if my WebLogic JMS JDBC store is on the same database for which I am doing other database work? A. No. WebLogic JMS is its own resource manager. That is JMS itself implements XAResource and handles the transactions without depending on the database (even when the messages are stored in the database). That means whenever you are using JMS and a database (even if it is the same database as the JMS messages are stored) then it is 2PC. You may find it will aid performance if you ensure the connection pool used for the database work exists on the same server as the JMS queue—the transaction will still be two-phase, but it will be handled with less network overhead. Another performance boost might be achieved by using JMS file stores rather than JMS JDBC stores. Q. How do I integrate another vendor's XAResource with WLS to get JTA transactions with another resource manager? A. In most cases WebLogic JMS will do this for you. For more information, see the "Using Foreign JMS Providers With WebLogic Server" white paper (jmsproviders.pdf) on the JMS topic page. Q. Why do I get an exception when I start up WebLogic JMS using an XA driver or with a TX data source? A. You cannot use a TX data source with JMS. JMS must use a JDBC connection pool that uses a non-XA resource driver (you can't use an XA driver or a JTS driver). Do not set the enableTwoPhaseCommit option. JMS does the XA support above the JDBC driver. Q. Is WL JMS XAResource compliant? A. Yes. WebLogic Server 6.1 or later fully implements the XAConnection, XAConnectionFactory, XAQueueConnection, XAQueueConnectionFactory, XAQueueSession, XASession, XATopicConnection, XATopicConnectionFactory, and XATopicSession methods. These methods are defined as optional in Sun Microsystems' JMS specification and are not part of the XAResource interface. Note: These interfaces are not needed since WebLogic JMS automatically registers itself with the WebLogic transaction monitor. Q. Why can't I receive a response to a message that I send within a transaction? A. If you are using container-managed transactions, the original message sent from the EJB will never be sent. Here is what is happening. The solution is to either use bean-managed transactions, or to break the send and receive into two separate methods. Q. What happens to a message that is rolled back or recovered? A. For more information about what occurs when a message is rolled back or recovered, refer to "Managing Rolled Back, Recovered, Redelivered, or Expired Messages" in Programming WebLogic JMS. Q. Is it possible to set aside a message and acknowledge it later? A. There are no special primitives for doing this. Here are two possible solutions. One approach is to use multiple sessions as in the following: while (true) { Create a session, subscribe to one message on durable subscription Save session reference in memory To acknowledge the message, find the session reference and call acknowledge() on it. } Another solution is to use transactions and suspend the work as follows: start transaction while(true) { message = receive(); if (message is one that I can handle) process the message commit } else { suspend transaction put transaction aside with message start transaction } } To "acknowledge" the message: resume user transaction commit To "recover" the message: resume user transaction rollback Each time you suspend, you need to push the transaction onto a stack or list possibly with the message so you can process it or roll it back later. This solution is high overhead in that there can be a large build up of outstanding transactions. Note that transactions have timeouts and it may rollback on its own, which means you can get the message again (in a different transaction). Note also that there are some practical limits on the number of transactions you should leave outstanding. The default limit is something like 10000. Eventually you want to go back to your stack/list and commit/rollback the transactions. Note that transaction references ( javax.transaction.Transaction) are not Serializable. Q. How should I use sorted queues or topics? A. Destinations are sorted as FIFO (first-in, first-out) by default; therefore, destination keys are used to define an alternate sort order for a specific destination. Destination keys can be message header or property fields. For a list of valid message header and property fields, refer to the "Message" section in Programming WebLogic JMS. Destinations can be sorted in ascending or descending order based on the destination key. A destination is considered to be FIFO if a destination key is defined as ascending for the JMSMessageID message header field, and LIFO (last-in, first-out) if defined as descending. The key defined for the JMSMessageID header field, if specified, must be the last key defined in the list of keys. You can define multiple destination keys to sort a destination. To create a destination key, use the Destination Keys node in the Administration Console. For more information, refer to "Destination Key Tasks" in the Administration Console Online Help. Q. How do I deal with a listener that doesn't keep up with messages being sent? A. Consider using the asynchronous pipeline for your message listeners to improve performance, as described in the "Asynchronous Message Pipeline" section of Programming WebLogic JMS. Q. How do I get a thread dump to help track down a problem? A. Ways to get a thread dump: setEnvscript in WL_HOME \server\bin): java weblogic.Admin -url t3://localhost:7001 THREAD_DUMP Ctrl+Break. kill -3. Q. Do client identifiers need to be unique? A. Yes, durable subscribers require unique client identifiers. For more information on configuring durable subscribers using the connection factory's Client ID attribute, or by programming your application to set a client ID in its connection (by calling the setClientID() connection method), see "Setting Up Durable Subscribers" in Programming WebLogic JMS. Q. How do I manage a queue to view and delete specific messages? A. Write a program that uses a QueueBrowser. Then delete specific messages by using a QueueReceiver with a selector with the message identifier, as shown in the following example: String selector = "JMSMessageID = '" + message.getMessageID() + " '"; Keep in mind that the queue browser is a not a "live" view of the queue. It is a snap-shot. Q. In what order are messages delivered to a consumer? A. Order is maintained between any producer and consumer for like delivery mode, sort order, and selector in the absence of a rollback or recover. There are no guarantees of order when multiple producers send to a single consumer or multiple consumers receive from multiple producers. Order is generally maintained between a producer and a consumer. However, non-persistent messages can get ahead of persistent messages of a higher sort order (i.e., higher priority), can move ahead of each other and a recover or rollback puts messages that were already received back into the queue/topic, which affects order. Most messaging systems (including WebLogic JMS) maintain order between a producer and a destination and then order between the destination and the consumer. So, once things arrive at the destination, the order does not change. Finally, the asynchronous pipeline that is supported in WebLogic JMS affects the ordering. By default there can be as many as ten outstanding messages pushed out from the server to an asynchronous client that have not been seen by the client yet. If the asynchronous consumer is "caught" up, these messages will not be sorted. Destination sorting does not occur in the pipeline. If a destination is sorted by priority, and a new message comes in of higher priority than those messages already in the pipeline, it will not leap ahead in the pipeline, it will become first in the destination. The size of the pipeline is configurable; see the MessagesMaximum setting on the connection factory used. If you want real priority sorting, change the maximum number of messages on the factory to one. For more information, see the "Asynchronous Message Pipeline" section of Programming WebLogic JMS. Q. How do I ensure message ordering even in the event of rollbacks and recoveries? A. In WebLogic JMS 8.1 message ordering can be maintained to single consumers on a queue or topic subscription - even in the event of rollbacks and recoveries, as described in "Ordered Redelivery of Messages" in Programming WebLogic JMS. Q. Is it possible to have multiple queue receivers listening on the same queue? A. Yes, although the JMS specification does not define the behavior here. Q. Is there a way to make a queue such that if one application has one object as listener on that queue, no other application can listen to the messages on that queue? A. No. An alternative is to create a topic with a single durable subscription because a durable subscription may only have one consumer associated with it. The only drawback is that selectors would no longer work the same as they do with queues. Changing the selector on a durable subscription "resets" the subscription as per Sun Microsystems' JMS specification, causing all messages currently in the subscription to be deleted. Note: If you configure a connection factory that has its Client ID set, this limits the connection factory to one client and may serve the purpose. Q. Why doesn't setting values work using javax.jms.Message.setJMSPriority, DeliveryMode, Destination, TimeStamp or Expiration? A. These methods are for vendor use only. The message values are overwritten on each send/publish. You should use the equivalent methods on the MessageProducer, QueueSender, or TopicPublisher to set these values (i.e., setJMSPriority, setDeliveryMode, setTimeToLive). Check to see that these values are not being overridden by the optional template configuration override values. Q. What care must be taken when multi-threading WebLogic JMS clients? A. The rules for multi-threading are described in section 2.8 of the JMS specification, with additional language in sections 4.4.6 on session usage, 4.4.9 on using multiple sessions, and 4.4.17 on concurrent message delivery. In a nutshell, it states that JMS sessions are single-threaded. Consequently, if multiple threads simultaneously access a session or one of its consumers or producers the resulting behavior is undefined. In addition, if multiple asynchronous consumers exist on a session, messages will be delivered to them in series and not in parallel. To take advantage of multiple threads with JMS, use multiple sessions. For example, to allow parallel synchronous receive requests, design the application so that only one consumer may be active per session and use multiple sessions. Q. How should an application be set up to subscribe to multiple topics? A. If you want to listen to N topics, using N subscribers and N sessions gives you concurrency up to N simultaneous threads of execution provided you have that many threads to work with. N subscribers and 1 session serializes all subscribers through that one session. If the load is heavy they may not be able to keep up without the extra threads. Also, if you are using CLIENT_ACKNOWLEDGE, N sessions gives you N separate message streams that can be individually recovered. Having 1 session crosses the streams giving you less control. As of version 6.x or later, WebLogic JMS on the server side efficiently uses a small, fixed number of threads independent of how many client sessions there are. Q. How should I use blocking and asynchronous receive() calls? A. The synchronous receive() method blocks until a message is produced, the timeout value, if specified, elapses or the application is closed. We strongly recommend that you avoid using blocking receive() calls on the server side because a synchronous receive() call consumes resources for the entire duration that the call is blocked. When methods are received asynchronously, the application is notified using a message listener only when a message has been produced, so no resources are consumed waiting for a message. Q. What precautions should I take when I use blocking receive() calls? A. If your application design requires messages to be received synchronously, we recommend using one of the following methods listed in order of preference: receive()method and set it to the minimum value greater than zero, that is allowed by the application to avoid consuming threads that are waiting for a response from the server.. receive()calls. Q. What is the NO_ACKNOWLEDGE acknowledge mode used for?. Q. When should I use multicast subscribers? A. Multicasting enables the delivery of messages to a select group of hosts that subsequently forwards the messages to multicast subscribers. The benefits of multicasting include:. Q. When should I use server session pools and connection consumers? A. WebLogic JMS implements an optional JMS facility for defining a server-managed pool of server sessions. However, session pools are now used rarely, as they are not a required part of the J2EE specification, do not support JTA user transactions, and are largely superseded by message-driven beans (MDBs), which are simpler, easier to manage, and more capable. For a detailed discussion on this topic, see the "MDBs vs. ServerSessionPools" section in the "WebLogic JMS Performance Guide" white paper ( WeblogicJMSPerformanceGuide.zip) on the JMS topic page. Q. How do I issue the close() method within an onMessage() method call and what are the semantics of the close() method? A. If you wish to issue the close() method within an onMessage() method call, the system administrator must select the Allow Close In OnMessage close() method within an onMessage() method call, the call will hang. check box when configuring the connection factory. For more information, see "JMS Connection Factory Tasks" in the Administration Console Online Help. If this check box is not selected and you issue thecheck box when configuring the connection factory. For more information, see "JMS Connection Factory Tasks" in the Administration Console Online Help. If this check box is not selected and you issue the The session or connection close() method performs the following steps to execute an orderly shutdown: close()method is being called).. When you close a session, all associated producers and consumers are also closed. For more information about the impact of the close() method for each object, see the appropriate javax.jms javadoc. Q. How do I publish an XML message? Q. How do I use WebLogic JMS in an applet? A. For detailed instructions and examples on how to accomplish this, see "Using BEA WebLogic JMS with Applets" on BEA's JMS topic page. Q. How do I use a startup class to initialize and later reference WebLogic JMS objects? A. This topic is covered in news://newsgroups.bea.com/3ad0d7f3@newsgroups.bea.com. The sample code does not cleanup properly at shutdown.) {} Load-on-start servlets can provide a nice solution to provide both initialization and cleanup. For more information, refer to What is the standard way to create threads, do initialization, etc. within the application server?. Q. Is it possible to send or receive a message from within a message listener? A. Yes. You can send to or receive from any queue or topic from within in a message listener. Outside of a MDB, you can do this by using the same Connection or Session that the onMessage() is part of. When you create your message listener, you pass a session into your constructor. Then you have access to the session in your onMessage() method and are able to make synchronous - not asynchronous - calls from within the onMessage() method. Do not use another Session that is servicing another onMessage(), because that would multi-thread the Session, and Sessions do not support multi-threading. However, when using this technique outside a MDB, there is no way to guarantee that the receipt of the message by the MessageListener, and the send of the new message, happen as part of the same transaction. So, there can be duplicates or even lost messages. For example: publish()and the acknowledge fails for whatever reason (network or server failure), then you will see the message again and will end up publishing twice (possible duplicate semantics). You can try to keep track of sequence numbers to detect duplicates, but this is not easy. publish(), you get at-most-once transaction semantics. If the publish()fails, you don't know if the failure occurred before or after the message reached the server. If you require exactly-once transactional semantics using onMessage(), then you must use transactional MDBs. In this case, the onMessage() method for a transactional MDB starts the transaction and includes the WebLogic JMS message received within that transaction. Then, you must ensure that the send or publish of the new message is part of the same transaction as the receipt of the message. In WebLogic Server 8.1, you can guarantee that this happens by using a connection factory that you get from a resource-reference defined for the MDB. For detail instructions on how to accomplish this, see "Using JMS With EJBs and Servlets" in Programming WebLogic JMS. By using a resource-reference, you also get automatic pooling of the JMS Connection, Session, and MessageProducer objects, and the transaction enlistment will happen automatically regardless of whether you use WebLogic JMS or another JMS provider, as long as the JMS provider supports XA. In earlier versions of the product, WebLogic JMS would automatically enlist itself with the current transaction if the UserTransactionsEnabled or XAServerEnabled flag was set on the connection factory. However, prior to release 8.1, the server will not pool any JMS objects or automatically enlist a foreign JMS provider in the transaction. In these earlier versions, you may want to cache JMS objects yourself. For more information, see How do I create a producer pool?. Q. How do I create a producer pool? A. For instructions on how to accomplish this, see "Using JMS With EJBs and Servlets" in Programming WebLogic JMS. For a detailed code sample, see the "Appendix A: Producer Pool Example" section in the "WebLogic JMS Performance Guide" white paper ( WeblogicJMSPerformanceGuide.zip) on the JMS topic page. Q. What are pending messages in the console? A. Pending means the message could have been:. Q. How do I use a less than or greater than on a message selector in ejb-jar.xml? A. Enclose the selector in a CDATA section. That will prevent the XML parser from thinking that less than or greater than is a tag. <jms-message-selector> <![CDATA[ JMSXAppID <> 'user' ]]> </jms-message-selector> Q. Can I use another vendor's destination with a WebLogic JMS API? A. WebLogic Server JMS does not know what to do with foreign destinations that it runs into. This issue has been discussed with Sun and the specification does not clearly define destinations well enough for vendors to interoperate at that level. They agree that it is sufficient not to handle foreign destinations preferably in such a way that sending/receiving still work. For WebLogic JMS will ignore it (set it to null). Q. What is the standard way to create threads, do initialization, etc. within the application server? A.. Q. Why do I get a JNDI problem when I name a Topic A.B and a second Topic A.B.C? A. This is a JNDI implementation issue. JNDI uses the dots to build a directory-like structure. A given element cannot be both a node and a leaf in the tree. In this example, B is used as a leaf off of A, but then is used as a node off of which C is a leaf. Q. What should an XPATH selector look like? A. For instructions and samples about using XPATH syntax with WebLogic JMS, see "Defining XML Message Selectors Using the XML Selector Method" in Programming WebLogic JMS. Q. How do I handle request/response using WebLogic JMS? A. There are several approaches to handling request/response processing with JMS. // create temporary queue for receiving answer qrequestor = new QueueRequestor(qsession, queue); TextMessage msg = qsession.createTextMessage(); TextMessage reply = (TextMessage) qrequestor.request(msg); WeblogicJMSPerformanceGuide.zip) on the JMS topic page. Q. Is it okay to add new sessions and subscribers to a Queue or Topic Connection once it has been started? A. Yes, with one caveat. You may not add new subscribers/consumers to a session if it already has active async consumers. Sessions must only be accessed single-threaded as per the JMS Specification. If you feel you need to do this, create a new Session and add it to that one instead. You can add receivers to a session that is part of a started connection. However, a receiver in itself is not asynchronous. You need a listener to make it asynchronous. The first creation of a receiver is always safe. If you then add a listener for that first receiver, you have to worry for any future receivers in that same session. You can create new sessions and the first receiver for that session with no worries. Once you want to create a second receiver in a session, if the first receiver has a MessageListener, you have to take care to make sure there are no other threads of execution in that session. You can do this by stopping the connection or actually creating your receiver from the onMessage routine of the first receiver. Q. What can I do when I get java.lang.OutOfMemoryError because producers are faster than consumers? A. Quotas can be used to help this situation. Your sender will then receive ResourceAllocationExceptions and the server will stay up. In release 8.1 or later, senders can be configured to block waiting for space rather than receive ResourceAllocationExceptions. For more information, see "Avoiding Quota Exceptions by Blocking Message Producers" in the Administration Console Online Help. You can also use the Message Paging feature, which saves memory by swapping messages out from virtual memory to a dedicate paging store when message loads reach a specified threshold. JMS message paging saves memory for both persistent and non-persistent messages, as even persistent messages cache their data in memory. For more information, see "Paging Out Messages To Free Up Memory" in the Administration Console Online Help. Q. How should connections and sessions be allocated? A. Think of a connection as a single physical connection (a TCP/IP link). A session is a means for producing and consuming an ordered set of messages. Creating a connection is generally expensive. Creating a session is less expensive. Generally people use one connection and share across all the threads with each thread having its own session. If you have thread groups and need to start/stop/close the resources for a given group, one connection per group is good. A group can have exactly one thread. Q. Is there a way to dynamically change an existing selector for a TopicConsumer using the setMessageSelecter(String)? A. No. Once you instantiate the consumer the selector is fixed at the time that the consumer is created. Changing the selector is like removing the current consumer, removing all associated messages and then creating a new one. Q. How can I avoid asynchronous message deadlocks? A. Due to a limitation in the JMS. Q. What are the advantages of message-driven beans? A. The message-driven bean is a stateless component that is invoked by the EJB container as a result of receiving messages from a JMS queue or topic. It then performs business logic based on the message contents, effectually freeing you from any JMS configuration and reconnection chores. The message-driven bean model allows EJB developers to work with a familiar framework and set of tools, and also provides access to the additional support provided by the container. The goal of the message-driven bean model is to assure that developing an EJB that is asynchronously invoked to handle the processing of incoming JMS messages is as easy as developing the same functionality in any other JMS MessageListener. One of the main advantages of using message-driven beans in place of the standard JMS MessageListener is that a JTA transaction can be started for you automatically and the received message will be part of that transaction. In this case, other operations can be infected with the same JTA transaction such as database operations. This is the only way to infect a message from an asynchronous consumer and another JTA operation with the same transaction. For more information on message-driven beans, see "Designing Message-Driven Beans" in Programming WebLogic Enterprise JavaBeans. Q. How does concurrency work for message-driven beans? A. For a queue, multiple JMS Sessions are created on each server instance where the MDB is deployed. The number of sessions created is never greater than the max-beans-in-free-pool setting in the MDB's deployment descriptor. JMS then delivers messages in parallel to the MDB instances as it would for any other kind of message listener. If a MDB is deployed to multiple servers in a cluster, Sessions are created for each MDB instance on each server. For a topic, however, one topic consumer is used to pass out messages to multiple threads to get concurrency, while producing only a single copy of each message. If multiple MDBs are deployed to listen on the same topic, then each MDB will receive a copy of every message. Therefore, when a MDB is deployed to multiple servers and it listens to a topic, each server will receive its own copy of each message. So, if you want a message to be processed by exactly one MDB, you should use a queue. Q. Can an MDB be a message producer or both a producer and consumer? A. of this in the question Is it possible to send or receive a message from within a message listener?. For more information, see "Using JMS With EJBs and Servlets" in Programming WebLogic JMS. Q. If an MDB uses a durable subscription, will messages be accumulated if the MDB is not deployed? A. The durable subscription is created when the MDB is deployed for the first time. The durable subscription is not deleted when the MDB is undeployed or deleted. This means that once the MDB has been deployed once, messages will continue to accumulate on the subscription, even if the MDB is undeployed or deleted. So, when an MDB is retired from service, you should delete the durable subscription to prevent a build-up of messages. You can use the administration console to do this, or you can write a standalone program using the Java API that calls unsubscribe on the durable subscription. Q. How do I use non-WebLogic JMS provider destinations to drive MDBs? A. See the "Using Foreign JMS Providers with WebLogic Server" white paper ( jmsproviders.pdf) on the JMS topic page. Q. Can you use a foreign JMS provider to drive an MDB transactionally? A. Yes. In WebLogic Server 7.0 or later, you can deploy an MDB that supports container-managed transactions against a foreign JMS provider. If the MDB is configured with a "transaction-type" attribute of "Container" and a "trans-attribute" of "Required", then WLS will use XA to automatically enlist the foreign JMS provider in a transaction. (See the next question for an example of an MDB that uses container-managed transactions.) If the foreign JMS provider does not support XA, then you cannot deploy an MDB that supports container-managed transactions with that provider. Furthermore, if the JMS provider does support XA, you must ensure that the JMS connection factory that you specify in the weblogic-ejb-jar.xml file supports XA—each JMS provider has a different way to specify this. See the "Using Foreign JMS Providers with WebLogic Server" white paper ( jmsproviders.pdf) on the JMS topic page for an example of how to configure an MDB to use a foreign provider. Q. How do I roll back a transaction within an MDB? A. To roll back(); } Q. How do server session pools and message driven beans compare? A. For a detailed discussion on this topic, see the "MDBs vs. ServerSessionPools" section in the "WebLogic JMS Performance Guide" white paper ( WeblogicJMSPerformanceGuide.zip) on the JMS topic page.
http://docs.oracle.com/cd/E13222_01/wls/docs81/faq/jms.html
CC-MAIN-2016-40
refinedweb
7,979
55.54
If you are like me, you find that flat-file processing can be pretty dry. Considering what Apache Camel does, its name is very fitting. While there are plenty of reasons for the name, it definitely makes sense that Apache Camel does a lot of lugging things around for you. This article will set up a basic Spring Boot app that incorporates Apache Camel to move some sample files around. Apache Camel This particular Apache offering is quite vast. From processing flat files, connecting to databases, and hooking up to SalesForce, Camel has a lot of handy components for you to use. To see what is available, check out. The basic idea here is to create what Camel calls a route. Routes can be defined as file drops to scheduled events or just simple recurring timers. There are a whole host of options on which to build a route. The next thing to understand is how messages are exchanged from route to route. For simplicity’s sake, we’ll just stick with the exchange. Think of the exchange as an object that has a bunch of fields for designating where it’s going, the body, a header, and a lot of other things. For our purposes, we will mostly be concerned with the body of the exchange. This is where our message will be found that we need to process. So let’s get started with a basic setup. Lace-Up Your Boots for Camel We’ll use Maven to set up our project. Setting up your pom.xml file, the most important things are pulling in the camel-core and camel-spring-boot-starter dependencies. Take note of the Camel “version” and the “rcversion” variables. Some of the things offered by the latest Camel are only release candidates but work well. You can see that it is just a plain-Jane Boot app other than that. <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <start-class>camel_starter.App</start-class> <java.version>1.8</java.version> <camel.version>3.0.0</camel.version> <camel.rcversion>3.0.0-RC3</camel.rcversion> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.apache.camel</groupId> <artifactId>camel-spring-boot-starter</artifactId> <version>${camel.rcversion}</version> </dependency> <dependency> <groupId>org.apache.camel</groupId> <artifactId>camel-core</artifactId> <version>${camel.version}</version> </dependency> </dependencies> Get That Camel Moving Create your first route by extending RouteBuilder. It will require you to override the configure() method. This is where all the dromedary magic happens. Do note that to get Boot to pick it up that you must add the @Component annotation to the class. @Component public class FileMoveRoute extends RouteBuilder { @Override public void configure() throws Exception { Tell The Camel What To Do The “from” line tells the Camel route what to do. In this case, it is listening to a folder for a dropped file. It doesn’t matter what the file is named or the type. We also are giving it a routeId with a unique string. There can only be one route with this ID. It will not start up properly if another exists. Lastly, we can log out a simple INFO message. from("") .routeId("uniqueRouteName") .log("Firing My First Route!") Which Way to Go? Now that we told the camel what to do, it has to decide what is next. We have created three options. - Checking to see if the file has the word “start” in the filename - Checking to see if the file has the word “edit” in the filename - Default failure .choice() .when(fileIsStart) .to("direct:GoToMyFileMover") .endChoice() .otherwise() .choice() .when(fileIsEdit) .to("direct:EditMyFileFirst") .endChoice() .otherwise() .to("direct:GoToMyFailureRoute"); Direct Routes Direct routes are just that! It will take your message directly to the “from” route with the same name. Pretty simple really. Hard for a camel to get lost! Explaining The “When” and Predicates A Camel predicate is a simple check returning a boolean to determine if you meet its criteria. Predicate fileIsStart = new Predicate(){ @Override public boolean matches(Exchange exchange) { File file = exchange.getIn().getBody(File.class); return file.getName().contains("start"); } }; Predicate fileIsEdit = new Predicate(){ @Override public boolean matches(Exchange exchange) { File file = exchange.getIn().getBody(File.class); return file.getName().contains("edit"); } }; Camel Directions First is our simple file mover. This route moves our dropped file over to another folder. Easy and simple, we’ve made it from start to finish. Our camel can rest. from("direct:GoToMyFileMover") .to("") .log("File Moved Successfully"); Second, we have an editing scenario. We simply write out a new file to an edit directory. We will give it a name. You can see how easy it is to set the body and see the output of our new file. We use the .process method in Camel to intercept the route and create a new file. We are overriding the process method of Processor to do so. You can create standalone processors and call them by passing them here, but for our purposes, we’ll not get into those weeds. We dropped off our packages along the way at an oasis. from("direct:EditMyFileFirst") .process(new Processor(){ @Override public void process(Exchange exchange) throws Exception { exchange.getIn().setBody("Edited file has been written!"); } }) .to("") .log("Edit File Created!"); Lastly, if our file doesn’t meet our criteria we log a message. “Send help” request goes back to the Camel company. from("direct:GoToMyFailureRoute") .log("Your File Didn't go anywhere, but was processed."); In all three scenarios, the file we send through is moved to a .camel subfolder. This gives a record of what the original file was and that it was processed. Camel Trip Over Well, we hope you enjoyed the short ride and see how easy it is to get started with Spring Boot & Apache Camel. Check out the starter project. Again, there are a vast amount of available components for connecting to all sorts of things. Check out the list and see what journeys you can set out on. Enjoy the ride!
https://keyholesoftware.com/2020/07/06/spring-boot-apache-camel-navigating-the-data-processing-desert/
CC-MAIN-2020-34
refinedweb
1,015
68.26
Hello guys, is there someone who were annoyed by this kind of problem? So, first of all I want you to notice that the feature class Roads has a POLYLINE geometry type, and there are no multipart features in it. import arcpy for i in arcpy.da.SearchCursor(r'C:\Users\...\Administrative_area.gdb\Roads', ["SHAPE@"]): print(i[0]) Normally, the output for this code will be something like this: And it works. Now the problem appears when I put this little piece of code in the main script: def get_near_data(self): with arcpy.da.SearchCursor(r'C:\Users\...\Administrative_area.gdb\Roads', ["SHAPE@"]) as reader: for f in reader: print(f[0]) And the output is not the same as in the first case. This is not geometry. I've noticed that if I change the path for feature class Roads to another feature class which has a polygon geometry type, it works just fine again, take a look: def get_near_data(self): with arcpy.da.SearchCursor(r"C:\Users\...\ArcGIS\Administrative_area.gdb\CountyBoundary", ["SHAPE@"]) as reader: for f in reader: print(f[0]) And the output is going to be like this: So, what is going on here? Why geometries of polyline feature classes aren't returned while geometries of polygons are?
https://community.esri.com/thread/225815-strange-arcpy-polyline-geometry-behavior-mixinspassthrough-object
CC-MAIN-2019-04
refinedweb
211
62.07
Hide Forgot Description of problem: When a project has more than 700 deployment config it results in below error when opening the page. ( ``` vendors~main-chunk-097f186a6bd6062a5833.min.js:159202 TypeError: Cannot read property 'pods' of undefined at a.a (deployment-config~deployment-config-overview-chunk-c0930d19396ba7f0219b.min.js:1) at No (vendors~main-chunk-097f186a6bd6062a5833.min.js:159202) at Ks (vendors~main-chunk-097f186a6bd6062a5833.min.js:159202) at Bs (vendors~main-chunk-097f186a6bd6062a5833.min.js:159202) at Fs (vendors~main-chunk-097f186a6bd6062a5833.min.js:159202) at Ms (vendors~main-chunk-097f186a6bd6062a5833.min.js:159202) at vendors~main-chunk-097f186a6bd6062a5833.min.js:159202 at t.unstable_runWithPriority (vendors~main-chunk-097f186a6bd6062a5833.min.js:159496) at li (vendors~main-chunk-097f186a6bd6062a5833.min.js:159202) at hi (vendors~main-chunk-097f186a6bd6062a5833.min.js:159202) ``` Version-Release number of selected component (if applicable): How reproducible: Steps to Reproduce: 1. Create a project with 700+ dc 2. Try to open the dc page it fails to load and gives js error 3. Actual results: Unable to open the page for deployment configs Expected results: should be able to open the page properly Additional info: project with less number of dc and pods doesnt give the same error. Only two projects which have more than 700 DC have this error. we cannot open DC page directly ( but able to open all of its tabs except for Details tab if we hit the url directly ( or so somehow error happens only on "Details tab" Im a bit confused from the screenshots attached. Is the error happening on the DC list page or the details page ? I could reproduce this in 4.5 and 4.6. The frontend error happens if a DeploymentConfig detail page was open and the API call for get Pod list needs a second "page" call to get the right Pods. This happen if the active project (namespace) has more then 250 running Pods in it. In 4.7 the code was already refactored and the new version doesn't contain this issue. The issue is merged now and will be part of the next 4.6 release. I expect that will be 4.9.10. Can we remove the needinfo attributes? Oh it automatically disappear if I post something. Thanks BZ :) Created attachment 1756670 [details] Can load deployment config in Openshift 4.6.9 Created attachment 1756671 [details] Cannnot load deployment config in Openshift 4.6 Verified on build version: 4.6.17 Browser version: Chrome 84.
https://bugzilla.redhat.com/show_bug.cgi?id=1921603
CC-MAIN-2022-21
refinedweb
414
60.72
Distributing Real World Tasks with a Web Application True Story Follows So we’ve been on the grind with Workout Generator, and the numbers are looking reasonably good: After almost 2 weeks in production, we’ve gotten over 60 people to enter credit card information to agree to a free trial potentially followed by a monthly payment. Of the people that begin the signup process, a little less than 10% continue through payment. It could stand to reason then that if we could increase traffic to the site, the payments could be scaled up as well The Plan to Raise the Numbers Right now, there are about 200 to 300 people that visit our site daily. Those people are visiting the site because they searched “Workout Generator” in Google. We want to create additional inlays into the site with as little work and cost possible. One such strategy is to create other content that’s free that leads users to the application. Given the current infrastructure that’s been setup, the easiest thing I could think of it would be to create a separate site, say “ExerciseDatabase.com” or something like that (I haven’t bought or even checked out that domain, but that’s the idea), and create a separate site that’s just an encyclopedia of exercises with video demonstrations. It seems like a relatively quick win because: - The exercise database already exists that I can filter against - Competition for a similar site sucks - Ideally I could create an application with hundreds of pages (1 for each exercise) that could potentially rank high on The Google - The time it would take to setup such a site would take me only a couple of hours The Problem Everything sounds good so far, but the downside is that the video quality of the existing exercises is not perfect. As standalone demonstrations there’s not too much of a wow factor. You can see the above image as a sample of poor video quality. At the time we put this together, I was off fighting The Great War in Afghanistan, and it was back in 2K9 when none of us had a cool SLR camera. Moreover, if we can re-film the videos, then not only can we use them for external purposes to try and garner traffic, but the video demonstrations on the app itself will drastically improve quality. The Solution Things have changed a bit since 5 years ago. Now I have a nice camera, and I have a brother-in-law that’s on the USA’s Olympic Rugby team. He expressed interest in helping us out with a few of his teammates. All of them lift weights and are generally capable of crushing skulls. Also, a lot of them have sweet tattoos. So we need to re-film about 700 exercises, and we can get help from a handful of people. Maybe 5 to 10 I guess? So given that I’m getting the help from all these guys, I wanted to make the tasks they were helping me with as simple as possible. A typical person that doesn’t even lift AND doesn’t even code would probably put together a spreadsheet of exercises, maybe print them out, maybe divvy out by person. Maybe spread the task out over a few days to make it manageable. But as a programmer, it could be made pretty painless to write a quick web application that divvies out exercises automatically. One of the lifters could simply visit a website on his phone and see the current video demonstration, then he would just need to do the exercise and mark it as filmed. Exercises would be unique to each request, and they’d be ordered by required equipment in order to batch together related exercises. In this way, there’s close to no overhead. One person films, and people line up and just complete exercises one after another. The Finished Web Application The web application is super simple and loads super fast and has no styling. I wrote an app in about an hour and just deployed it to Heroku. There’s just one URL, one view, and one model. Here’s the entire essence of the view code. The model is just an implementation of the method calls you see here: def home(request): if request.method == "POST": action = request.POST['action'] action_map = { 'discard': Film.mark_will_not_film, 'later': Film.mark_in_progress, 'filmed': Film.mark_filmed, } fn = action_map[action] exercise_id = int(request.POST['exercise_id']) fn(exercise_id) try: exercise = Film.get_next_exercise() except ValueError: return HttpResponse("<h1>YOU'RE ALL DONE! THANKS!</h1>") finished_count = Film.get_finished_count() total_count = Film.get_total_count() render_data = { "dev": True if os.environ.get("I_AM_IN_DEV_ENV") else False, "video_id": exercise.video_id, "exercise_name": exercise.name, "finished_count": finished_count, "total_count": total_count, "exercise_id": exercise.id } return render_to_response("basic_navigation/base.html", render_data)
http://scottlobdell.me/2015/02/distributing-real-world-tasks-web-application/
CC-MAIN-2019-26
refinedweb
803
63.7
Storybook lets us interactively develop and test user interface components without having to run an application. Because Storybook acts as a component library with its own Webpack configuration, we can develop in isolation without worrying about project dependencies and requirements. In this post, you are going to learn how to integrate Storybook with an existing Vue.js project by using the popular Kanban Board Progressive Web App (PWA), available on GitHub, created by my teammate Steve Hobbs. This process can be followed for a new Vue project as well. Running the Kanban Board Project Execute these commands to get the Kanban Board project up and running locally: git clone git@github.com:elkdanger/kanban-board-pwa.git cd kanban-board-pwa/ npm install npm run dev To see the application running, open in your browser: You don't have to run the app to use Storybook. If you prefer, you can stop it and close the browser tab. Finally, open the kanban-board-pwa project in your preferred IDE or code editor. Setting Up Storybook with Vue With kanban-board-pwa as your current working directory, run the following command to install Storybook using npm: npm i --save-dev @storybook/vue Storybook also requires that you have vue and babel-core installed. Since the kanban-board-pwa was created using the Vue CLI, these two dependencies are already installed. Finally, create an npm script that lets you start and run Storybook easily. Under the scripts section of your package.json file, add the following: { // ... "scripts": { // ... "storybook": "start-storybook -p 9001 -c .storybook" } // ... } The -p command argument specifies the port where Storybook is going to run locally: in this case 9001. The -c command argument tells Storybook to look for a .storybook directory for configuration settings. You'll do that next. Configuring Storybook with Vue Storybook can be configured in many different ways. As a best practice, its configuration should be stored in a directory called .storybook. Create that directory under your root folder: . ├── .babelrc ├── .dockerignore ├── .editorconfig ├── .eslintignore ├── .eslintrc.js ├── .git ├── .gitignore ├── .idea ├── .postcssrc.js ├── .storybook // Storybook config directory ├── Dockerfile ├── LICENSE ├── README.md ├── build ├── config ├── index.html ├── node_modules ├── package-lock.json ├── package.json ├── screenshots ├── src └── static Within .storybook, create a config.js file to hold all the configuration settings. Here, you have to define critical elements that would make Storybook aware of your Vue application. Defining Vue Similar to the src/main.js file, you we need to import vue. Update config.js as follows: // .storybook/config.js import Vue from 'vue'; Defining Vue Components Just like it's done for Vue projects, you need to import and globally register with Vue.component any of your global custom components. Update the config.js to import and register the TaskLaneItem component: // .storybook/config.js import Vue from 'vue'; // Import your custom components. import TaskLaneItem from '../src/components/TaskLaneItem'; // Register custom components. Vue.component('item', TaskLaneItem); This has to be done because Storybook runs in isolation from the Vue application. Take note that components registered locally are brought in automatically. These are components that are registered using the components property of a Vue component object. For example: new Vue({ el: '#app', components: { 'component-a': ComponentA, 'component-b': ComponentB } }); ComponentA and ComponentB are registered locally under #app. TaskLaneItem is a global custom component so you have to import it and register it with Vue in order to instantiate it independently within Storybook. Configuring and Loading Stories You need to import the configure method from @storybook/vue to run Storybook and implement it to load stories (you'll learn what stories are soon): // .storybook/config.js import { configure } from '@storybook/vue'; import Vue from 'vue'; // Import your custom components. import TaskLaneItem from '../src/components/TaskLaneItem'; // Register custom components. Vue.component('item', TaskLaneItem); function loadStories() { // You can require as many stories as you need. } configure(loadStories, module); Storybook works in a similar way to testing tools. The config.js file executes the configure method, which takes as argument a function called loadStories and a module. loadStories will have stories defined on its body. A story describes a component in a specified state. You'd want to write a story for each state a component can have, such as active, inactive, loading, etc. Storybook will then let you preview the component in its specified state in an interactive component library. You'll soon be setting that up. For better project management, it's ideal to store the stories next to the components. Within src, create a stories.js file to host all the stories you'll use. Then, you can use the stories.js file to quickly load the stories in the config.js file like so: // .storybook/config.js // ... function loadStories() { // You can require as many stories as you need. require('../src/stories'); } configure(loadStories, module); When loadStories is run, Storybook will import all the stories present in src/stories.js and execute them. This makes the maintenance of the config.js file much easier by keeping it highly focused on the configuration of Storybook rather than its implementation. All the action, for now, happens within the src/stories.js file. All custom components and Vue plugins should be registered before calling configure(). "Storybook lets us interactively develop and test user interface components without having to run an application. Learn more about how to integrate it with VueJS." Writing Storybook Stories for Vue It's time to start writing Storybook stories and bring the component library to life. Head to src/stories.js and start it like so: // src/stories.js import { storiesOf } from '@storybook/vue'; storiesOf('TaskLaneItem', module); So far, the storiesOf method is imported. This method will help you create stories for a component, in this case, you are using the TaskLaneItem component to fulfill that role. You don't need to import it into src/stories.js because TaskLaneItem has already been registered globally with Vue.component. Using, Storybook's declarative language, you tell it that you want stories of TaskLaneItem: storiesOf('TaskLaneItem', module); If you think about this process in terms of an actual book, this is the book's binding and cover. Now, you need to fill it with pages full of stories. You can do that declaratively too using the add method: // src/stories.js import { storiesOf } from '@storybook/vue'; storiesOf('TaskLaneItem', module).add('Default TaskLaneItem', () => ({ template: '<item :</item>' })); add acts like adding a chapter in a book that has a story. You'd want to give each chapter a title. In this case, you are creating a story titled Default TaskLaneItem. add takes as argument the story title and a function that renders the component being staged.', TaskLaneItem); This Vue component definition object can be refactored to make it more modular by making id and text discreet props: // src/stories.js import { storiesOf } from '@storybook/vue'; storiesOf('TaskLaneItem', module).add('Default TaskLaneItem', () => ({ data() { return { item: { id: 10, text: 'This is a test' } }; }, template: '<item :</item>' })); You now have the foundation of writing a story. It's time to see if everything is working by running Storybook. "Storybook lets you describe the presentation and state of a component in isolation through stories that are compiled in a component library. Learn how to write Storybook stories for VueJS." Running Storybook In your terminal, run the following command: npm run storybook If everything runs successfully, we will see this message in the console: info Storybook started on => Open that URL, in the browser. Let it load and you'll see your own Storybook in full glory: Right now, the TaskLaneItem component doesn't look too good and the text is hard to read in comparison to how it looks on the live application: Open the src/components/TaskLaneItem.vue file that holds the definition of the TaskLaneItem component. Notice that it doesn't have much styling other than a background color being defined. The complete styling for this component is coming from Bootstrap. Thus, the next step is for you to allow Storybook to use Bootstrap. Adding Custom Head Tags to Storybook Open index.html and notice that the kanban-board-pwa app uses different tags within the <head> element. The two relevant tags for previewing components correctly in Storybook are the <link> tags that introduce Bootstrap and FontAwesome into the project. Since Storybook runs in isolation from the app, it is not able to see or use these tags defined within index.html. As a solution, you can create a preview-head.html file under the .storybook configuration directory and add the needed <link> tags like so: "> Restart Storybook by stopping it and then executing npm run storybook again. This lets Storybook use your updated configuration. Open in the browser again and now you should see a much better-looking preview of TaskLaneItem that includes the same styling present in the full app: Previewing Component Changes in Storybook So far, you've staged a component with its existing definitions and configuration. The most powerful feature of Storybook is being able to see changes live without having to run the application. Let's say that you want to make the color of the text within TaskLaneItem orange, increase its padding, and add an orange border. Will this look good? Find out by making these changes within the <style> tag present in TaskLaneItem.vue: // src/components/TaskLaneItem.vue <template> // ... Template definition </template> <script> // ... Script definition </script> <style> .card.task-lane-item { background: #627180; border: solid orange 5px; } .card-title { color: orange; } .card-block { padding: 20px; } </style> Save the file and you'll see Storybook update the preview of the component right away! Think about the time you can save by experimenting with a component's look and feel in isolation. Instead of assembling the whole UI puzzle, you can just preview how one piece looks. However, Storybook does let you run components in composition. Before moving on, reverse the style changes made to TaskLaneItem, it already looks pretty good. Using Vuex with Storybook You have learned how to preview a simple presentational component. Now, you are going to create a story for the TaskLane component which has a more complex structure and uses a Vuex store to hydrate itself with data. First update .storybook/config.js to import and register TaskLane: // .storybook/config.js // ... // Import your custom components. import TaskLaneItem from '../src/components/TaskLaneItem'; import TaskLane from '../src/components/TaskLane'; // ... // Register custom components. Vue.component('item', TaskLaneItem); Vue.component('lane', TaskLane); // ... Next, head back to src/stories.js and create a story of TaskLane: // src/stories.js // ... TaskLaneItem stories storiesOf('TaskLane', module).add('Default TaskLane', () => ({ data() { return { doneItems: [ { id: 10, text: 'This is a test' }, { id: 12, text: 'This is another test' }, { id: 14, text: 'This is yet another a test' }, { id: 16, text: 'This is one more test' } ] }; }, template: ` <div class="col-md"> <lane id="done" title="Done" :</lane> </div> ` })); This is similar to what you did before for TaskLaneItem, the main difference is that you are wrapping lane within a div with the col-md class and you are passing an array of doneItems to TaskLane through the items prop. Recall that you are using laneas the component tag name within the template because that is the name that you used to register the component with Vue.component. Since TaskLane registers TaskLaneItem locally as seen in the src/components/TaskLane.vue file, Storybook automatically brings TaskLaneItem into the scope of TaskLane for this story. There's no need to create a components property within the component definition object of the Default TaskLane story. Save the file. The changes may not show correctly in Storybook until you refresh the page, so go ahead and do so. Click on the TaskLane menu item to expand it and then click on Default TaskLane, you should now see a preview of the TaskLane component: TaskLane uses TaskLaneItem to list tasks in the Kanban Board. These TaskLaneItem components can be dragged and dropped between TaskLane components as configured for this app. Notice how the Storybook TaskLane preview is completely interactive. You can drag and move around any of the visible items within the lane. However, as you drag components within the lane, their position is not persistent. If you open the developer console, you will also see a lot of errors such as the following: vue.esm.js:591 [Vue warn]: Property or method "$store" is not defined on the instance but referenced during render. What's happening? Head to the definition of TaskLane present in the src/components/TaskLane.vue file. Notice that this component uses the vuex store created for this project to update items: // src/components/TaskLane.vue // ... Template tag <script> // ... Script imports export default { // ... Other properties computed: { itemCount() { if (!this.items) return ''; if (this.items.length === 1) return '1 task'; return `${this.items.length} tasks`; }, draggables: { get() { return this.items; }, set(items) { this.$store.commit('updateItems', { items, id: this.id }); } } } }; </script> // ... Style tag The instance of the vuex store is present through $store. It is used to commit an updateItems mutation that updates the lane to which a task lane item belongs. However, the instance of TaskLane within the story is unaware of the existence of this store. More importantly, you are manually passing an array of items to TaskLane for it to render. Why is this a problem? The kanban-board-pwa application architecture uses a Vuex store as the single source of truth for the state of the application. Any component that needs to render data has to get it from the store. Vuex stores are reactive; thus, when there are changes in the structure of the store, the components that are subscribed to the affected data get updated. The problem is that within the Storybook sandbox, the store has not been initialized with any data. Also, TaskLane gets its items data from its parent component, KanbanBoard. As seen in the KanbanBoard component definition in src/components/KanbanBoard.vue. This parent component queries the store to create computed properties that it passes down to TaskLane components: //> <script> import { mapState } from 'vuex'; import TaskLane from './TaskLane'; export default { name: 'KanbanBoard', components: { 'task-lane': TaskLane }, computed: mapState({ todoItems: s => s.items.todo, inProgressItems: s => s.items.inProgress, doneItems: s => s.items.done }) }; </script> You'd want to instantiate Tasklane in isolation — that's the purpose of using Storybook. Instantiating the whole KanbanBoard to be able to pass items props from the store to Tasklane is not a solution either because the store would still be empty. The first step to solve this problem is to add items to the store when the Storybook project is created. Head to .storybook/config.js and update the file as follows: // ... Other imports import store from '../src/store'; // .. Import your custom components. store.commit('addItem', { text: 'This is a test' }); store.commit('addItem', { text: 'This is another test' }); store.commit('addItem', { text: 'This is one more test' }); store.commit('addItem', { text: 'This is one more test' }); // ... Register custom components. // ... Now, when the Storybook project is built, the store will be populated with those four items. However, if you make changes to the Storybook project files since the items are being stored in Local Storage in the browser, you will see duplicate items. This is solved by reloading the browser window where Storybook is hosted. The id for each item is created by the store automatically. Next, update the Default TaskLane story within src/stories.js to pass store items as props to the TaskLane component: // src/stories.js import { mapState } from 'vuex'; import { storiesOf } from '@storybook/vue'; import store from '../src/store'; // ... TaskLaneItem stories storiesOf('TaskLane', module).add('Default TaskLane', () => ({ computed: mapState({ items: s => [...s.items.todo, ...s.items.inProgress, ...s.items.done] }), store, template: ` <div class="col-md"> <lane id="todo" title="Todo" :</lane> </div> ` })); Similar to the logic present in src/components/KanbanBoard.vue, you use mapState to generate computed getter functions for you from the store. It's important to understand how the kanban-board-pwa app works when adding items: If you look back at the KanbanBoard template, you'll see that each lane is given an id value: //> That id matches up (intentionally) with the array symbol in the store so that it becomes trivial to update the list dynamically without too much data overhead — a fine solution for the scope of this demonstration. Save your work and refresh Storybook. You should see the following: Rearrange items within the lane and observe how they remember their new position: You didn't have to use vuex directly. But, in the case that you'd have wanted to create stores from scratch within a story, you'd have to import vuex and install it like so: // .storybook/config.js import Vuex from 'vuex'; // Vue plugins // Install Vue plugins. Vue.use(Vuex); You would then instantiate a new store within the story like this: import Vuex from 'vuex'; storiesOf('Component', module) .add('Default Component', () => ({ store: new Vuex.Store({...}), template: `...` })); Any required Vue plugins, such as vuex, need to be installed using with Vue.use. Assembling Complex Components in Storybook It was cool seeing how to drag and drop items within a lane to rearrange them, but what would be even cooler would be to drag and drop items between lanes. You'll now create a story that presents the three lanes that exist in the full app: Todo, In Progress, and Done. This will be done without having to instantiate the KanbanBoard component. Head to src/stories.js and create the Three TaskLanes story: // src/stories.js // ... imports // ... TaskLaneItem stories storiesOf('TaskLane', module) .add('Default TaskLane', () => ({ computed: mapState({ items: s => [...s.items.todo, ...s.items.inProgress, ...s.items.done] }), store, template: ` <div class="col-md"> <lane id="todo" title="Todo" :</lane> </div> ` })) .add('Three TaskLanes', () => ({ computed: mapState({ todoItems: s => s.items.todo, inProgressItems: s => s.items.inProgress, doneItems: s => s.items.done }), store, template: ` <div class="row"> <div class="col-md"> <lane id="todo" title="Todo" :</lane> </div> <div class="col-md"> <lane id="inProgress" title="In progress" :</lane> </div> <div class="col-md"> <lane id="done" title="Done" :</lane> </div> </div> ` })); Here, you use the same computed property present in KanbanBoard that uses mapState to generate a computed getter function for each category of lane items. Three lanes are created with todo, inProgress, and done as id values to match the array symbols in the store. Save your work and head back to Storybook. Click on the TaskLane menu tab and then on Three Tasklanes. You should see something like this: If you see duplicate items, refresh the Storybook window. Now, drag and drop items between lanes. Each item should remember its new lane and its new position in the lane. Cool, isn't it? In practice, you can create components from the bottom to the top: start with the small presentational components, tweak their style and content, then move to the larger components that rely on component composition for their presentation. Storybook lets you focus on treating each component like a truly modular independent piece of the UI puzzle. As an additional benefit for large teams, creating a component library allows you to reuse components not only within a project but across organization projects that require to have a consistent look and feel for effective branding. Recap You have learned how to preview the presentation of basic and complex components in an interactive way through Storybook's component library while being able to access and use Vue plugins such as vuex. Storybook can be also used to preview actions triggered through components such as firing up a function upon clicking a button as well as for UI testing. These are more advanced use cases. Let me know in the comments below if you'd like to read a blog post about extending Storybook for Vue to cover event handling and testing. At Auth0, we have been using Storybook extensively. To learn more about our experience creating component libraries with Storybook and the benefits we have found, please read our "Setting Up a Component Library with React and Storybook" post. Auth0: Never Compromise on Identity So you want to build an application? You're going to need to set up user authentication. Implementing it from scratch can be complicated and time-consuming, but with Auth0 it can be done in minutes. For more information, visit, follow @auth0 on Twitter, or watch the video below: Auth0 Docs Implement Authentication in Minutes OAuth2 and OpenID Connect: The Professional GuideGet the free ebook!
https://auth0.com/blog/using-storybook-with-vuejs/
CC-MAIN-2020-40
refinedweb
3,417
57.77
> I haven't followed this thread for quite some time, but since the > PEP still seems alive, :-) > let me add some experience I've had with > using the already existing singletons (Py_True and Py_False) > in Python for recognizing truth values. > > Py_True and Py_False can be exposed in Python via > > True = (1==1) > False = (1!=1) Yuck. What a horrible implementation detail. > and most comparison operations and quite a few other APIs > returning truth values make use of these singletons. This works purely by accident. Given that at least Py_False is also known as &_Py_ZeroStruct, I'm surprised that the code that optimizes ints doesn't initialize small_ints[NSMALLNEGINTS] with Py_False. > I thought it would be a good idea to use those two > singletons for protocols which use booleans such as > XML-RPC. My experiences with this approach are, well, > not so good :-/ > > The reason is that True and False are really integers > and not of a special new type. Now they are singletons, > which is good, since they represent the only states > a boolean can have and in many cases work reasonably > well as boolean representative, but not always > (e.g. arithmetic operations such as True - True == False). > Also, when trying to recognize the two singletons you have > to use the "is" comparison -- "==" will fail to > differentiate between 1 and True... > > def isboolean(x): > return x in (True, False) > > ...doesn't work... > > def isboolean(x): > return (x is True) or (x is False) > > ..does. The correct way if PEP 285 is accepted would of course be isinstance(x, bool). > As a conclusion, I think it would be better to make bool() a > new type which does *not* inherit from integers, but which > does know how deal with other types which are commonly > used together with booleans such as integers. However, the > type should implement boolean algebra and not try to > mimic integer arithemtic, i.e. True - True raises an > exception. That would break more code. E.g. (a!=0) + (b!=0) + (c!=0) counts how many of (a, b, c) are nonzero; this would break. > Py_True and Py_False should then be made singletons > of this new type (possibly after a transition phase which > replaces the singletons with a version that doesn't raise > exceptions but instead issues warnings). That's what the PEP does (but with a different type). > This may sound painful at first, but in the long run, > I believe, it'll result in the same benefits as other > painful changes have or will (e.g. the change from integer > division to floating point division). I don't see the introduction of the bool type as painful at all. I find getting it accepted painful though. :-( --Guido van Rossum (home page:)
https://mail.python.org/pipermail/python-dev/2002-April/022133.html
CC-MAIN-2019-39
refinedweb
453
71.65
Description I am trying to render a custom font on a 256x64 display with 4-bits per pixel. When I display text using the font, it shows the text with the font, but it renders with some glitches: it looks jarred or something, not sure how to describe it. It also glitches a lot when updating the text: See how the D and the numbers glitch when updating the label to the same text. What MCU/Processor/Board and compiler are you using? NXP MIMXRT1011 with arm gcc 10.3.1 What LVGL version are you using? v8.1 What do you want to achieve? Nicer smooth rendering. What have you tried so far? I know that I don’t have issues drawing to my display. I tried rendering images and animations and they look very smooth. So I am confident that it is not a hardware issue or an issue with my flush function, etc. I checked that the font doesn’t have issues in the simulator, it renders just fine. I tried enabling/disabling antialiasing, subpixel rendering. I also tried regenerating the fonts with different bits-per-pixel and with/without subpix rendering. I still got glitchy text. Code to reproduce The following codes illustrates how I’m using the font in my project. This code works in the simulator and renders properly, but it does not look the same in my device. #include "lvgl.h" LV_FONT_DECLARE(inter_medium_35) static lv_style_t text_style_regular; static lv_obj_t * m_content_text; void test_run(void) { lv_style_init(&text_style_regular); lv_style_set_text_font(&text_style_regular, &inter_medium_35); lv_style_set_text_color(&text_style_regular, lv_color_black()); lv_style_set_align(&text_style_regular, LV_ALIGN_TOP_LEFT); lv_style_set_width(&text_style_regular, 480); m_content_text = lv_label_create(lv_scr_act()); lv_obj_add_style(m_content_text, &text_style_regular, LV_STATE_DEFAULT); lv_label_set_text(m_content_text, "This is a very very long text that should be constantly scrolling"); lv_label_set_long_mode(m_content_text, LV_LABEL_LONG_SCROLL_CIRCULAR); } Find the font file attached (generated with 4 bpp and subpix rendering): inter_medium_35.c (803.0 KB)
https://forum.lvgl.io/t/how-to-properly-render-fonts/7342
CC-MAIN-2021-49
refinedweb
304
56.66
Back to: ASP.NET Web API Tutorials For Begineers and Professionals ASP.NET Web API Content Negotiation In this article, I am going to discuss ASP.NET Web API Content Negotiation with an example. Please read our previous article where we discussed ASP.NET Web API Service using the SQL Server database. From the rest architecture point of view, it is very important to understand the concept of Content Negotiation in Web API. As part of this article, we are going to discuss the following important concepts related to Content Negotiation. - What is Content Negotiation and it’s needed in Rest Services? - How does the Web API Framework know in which format the client expects the response? - Understanding the Accept and Content-Type headers in a request. - Example to implement Content Negotiation in ASP.NET Web API Application. - How to request data in JSON Format? - How to request data in XML Format? - What does the Web API Framework do when we request for data in a specific format? What is Content Negotiation and it’s needed in Rest Services? We know that there are three pillars of the internet and they are: - The resource - The URL - The representation The first two are (i.e. the resource and the URL) very straightforward but the last one (i.e. the representation) is a little confusing to understand. The representation is very important in the modern web. Why? Because people are currently not only using Desktop computers to browse the web, but they also are using various types of devices (tab, mobile, etc.) to consume web applications. And the important and the interesting fact is that all these various devices expect the data in various formats. For example, a few clients want the data in normal HTML while some of them want the data in a normal text format. Others may need the data in JSON format and still some other wants the data in XML format. Content Negotiation Definition: We can define Content Negotiation as “the process of selecting the best representation for a given response when there are multiple representations available”. One of the standards of the REST service is that the client should have the ability to decide in which format they want the response – whether they want the response in XML or JSON etc. This is called Content Negotiation. Now, the fact should be clear that “Web API Content Negotiation” means the client and server can negotiate. Always It is not possible to return data in the requested format by the Server. That’s why it is called negotiation, not demand. In such cases, the Web API Server will return the data in the default format. How does the Web API Framework know in which format the client wants the response? This is done by checking the below headers of the request object. - Content-type: The content-type header value request to the Web API Server to represent data in this format. The values for Content-type includes “application/json“, “application/xml“, etc. - Accept: The Accept header value specifies the media types which are acceptable for the response, such as “application/json” and “application/xml” or any other custom media type such as “application/vnd.dotnettutorials.employees+xml“. - Accept-Charset: The Accept-Charset header specifies which character sets are acceptable, such as UTF-8 or ISO 8859-1. - Accept-Encoding: The Accept-Encoding header specifies which content encodings are acceptable, such as gzip. - Accept-Language: The Accept-Language header specifies the preferred natural language support, such as “en-us“. Understanding the Accept and Content-Type headers: A request that is sent to the server includes Accept and Content-Type headers. Using the Accept header and Content-Type the client can specify the format for the response. For example Content-Type: application/xml returns XML Content-Type: application/json returns JSON Accept: application/xml returns XML Accept: application/json returns JSON Depending on the Accept header and Content-Type value in the request object, the server sends the response. This is called Web API Content Negotiation. Example to understand Content Negotiation in ASP.NET Web API. In this article, we are going to work with the same example that we started in our previous article where we discussed the step by step procedure of working with SQL Server. Below is our controller namespace EmployeeService.Controllers { public class EmployeesController : ApiController { public IEnumerable<Employee> Get() { using (EmployeeDBContext dbContext = new EmployeeDBContext()) { return dbContext.Employees.ToList(); } } public Employee Get(int id) { using (EmployeeDBContext dbContext = new EmployeeDBContext()) { return dbContext.Employees.FirstOrDefault(e => e.ID == id); } } } } How to Request Web API Service to Return Data in JSON Format? The JSON format is currently the most popular format of data representation. So, first, we will see how to return the data in JSON format from the Web API. We are using a tool called Fiddler to test the API services. So please read how to use Fiddler to test the web API tutorial before proceeding to this article. Here is our HTTP header information to get the employee details whose id is 1. Select the Compose Tab. Then select the HTTP verb as “GET”. Then provide the URL and click on the Execute button as shown in the below image. Here you can see that we did not set the Content-Type header value to request the data in JSON format but the Web API returning the data in JSON format. The reason is by default the Web API will return the data in JSON format if we do not specify any “Content-Type” header in the request. See the following output. And obviously, we can also modify the header value like the following to get the data in JSON format. Both requests will give us the same output in reality. How to Request Web API Server to return the data in XML format? In this example, we will request the Web API to return the data in XML format. When the application used SOAP-based messages (it’s not that SOAP is obsolete in modern applications, it’s still there but people like to use smarter JSON rather than too much informative and stuffy XML). Now to get the data in XML format we need to set the Content-Type header of the Http Request to application/xml as shown below. Once you click on the execute button, you will get the data in XML format as shown in the below image. The above two are the formats (i.e. JSON and XML) that the Web API supports by default. If you want other than these two types of representations then you need to implement a media type formatter in the Web API. Understanding Accept Header in Http Request: In our previous examples, we saw how a content-type header works with Http Request. In this example, we will understand the “Accept” header of the Http Request. By checking the “Accept” header value, the Web API understands which represents the client is able to accept. For example, if we specify that the client can understand the following representations: application/xml , application/json, text/javascript Then the Web API will return the data in JSON format, the reason is JSON is the default format of the Web API, although the client’s first preference is the XML format. We will prove it with a small example. Have a look at the following screen. Request With Accept Header: And the output will be Understanding Accept-Language header In the Accept-Language header, we can specify the preferred language that we want to get from the Web API application. The Accept-Language header is used as Accept-Language: en-IN, en-US The above Accept-Language header indicates that my first choice of language is Indian English but if that is not possible then please give me US English and if that is not possible then please provide the data in the default language. So Web API Content negotiation is a mechanism, or algorithm, used to determine, based on the client’s request, which media type formatter is going to be used to return an API response. In the next article, we will discuss what is media type formatter and how it works with some examples. What does the Web API Framework do when we request data in a specific format? The controller in Web API first generates the data that we want to send to the client. For example, if we have asked for the list of employees. The Web API Controller generates the list of employees, and hands the data to the Web API pipeline which then looks at the Accept header value and depending on the format that the client has requested, the Web API will choose the appropriate formatter. For example, if the client has requested for the data in XML format, then Web API uses XML Formatter. similarly, if the client has requested the data in JSON format, then Web API uses JSON Formatter. These formatters are called Media Type Formatters. ASP.NET Web API is greatly extensible. This means we can also plug-in our own formatters, for custom formatting the data. Multiple values can also be specified for the Accept header. In this case, the server picks the first formatter which is a JSON formatter and formats the data in JSON. Accept: application/xml,application/json You can also specify a quality factor. In the example below, XML has a higher quality factor than JSON, so the server uses XML formatter and formats the data in XML. application/xml;q=0.8,application/json;q=0.5 If you don’t specify the Accept header in the request then by default the Web API returns the data in JSON format. When the response is sent to the client, notice that the Content-Type header of the response is set to the appropriate value. For example, if the client has requested for application/xml, then the server sends the data in XML format and also sets the Content-Type=application/xml. Role of Media Type Formatter: The Web API uses the formatters for both request and response messages. When the client makes a request to the server, the client has to set the Content-Type header to the appropriate value to let the server know the format of the data that we are sending. For example, if the client is sending JSON data, the Content-Type header is set to application/json. The server knows it is dealing with JSON data, so it uses JSON formatter to convert JSON data to .NET Type. Similarly, when a response is being sent from the server to the client, depending on the Accept header value, the appropriate formatter is used to convert the .NET type to JSON, XML, etc. We can also very easily change the serialization settings of these formatters. For example, if we want the JSON data to be properly indented and use camel case instead of Pascal case for property names, all we have to do is modify the serialization settings of JSON formatters as shown below. With our example, this code goes in WebApiConfig.cs file in the App_Start folder. config.Formatters.JsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented; config.Formatters.JsonFormatter.SerializerSettings.ContractResolver= new CamelCasePropertyNamesContractResolver(); In the next article, I am going to discuss Media Type Formatters in Web API with an example. Here, In this article, I try to explain ASP.NET Web API Content Negotiation step by step with some examples. I hope now you understood Content Negotiation in Web API. 4 thoughts on “Web API Content Negotiation” Great ..details Thank you Great ….Tutorials…. thanks to make this topic easy to understand.
https://dotnettutorials.net/lesson/content-negotiation-web-api/
CC-MAIN-2020-05
refinedweb
1,953
55.34
A collection of helper functions used by o-comments and o-chat. This module provides a useful way to handle application level configurations. It supports setting and reading configurations, also overriding existing values (helpful when the application should be working on different environments with partially different configuration). In order to create a configuration, you should create an instance first: var config1 = new oCommentUtilities.EnvConfig(); In order to keep an isolated configuration object of your application, which is accessible within your whole application, the following method can be used: var EnvConfig = require('js-env-config'); module.exports = new EnvConfig(); Gets the whole configuration if without parameter, or a field if a field is given as parameter. Getting the whole configuration object: config.get(); Getting a field of the configuration object: config.get('aField'); Sets the configuration. The current configuration is merged with this object. Existing fields that have primitive type values and the same field has value in the object given to set, are overwritten. Setting an object: config.set({ 'configField': 'value' }); Setting a key/value: config.set('aField', { 'configField': 'value' }); This is equivalent with the following object: { "aField": { "configField": "value" } } This module helps creating custom events, listening on custom events and triggering them. It is similar to jQuery's event system (except that it doesn't support namespacing). The constructor has no parameter. var myEvent = new Events(); Registers a new event handler to an event. myEvent.on(event, handler) Where: Registers a new event handler to an event. Similar to 'on', but the handler is called only once. myEvent.one(event, handler) Removes one or more event handlers. myEvent.off(event, handler) Where: If handler is omitted, all event handlers from the event specified are removed. If both event and handler are omitted, all event handlers are removed. Triggers an event: it causes calling all the event handlers that are listening for the event name. myEvent.trigger(event, customData) Where: This module provides a similar solution for JSONP communication as jQuery. For more information on JSONP, visit . The module is actually a single function. It should be called the following way: commentUtilitis.jsonp({ url: "URL here", data: "Data here" //optional }, function (err, data) { if (err) { throw err; } // use the data }); Both parameters (configuration object and callback) are required. Also, the configuration should contain the 'url' field. If data should be sent, it can be part of the URL directly, or can be provided as the data field within the configuration object. The data field should be an object with key-value pairs. The callback has a Node.js inspired form. The first parameter is the error parameter, while the second one is the data parameter received from the server as a response. This module provides a similar solution for loading a Javascript file asynchronously as jQuery's $.getScript() (). The module is actually a single function. It can be called the following ways: 1. oCommentUtilities.scriptLoader({ url: "URL here", charset: "utf-8" //optional }, function (err) { if (err) { throw err; } // loaded successfully }); 2. oCommentUtilities.scriptLoader("URL here", function (err) { if (err) { throw err; } // loaded successfully }); Both parameters (configuration object/URL and callback) are required. Also, if the configuration is an object, it should contain the 'url' field. The callback has a Node.js inspired form. The parameter is either 'null' or an Error instance. If it doesn't contain an error, the loading finished with success. Wrapper around localStorage and sessionStorage, but enhanced with automatic type conversion. Automatic type conversion means the followin: for example, if you store an object which can be serialized into a JSON string, when you read it back you will get the same Javascript object and not just a plain string. The module exposes two main fields, both having the same API: oCommentUtilities.storageWrapper.localStorage //wrapper around native localStorage oCommentUtilities.storageWrapper.sessionStorage //wrapper around native sessionStorage Both submodules has the same public API. The difference is only the place the data is saved (as it is in the native API). Available methods: Saves an item in the storage. It has the following form: setItem(key, value); The value is saved in the storage with the key. The value can be looked up using the key provided. The item is saved in the following format: {type}|{value converted/serialized to string} For example, a boolean "true" value is saved in the following way: boolean|true Objects that can be serialized are saved with the type "json". Reads the item and returns it in the original type that was saved. getItem(key); For example, if a boolean true was saved, it is not returned as a string, but as a boolean type. Returns true or false and it says if there is an item with that key. hasItem(key); Removes the item saved with the key provided. removeItem(key); Clears all entries for the current domain. Returns the native localStorage or sessionStorage object. Logging helper which uses the native "console" to log. It also extends IE8 logging capabilities by stringifying complex objects. Where console is not available, the logger fails silently. The module supports the following methods: The logger can be configured with the following: enable/disable, set the minimum level that is logged. By default is logging disabled (recommended settings for production). Default level of logging is 'warn'. Enables the logging. logger.enable(); Disables the logging. logger.disable(); Sets the minimum level that should be logged. The levels are the following: logger.setLevel(level); Where level can be: Available functions: This submodule is meant to generate a callback only when all functions provided finished their execution. This is achieved by passing a callback as parameter to the functions that are executed. The submodule itself is a single function and can be called in the following way: oCommentUtilities.functionSync.parallel({ func1: function (callback) {}, func2: function (callback) {}, func3: { args: ['param1', 'param2'], func: function (callback, param1, param2) {} } }, function (dataAggregate) { // where data aggregate is: // { // func1: 'dataFromFunc1', // func2: 'dataFromFunc2', // func2: 'dataFromFunc2' // } } }); Functions provided within the object can be in the following forms: For more information on the technical side, please visit the detailed documentation (docs/index.html). This module is able to instantiate classes extended from o-comment-ui/Widget.js using markup in the DOM. This feature reads the DOM for certain types of elements. An example element: <div data-</div> Key parts of the DOM element: data-o-component: defines the type of Widget element, in this example o-chat. data-o-{modulename}-config-{key}: configuration options that are passed to the Widget constructor. {key}has the following rule: --means new object level, -means camel case. Example: data-o-comments-config-livefyre--data-format--absolute="value"is transformed to: {"livefyre": {"dataFormat": {"absolute": "value"}}}. In order to start the DOM construction, the oCommentUtilities.initDomConstruct function should be called with a configuration object, which has the following fields: data-o-component="{modulename}". If none is specified, it falls back to document.body. 'o-chat'. It is used as class and also as part of the data attributes. 'oChat'. oChat. data-{namespace}-auto-init="false"(e.g. data-o-chat-init="false") will be considered. This is useful when there are two phases of initialization: one on o.DOMContentLoadedand one on demand (lazy load). On o.DOMContentLoadedthere will be loaded only the widgets which don't have this attribute, while the others only on explicit call. Example: var initDomConstructOnDemand = function () { oCommentUtilities.initDomConstruct({ classNamespace: 'o-chat', eventNamespace: 'oChat', moduleRef: oChat, classRef: oChat.Widget }); } document.addEventListener('o.DOMContentLoaded', function () { oCommentUtilities.initDomConstruct({ classNamespace: 'o-chat', eventNamespace: 'oChat', moduleRef: oChat, classRef: oChat.Widget, auto: true }); }); In some cases this module should be called on demand by the product, so it could be exposed as a public API as part of the module which uses it. Example: (from o-chat/main.js) var Widget = require('./src/javascripts/Widget.js'); exports.init = function (el) { return oCommentUtilities.initDomConstruct({ context: el, classNamespace: 'o-chat', eventNamespace: 'oChat', moduleRef: this, classRef: Widget }); }; This way all the configurations are abstracted, the product should not care about setting them. If you want to obtain a reference of the created Class instances, you should listen on the body to the event {namespace}.ready (e.g. oChat.ready), which will have the following details: Example: document.body.addEventListener('oChat.ready', function (evt) { //evt.detail.id and evt.detail.instance are available }); The instance that is already created will have a flag that says that it shouldn't be created again, even if initDomConstruct is called again. The flag that is set is data-{namespace}-built="true" (e.g. data-o-chat-built="true"). If you are creating instances in another way (programatically), the container element should have this flag set. The return value is an array with all the instances of Class (e.g. oChat.Widget) created. Helpers for working with cookies. Reads a cookie by name. oCommentUtilities.cookie.get('name'); Sets a cookie. oCommentUtilities.cookie.set('name', 'value', 36 /*days */); Removes a cookie oCommentUtilities.cookie.remove('name'); ftUser is a helper for obtaining information about the FT user, information like logged in status, user ID, email address, session ID. Methods exposed that can be used:
https://registry.origami.ft.com/components/o-comment-utilities@2.4.0/readme?brand=internal
CC-MAIN-2019-47
refinedweb
1,518
50.53
Sorry for posting in the wrong section, i knew the code was not a loop, but i did not know it was a control statement. I'm not sure how you supposed to know these things when you're a total noob,... Type: Posts; User: reddevilggg Sorry for posting in the wrong section, i knew the code was not a loop, but i did not know it was a control statement. I'm not sure how you supposed to know these things when you're a total noob,... When i run this code the 'else' output always displays. Why is that ?? import java.util.Scanner; public class Post { public static void main(String[] args) { Scanner myKeyboard =... Thank you both for your help, and due to your help i've done it . Thanks Again I've tried the substring and this is the best i can do The output is Which shows the first initial, then first space +1 and second space +1. Then what is inclusive of the name... There is going to be 2 spaces as i have to assume that the user input 3 names, first, middle and last name. I've tried loads of things, nothing works for me, the longer i stay on this tutorial the... This is it so far, i just do not understand what i need to do import java.util.Scanner; public class Initials { public static void main(String[] args) { Scanner input =... Yeah, i've tried loads of ways, but being a beginner it's the syntax that lets me down. i'm not sure exactly what or how to get it correct. Everything i do either doesnt work or is an error. I... yeah, i understand the logic behind it. Thats as far as it goes. I been trying to include a char method, but i just keep get red errors. I'm lost. i'm using the indexOf method because its part of a tutorial i'm following to make sure that i'm understanding how to use it (ironic, i know). It gives the poistion of the space +1, which will give... I'm still having problems, as you can see in the code below, the output displays the first initial then the others as an int (number of spaces), i know i've got the code as an int, but this is the... Cheers. i'll take a look Thanks again Sorry about not enclosing the code in tags. You say "Now find the space as there are many functions provided by String. You can easily find the space and then get the index of that location. Add... I've got this so far, but the program has to be for ANY name import java.util.Scanner; public class Initials { public static void main(String[] args) { Scanner input = new... i'm trying to write a program that displays your initials after you input your full name, only using the string methods . I'm at a loss, can anyone help ?? Thanks everyone :-) I'm a Java beginner, i'm writing a simple program to convert pounds to euros, but i would like the output answer to be rounded up to 2 significant figures, can anybody help. here is the code ... Started using Java today. i'm completly new to it. I'm trying to get ahead on my Uni course as Java starts next semester.
http://www.javaprogrammingforums.com/search.php?s=1a49b4f5f349a1cab780691b7c76523e&searchid=836935
CC-MAIN-2014-15
refinedweb
566
81.43
Bulrush theme for Pelican Project description Bulrush A Bulma-based Pelican blog theme; clean, flexible and responsive. The icons are from Font Awesome by Dave Gandy. The pure HTML/CSS "Fork me on GitHub" ribbon is based on github-fork-ribbon-css by Simon Whitaker; I modified it to be flatter. Features Responsive design - four column layout on desktop (≥980px), three column on tablet (≥769px), single column on mobile. Tabbed navigation bar collapses into drop-down "burger menu" on mobile. Meta tagging functionality - support for Open Graph and Twitter Cards meta tags, giving enhanced display when sharing articles on social media sites (note: currently only available for articles and pages). Printable layouts - the navigation is hidden when printed, avoiding wasted space. Custom styling - additional CSS files can be included to customise the default styling. Service integrations - including Disqus, GitHub, Google Analytics and MailChimp. PyPI package available - so it can be pip install-ed. Installation Bulrush is available via the Python Package Index, so you can install it with: pip install bulrush The main exports from the module are: PATH: the path to the theme; FILTERS: the additional Jinja filters used by the theme; and ENVIRONMENT: the Jinja environment required by the theme. You can use them in your pelicanconf.py as follows: import bulrush THEME = bulrush.PATH JINJA_ENVIRONMENT = bulrush.ENVIRONMENT JINJA_FILTERS = bulrush.FILTERS Other Requirements You need to make the appropriate Pelican plugin, assets, available. One way of achieving this is to make the pelican-plugin repository a submodule of your site, then you can add to your pelicanconf.py: PLUGIN_PATHS = ['pelican-plugins'] PLUGINS = ['assets'] Note: referencing the Pelican plugins in this way may have implications for the license of your project. See Alternative If you don't want to install the theme from PyPI you can simply give Pelican a relative path to the inner bulrush/ directory. For example, add bulrush as a submodule and set: THEME = 'bulrush/bulrush' In this case you will need to configure the environment and filters yourself and ensure that webassets is installed from PyPI. Additional Screenshots 480 x 480px (mobile): 840 x 480px (tablet): 980 x 480px (desktop): Settings As well as the basic settings, Bulrush supports the following options in your pelicanconf.py: If DISPLAY_CATEGORIES_ON_MENU is omitted or set explicitly to True, the categories are shown in the tabbed navigation with any MENUITEMS. If DISPLAY_PAGES_ON_MENU is omitted or set explicitly to True, they are listed in the sidebar with any SOCIAL or other LINKS. Social Links Appropriate icons are provided in the sidebar for a range of sites in the SOCIAL link list. Have a look in social.html to see which titles this applies to. If none of the sites are a match, then: - if the second, URL element in the tuple starts with 'mailto:', an envelope icon is used; otherwise - a globe icon is used. MailChimp Configuration If you're using MailChimp to handle a mailing list for your blog, you can configure a subscription form in the sidebar. You need to set three values to enable this, which you can get from the signup form creator. Simply look for the form action: <form action="//user.region.list-manage.com/subscribe/post?u=abc123&id=def456" ... and extract the relevant sections: MAILCHIMP = dict( domain='user.region.list-manage.com', user_id='abc123', list_id='def456', validation=True, # enable jQuery validation ) If you set validation=False (or leave it out entirely) you will reduce the page load (as it won't need 140KB of JavaScript) but won't get inline form submission or email validation. You can also add rewards_url, providing your unique MonkeyRewards URL, to enable a "Powered by MailChimp" link. License Settings You can provide one of two options to specify the license for your content: License name ( str): The name of the license to display. Unless otherwise specified, a default icon ( file-text-o) will be used and the entry will link to the current page. Creative Commons license names (e.g. 'CC BY-SA 4.0') are automatically recognised and an appropriate icon and link are generated. License definition ( dict): A dictionary specifying the name, urland optional icon(must be a Font Awesome icon name, default is file-text-o). The license details will be displayed at the bottom of the sidebar on every page. Custom Styling If any of the entries in EXTRA_PATH_METADATA have 'path's ending with '.css' they will be included in the base template, allowing the site style to be overridden as required. For example, in your pelicanconf.py: # Static files STATIC_PATHS = [ 'extra', ... ] EXTRA_PATH_METADATA = { 'extra/custom.css': {'path': 'custom.css'}, ... } In use Here are few current users of Bulrush (or modified versions of it): If you'd like to be featured here (or are and would prefer not to be), feel free to submit a pull request. Project details Release history Release notifications | RSS feed Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/bulrush/
CC-MAIN-2022-21
refinedweb
831
55.13
Unanswered: Progress Bar inside a Grid cell Hi, I want to put a progressbar inside a grid. I created a renderer function like this : function extjsRenderer(value) { var id = Ext.id(); (function() { if (value < 50) { var bar = new Ext.ProgressBar({ height: 15, renderTo: id, value: (value / 100) }); } else if (value < 75) { var btn = new Ext.Button({ renderTo: id, text: 'Price: ' + value }); } else { var txt = new Ext.form.TextField({ value: value, renderTo: id, height: 15 }); } }); return (String.format('<div id="{0}"></div>', id)); } But I am getting the error as "Object does not support the method 'format'". So, I removed String.format,but instead of a progress bar it is showing me ext-gen1031,ext-gen1032,ext-gen1033 inside the grid. Can you tell me what is wrong in my code? Thanks, Sangita Hi, I am able to see the progress bar by changing the return statement to return '<div role="presentation" class="x-progress x-progress-default" id="progressbar"><div style="height: 20px; width: 35px;" id="progressbar-1022-bar" class="x-progress-bar"><div id="' + id + '" class="x-progress x-progress-default"></div></div></div>'; But It is a static bar. I have used animate attribute to show the progress as follows : animate: {from:{height: 20,width: 0}, to:{height: 20,width: 30}, duration: 200} But, i am unable to see the progress and its a static bar. Is there any other way to achieve this? Thanks, Sangita - Join Date - Nov 2007 - Location - Stockholm, Sweden - 2,938 - Vote Rating - 161 - Answers - 33 String.format is not a function. Ext.String.format exists though, but it won't help you in your first post. You are trying to render to an element that does not exist. You are making it overcomplicated, just use a TemplateColumn that outputs 2 nested divs and style those using CSS. Very simple problem - Join Date - May 2010 - Location - Guatemala, Central America - 1,469 - Vote Rating - 302 - Answers - 12 Nice trick - Notts/Redwood City - 30,589 - Vote Rating - 55 - Answers - 15 That will leave orphaned ProgressBar instances all over the place after having rendered into the transient cell. Use a special renderer which reuses a single instance of ProgressBar, and just gets the correct markup to use in the cell: Code: var progressRenderer = (function () { var b = new Ext.ProgressBar({height: 15}); return function(progress) { b.updateProgress(progress); return Ext.DomHelper.markup(b.getRenderTree()); }; })();Search the forum: Read the docs too: Scope: Hi Animal, thx for this tip. I'm having the same problem that with every new column creation (e.g. when sorting) a new ProgressBar instance is created. Do I understand your code correctly, that I should create the progressBar only once and each time my cell render function is called it just returns the progressBar Markup in the return statement? [UPDATE] Ok, got it working, but now the PB doesn't size correctly... The 100% it sizes too are of course not the 100% of the grid cell it renders to later! Excellent solution ! Thanks too Animal ! After a few tries, it works ! (ExtJS 4.1.3). The 'older' solution () worked with ExtJs 4.0.7, but with ExtJS 4.1.3, the rendering of the column generated javascript errors. Code: { text : 'Column Title' width : 130, sortable : true, dataIndex: 'ColumnDataIndex', renderer: function (v, m, r) { var tmpValue = v / 100; var tmpText = r.data.Data1 + ' / ' +r.data.Data2; var progressRenderer = (function (pValue, pText) { var b = new Ext.ProgressBar(); return function(pValue, pText) { b.updateProgress(pValue, pText, true); return Ext.DomHelper.markup(b.getRenderTree()); }; })(tmpValue, tmpText); return progressRenderer(tmpValue, tmpText); } }, Result in grid : Hi guys, I used this code for adding a progressbar in my grid and works fine. But after adding a progressbar inside a grid cell, is it also possible change progressbar's alignment in the cell and the label's alignment inside the progressbar (for example all to right or all to center)? How can I do it? Using this code, I have progressbar (and its label) only aligned to left and I don't know how to change it... I hope that problem is clear.If it isn't, please tell me, thank you!! again, thanks a lot greetings
https://www.sencha.com/forum/showthread.php?187168-Progress-Bar-inside-a-Grid-cell&p=774460
CC-MAIN-2016-07
refinedweb
696
65.93
Bye SaveCookie, Hello org.netbeans.api.actions.Savable By Geertjan-Oracle on Dec 14, 2011 If you're using the NetBeans Platform as the basis of your own applications, you are going to find this particular blog entry, applicable to NetBeans Platform 7.1, extremely interesting! When you're working with a modular framework such as the NetBeans Platform, your work consists of plugging your business logic into existing hooks provided by the framework. For example, rather than create your own Save button, you're going to want to reuse the existing Save button in the framework, assuming it has one. That way, the application won't have 100's of Save buttons; instead, there'll be a single Save button that will save whatever is currently in need of being saved. That's where the NetBeans Platform's SaveCookie came into play. Implement the SaveCookie class, which means you need to create an implementation of the SaveCookie's "save()" method, put the implementation into the Lookup whenever there's something needing to be saved, and the Save button will automatically become enabled, delegating to your implementation, since the Save button (in fact, the SaveAction that's invokable from a button, menu item, and keyboard shortcut) is listening to the Lookup for the presence of SaveCookie implementations. However, there have always been a number of problems with SaveCookie. Firstly, it is part of the Nodes API, meaning that you need to depend on that entire API even though you're only using the SaveCookie and possibly don't need to use any Nodes at all. Secondly, the SaveCookie is connected to DataObjects since, when you close the application, all unsaved DataObjects, i.e., all DataObjects with a SaveCookie in their Lookup, are displayed in a small Exit dialog, prompting you to save them prior to closing the application. However, what if your SaveCookie doesn't apply to a DataObject at all? Then you're out of luck since the Exit dialog will not display the fact that you have an outstanding SaveCookie. Thirdly, the "Save All" button (i.e., its underlying Action) would only become enabled for DataObjects, causing a lot of confusion when you're first working with SaveCookies. Finally, there was no way to modify the Exit dialog. E.g., maybe you'd like to change the text or add an icon. The only thing shown is the DataObject's display name, while you might have two DataObject's representing two versions of the same file open, one from the trunk and another from the branch. Wouldn't it be handy to show more than the display name, e.g., the path, to distinguish the two versions? In 7.1, all the above problems are things of the past. Though, of course, since backward compatibility is holy in the NetBeans Team, you can continue using SaveCookies exactly as before. However, if you have a problem with any of the above limitations, you can switch to the org.netbeans.api.actions.Savable interface instead. There's even a default implementation, org.netbeans.spi.actions.AbstractSavable. Both of these are in the UI Utilities API, i.e., not in the Nodes API, and there's no connection with DataObjects at all. "Save All" now works automatically and the content of the Exit dialog (which now includes any objects with outstanding saves) is customizable. public final class DemoTopComponent extends TopComponent implements DocumentListener { InstanceContent ic = new InstanceContent(); public DemoTopComponent() { initComponents(); setName(Bundle.CTL_DemoTopComponent()); setToolTipText(Bundle.HINT_DemoTopComponent()); associateLookup(new AbstractLookup(ic)); jTextArea1.getDocument().addDocumentListener(this); } @Override public void insertUpdate(DocumentEvent e) { modify(); } @Override public void removeUpdate(DocumentEvent e) { modify(); } @Override public void changedUpdate(DocumentEvent e) { modify(); } private void modify() { if (getLookup().lookup(MySavable.class) == null) { ic.add(new MySavable()); } } private static final Icon ICON = ImageUtilities.loadImageIcon("org/savable/Icon.png", true); private class MySavable extends AbstractSavable implements Icon { MySavable() { register(); } @Override protected String findDisplayName() { try { final Document doc = jTextArea1.getDocument(); String s = doc.getText(0, doc.getLength()); int indx = s.indexOf('\n'); if (indx >= 0) { s = s.substring(0, indx); } return "First line '" + s + "'"; } catch (BadLocationException ex) { return ex.getLocalizedMessage(); } } @Override protected void handleSave() throws IOException { tc().ic.remove(this); unregister(); } DemoTopComponent tc() { return Dem(); } } ... ... ... The code that you see above comes from the issue (see link to it at the end of this blog entry) where the need for all this functionality is outlined, solved, and integrated. It can be seen as the "hello world" sample of the new Savable interface. Above, use is made of the new global registry for Savables. You register/unregister Savables into this registry, while the AbstractSavable provides the "register" and "unregister" calls so that you can let it do this work for you. If you don't register your Savable, the Exit dialog will not show information about the object's unsaved state (if the object is unsaved), when you close the application: This also means some of the tutorials using SaveCookie need to be updated to use the new AbstractSavable class. For example, the NetBeans Platform CRUD Tutorial will be updated soon. Related reading: - - (in German) - - Finally, if your Savable also implements SaveAsCapable (requiring dependencies on the Nodes API, File System API, and Datasystems API), the "Save As" Action will become enabled and the "Save As" dialog will open when the Action is invoked. You'll also be able to implement the "saveAs" method, which is part of the SaveAsCapable interface, for customizing the Action. According to the documentation of AbstractSavable the save() method calls handleSave() and unregister(), so you can remove this from your implementation of handleSave(). Posted by Holger Stenger on December 14, 2011 at 10:07 PM PST # Cool. I wish this was implemented earlier. it would have saved me so much trouble 2 years ago. Posted by guest on December 16, 2011 at 01:18 AM PST # Simply awesome! I changed my code to use this feature and i'm finally able to get rid of the 'fake' DataObject i had to create just to get the Exit Dialog to show up. You could however enhance your example by overriding TopComponent.canClose() method. Here's what i came up with (notice that i'm using Cancellable interface too to clear any edits the user might have done): @Override public boolean canClose() { Savable savable = getLookup().lookup(Savable.class); if (savable == null) { return true; } String msg = "Form '" + getDisplayName() + "' has unsaved data. Save it?"; NotifyDescriptor nd = new NotifyDescriptor.Confirmation(msg, NotifyDescriptor.YES_NO_CANCEL_OPTION); Object result = DialogDisplayer.getDefault().notify(nd); if (result == NotifyDescriptor.CANCEL_OPTION || result == NotifyDescriptor.CLOSED_OPTION) { return false; } if (result == NotifyDescriptor.NO_OPTION) { Cancellable cancellable = getLookup().lookup(Cancellable.class); if (cancellable != null) { cancellable.cancel(); } return true; } try { savable.save(); return true; } catch (IOException ex) { Exceptions.printStackTrace(ex); return false; } } The reason i'm pasting this code is to show that this method is only coupled with NetBeans stuff. Not a single class of my own, whatsoever. Pretty cool! Best regards Posted by metator on January 12, 2012 at 04:23 AM PST # I have been go through source and found out the "unregister();" seem unnecessary on the sample code above. The code "save" method on the AbstractSavable.java shows: for (Savable s : Savable.REGISTRY.lookup(t).allInstances()) { if (s == this) { handleSave(); unregister(); return; } } "Save All" button call to save method, "unregister()" are always been called aftet handleSave()...... Posted by Aknine on April 21, 2012 at 05:05 PM PDT # I found that if you want to call the handleSave() method yourself (prior to performing an action for example) without forcing the user to click on the SaveAllAction button, then the unregister() needs to be in the handleSave() method or the SaveAllAction button will remain enabled... Posted by jauten on April 27, 2012 at 11:01 AM PDT # Is there anyway to set the file filter and initial folder for the Save As dialog? I have several document types with different file extensions and I would like the file saved in the project folder. Posted by guest on November 15, 2012 at 09:17 AM PST # Hi Geertjan, This Savable , Abstract Savable API's cannot be found in Netbeans 7.0 What can I replace it with ? Posted by Nigel Thomas on November 22, 2012 at 11:44 PM PST # Why can't you use NetBeans Platform 7.2? And, if you must use 7.0, which I can't imagine why you need to use it, research the SaveCookie class, which is the old way of doing what is described in this blog entry. But you already knew that because that's exactly what this blog entry tells you. Posted by Geertjan on November 22, 2012 at 11:49 PM PST # thanks Geertjan. But if I want check something before the saving,when user input incorrect, alert and cancel the saving,how to implements it ? Posted by guest on November 24, 2012 at 10:56 AM PST # Haye you worked through the NetBeans Platform CRUD Application tutorial? Posted by Geertjan on November 25, 2012 at 08:03 AM PST # Hi, thanks for your post. I have a problem with Savable though. When files are being saved locally I need to deploy them to a server. So I need to handle the save event. I did this implementing Savable: public class VFDataObject extends MultiDataObject implements Savable { ....... @Override public void save() throws IOException { ....... } } And it worked perfectly for the Save event. But then I realized I need to extend HtmlDataObject instead of MultiDataObject: public class VFDataObject extends HtmlDataObject implements Savable { ....... @Override public void save() throws IOException { ....... } } And now the save() doesn't get executed. Why? Since HtmlDataObject extends MultiDataObject. What should be done to make that work? Thanks a lot. Posted by Volodymyr on July 08, 2014 at 02:13 AM PDT # I don't think HtmlDataObject is a public API class, is it? I would advise to avoid it. Posted by Geertjan on July 08, 2014 at 02:18 AM PDT # Hi, Geertjan, thanks for your great works. i'm following this tutorial, save dialog only appear when application is closed but when i close the topComponent one by one save dialog is not showing. The dialog showing later when application is about to close though. How to make the save dialog appear the moment single topComponent closed, like netbeans way? override componentClosed()method seems working but not clean and feel cumbersome for me. Posted by wayan on July 29, 2014 at 05:21 AM PDT # I have just a small query. In the save Prompt, that appears on exit, a Help button is available.How can I implement that Help button.Currently on clicking that button ,nothing happens .But I want it to take me to the help Contents in my IDe Posted by Sreedevi on September 23, 2014 at 08:09 AM PDT # Hey Geertjan, Thank you for a nice tutorial. I just have a question regarding the "Save All" capability and Savable.REGISTRY. When a user clicks "Save All" button, I present a confirmation dialog to him, as in. If he cancels/denies the confirmation dialog, is there a way to leave the AbstractSavable in the Savable.REGISTRY, as the user does not want to save that particular file at the moment, but might be interested in saving it later? I see that unregister() is always called after handleSave() in AbstractSavable, which is causing this behaviour. I managed to overcome this by having static maxUID and non-static UID in static MySavable so that I can add new MySavable on cancel (if I just compare TopComponents in equals method, they are the same and add/register is ignored). But I think this is a bad coding practice, as MySavable should conceptually be an inner class, existing only in the scope of TopComponent and not a static inner class. Additionally findDisplayName() + " saved." is shown in the bottom left corner of the IDE no matter what the user chooses after Save / Save All. Thanks :) Posted by Boris Perović on January 28, 2015 at 06:19 AM PST #
https://blogs.oracle.com/geertjan/entry/bye_savecookie_hello_org_netbeans
CC-MAIN-2015-32
refinedweb
2,001
55.74
You can use hashlib.md5() Note that sometimes you won't be able to fit the whole file in memory. In that case, you'll have to read chunks of 4096 bytes sequentially and feed them to the Md5 function: def md5(fname): hash_md5 = hashlib.md5() with open(fname, "rb") as f: for chunk in iter(lambda: f.read(4096), b""): hash_md5.update(chunk) return hash_md5.hexdigest() Note: hash_md5.hexdigest() will return the hex string representation for the digest, if you just need the packed bytes use return hash_md5.digest(), so you don't have to convert back. There is a way that's pretty memory inefficient. single file: import hashlib def file_as_bytes(file): with file: return file.read() print hashlib.md5(file_as_bytes(open(full_path, 'rb'))).hexdigest() list of files: [(fname, hashlib.md5(file_as_bytes(open(fname, 'rb'))).digest()) for fname in fnamelst] Recall though, that MD5 is known broken and should not be used for any purpose since vulnerability analysis can be really tricky, and analyzing any possible future use your code might be put to for security issues is impossible. IMHO, it should be flat out removed from the library so everybody who uses it is forced to update. So, here's what you should do instead: [(fname, hashlib.sha256(file_as_bytes(open(fname, 'rb'))).digest()) for fname in fnamelst] If you only want 128 bits worth of digest you can do .digest()[:16]. This will give you a list of tuples, each tuple containing the name of its file and its hash. Again I strongly question your use of MD5. You should be at least using SHA1, and given recent flaws discovered in SHA1, probably not even that. Some people think that as long as you're not using MD5 for 'cryptographic' purposes, you're fine. But stuff has a tendency to end up being broader in scope than you initially expect, and your casual vulnerability analysis may prove completely flawed. It's best to just get in the habit of using the right algorithm out of the gate. It's just typing a different bunch of letters is all. It's not that hard. Here is a way that is more complex, but memory efficient: import hashlib def hash_bytestr_iter(bytesiter, hasher, ashexstr=False): for block in bytesiter: hasher.update(block) return hasher.hexdigest() if ashexstr else hasher.digest() def file_as_blockiter(afile, blocksize=65536): with afile: block = afile.read(blocksize) while len(block) > 0: yield block block = afile.read(blocksize) [(fname, hash_bytestr_iter(file_as_blockiter(open(fname, 'rb')), hashlib.md5())) for fname in fnamelst] And, again, since MD5 is broken and should not really ever be used anymore: [(fname, hash_bytestr_iter(file_as_blockiter(open(fname, 'rb')), hashlib.sha256())) for fname in fnamelst] Again, you can put [:16] after the call to hash_bytestr_iter(...) if you only want 128 bits worth of digest.
https://pythonpedia.com/en/knowledge-base/3431825/generating-an-md5-checksum-of-a-file
CC-MAIN-2020-29
refinedweb
468
67.76
Actually, part of me is thinking that there are valid use cases for having fl and hl.fl with different values. e.g, receive name etc. in “clean” form in fl field and receive both name and address in html formatted form (by specifying in hl.fl) On Fri, Aug 18, 2017 at 10:57 AM, Nawab Zada Asad Iqbal <khichi@gmail.com> wrote: > Actually, i realize that it is an incorrect use on my part to pass only > id+score in fl and specify more fields in the hl.fl fields. This was > somehow supported in older versions but the new behavior is actually a > performance improvement for the scenario when user is asking for only ids. > > > Nawab > > On Fri, Aug 18, 2017 at 8:33 AM, Nawab Zada Asad Iqbal <khichi@gmail.com> > wrote: > >> Thanks Erick for the pointing to better option. I will explore that. >> After your email, I found that if i have specified 'fl=*' in the query then >> it is doing the right thing (a 2 pass process). However, my queries had >> 'fl=id+score' (or sometimes fl=id&fl=score), in both of these cases I found >> that the shards are asked for highlighting all the results on the first >> request (and there is no second request). >> >> The fl=* query is (in my sample case) finishing in 100 msec while same >> query with fl=id+score finishes in 1200 msec. >> >> Here are the two queries; >> >> >> l=*&start=200&rows=200&q=nawab&shards=solrdev.test.net:8984/ >> solr/filesearch,solrdev.test.net:8985/solr/filesearch,solrd >> ev.test.net:8986/solr/filesearch&wt=json >> >> >> >> l=id&fl=score&start=200&rows=200&q=nawab&shards=solrdev.test >> .net:8984/solr/filesearch,solrdev.test.net:8985/solr/filesea >> rch,solrdev.test.net:8986/solr/filesearch&wt=json >> >> >> Thanks >> Nawab >> >> >> >> >> On Fri, Aug 18, 2017 at 7:23 AM, Erick Erickson <erickerickson@gmail.com> >> wrote: >> >>> I don't think you're reading it correctly. First of all, if you're >>> going to do be doing deep paging you should be using cusorMark, see: >>>. >>> >>> Second, it's a two-pass process if you don't use cursormark. The first >>> pass gets the candidate docs from each shard. But all it returns is >>> the ID and sort criteria. Then the aggregator node gets the _true_ top >>> N after sorting all the lists from each shard and issues a second >>> request for _only_ those docs that have made the top N from each sub >>> shard, and those should be the only ones highlighted. >>> >>> Do you have any evidence to the contrary that they're all being >>> highlighted? Or are you misinterpreting the log message for the first >>> pass? >>> >>> Best, >>> Erick >>> >>> On Thu, Aug 17, 2017 at 5:43 PM, Nawab Zada Asad Iqbal <khichi@gmail.com> >>> wrote: >>> > Hi, >>> > >>> > In a multi-node solr installation (without SolrCloud), during a paging >>> > scenario (e.g., start=1000, rows=200), the primary node asks for 1200 >>> rows >>> > from each shard. If highlighting is ON, then the primary node is >>> asking for >>> > highlighting all the 1200 results from each shard, which doesn't scale >>> > well. Is there a way to break the shard query in two steps e.g. ask >>> for the >>> > 1200 rows and after sorting the 1200 responses from each shard and >>> finding >>> > final rows to return (1001 to 1200) , issue another query to shards for >>> > asking highlighted response for the relevant docs? >>> > >>> > >>> > >>> > Thanks >>> > Nawab >>> >> >> >
http://mail-archives.apache.org/mod_mbox/lucene-solr-user/201708.mbox/%3CCAN+whnJ4bYJJP_X0-USnkV6XHpcZbJf=C4zFCAZQHADvX=8EYw@mail.gmail.com%3E
CC-MAIN-2020-10
refinedweb
573
63.09
page last updated on 1/4/2021 Notes Based on Getting started page from NVIDIA These notes are ideal for somebody that is familiar with the Raspberry Pi and should be used in conjuntion with the NVIDIA documentation. After downloading the image. Used the Raspberry Pi Imager to write the SD card image which can be found here: Select “Use custom” and select JETSON NANO SD CARD IMAGE file and the target SD card. Power up board with the new SD card Follow the configuration step prompts Select your language... Select your timezone... Configure your user account... The operating system is ready to go... Install the "Hello World" example (this setup is without Docker) We installed and built the “Hello World” project per the instruction found here: Command summary: Run from the command prompt - Some step details... during the "cmake ../" command the following prompts will allow some selections.. Select models to download, we left the defaults and selected "OK" Select PyTorch for installation. This is unselected by default... Select PyTorch, then "OK" This step takes a while... Next execute the Make command Next run the "sudo make install" command Finally execute the "sudo ldconfig" command Confirm PyTorch is up and running... Start python3 (python (2) will not work) import torch (imports the PyTorch library) x=torch.rand(5,4) (creates a tensor with random values) print(x) (prints the tensor) The basic PyTorch XOR example should also run. You should have a basic Jetson Nano system up and running..
https://www.zagrosrobotics.com/shop/custom.aspx?recid=102
CC-MAIN-2021-04
refinedweb
249
65.52
PyMongo's New Default: Safe Writes! I joyfully announce that we are changing all of 10gen's MongoDB drivers to do "safe writes" by default. In the process we're renaming all the connection classes to MongoClient, so all the drivers now use the same term for the central class. PyMongo 2.4, released today, has new classes called MongoClient and MongoReplicaSetClient that have the new default setting, and a new API for configuring write-acknowledgement called "write concerns". PyMongo's old Connection and ReplicaSetConnection classes remain untouched for backward compatibility, but they are now considered deprecated and will disappear in some future release. The changes were implemented by PyMongo's maintainer (and my favorite colleague) Bernie Hackett. Contents: - Background - The New Defaults - Write Concerns - auto_start_request - What About Motor? - The Uplifting Conclusion Background MongoDB's writes happen in two phases. First the driver sends the server an insert, update, or remove message. The MongoDB server executes the operation and notes the outcome: it records whether there was an error, how many documents were updated or removed, and whether an upsert resulted in an update or an insert. In the next phase, the driver runs the getLastError command on the server and awaits the response: This getLastError call can be omitted for speed, in which case the driver just sends all its write messages without awaiting acknowledgment. "Fire-and-forget" mode is obviously very high-performance, because it can take advantage of network throughput without being affected by network latency. But this mode doesn't report errors to your application, and it doesn't guarantee that a write has completed before you do a query. It's not the right mode to use by default, so we're changing it now. In the past we haven't been particularly consistent in our terms for these modes, sometimes talking about "safe" and "unsafe" writes, at other times "blocking" and "non-blocking", etc. From now on we're trying to stick to "acknowledged" and "unacknowledged," since that goes to the heart of the difference. I'll stick to these terms here. (In 10gen's ancient history, before my time, the plan was to make a full platform-as-a-service stack with MongoDB as the data layer. It made sense then for getLastError to be a separate operation that was run explicitly, and to not call getLastError automatically by default. But MongoDB is a standalone product and it's clear that the default needs to change.) The New Defaults In earlier versions of PyMongo you would create a connection like this: from pymongo import Connection connection = Connection('localhost', 27017) By default, Connection did unacknowledged writes—it didn't call getLastError at all. You could change that with the safe option like: connection = Connection('localhost', 27017, safe=True) You could also configure arguments that were passed to every getLastError call that made it wait for specific events, e.g. to wait for the primary and two secondaries to replicate the write, you could pass w=3, and to wait for the primary to commit the write to its journal, you could pass j=True: connection = Connection('localhost', 27017, w=3, j=True) (The "w" terminology comes from the Dynamo whitepaper that's foundational to the NoSQL movement.) Connection hasn't changed in PyMongo 2.4, but we've added a MongoClient which does acknowledged writes by default: from pymongo import MongoClient client = MongoClient('localhost', 27017) MongoClient lets you pass arguments to getLastError just like Connection did: from pymongo import MongoClient client = MongoClient('localhost', 27017, w=3, j=True) Instead of an odd overlap between the safe and w options, we've now standardized on using w only. So you can get the old behavior of unacknowledged writes with the new classes using w=0: client = MongoClient('localhost', 27017, w=0) w=0 is the new way to say safe=False. w=1 is the new safe=True and it's now the default. Other options like j=True or w=3 work the same as before. You can still set options per-operation: client.db.collection.insert({'foo': 'bar'}, w=1) ReplicaSetConnection is also obsolete, of course, and succeeded by MongoReplicaSetClient. Write Concerns The old Connection class let you set the safe attribute to True or False, or call set_lasterror_options() for more complex configuration. These are deprecated, and you should now use the MongoClient.write_concern attribute. write_concern is a dict whose keys may include w, wtimeout, j, and fsync: >>> client = MongoClient() >>> # default empty dict means "w=1" >>> client.write_concern {} >>> client.write_concern = {'w': 2, 'wtimeout': 1000} >>> client.write_concern {'wtimeout': 1000, 'w': 2} >>> client.write_concern['j'] = True >>> client.write_concern {'wtimeout': 1000, 'j': True, 'w': 2} >>> client.write_concern['w'] = 0 # disable write acknowledgement You can see that the default write_concern is an empty dictionary. It's equivalent to w=1, meaning "do regular acknowledged writes". auto_start_request This is very nerdy, but my personal favorite. The default value for auto_start_request is changing from True to False. The short explanation is this: with the old Connection, you could write some data to the server without acknowledgment, and then read that data back immediately afterward, provided there wasn't an error and that you used the same socket for the write and the read. If you used a different socket for the two operations then there was no guarantee of "read your writes consistency," because the write could still be enqueued on one socket while you completed the read on the other. You could pin the current thread to a single socket with Connection.start_request(), and in fact the default was for Connection to start a request for you with every operation. That's auto_start_request. It offers some consistency guarantees but requires the driver to open extra sockets. Now that MongoClient waits for acknowledgment of every write, auto_start_request is no longer needed. If you do this: >>> collection = MongoClient().db.collection >>> collection.insert({'foo': 'bar'}) >>> print collection.find_one({'foo': 'bar'}) ... then the find_one won't run until the insert is acknowledged, which means your document has definitely been inserted and you can query for it confidently on any socket. We turned off auto_start_request for improved performance and fewer sockets. If you're doing unacknowledged writes with w=0 followed by reads, you should consider whether to call MongoClient.start_request(). See the details (with charts!) in my blog post on requests from April. Migration Connection and ReplicaSetConnection will remain for a while (not forever), so your existing code will work the same and you have time to migrate. We are working to update all documentation and example code to use the new classes. In time we'll add deprecation warnings to the old classes and methods before removing them completely. If you maintain a library built on PyMongo, you can check for the new classes with code like: try: from pymongo import MongoClient has_mongo_client = True except ImportError: has_mongo_client = False What About Motor? Motor's in beta, so I'll break backwards compatibility ruthlessly for the sake of cleanliness. In the next week or two I'll merge the official PyMongo changes into my fork, and I'll nuke MotorConnection and MotorReplicaSetConnection, to be replaced with MotorClient and MotorReplicaSetClient. The Uplifting Conclusion We've known for a while that unacknowledged writes were the wrong default. Now it's finally time to fix it. The new MongoClient class lets you migrate from the old default to the new one at your leisure, and brings a bonus: all the drivers agree on the name of the main entry-point. For programmers new to MongoDB, turning on write-acknowledgment by default is a huge win, and makes it much more intuitive to write applications on MongoDB.
http://emptysqua.re/blog/pymongos-new-default-safe-writes/
CC-MAIN-2015-18
refinedweb
1,280
52.7
Introduction Working on a recent Pi project, I needed to use some servo's. This blog post discusses a servo controller project that can be used for toy and model cars, planes, model robots and so on. There are existing controllers out there, but I didn’t have one, and besides some of them seemed expensive – I didn’t want to spend $15+ on something I could make for $2. Also this was an opportunity to try to design something hopefully better (in some ways) than existing off-the-shelf controllers, and also explore how to create a custom hardware peripheral for attaching to the Pi. It isn't hard, anyone can do it : ) The aim was to build something that could connect between the Pi (or any other single board computer or micro-controller, such as the Beaglebone, Arduino, and so on), and the servos, as shown in red here. It is explained in more detail below, but in brief, it would allow the Pi, or any micro-controller of choice to communicate using a standard I2C interface, and the servo controller would generate the correct pulse width modulation (PWM) signals to control multiple servos, which would create the motion for the desired task. But first, it is good to understand the Servo, to know how to use it and its strengths and weaknesses. What are Servos'? When motors are running, it is hard to know how much they have turned, and when to shut off a motor precisely, to do accurate things like robotics. It would also be nice to adjust the voltage so that the motor can accelerate and get stuff done, but slow down as the robot approaches a human! Servo systems are different from standalone AC or DC motors in that they have feedback. The feedback can be used to precisely control the motion (position and speed). In industrial scenarios, servo motors are composed of an AC or DC motor (specially built to have very smooth rotation) and a rotary encoder (a device that generates pulses on a wire as a shaft is turned), and circuitry known as a servo amplifier (an amplifier just generates a voltage based on an input signal). This is connected up to the industrial machine controller or robot brains (using a digital interface) and position and speed commands are sent digitally to the servo amplifier. Much like any amplifier, it will generate a voltage, which drives the motor in either direction depending on the polarity of the voltage. The feedback from the encoder is used as an ‘error signal’; as it approaches the desired settings, then the servo amplifier output voltage is reduced, therefore allowing the motor to slow down and stop as it approaches the correct position. The machine cannot be knocked out of position, because the encoder will generate pulses that produce an error signal into the servo amplifier, which will generate a correction voltage to bring the machine back to where it was specified to be according to the original message sent from the machine controller. In hobby territory, a similar system is used but compacted into the space of a few cubic centimetres. Instead of a high-performance motor, often just a brushed DC motor is used, although higher-end hobby servos will have brushless motors. The rotary encoder is expensive so it is swapped out with a cheaper (and lower-performance) alternative: a variable resistance, known as a potentiometer. The servo amplifier is composed of an analog to digital converter (to read the potentiometer resistance) and the amplification occurs using digital pulses and a H-bridge. Instead of a fancy isolated digital interface, the hobby servo uses a PWM input signal where the pulse width determines the position that the motor should move to. Instead of multiple rotations that may be needed to move industrial machines into position, the hobby servo often just rotates through a smaller rotational distance – maybe only 180 degrees for example – to suit hobby requirements such as controlling toy wheel steering or model aeroplane surfaces. Instead of a direct connection from the motor shaft to the industrial machine for the best precision, the hobby servo has to make do with limited power and will have gearing on the output shaft; this will introduce some slack, also known as ‘backlash’, which can reduce accuracy further. If you break open a hobby servo, you'll see all these components. The PCB will contain the circuit that takes the desired motion signal (the PWM input), and the H-bridge circuit which is switched on and off rapidly to generate an average voltage to drive the motor. Instead of the rotary encoder attached to the back of the motor, there will be a potentiometer near the motor, attached via a gear. There will be three wires egressing from the servo; two of them are for the power source, and one of them is for the input PWM signal referenced to the ground wire. How are Hobby Servo Motors Controlled? Hobby servos come with a three wire connection; the power connections (around +4.8 to 6V DC and 0V connection) and a PWM input connection which can be driven by a 5V logic level signal, but 3.3V seems to work too usually. The PWM rate is about 50Hz, although it is non-critical. The high pulse width is what controls the position of the servo. The actual values vary wildly from one hobby servo type to another. Sometimes a value of between 1000usec to 2000usec (1 to 2msec) is stated to move the servo shaft from its extreme clockwise position to its extreme anti-clockwise position (looking at the servo shaft end-on). A value outside of the range will not cause any additional motion. Other hobby servos may use a different pulse range, such as between 600usec and 2400usec. In most cases the centre position can be assumed to be achieved at about 1500usec pulse width. The PWM pulses (at that 50Hz rate mentioned above) need to produced with little jitter in the pulse width, otherwise the servo will make a chattering noise as the servo amplifier keeps generating a voltage to adjust the motor on every slight change in the generated pulse width. Although PWM pulses can be produced with just timer circuitry (such as with 555 timer chips), a more popular way is to use digital circuits or computers/microcontrollers. Trying to generate PWM pulses in software is not easy, because most computers are not designed for such tasks. They will produce slightly varying pulse widths with lots of jitter! Single board computers such as the Raspberry Pi or BeagleBone Black often have dedicated circuitry inside that can generate pulse trains with accuracy. But often SBCs are not designed to control many servos simultaneously. Furthermore, their dedicated circuitry is for general pulse trains, and so some coding is needed to make it suitable for use with the pulse width sizes required for operation with hobby servos, which is fine, but for quick projects sometimes it is easier to offload the PWM generation to an external chip, and just send instructions from time to time (using a serial interface such as I2C or UART) whenever the position of the servo shaft needs changing. I2C and UART capabilities are present on nearly all SBCs and microcontrollers, so these are handy interfaces to use. What else is out there? A google search revealed that one way to control it is to use a PCA9865 chip. This generates sixteen PWM outputs for general purposes (primarily to control LED brightness), under I2C control. It isn’t dedicated for servo use, so the developer still needs to do a lot of coding to make it achieve the desired effect. Adafruit has some library code for it. The PCA9685 has only 12-bit resolution, and this means that the granularity of a servo is not being used to its full potential. As an example; my cheap SG-5010 servo (which rotates across its full range with a pulse width between 400 and 2350usec) has at least 500 visibly discernible steps (about 0.35 degrees per step) from its most anti-clockwise to its most clockwise position (to find this out, I varied the pulse width gradually, and counted how many discrete movements I could see). A PCA9685 servo controller set to output pulses every 50Hz, can only resolve 390 steps due to its 12-bit resolution. To improve this, the pulse rate could be increased, but even at 60Hz, the PCA9685 can only resolve 475 steps. A better quality servo than my SG-5010 may well have a resolution in excess of 500 steps. Hobby servos are not accurate devices and so each step will not be identical. Also there be backlash in the end mechanism that the servo is connected to. Nevertheless there could be a requirement to finely trim the servo position as closely as possible, and that is harder to do with just 475 steps available. One other thing that bothered me, was that if I was to use a PCA9685, I’d have to do a lot of calculations in the controlling software. The PCA9685 as a generic PWM device does not understand degrees of rotation, or lengths, or percentages of full travel. These have to be done by the user, or in the library code, to translate into a number that the PCA9685 understands. There are also dedicated, fully built modules but at prices that make no sense (to me anyway). This project was an opportunity to try to address all these problems (and hopefully not introduce too many new ones!). The Design To make this project nice and easy, I used a 20-pin DIP chip – a Texas Instruments MSP430 microcontroller. It is very low cost, easy to hand-solder, the programmer is cheap at $10 and it doesn’t need a lot of software installed on the PC. The steps to program the chip are described in this other project Cyclops-1000: An Electronic Eye for Rotational Speed Measurement (see the section Working with the Microcontroller). In contrast the PCA9685 supports up to 16 servos, but for my project I was going to aim for just 8. I figured 8 servos is a good quantity to start with, and if the user wishes to add more, then the I2C bus supports adding more ICs. I’d rather control 8 servos more accurately and with more features, than have a board with 16 servos controlled with less accuracy and less features. The MSP430 will be coded up to implement the design shown in the block diagram below. It was fun to plan how it should work; that's the benefit of using a microcontroller instead of someone else's servo controller! The microcontroller datasheet was used to check that each pin could do what was desired. For future flexibility, some pins were allocated to be usable for analog inputs too, since the microcontroller datasheet shows that those pins support that capability. An address pin (A0) was created in the design to allow two of these devices to be connected to the I2C bus. Since there are only 20 pins available with this microcontroller, I reused one of the servo pins to also work as a mode switch. This is a typical trick where the pin can be programmed as an input at power-up, and if it detects a certain voltage level then the code internally switches modes of operation. I2C Commands The block diagram above shows that there are about 12 different parameters (registers) that can be sent to the controller from the Pi/Arduino. This is just an initial design to get things progressing, and more capabilities could be added later. I2C commands will be used to set the position of each servo, but there are also commands to set the min/max width of the pulses that the servo expects, and also the user-friendly number range that is desired. So, if I had a 180 degree servo where the datasheet specified that it needed pulses between 800 and 2200usec, and for my application I wanted to specify the motion as a percentage between 0 and 100 (100 representing 180 degrees) then I’d want to configure the controller with these parameter values using I2C: WidthMin = 800 WidthMax = 2200 UserMin = 0 UserMax = 100 Then, to move the fourth servo (SERVO3, since the numbering starts from zero) to its halfway or centred position, I’d want to set this parameter value: SERVO3 = 50 I needed to construct some system for sending these parameters over I2C. I settled on this: The first byte will always be the slave address (0x31, or 0x30 if the A0 pin is connected to ground). The second byte will be the desired command. A command of 0x00 will mean SERVO0. 0x01 will mean SERVO1 and so on. There will also be commands to set the width and user min/max values. The actual settings will be 16-bit integers, which means that two bytes are needed to send them. The ordering is least-significant-byte first. Here are the I2C values to set the fourth servo (SERVO3) to the decimal value 50 (which is 0x0032 in hexadecimal): In Python on the Raspberry Pi this is easy, it takes just three lines: from I2C import I2C servo=I2C(0x31) servo.write_subaddr_int(3, 50) Line 2 shows the I2C interface being set up to communicate to the 0x31 slave address, and line 3 shows that servo 3 (fourth servo) is being set to the value 50. That write_subaddr_int function will automatically convert the number 50 into a two byte integer and send all the bytes in the correct order. Wiring It Up The top view pin configuration that was chosen is shown here: Here is how it would be connected up to a servo (more servos can be added of course): The schematic is shown below. The resistors R2 and R3 are pull-up resistors for the I2C bus. The Pi already has them so R2 and R3 are not needed for it, but the Arduino would require them. Note that the simpler Arduino boards (like Arduino Uno) use a 5V supply, but this servo controller uses 3.3-3.6V, so the SDA and SCL pull-up resistors must go to the 3.3V pin on such Arduino’s, and not to the 5V pin. Resistor R1 and C3 form the reset circuit. Capacitors C1 and C2 provide supply decoupling to the microcontroller. Capacitor C4 provides supply decoupling for all the attached servos. Summary This first part of this mini-project investigated the motivation to create a $2 servo controller that could in theory perform better and have more features that existing off-the-shelf options. The operation of servos was described, and how the design could look internally with an I2C instruction decoder and PWM generator. A format/scheme for sending commands was also created, and the wiring diagram to see how it could be used. As next steps, a PCB will be created, and some coding will be done!
https://www.element14.com/community/community/raspberry-pi/raspberrypi_projects/blog/2018/03/11/building-a-hobby-servo-controller-part-1
CC-MAIN-2018-22
refinedweb
2,523
56.39
One of the key advantages to having an IDE instead of a plain-text editor is the debugging experience. Debugging involves being able to pause program execution at an arbitrary point and having the ability to inspect the content of variables. CLion supports the debugging experience using the GDB debugger (and LLDB on OS X since version 1.1 and on Linux since version 2016.2). Here’s a look at some of the core debugging features that are supported. Upd. (changes since CLion 2016.1 and 2016.2) Learn how to attach for debug to local process started not from the CLion (from CLion v2016.1). Check major changes (since v2016.2) in GDB and LLDB drivers and addresses such problems as: - Command timeouts. - Stepping problems. - Debugger performance issues. Please, find more details in our blog post by the link. Try remote GDB debug (since v2016.2). Breakpoints In order to inspect the state of the program at a particular point, you need to pause the program. Breakpoints are used for exactly this purpose. A simple breakpoint stops the execution of a program at a particular line. To make one, simply press Ctrl+F8 (Windows/Linux)/ ⌘F8 (OS X) or, alternatively, click the mouse in the grey gutter area to the left of the code. The line with the breakpoint will be highlighted, and the breakpoint itself will appear as a red circle: Now, when you run the program in debug mode (by choosing the menu item Run|Debug Shift+F9 (Windows/Linux)/ ^D (OS X)), program execution will stop at the line you selected. A conditional breakpoint will only stop at a particular line if some condition holds. To edit the condition, you can right-click the breakpoint and type in the condition in the window that pops up. You even get code completion right in the editor! With this pop-up window open, you can press Ctrl+Shift+F8/ ⇧⌘F8 to open up the full breakpoint editing window: Some of the options available here include: - Suspend — this check box determines whether the execution pauses at a particular point or not. Leaving this unchecked means program execution will continue, but any breakpoint rules (e.g., logging) will still be executed. - Condition — determines the condition on which this breakpoint triggers. Leaving this out ensures that the breakpoint is always hit. - Log message to console writes to the console information about the breakpoint being hit. - Log evaluated expression lets you log the result of specific evaluation. - Remove once hit ensures that after you hit the breakpoint once, the breakpoint is removed. This can be useful in cases where you only want to log the first occurence of a particular point being hit. - Disabled until selected breakpoint is hit does exactly what it says: it disables the current breakpoint until some other breakpoint is encountered. This is useful in situations where, for example, you only want to investigate a point in code when it is called from a specific function of your choosing. There are two options here: - Disable again disables the breakpoint after it is hit until the dependant breakpoint is hit again (in which case it is re-enabled). - Leave enabled leaves the breakpoint forever enabled and thus no longer dependant on any other breakpoint being hit first. Exception Breakpoints But that’s not all! In addition to ordinary breakpoints, CLion also supports exception breakpoints which, as the name suggests, trigger when the program throws an exception. The set of options related to exception breakpoints is similar to line breakpoints: you can specify whether you want to suspend execution, log message to the console, remove the exception once it’s hit, or only enable it when some other breakpoint is hit first: Debugger User Interface So, what exactly happens when a debugger hits a breakpoint? Apart from the execution pausing, you get to see the following Debug tool window: There’s a lot going on here, so let’s start by discussing the two primary tabs (the top-level tabs, so to speak). They are: - Debugger — this actually shows the various debugging options that we are going to discuss in just a moment. - Console — this area shows the command-line output, if your application has any. Directly to the right of these tabs is a set of buttons that allow you to navigate around the code being debugged. They include letting you - Show Execution Point ( Alt+F10), - Step Over ( F8), - Step Into ( F7), - Force Step Into ( Alt+Shift+F7), - Step Out ( Shift+F8), - and Run to Cursor ( Alt+F9). There’s also a button that lets you Evaluate Arbitrary Expression ( Alt+F8) — we’ll talk about this later. To the left of the tabs is a vertical column of buttons that contains higher-level controls for debugging, including buttons for resuming execution or stopping the application, an ability do display breakpoint settings, and other miscellaneous controls. So let’s get back to the Debugger tab. This tab has lots of things going on. First of all, on the left, it lets you actually pick the threads that you want to inspect. Modern applications run on many threads, so you can pick one from a drop-down list: Directly below that is the stack frame, i.e., a list of the nested functions that were invoked as you were going through the code. Each entry lists the full name of the function (or constructor), the file name and the line number. Clicking the line causes CLion to open the corresponding file at the specified line number: To the right of the stack frame, we have two tabs: Variables and GDB (LLDB). We’ll talk about variables in just a moment; as far as GDB (LLDB) is concerned, this tab essentially shows the command-line output from GDB (LLDB) itself, since that’s the debugger that’s being used to debug our app. Variables The simplest way to view the state of a variable is, of course, in code. Simply hover the mouse over the variable in question and you should see something like the following: If you press Ctrl+F1 (Windows/Linux)/ ⌘F1 (OS X) at this point, a window will pop up containing the inner states of the variable you are after: Of course, you get a more comprehensive view of variables in the Debug tool window. For a chosen function in the stack frame, the Variables tab shows the state of all the variables. In a complicated application, it can get quite busy: For any one variable we can expand the tree to see its contents: If you want to cut out the noise a little bit, simply right-click the variable and choose Inspect: this opens up a separate window for inspecting this variable only: It is entirely possible to actually alter the values of the variables in the debug session. Right-click the variable and choose Set Value. The editor will open in-place over the current value, letting you type in the new value: GNU STL Renderers As a special enhancement of the debugging experience, CLion treats STL containers with extra care, making sure you get the best possible representation during the debug process. For example, here’s a look at how an std::map can be presented in the debugger: This feature works in GCC, and in the case of Clang it works for libstdc++ only. This requires the following setting to be added to CMakeLists.txt: Watches Capturing every single variable at every single point results in far too much information. Sometimes, you want to focus on a specific variable and the way it changes throughout program execution, including monitoring changes when the variable in question is not local to the code you are inspecting. This is what the Watch area of the Debug tool window is for. To start watching a variable, simply press the Add button ( Alt+Insert (Windows/Linux)/ ⌘N (OS X)) and type in the name of the variable to watch. Code completion is available here too. Alternatively, pick an existing variable, right-click it and choose Add to watches. Now the window will keep displaying the value of the variable even if you are in some nested part of the stack frame: Evaluating Expressions You can see variable states on a breakpoint, but what if you want to see the sum of two variables, or evaluate the result of a function call then and there? There’s functionality for that too. Simply press the Evaluate Expression button ( Alt+F8) on the Debug tool window and type in your expression. As always, you get code completion here, and after you press the Evaluate button, the result area below will display the result of the evaluation: You can also use a shortcut ( Ctrl+Shift+Enter) to add this expression to watches. That’s right – watches can contain arbitrary expressions, not just single variables! Watch CLion debugging features in action: Conclusion This post has shown what CLion can do for you when debugging. You can evaluate these features for free for 30 days, simply download the build from our site. Give it a go, and let us know what you think! ■ This is an awesome IDE for gcc/g++ right now. I would love to be able to connect a debug session remotely to a gcc/g++ application running on a cross-compiled ARM embedded target. Please support that at some point (soon). Thanks. Feel free to upvote: debugging from within Clion doesn’t work at all on my Linux Mint 17 machine with gcc 4.8.2. It doesn’t show variable data, sometimes my application gets terminated with some “command timeout” message, and more of the same. Note that this is a standard out-of-the-box OS installation, and Clion has not been tweaked either. Note also that debuggin from within QtCreator works flawlessly (thank God) Have you tried debugging with the bundled GDB (that comes with CLion) but from the console? Does it work? It is very often to got “command timed out” message and the gdb does not have any response. When use top command, the gdb process used 100%CPU and I have to manually kill it. Have you experience this with 1.0.3 as well? We’ve fixed some similar issues there. If yes, please, submit to. Same with version 1.0.3 Please, try the latest 1.0.4 that includes more fixes for exactly this problem: Could you please try this build: and share if the problem is still there. Hi, would it be possible to add a functionality similar to Image Watch for Visual Studio ( )? It would be incredibly helpful for me (and I believe also for others) :). Thanks. Thanks for the suggestion. I’ve added it to the tracker (). You can follow to get the updates, upvote, comment. Still this doesn’t look like a top prio task for now, but we’ll consider it for later. Thanks again. Inject CUDA debugger in your IDE and it will be perfect product. Feel free to comment about it in this feature request about CUDA support: CLion looks awesome and I guess I’ll soon offer myself yet another Jetbrain license. Though There is a feature I can’t find anywhere in documentation. One of the most useful feature of a debugger when multiple threads walk on each other toes is “data breakpoint”: It enables you to find who the hell is overriding your favorite variable in a matter of seconds! I can’t count how often I’ve used this in Visual Studio. Does such feature exist in CLion ? Data breakpoints are called watchpoints in GDB and supported in CLion: right-click on any variable and select ‘Add Watchpoint’. I don’t see “Add Watchpoint” when I right-click a member variable. Bug or not supported? If you still experience the problem, please, submit some description to our tracker. For me this feature is also missing. I submitted this issue to the tracker. Please upvote by pressing the little thumb if you also want this feature. Thanks for creating a request! So far I am very impressed with the quality of Clion. Well done! Debugging visualizers: You mention you pay special attention to STL classes to display them nicely in the debugger. I am using Clang, with stdlib=libc++, not libstdc++, so i am not getting the pretty debugging visualization as you note above. Is it possible for me to write my own? Because this would in general not just apply to STL classes, but to any classes, even user created ones. In Visual Studio this is called Visualizers. Is there something similar already in CLion, or planned for the future? Because CLion uses GDb as a debugger now, you can provide a custom GDB extension and set it in gdbinit. Where should the .gdbinit file be stored ? I tried under /home/[user]/.gdbinit and /path/to/clion/bin/gdb/.gdbinit and it didn’t work. I have a special function that shows unicode strings in gdb ~/.gdbinit, that is /home/[user]/.gdbinit, should work. In the home directory it works, but shouldn’t it work also putting the file in the build directory, “cmake-build-debug”? I’m trying to enhance the clion integration with conan with a new conan generator that generates a “. gdbinit/.lldbinit” file containing the paths of the source code for the dependencies. But copying the “.gdbinit” file to the userhome doesn’t feel good. The config files should be taken from the build directory. In which folder is the debugger launched? gdb/lldb take these files from the current folder automatically. Unfortunately I can’t get the debugger to work correctly at all. No variables values are appearing. The types are shown correctly. I use CLion 1.0.3, Mac OS 10.10.3. Bundled GDB 7.8 is activated. First usage of a debugging session Mac OS is asking for permissions to allowing control over the software to debug, which I allow. Hope there is a quick fix, because debugging is quite crucial for productive software development. Thank you! Could you provide some screenshot or some sample to reproduce. Send it to clion-support at jetbrains.com please. We’ll get in touch asap. Hello! Did you get my mails? Thank you Yes. Sent you the answer already. I experience exactly the same situation on Mac. Just in my case I get “command timed out” message. Have you fixed it yet? What version are you using? If 1.0.5 (the latest update) then please share the debug log: collect debug logs (Help | Configure Debug Log | Add #com.jetbrains.cidr.execution.debugger) while starting a session and send to us (logs can be found in Help | Show Log) to clion-support at jetbrains.com. It should be fixed, but if you still get it, please, provide some log to us, will have a look. Could you please try this build: and share if the problem is still there. Could you please try this build: and share if the problem is still there. Hi everyone, How do I watch the values of an vector? When I add to watches it is showed the pointers. What do you see in Variables tab? Do you have GNU C++ library renderers ON in settings Build, Execution, Deployment | Debugger? What OS/compiler/standard library do you use? Hi Anastacia, Thank you for answer. The new version of Clion 1.1 changed the debugger from GDB to LLDB. With this, I can see the values now. Great. Happy to hear that. Hey there! Is it possible to open up a console window when you run the program, instead of using the build in window? No, it’s not. And why do you need it? What’s the use case? Well, sometimes I need to put the end-of-file marker (aka ctrl-z in Windows) and I can’t do it in the built-in window but in console. Using alt+026 puts this “→”. I guess, it isn’t the eof-marker. Probably, you can suggest another way to put marker. It would be nice too. Have you tried Ctrl+D? Oh. Thanks Dear Anastasia, I have the same request. I am developing a console application that uses ncurses library for text “formatting”, and the output of the built-in window is incorrect for colored text at least on OS X. Viktor, I believe this is connected to the following problem: Dear Anastasia, thank you for the answer. Indeed, the problem is described as what I’m experiencing is. I guess, the best solution might be having an option “debug in a new window” or “run in a new window” along with “debug” and “run” options. Having said that, currently it is almost possible by having a terminal win a running debug application and attaching CLion using remote debugging. If you had an option of running an application in a separate terminal session and attaching to it automatically, that would be awesome. The problem described in is partially solved by exporting a “TERM” environment variable in configuration settings, i.e.: “TERM=xterm” ok, thanks for the update When I debug my code ,It’s very slow.Logs show an error happend: clion1.1 gdb 7.8 (bundled) archlinux with rf kernel(4.1.2-pf #1 SMP PREEMPT Wed Aug 12 14:24:15 CST 2015 x86_64 GNU/Linux) logs: 2015-08-21 18:08:16,348 [ 849897] INFO – #com.jetbrains.cidr.lang – myckeys_test.cpp: DFA time is over 2015-08-21 18:08:16,604 [ 850153] INFO – brains.cidr.execution.debugger – Debugger started 2015-08-21 18:08:22,870 [ 856419] WARN – brains.cidr.execution.debugger – >-var-create – * “idSize” 2015-08-21 18:08:22,870 [ 856419] WARN – brains.cidr.execution.debugger – -var-create – * “idSize” 2015-08-21 18:08:27,980 [ 861529] WARN – brains.cidr.execution.debugger – -var-create – * “idSize” 2015-08-21 18:08:33,566 [ 867115] WARN – brains.cidr.execution.debugger – -var-create – * “idSize” 2015-08-21 18:08:38,677 [ 872226] WARN – brains.cidr.execution.debugger – -var-create – * “idSize” 2015-08-21 18:08:43,983 [ 877532] WARN – brains.cidr.execution.debugger – -var-create – * “idSize” 2015-08-21 18:08:49,316 [ 882865] WARN – brains.cidr.execution.debugger – -var-create – * “idSize” 2015-08-21 18:08:54,549 [ 888098] WARN – brains.cidr.execution.debugger – <^error,msg="-var-create: unable to create variable object" 2015-08-21 18:08:58,972 [ 892521] WARN – brains.cidr.execution.debugger – Cannot detach/abort. Forcing driver termination 2015-08-21 18:08:58,990 [ 892539] INFO – brains.cidr.execution.debugger – Execution finished com.intellij.execution.ExecutionException: Execution finished at com.jetbrains.cidr.execution.ExecutionResult.get(ExecutionResult.java:51) at com.jetbrains.cidr.execution.debugger.backend.gdb.GDBDriver.executeCommand(GDBDriver.java:2247) at com.jetbrains.cidr.execution.debugger.backend.gdb.GDBDriver.executeCommand(GDBDriver.java:2242) at com.jetbrains.cidr.execution.debugger.backend.gdb.GDBDriver.getVariables(GDBDriver.java:1334) at com.jetbrains.cidr.execution.debugger.CidrStackFrame$3.run(CidrStackFrame.java:143) at com.jetbrains.cidr.execution.debugger.CidrDebugProcess$MyCommandProcessor.consume(CidrDebugProcess.java:678) at com.jetbrains.cidr.execution.debugger.CidrDebugProcess$MyCommandProcessor.consume(CidrDebugProcess.java:671) at com.intellij.util.concurrency.QueueProcessor$2$1.run(QueueProcessor.java:110) at com.intellij.util.concurrency.QueueProcessor.runSafely(QueueProcessor.java:238) at com.intellij.util.concurrency.QueueProcessor$2.consume(QueueProcessor.java:107) at com.intellij.util.concurrency.QueueProcessor$2.consume(QueueProcessor.java:104) at com.intellij.util.concurrency.QueueProcessor$3$1.run(QueueProcessor.java:215) at com.intellij.util.concurrency.QueueProcessor.runSafely(QueueProcessor.java:238) at com.intellij.util.concurrency.QueueProcessor$3.run(QueueProcessor.java:212)) Caused by: com.intellij.execution.ExecutionFinishedException: Execution finished at com.jetbrains.cidr.execution.debugger.backend.gdb.GDBDriver.sendRequest(GDBDriver.java:1874) at com.jetbrains.cidr.execution.debugger.backend.gdb.GDBDriver.sendRequestAndWait(GDBDriver.java:1857) at com.jetbrains.cidr.execution.debugger.backend.gdb.GDBDriver.sendRequestAndWait(GDBDriver.java:1849) at com.jetbrains.cidr.execution.debugger.backend.gdb.GDBDriver.a(GDBDriver.java:1606) at com.jetbrains.cidr.execution.debugger.backend.gdb.GDBDriver.a(GDBDriver.java:1561) at com.jetbrains.cidr.execution.debugger.backend.gdb.GDBDriver.a(GDBDriver.java:1376) at com.jetbrains.cidr.execution.debugger.backend.gdb.GDBDriver.access$7300(GDBDriver.java:45) at com.jetbrains.cidr.execution.debugger.backend.gdb.GDBDriver$30.run(GDBDriver.java:1341) at com.jetbrains.cidr.execution.debugger.backend.gdb.GDBDriver$30.run(GDBDriver.java:1334) at com.jetbrains.cidr.execution.debugger.backend.gdb.GDBDriver$36.run(GDBDriver.java:2274) at com.intellij.util.concurrency.QueueProcessor$RunnableConsumer.consume(QueueProcessor.java:298) at com.intellij.util.concurrency.QueueProcessor$RunnableConsumer.consume(QueueProcessor.java:295) … 14 more 2015-08-21 18:08:59,010 [ 892559] INFO – brains.cidr.execution.debugger – Debugger exited with code 0 2015-08-21 18:09:02,202 [ 895751] INFO – #com.jetbrains.cidr.cpp – Executing CMake: /home/czj/tools/clion-1.0.5/bin/cmake/bin/cmake -G "Unix Makefiles" /tmp/cmake_check_environment0.tmp 2015-08-21 18:09:14,278 [ 907827] INFO – #com.jetbrains.cidr.lang – myckeys_test.cpp: DFA time is over 2015-08-21 18:09:14,765 [ 908314] INFO – #com.jetbrains.cidr.lang – myckeys_test.cpp: DFA time is over 2015-08-21 18:09:30,532 [ 924081] INFO – #com.jetbrains.cidr.lang – myckeys_test.cpp: DFA time is over 2015-08-21 18:09:31,001 [ 924550] INFO – #com.jetbrains.cidr.lang – myckeys_test.cpp: DFA time is over 2015-08-21 18:09:59,296 [ 952845] INFO – ellij.concurrency.JobScheduler – 50 ms execution limit failed for: com.intellij.openapi.progress.impl.CoreProgressManager$1@5f3dd194; elapsed time was 173ms codes: #include using namespace std; int main() { cout << "Hello, World!" << endl; unsigned char hello[2048]={0}; for(int i=0;i<2048;i++){ hello[i]=i%256; } int i=20; int j=30; int t=i+j*2; cout<<"t="<<t<<"hello="<<hello[302]<<endl; return 0; } when debug step in loop ,"WARN – brains.cidr.execution.debugger – Cannot detach/abort. Forcing driver termination" Could you please try this build: and share if the problem is still there. Thanks for reporting this. It looks like a known issue () that we’re currently working on. However to make sure that it is your case could you please send us full logs of debugging (you can attach them to the issue I’ve provided). Just put into Help -> Configure Debug Log Settings . The logs will be at Help -> Show Log in Files Hello So far, I’m very happy with CLion. I’m running latest 1.1. My only real issue currently is that, when starting to debug my executable, I need to wait for 45 seconds before the program really starts )and my first breakpoint is hit in main( ) ) Very strange because when running with gdb from a bash session, startup is instantaneous. There are obviously gears turning under the hood, but some feedback/customization would be nice. 5 seconds would be slightly annoying, but 45 seconds is nearly a no-go for me (my dad who used punch cards would disagree but…) Thanks for any help you can provide Best Benjamin (Belgium) Could you send us your logs? You need to put into Help -> Configure Debug Log Settings . The logs will be at Help -> Show Log in Files Could you please try this build: and share if the problem is still there. Hello! I have some problem: Clion duplicates and reprinting all input data. How can I turn it off? Could you please provide more details on the problem? OS, CLion version, some code sample? Send it pls to clion-support at jetbrains.com and we’ll see what’s going on for you there. Anastasia it is my code: #include #include using namespace std; int main() { cout <“; int a; cin>>a; cout<5 input a–>5 5 Why is duplicates code input a–>5? Thanks you! I’m sorry, that’s not gone #include #include using namespace std; int main() { cout <“; int a; cin>>a; cout<<a; _getch(); return 0; } Code not sent… Looks like this one:. Pls add your case to the comments. Hi, I am new to CLion. I am trying to debug a simple c++ code and none of my breakpoints that I set seems to have any effect. The code simply runs through them without stopping. I am running version 1.1 on Mac OS X 10.10.5. Any idea what could be the issue? Thanks, Are you using default LLDB or switched to GDB? Could you send the project to reproduce and share with us what you do to debug, step by step. Are you pressing Run or Debug button? How do you set breakpoints? Maybe you can create short video to show us the case? Hi, I have tried both GDB and LLDB and the same occur with both. Also, I have a different project with which it stops just fine. I am indeed using the debug button and setting Configurationto Debug in the configuration. I set the breakpoints by clicking in the grey margin on the left. data-url=”” Hi I have found the problem actually. I had a set(CMAKE_BUILD_TYPE RELEASE) in my CMAKE and despite the debug option in the configuration it would not stop. Removing this unwanted statement solved my issue. Thanks for your support and reactivity. Hi, Is it possible to debug a library compiled within CLion but called from a python script? To be more specific, I have a fortran/c++ project that I compile into a library from CLion. Then I call this library from python using ctypes and I would like to be able to debug the underlying fortran/c++ code with CLion. After compiling the library I created a configuration file that calls my python script. I can execute this liking the play button without any trouble. However, If I try to debug it then I obtain a couldn’t create target error message. I attach a the video: . Currently it’s not possible. You need attach to process functionality for this, that’s not ready yet: So now that attach to process is available (well, in the EAP version of CLion), how can we debug cpp code called from Python ctypes? Currently you can connect to the local process either with Python or with C/C++ debugger. It’s not possible to connect with one to debug both. So most likely it will be working in case of CPP-process you can try to connect to, that is called via ctypes. If you try, we’ll be glad to listen to your feedback and experience. With CLion 2017.3, it is possible and works well. In fact you can debug at the same time the python code and the underlying C++ code, all with CLion. To do this you need to first start debugging the python code, and then “Attach to local process”, and select the python process. You will effectively have two debuggers – one for the python code and one for the C++, in two different tabs within CLion. Note however, you cannot “step into” directly from the python ctypes call into C++, you need to attach and set a breakpoint in the C++ code. I’m using CLion 1.2.1 and would like to get the debugger functionality working. I am using the bundled gdb and cannot get it working, I get a connection timed out error message. /g/g15/kmccandl/Phoenix/vbl-upgrade/miniapp/build/Debug/testpropagator Command timed out The GDB dialog says: GNU gdb (GDB)". python >>>>>No source file named /g/g15/kmccandl/Phoenix/vbl-upgrade/miniapp/vblfourierpropagator.cpp. However, this file does indeed exist: sierra1620{kmccandl}:ls -l /g/g15/kmccandl/Phoenix/vbl-upgrade/miniapp/vblfourierpropagator.cpp -rw------- 1 kmccandl kmccandl 7476 Dec 2 07:19 /g/g15/kmccandl/Phoenix/vbl-upgrade/miniapp/vblfourierpropagator.cpp Do you know what I can do to diagnose further what is wrong? Are there any symlinks there? If yes, is this reproducible in case you open the project by the original path, without symlinks? Also debug logs can be helpful. Configure debug logs (call Help | Configure Debug Log, add #com.jetbrains.cidr.execution.debugger in the windows),collect them while starting a session and send to us (logs can be found in Help | Show Log) to clion-support at jetbrains.com. Did you find a solution for this? I am having a similar problem in CLion 1.2.2. I get the same “No source file named…” message for the file where I set the breakpoint. The debugger therefore does not stop at the breakpoint. We didn’t get any logs or answers, as far as I know. Could you please check about the symlinks (as I asked above)? And send logs to us as described. Thanks for the logs. As I’ve replied in the email, I’ve put it into. Could you also check if it works with the debugger from the system (not the bundled one)? Please, reply in the corresponding ticket, if possible. I found the issue, but it was on our side. We have code in our cmake file that sets the build type depending on the directory that cmake is called from (debug or release). This code defaults to release if it can’t match the directory that cmake is called from (which it can’t since CLion uses its own directories). So the ticket might be invalid. Nevertheless, I would really like to be able to set the directory cmake is called from. Are you planning to add this in the future? Thanks for letting us know. Currently files under ~/.clion/system/cmake/generated are not intended to be used directly, they are managed and updated by the IDE. You can still change the whole IDE’s system path (). If you still see some reasoning in changing cmake dir, then please leave the comment here:, and describe the use case. We are considering the option for now. Could you please try this build: and share if the problem is still there. Hi, When debugging a project, I met the annoying “Command timed out” problem with Clion 1.2.4, no matter whether I used the bundled gdb(7.8) or the host gdb(7.10.1). The debugger window just showed the information “collecting data” and gdb was eating a lot of memory and cpu resources, but no further information came and the debug operation disabled. How could this problem be resolved? Could you please collect debug logs as described here () and submit a request with OS, product version and GDB versions? We’ll investigate. Thanks in advance. Request has been submitted.Hope you guys can resolve this as soon as possible. Thanks. We saw it. Hope to investigate and find the reason soon. By the way, we asked you for the logs. Have you submitted them? Can’t find them still. Could you please try this build: and share if the problem is still there. Hi, I’m writing openGL code that uses some global variables. When I’m in the debugger, it won’t let me examine my global variables. I unchecked the “hide out of scope” option, but that didn’t help. What can I do to to inspect these global variables from within any function? Currently, there is no dedicated view for globals, though you can use Evaluate dialog (Alt+F8) as a workaround. Here is a feature request that should be able to solve your case:. Feel free to leave a comment there. When will the features mentioned in this EAP appear in the final release? I am in need of this attach to local processes feature as I am working on a multi-processes project. So it a pity this still can’t be seen in the current version. Attach to local process is available since 2016.1 release a week ago. Hi, We are using CLion2016.1.1. We use GNU GDB 7.8 for debugging. Windows is our platform. Our most annoying problem is that while debugging 1. Sometimes we don’t see values for some variables in the Debugger->Variables Tab. 2. Sometimes we see values which are not the same if we compare those in the Variables & Watches Tab in Debugger. 3. The worse case is that the values in Variables and Watches are different to what we see in console if we print the values to console. In short the debugger is not usable. We really like CLion but with this untrusty debugger we are forced to think about moving to a different IDE. If there is already a solution to the problem or is a known issue, please let us know the latest status. Appreciate any helpful reply on this. Forgot one more important issue. The GDB crashes if we debug an inline function. Could you please provide us the logs on the crash (-) or at least the code sample to reproduce? We are sorry for such a problem. We are currently working on a set of problems in debugger including this one described:. We can’t provide any estimations, though we do our best to finish it asap. Thanks for info. Looking forward to getting the fix asap. Could you please try this build: and share if the problem is still there. During startup program exited with code 127. Process finished with exit code 0 Do you mean you experience some problem in CLion? Could you then please provide more details. I have the same problem, when The program can run smoothly, but when trying to debug with breakpoint. CLion just display During startup program exited with code 127. Process finished with exit code 0 Which version do you use? Could you please collect logs as described here when the problem happens and report to our support:- This EAP build has been a major improvement. I am looking forward to the next release. Thanks! Hi, CLion is a great IDE, but I experience one major issue — I work on a big project and CLion does not open some .cpp files (no visible pattern), files are not opened by double clicking in the project view, from Cmd+Ctrl+O window or by pressing Cmd+Ctrl+Up in corresponding header. I could not find any solution on the Internet so far. Could you please attach the screenshot of how these files look like on the project view window? Sure, I have uploaded it here (I had to erase filenames, sorry about that) I can open the first and the third cpp files, but if I double click the second one nothing happens. what if i want to compile using cmake/clion but attach to a different process then the “main” one can i change the build configuration so it doesn’t attach itself automatically to a single process? To attach to any process running locally simply use Run | Attach to local process. Then select the process in the list. I am using CLion 2016.2.2 Build #CL-162.1967.7, built on September 5, 2016 On OSx 10.11.6 to debug a program on a remote linux server. I am using a custom build of GDB which works form the command line. When launching the debugger in Clion it keeps failing: GNU gdb (GDB)15.4.0 –target=x86_64-linux-gnu”. Type “show configuration” for configuration details. For bug reporting instructions, please see: . Find the GDB manual and other documentation resources online at: . For help, type “help”. Type “apropos word” to search for commands related to “word”. python >>>>>>>No source file named /Users/rogerblain/Documents/dataengine/src/main/core_engine.cpp. No source file named /Users/rogerblain/Documents/dataengine/src/main/core_engine.cpp. The source file does exist! Or O get: >>>>>>No source file named /Users/rogerblain/Documents/dataengine/src/main/core_engine.cpp. No source file named /Users/rogerblain/Documents/dataengine/src/main/core_engine.cpp. warning: Unable to find dynamic linker breakpoint function. GDB will be unable to debug shared library initializers and track explicitly loaded dynamic code. 0x00007ffff7dddaf0 in ?? () warning: Could not load shared library symbols for 11 libraries, e.g. /lib/x86_64-linux-gnu/libpthread.so.0. Use the “info sharedlibrary” command to see the complete listing. Do you need “set solib-search-path” or “set sysroot”? [Inferior 1 (process 17514) exited with code 01] I also need to know how to run with: extended-remote? Have you configured path mappings in the configuration settings? I have a similar problem, I can not make shared library breakpoint, although the executable breakpoint is OK。I cross debug my linux program on my windows pc,and I use the mingw64 gdb。 May I ask you to report an issue () with a reproducible example and/or with debugger logs captured like described here:-? How to view static and global variables in debug mode, rather than add to watches. Unfortunately, no was currently. We have the following features requests about the topic: – – I can’t find how to make breakpoints work. I built a library and some tests using makefile. I’d like to start tests in the debugger using Clion. Since makefile creates hidden folders for the binaries and I can’t specify path to the binary in Debug Configuration->Executable, I copy tests/libraries to different folder. Whenever I set the breakpoints and start debugger, I see that a test is running but it never hits the breakpoints. If I pause the debugging, I see correct stack trace Clion can’t find appropriate source files. Do I need to change some configuration to help CLion to find all sources?. Unfortunately, since 2016.2 using lldb, I can only see the first element of arrays in the Variable view. In 2016.1 I could expand the array/pointer variable and it showed the first elements at that address. Makes Clion very uncomfortable for me. Yes, this is a known bug –. Thanks for pinging. I am trying to debug a fortran project. I can compile it within CLion IDE however it seems that I am unable to set any breakpoints ? Is that expected? F. Do you mean a project in Fortran? Anastasia, I have remote debugging working but I am unable to step into libraries. Is there a way to use “set solib-search-path” from the Clion ide? Thanks, Seth I keep getting How can I ensure that it’s built with the proper debug options? When the build is run the actual cmake command is printed to messages tool window. You can check it there. As well as the rest of the build output. Are there any plans to add breakpoints based on data changes? In MSVC you can set a breakpoint to trigger if a specified memory range is modified. Do you mean adding a data breakpoint monitoring an arbitrary memory range, not only some variable/member? Because the latter is already possible using watchpoints. Hello, could you help me, I just want to know how to turn off the disassembly view.. I also want to know this !Do you know now?Can you tell me? Hi, is it possible to debug forked processes? cheers Unfortunately no easy way: However, you should be able to attach to it via “Attach to local process” using the process id Hello, This is the 2nd time i use Clion for school projects and i’m very happy with it. Unfortunately,n there is something i don’t understand: The first time i used it was on Manjaroo with the latest build. Out of the box the debuger would show me variables & stop at breakpoints. Now i am on Fedora 26, still with latest Clion and when i hit ‘debug’ the debuger would stop at any breakpoints & i wouldn’t have any variables in the below frame. I eventually resolved the problem by adding: set(CMAKE_CXX_FLAGS “-g”) after some searching on the web. And i noticed that even tough gdb would stop, all of the breakpoints (even some that i knew couldn’t get hit), were checked with the ‘v’ on it. So my questions are: – Why did i have to add a cxx flags on fedora and not in manjaroo (if i recall right there was some flags in my CMakeLists.txt) – Is my flag right ? Is it no better to do: set(CMAKE_CXX_FLAGS “${CMAKE_CXX_FLAGS -g} ? – Why are all the breakpoints checked ? Even impossibles ones .. Thank you very much for your time ! i mistyped the sentence “Now i am on Fedora 26, still with the latest build and the debuger WOULDNT stop at any breakpoints”. Thank you. Well, indeed, for the debugger to work, it requires a binary built with debug info, and that’s what -g is for. However, usually you don’t need to specify it by hand as long as you build and run a proper CMake configuration (for instance, Debug or RelWithDebInfo), in that case CMake would add the necessary flag for you. As for breakpoints, currently they become “checked” after registering them in the GDB/LLDB, regardless whether they can hit or not. In fact, even breakpoints outside any function would map to the first instruction of some function (usually the nearest one below), so they could hit, in theory. Regarding your debugging issues on Fedora, may I ask you to create a ticket in the tracker, with some additional logs collected as described here:-? You will need to reproduce the issue _after_ enabling logging. Thank you! Dear clion team, I am trying to debug an imported c++ project. Instead of receiving an exception breakpoint the program quits and shows ‘Process finished with exit code 1’ in the console. What could possibly cause the problem? I sent my log files to clion-support at jetbrains.com Kind regards, Benjamin We’ll investigate the logs and will answer you via a support channel. When my code crashes, can Clion show me the crashed line of code, like other tools would for say a Java program? can you please let me know?! this is a deal-breaker for me as I’ve wasted lots of time on this during my trial period. Thanks in advance! Do you mean a crash on run? Or during the debug session? So far the debugger and STL containers has not worked for me. I click on the arrow but instead of giving the elements of the set (or map) the arrow disappears and the ui remains the same. Is anyone else having this problem? Could you please specify the OS, the debugger and the code sample where you see the issue? Thanks Hi, I also came across a problem when I was using the debug and watch in Clion. The debugger and watches can’t display the right length of a set and stack, for example, let’s say a set “set iSet” contains 1, 2, 3, 4, 5. However, when I was using the debugger and watches, it says the length of iSet is 0, let alone to check each variable in iSet. Currently, i am on a Mac OX, using the g++ to compile C++ codes. Do you know how can I solve this problem? Thank you. Do you use GDB or LLDB? Hello, I’m facing a weird bug where whenever I step into the loop using ‘Step Over’, CLion losts track of where the process was, and doesn’t let me continue anymore as the program is paused, and ‘Resume Program’ button is not activated. I am currently using – MacBook Pro (15-inch, 2016) MacOS Mojave Version 10.14.2 CLion 2018.3.1 Build 183.4588.63(Latest Build) Thank you! Forgot to mention the most important thing.. I am currently using lldb as a debugger. Could you please collect the additional debugger logs as described here:-, and send to our support clion-support at jetbrains.com? CLion is performing admirably. However, the console output in debug does not much stdout when running the same program from the command line. Here is stdout when I get the following: ./test………….. –gtest_output=xml:/home/unix2/………………test.xml Running main() from gmock_main.cc [==========] Running 4 tests from 1 test case. [———-] Global test environment set-up. [———-] 4 tests from TEST_…. [ RUN ] TEST_one [ OK ] TEST_one (4 ms) [ RUN ] TEST_two [ OK ] TEST_two (2 ms) [ RUN ] TEST_three [ OK ] TEST_three (2 ms) [ RUN ] TEST_four [ OK ] TEST_four (2 ms) [———-] 4 tests from TEST_…. (10 ms total) [———-] Global test environment tear-down [==========] 4 tests from 1 test case ran. (10 ms total) [ PASSED ] 4 tests. make[1]: Leaving directory ….. However, when run from in CLion, I do not see the stdout. I only see Testing started at 5:16 PM … /home/unix2/…./cmake-build-debug/… –gtest_filter=* –gtest_color=no Running main() from gmock_main.cc Process finished with exit code 0 [… replace filepaths] Why does the debug console not show the full stdout output and how can I retrieve that? Thank you!! Are you running a Google Test Run configuration in CLion? You can run Google tests from the IDE, CLion detects them and provides built-in results viewer. If you still want to run tests w/o CLion’s Google Test integration, please provide the details at for us to investigate. Maybe some screenshots or a short screencast can be added to get into the details better. I cannot seem to make exception breakpoints work in remote debugging. Any known issues with this By remote debugging, do you mean remote GDB server debug or full remote mode? Full remote as described here Full remote as described here Could you please set a detailed debugging logging as described here:-, collect logs and send them to our support clion-support@jetbrains.com? I am running big applications in Python in PyCharm and I am calling shared libraries in c++. So, my C++ code cannot be called and debugged in CLion as a standalone program. I was using Visual Studio Code where I could configure python script to run my process, then the c++ debugger gets attached to this process so I can place breakpoints in C++ code and debug them. Can I do similar things with CLion: run a python process and set CLion breakpoint in a library c++ function? Not out of the box unfortunately. You can run a python process and then attach to it using GDB/LLDB from CLion in order to debug your native extension.
https://blog.jetbrains.com/clion/2015/05/debug-clion/
CC-MAIN-2019-22
refinedweb
7,730
67.04
In this section we will discuss about the first java program example. To create a Java program we would be required to create a Java class. In this class we will print a string like "IIT Mumbai". To demonstrate about a Java program I am giving a simple example. Example Here I am giving a simple example which will demonstrate you about how to write your first program in Java. In this example I have created a simple class named College.java. In side this class created a method named displayDetails() which will print the string "IIT Mumbai" on call. This class also contained a public static main method inside which Instantiate the class and called the method displayDetails(). Source Code public class College { String str = "IIT Mumbai"; public void displayDetails() { System.out.println(str); } public static void main(String args[]) { College college = new College(); college.displayDetails(); } } Output Advertisements Posted on: December: First Java Program Example Post your Comment
http://www.roseindia.net/java/example/java/core/first-java-program-example.shtml
CC-MAIN-2016-36
refinedweb
159
57.37
Jumbo shrimp. Instant classic. Military intelligence. C++ refactoring browser. Spot the pattern yet? Up until recently, there have been more sightings of Nessy and Bigfoot than of working C++ refactoring browsers. After months of using refactoring intensively in C++, my fingers are screaming for mercy and threatening me with repetitive stress syndrome. Fortunately, things seem to be changing a bit. I recently learned of SlickEdit‘s support for C++ refactoring, so I couldn’t resist taking it for a test drive. C++ refactoring is hard. There’s no doubt about that. Just parsing C++ is hard, as I quickly found out when I wrote some scripts a couple of years ago to analyze the structure of a C++ program. Even with the help of Doxygen pre-processing, my analysis was full of holes and exceptions. Writing a robust program to correctly interpret and modify the structure of a C++ program is a nightmare come true. Frankly, I had pretty much given up all hope of every having good automated refactoring tools for C++. My best hope was that new language designers keep refactoring in mind as a primary goal of their languages, so at least we’ll have those tools in whatever language we’re programming with in ten years. So along comes SlickEdit version 10 with great promises of C++ refactoring. Surprisingly enough, that’s just one small bullet point completely hidden by a bunch of bullet-point items of no great interest or uniqueness (smart line selections? keyboard emulation? what year is this, 1992?). As a matter of fact, refactoring isn’t even mentioned in SlickEdit’s “cool features” web page! That’s not an auspicious beginning. Fortunately, things get better. The installation for the Linux demo version of SlickEdit v10 worked without a hitch. The refactoring actions feature prominently in the Tools menu and the right-click context menu. I loaded a small project I was working on (just a handful of classes-nothing big) and started applying them one at the time. Rename This is the big one. If I can only have one refactoring, I’ll take this one. Being able to rename variables, functions, and classes takes care of 75% of the refactorings I do. A tool that could reliably do that would be a major productivity boost (reliably being the key word there). How does SlickEdit’s rename work? Member variables were a dream to rename. But frankly, I can usually do that with “replace in file” and doing one edit in the header file, so that’s not very challenging. Still, good start. Trying to rename member functions was not quite as successful. Sometimes it would work like a charm, and rename the function in the cpp file, the header file, and everywhere else it was called from. Sometimes however, it would look at my code and proclaim that there was nothing to rename. Nothing? I had just right clicked on top of the function to rename! Some other times it would rename the function in a couple of classes and totally miss where it was being used. After some experimentation, it turns out that “Quick Rename” (which supposedly is not nearly as robust) worked time and time again without a single problem. That’s good I guess, but it left me with a very uneasy feeling. Thumbs up for the user interface for refactoring too. As soon as you enter your refactoring and your parameters, you are presented with a list of the files that will be modified and a diff of each of them, so you can cancel the operation if something went horribly wrong. It certainly makes you feel a lot more in control. Extract method This is a fairly common refactoring. I actually thought it would be fairly complicated, but in every test I did, SlickEdit handled it admirably. The tricky part is to figure out what arguments the new function needs to take, and every time it figured it out correctly. You even get an option to name the new function and tweak the arguments it takes before applying the refactoring. Again, great user interface. My only quibble with this refactoring is that the new methods are all made public. Uh? Would it have been so difficult to give us an option? If anything, I have just moved code from a member function to another member function in that class. By default it should be private, not public. Oh well, I just have to move one line. But it’s a bit annoying to have to tweak the header file by hand. Modify parameter list Another big one. Sometimes it’s quite painful to add a new parameter to a function that is called from dozens or hundreds of tests. So much so that it really discourages us from doing the “right” thing and is tempting to create a new function instead. Sometimes, after the second time you need to add a new parameter, we just create a struct with the parameters that the function takes and save some pain in the future. Not a particularly elegant solution, so this refactoring tool would come in very handy. Unfortunately this one completely failed for me. Most of the time, trying to add a new parameter to a function would just come back and tell me there’s nothing to do. Same thing with rearranging the order of parameters. At best, once I got it to actually add the new parameter, it only changed the function and the header file, not the calling code. Doh! Misc inheritance chain refactorings SlickEdit has a set of refactorings intended to do operations in the inheritance chain: push down, pull up, extract super class, etc. I don’t work with big inheritance chains these days, so they’re not very useful to me and I didn’t test them at all. Actually, now that I think about it, the only inheritance I use are interfaces and mock objects. Then again, I suspect this would be extremely handy for manipulating legacy code (like some currently popular game engines). Extract class This seems like a really large refactoring. Extracting a whole class out of a set of code? Rename didn’t work consistently, and modify parameter list didn’t work at all. I certainly wouldn’t want to try something of this magnitude. Let’s get the other ones working before we jump on this one. Convert local to field This one seems marginally useful, and it’s not something I do in a regular basis. All it does is to prepend an m_ to the variable and add it to the header file. What if you don’t prefix your member variables with m_? Is there a way to turn that off? Also, the new member variable wasn’t added to the constructor(s) initialization list. Move method At first I thought that it was a totally pointless refactoring since it’s describing as moving a method from one class to another (I can’t remember when was the last time I did that). But it turns out it can be quite useful to move a non-member function into a class. That’s something I do sometimes when a helper function in an anonymous namespace starts needing more and more state from the object that uses it, and eventually it becomes clear that it wants to be a member function. Move method will make it a static member function, and then you can follow that up with Convert static method to instance method and voila. Encapsulate field I’m sure some people will rave about this one, but I’m not too thrilled about it. It creates set/get methods of a member variable. Frankly, I don’t like set/get methods. I think that, most of the time, they’re a smell of bad design. I’m not sure I want to make it any easier for people to create them, so I would be happier without this refactoring tool at all. Besides, what’s with making them inline by default? At least give us an option to put them in the cpp file. Replace literal with declared constant This one takes a literal (magic number/string) and replaces with with a constant or a define. Now we’re really reaching the bottom of the barrel. Is it really faster to navigate a three-level menu to select this than to do it by hand? It’s good that you get an option to create the new constant as const, static const, or an evil #define, but it doesn’t place it in an anonymous namespace, even if one already exists in that compilation unit. Create standard methods This one will add a constructor, destructor, copy constructor, and assignment operator to the class. At first I thought it wasn’t a big deal. I already have macros that do that for new classes. Then I realized you can do this with an existing class, and it will take care of assigning all member variables. That’s pretty cool, but of limited practical use. I haven’t had to go back to many existing classes and add assignment operators. Still, I could see how it could be useful. All in all, SlickEdit managed to impress me because I wasn’t really expecting functional C++ refactorings. On the other hand, it is clearly far from being robust enough to be relied upon for production work. Maybe the next version? For me, they just need to fix the rename and I’m almost there. One cool aspect of SlickEdit is its powerful scripting language, where it has access to all the commands you can do from the menu. That means that I can write a script that, as part of what it does, kicks off some refactoring step. That’s extremely useful to adapt the refactorings to my own environment. One thing I didn’t see is whether the script language has access to the logical structure of the C++ program or whether it’s just limited to calling the refactoring function. It would be great to have more control and be able to create custom refactorings. SlickEdit is a bit puzzling because it parses all the header files during each refactoring. And by all, I mean all. Not just the ones in your projects, but all the standard include files that you might have included. I don’t really understand why it does that. I’m clearly not going to change standard header files, so I think that limiting a refactoring only to files that are presently loaded in the project would be good. With my toy projects with a handful of classes, the refactorings were very fast (a second or two), but I fear how it might scale to a large project. Next time they have an improved version I’ll have to load it up with a large codebase and see how it fares. It seems as if refactoring tools for C++ are just around the corner, but still tantalizingly out of reach. At this point I’m not ready to switch to SlickEdit based on the strength of its refactoring tools alone, although I’m still going to take a closer look at it. Right now I would prefer a standalone command-line refactoring tool that could be easily integrated in any environment. Anybody knows of any other decent C++ refactoring tools? Hey Noel, I notice that SlickEdit also have a beta going for Visual Studio. Since our company primarily mainly use Visual Studio (and the other team mixes into the mix CodeWarrior) having the refactoring tools available inside Visual Studio looks useful. I will have to go through and test the functionality of the refactoring tools inside Visual Studio. It’s not there yet. I ran the PC demo, and the thing crashes as if it would go out of style tomorrow. What’s worse, I send the company a list of detailed bug reports (+repro cases) several pages long, and never heard back from them – not my idea of customer service. Yes, it was only the demo – still, at least a “Yup. Got it” would’ve been appropriate. Add to that the fact that I have a Mac laptop while I do most of my “work” work at a PC, and they want me to buy dual licenses for that setup. I’m not shelling out $600 for a buggy editor. Cool, I hadn’t seen the Visual Studio plugin beta. I’ll give it a try over the next few days with a much larger codebase at work and see how it goes. Oh, it’s only for VS 2005 🙁 I guess that will have to wait then. Thats very cool. thanks, I will have to check this refactoring engine out. I was trying to build a refactoring/reflection/metaobjects system for C++ when I gave up on C++ and moved on to D. Ive never even heard of a language more difficult to parse than c++. You can parse D code with your eyes closed so building these tools are cake. No required forward references is more liberating than you can imagine and the compile times are 1/50th of c++. I think D is the future for game development. I gave the demo a whirl for our Spider-Man codebase – it can supposedly handle a .NET project, but we use makefiles, and it would have taken me a lot of work to show SlickEdit where all the files were, and I’m barely even a programmer anymore, so I gave up. But I’m surprised by Robert’s claims about bad customer support: they kept asking me what my problems were, assigned a tech guy to me, etc. Hi Noel, If you’re interested in C++ refactoring tools, you may want to try out Ref++: My experiences so far haven’t been great, but I’ve only tried it on a huge legacy codebase, which shall not be named. – Kim Interesting the link for Ref++. I will definitely give it a try. It’s unfortunate that it’s only a Visual Studio plug-in and not a standalone tool with an option to integrate in VS. Jamie: I have no idea. I used to use SlickEdit, and they had better support back then. Maybe because I was only a demo user? Anyways – the dual license for PC/Mac was the real kicker for me. I could’ve lived with the occasional crash(can’t be worse than VisualStudio….), but $600 out of my own pocket is beyond what I’m willing to spend on a tool I agree with you it sucks to get charged twice for 2 platforms but in general price should not be that big of an issue if it makes you more productive. Especially if you are a programmer your editor is the single piece of software you use the most. Get a good one. $300 is about $1.20 a day (assuming 250 days of work a year). I’ve been with slickedit since version 1 and I know it’s certainly been worth for me. They’ve had many things relatively early (first?) for example tags with pop up help since 1998? Of course some of that stuff is now built into VC++ but back then, especially when joining a project already in progress with a large unfamiliar code base it makes it extremely easy to jump around the code quickly. Pop into a function or structure def, follow it’s fields or variables, pop back out to where you were. I’ve never had any real issues with support over the 12 years I’ve been using it. I’m sorry to hear you had trouble. Of course programmers and editors are like religion so use whatever makes you happy and productive. This is probably a sad reason but I originally choose slickedit because it nearly perfectly emulated Brief. Something other editors claimed but all of them failed at. One thing I like about it (I’m sure some other editors can do this) is that you can configure it to never need a mouse. I can jump between windows, split them, join them etc. Open files, search, etc all without every touching a mouse and without having to tab around dialogs. Thanks for the fair and balanced review. I’m the Director of Software Development at SlickEdit, and thought I’d share a little about this feature. As you noted, C++ refactoring is an extremely difficult problem. You have to contend with macros, templates, and the liberties the compiler vendors have taken with the language spec. We designed our approach around a strong parsing and type analysis engine, and consequently it is very sensitive to the code that it is processing. When I wrote our Cool Features document, I consciously left off the C++ Refactoring because it doesn’t work for all codebases and still struggles with some situations. If it worked as well as the features currently listed, it would definitely have made the list. We are continuing to enhance the engine and work on additional “quick” refactorings that are based on our tagging engine. As you pointed out in the review, we consider these to be less “robust”. That doesn’t mean that they are more fragile, but that they may make changes that are not strictly accurate, where the regular refactorings will do more analysis to weed out these cases. Unfortunately, we don’t provide access to the underlying representation of the code, as you have asked. Likewise, it would be very difficult to provide a means to allow users to write their own refactorings. But that’s a really great idea! Feel free to contact me with ideas and questions. We’re a company of hard-core C++ programmers and we love to talk about coding!
http://gamesfromwithin.com/are-we-there-yet-slickedits-c-refactoring
CC-MAIN-2018-47
refinedweb
2,992
72.16
I am a Sun Certified Java programmer. Graduated from BITS, Pilani in 2006. Big fan of Flex, Java and BlazeDS. I believe that If it is RIA it is on Flash Platform and all applications should be RIAs. Currently working as a Computer Scientist in the Flash Builder team at Adobe. Feel free to follow me on twitter or facebook 🙂 Twitter: Note: The views expressed on this blog are entirely mine 🙂 Advertisements Hi i want to put and HTML page inside the flex website is there a way to do it as i dont want to make a popup Regards Jorge Cordero Hi Jorge, Visit the URL below for more details 🙂 hi sujit, were you figure out any drilled down feature wise difference between flex and AIR, except the URL and Desktop compatibility. rgds ravish Hi Ravish, Can you please explain what kind of a comparison you are looking for? Is it in terms of the API or is it the security? Hi Sujit, is ther any sample source code avil to integrate flex with struts… Hi sujit, I am a flash developer. recently i made a CAD application in flash using AS2. this was my first experience of any note in object oriented programming..however the project even though fairly complex went very well.. Now the clients wants me to convert this to flex. I have no prior exp. in flex, i just downloaded flex 2 builder. But am having lil problems figuring out what excatly needs done here. I am just looking for some hints n suggestions on how to go about this. warm regards siddhartha ** the application is basically a drawing application, which allows for object to be drawn, scaled, rotated, depths changed, erased, application state saved as SVG , undo/redo and few others things.. ** the client wishes to have the GUI as components extending some mx classes, but he is ready to accept for now a single component created (i only vaguely understand what that implies right now). regards sid Hi Sujit, It was good to get an update from your blog about the interest in Flex among Indians. I would like to see the applications created in 6 hours, waiting for that! It would be good if you send it across by email, if not possible to put on blogs. I would be happy to see the faster development results from the platform which I am thinking of using in startup. I am Prashant Sachdev (MBA, Babson College, Boston) starting a company in area of audio / video metadata. To start with I will be building the basic functionality similar to (veotag dot com) and currently looking for people who have some experience with Flash / Flex / AIR / actionscript. Do let me know some people who you might know and could be interested in working for startup. It would also be good to talk with the guys who participated in the contest – 6 hours application development. Do connect me with them too and especially with the winners they might have interest working with videos. Thanks Prashant Sachdev Hey Sujit, your tutorials are good.. I am using RemoteObject service call to get the data back from server into flex. Here is my problem: I am getting array of java objects into flex application, when i try to convert the java object to actionscript object in flex, am getting the error as “TypeError: Error #1034: Type Coercion failed: cannot convert Object@d68cd59 to com.mlfcst.actionscript.dto.CardEconVar.” Here is the code: ………………………. public function setEconVarDetails(event:ResultEvent):void { a_econVars= event.result as Array; var econVar:CardEconVar = new CardEconVar(); econVar = CardEconVar(a_econVars[0]); —–> getting error here } Here is my AS file: ………………………. package com.mlfcst.actionscript.dto { [RemoteClass(alias=com.mlfcst.flex.dto.CardEconVar)] public class CardEconVar { public var cardEconVarId:int; private var groupId:int; } } Here is my java code: …………………………….. package com.mlfcst.flex.dto; import java.io.Serializable; public class CardEconVar implements Serializable { private int cardEconVarId; private int groupId; public CardEconVar() { } public int getCardEconVarId() { return this.cardEconVarId; } public void setCardEconVarId(int cardEconVarId) { this.cardEconVarId = cardEconVarId; } public int getGroupId() { return this.groupId; } public void setGroupId(int groupId) { this.groupId = groupId; } } your help would be greatly appreciated.. Thanks, Baji. Hi Sujit, Thank you for the time and energy you put into your blog. I have a simple issue: I’m building a Flex/AIR app and need to print generated independently of the application. I only need to point to them and print them. Should I pursue this with LiveCycle, Blaze or something else? All the best, Jerry Hello Sujit, This is sandeep from tcs gandhinagar. I’m interested in adobe AIR and flex, I’m a beginnear in this field and don’t know much about. Could u suggest me some good tuts to start wid and and ebooks u have related to them. It would be very helpfull. I have 1 year exp in java. Hi Sandeep, Please visit the URLs below. Flex dev guide: Flex language reference: Deveoper network: Hope this helps. Hi Sujith, Is it necessary to install Flex Builder 3 Eclipse Plug-in to use BazeDS? I am not able to download above mentioned builder. But I have standalone version of Flex Builder 3. Thnaks, Dipak Hi Dipak, You need not have Flex Builder or Flex Builder Eclipse plugin to use BlazeDS. If you are having standalone version of Flex Builder that’s great and enough. BlazeDS is a server side software and will help Flex application to communicate with server side classes. Hope this information helps. Hi Sujit, Thanks a lot for your quick reply. I have to develop one chat application for my application. Could you please help me how to proceed. I know flex basics but dont have any idea about client-server and BlazeDS. I am from different background(C++ and database) and flex is totally new for me. Thanks and Regards, Dipak Hi Sujit, Thanks a lot for your quick reply. I am developing a chat application. Could you please help me how to proceed. I am new to Flex and BlazeDS. Thanks, Dipak Kumar Hi Sujit, I got the chat application done with the help of your blogs and one doc from Christophe Coenraets. Adobe documentation is really helpfull. Thanks a lot. -dipak Hi Dipak, I am sorry, I got stuck with my work and so could not reply 😦 good to know that you got this working 🙂 I hope you are using Messaging feature of BlazeDS 🙂 Feel free to contact me 🙂 Hi Sujit, Yes I have used Messaging feature of BlazeDS. Can I use BlazeDS for file transfer (like images or text file) in my chat application? If yes can you help me please. Thanks, Dipak Hi, I have a servlet at the moment. I want to integrate it with Flex UI. How can I pass my data from MXML to the servlet and then get the result back? Pls help Thanks, Neha Hi Evangelist! I m really proud to put my comments here.. It was fantastic job.. Keep it up man.. I m new to Flex… Can u guide me? What are the prerequisites I have to follow for getting into flex? Hi Sabari, If you are comfortable with any object oriented programming language, you can go ahead develop in Flex with a very small learning curve. Please visit the URL below for details. Hope this helps. hi Neha, You can use HTTPService component and invoke the servlet. Please find more details on how to do that at the URLs below. Hope this helps. Hi Sujit I’m working on a web site which will have a java enterprise application based backend and a flex 3 frontend. So far I’ve managed to get them to talk and things are going well. (Partly due to some of your excellent tutorials!) However I have run into a problem with sessions. What happing is that I have a EJB factory in the WEB tier of my J2EE application which looks up the EJBs in the business tier. The EJBs need store and retrieve stuff from the session, but when I try to instanciate a Flex session in the business tier, I just have a null returned. This is how I’m instanciating the flex session object (in the business tier of the J2EE applicaion): session = FlexContext.getFlexSession(); I’m not sure this is relevent (as its a HTTP session listener), but in the web.xml deployment descriptor I noticed this: flex.messaging.HttpFlexSession Thanks for your time in advance, you help is greatly appreciated. Regards Drayton Hi Drayton, That is how you have to get access to the session object. But I think this will return a valid session object only when the request is through BlazeDS. is your request through BlazeDS (MessageBrokerServlet)? Hi Sujit, thanks for the response! Well I’m not quite sure what you mean by is my request through BlazeDS. If you mean am I using a Flex destination to make a call, then yes it is through BlazeDS. But I do not make use of the ‘MessageBrokerServlet’ directly, there is a reference to it in my web.xml, but thats about it. This is the Java method in my business tier of my application: public String sayHello() { Date now = new Date(); session = FlexContext.getFlexSession(); return “Hello, I am ” + this.getClass().getName() + “The time is: ” + now + “” + (session != null ? “Your session id is:” + session.getId() : “Your session object is NULL!”) +””; } When I call this method, I get the ‘Your session object is NULL!’ response. Thanks once again for your help! Hi Drayton, Can you please check if the session listener is configured in web.xml under web-app tag as shown below. flex.messaging.HttpFlexSession Hope this helps. Hi, i am new to BlazeDS, i need to connect the EJB/Hibernate and Flex using BlazeDS. i am going to write EJB/Hibernate in Rational Application Developement, server is websphere and database is DB2. can you tell steps for create this Application.. thanks areef Hi Abdul, There are adapters for all these. Please visit URL below for details. Hope this helps. Hi Sujit, thanks for opportunity 🙂 I have started exploring BlazeDS (Turnkey) and after I followed and understood a simple hello world remoting example, it became very confusing to me 😐 Locally everything runs fine in IE, but remotely its a living hell… it simply does not work in IE, but in Firefox its Ok. I have tried the blazeds samples and they do work in IE, locally and remotely, but if I use my own java sql classes to retrieve data, it does not work, only in Firefox. In IE the following error appears: code: Client.Error.DeliveryInDoubt error Detail: Invalid URL url: ‘ amf’ It’s very frustrating 😦 I can’t see anything related with this on the web, at least something that makes sense to me. Thanks again Sujit, thanks Hi Jorge, Can you please try changing the nofearp_2008 to complete name with .com etc. something like nofear_2008.com Looks like Firefox is resolving it to default domain, but IE is not. Hope this helps. Hi Sujit, thanks for the tip. I’m going to create a virtual host in Tomcat in order to try what you are saying, or there is another way to try this? I’m using a VMWARE virtual machine (nofearp_2008) with Server 2008 as server machine. Thanks again Sujit Hi Jorge, Please try accessing any URL to a resource on the nofearp_2008 server from IE. See if IE is resolving the address properly. Hope this helps. Hi Sujit, thanks for helping all developers.I am working in a tight dead line project where Flex in presentation layer interacts with BlazeDS using RMI. Again BlazeDS interacts with java/JDBC classes using RMI. I searched in so many places but couldnt get how to do. Please let me know what API of BlazeDS i have to use and please give me any samples which i can use for this. I have to deliver within 15 days these changes to investment bank. Can you please give us your email id????????????? Thanks HariKrishna Hi Sujit, I want to call a java method from a Flex AIR application. I am new to flex. Can you guide me on the same? Thanks, Dhriti Hi Driti, Please have a look at the article in this URL Hope this helps. Hi Sujit, I have one Flex web application. Can you please tell me how can I convert it into a Flex AIR application. Thanks, Driti Hi Sujit, I am using mx:Tree to show the data. Certain leaf node display the check box and certain radio button using the item renderer. First time tree is expanding properly. But when I am closing and opening it again, all the leaf nodes show overlapped radio button and check box. Here is the code updateDisplayList method is used to add the radio button and checkbox to leaf node. override protected function updateDisplayList(unscaledWidth:Number,unscaledHeight:Number):void { super.updateDisplayList(unscaledWidth, unscaledHeight); if(super.data) { super.label.text = TreeListData(super.listData).label; var currentChoice:Choice = TreeListData(super.listData).item as Choice; if(currentChoice!=null){ super.label.text = currentChoice.name; super.label.x = 90; if(currentChoice.multiSelect){ this.radio.selected = currentChoice.selected; this.radio.enabled = currentChoice.enabled; this.radio.y = 18; this.radio.visible = true; this.radio.x = super.label.x +10 ; this.radio.name = super.label.text; addChild(radio as DisplayObject); }else{ this.check.selected = currentChoice.selected; this.check.visible = true; this.check.enabled = currentChoice.enabled; this.check.y = 18; this.check.x = super.label.x + 10; this.check.name = super.label.text; addChild(check as DisplayObject); } } } } Hi Driti, In Flex Builder create a new AIR based project and then copy the files in src folder of your old Flex project into the new AIR project created. Also copy the SWC files, if you have any. Hope this helps. Hi Driti, Please try overriding the set data function also. If you are already using this, please send code to reproduce the issue to sujitreddy.g@gmail.com Hope this helps. Hi Sujit, Thanks for your input. I have already override the set data method. I have forwarded code on provided id. Thanks, Driti hi sir i working with flex from two weeks. i am working with eclipse. plz be send work space project. That project taken on my eclipse see the paths and depoly and see the output in tomcat server project zip send them to my mail plz flex with java plz send me sir Hi Surendra, Please check out this URL Hope this helps. hi sujit, This is masood sofi,I developed an e-personal diary in flex camp at hyd on feb28-09,Please tell me how u like that idea. Hi Sujit I am from Hyderabad, do you live in hyderabad as i would like to know about training on flex. Regards Sudhakar Hi Masood, Very nice idea. You might want to take a look at Hi Sudhakar, No, I don’t live in Hyderabad 🙂 Please find URLs below which are good resources for learning Flex. Flex developer guide: Flex in a week videos: Hope this helps. Hi Sujit, From JSP, on form submit, I am navigating to flex application. If the form method is get, I am able to read the URL parameters but if the method is post, I am not able to read the URL parameter. Can you help me out in this issue. Thanks, Driti Hi Driti, If the method is POST the data is not passed as query string. Please find details on how to pass data to Flex application at the URL below. Hope this helps. Hi Sujit, I am new to the flex and action script , Previously i have displayed the recodrs in datagrid and selected index displayed in form. Now the problem is: read the data from xml file and displayed on the form with ids give me the sample example suji Hi Lakshmi narayana, I did not understand what you want to do. Can you please explain what exactly you want to do. Sujit, I want to create a community website in flex using blazeds. Do i have to hire a dedicated server or it will work on the normal remote server. Is it possible that if 1000’s of user are using the site at the same time will not impact the performance or wait time to the user. Also is it possible to make a chatting application possible on normal server. Is it possible that if 1000’s of user are using the chat at the same time will not impact the performance or wait time to the user. Thanks. HI SU. HiSu Please helpme on this I have not read much on your blog so far but wanted to ask you a quick question.I want to build a full application with left navs and top navs as well and of course things change when user click or take an action in the centeral pane which effect dynamically top and right navs.So what in you opinion is the best way to develop any such application. Using just Flex or some framework like Carigorm or Mate is a good idea and the passing the information between pages via this show / hide mechanism or should i use jsp as a parent and then pass parameters to child swf files..basically what in your opinion is a good idea to build an enterprise like application.I plan to use springs and hibernate at the server side using blazeds. Please suggest ! Hi Sujit, Can we do remote desktop feature using fvnc(flash vnc client)? Hi Sandy, A normal server will do. If you are using a normal polling channel for Messaging, then number of users shouldn’t be a problem. Hope this helps. Hi Lakshminarayana, Please check out the article at the URL below. Hope this helps. Hi Harsh, Go for Mate or Cairngorm and use BlazeDS on the server to exchange messages. Hope this helps. I’m a beginnear to flex.i know some of the consepts,how to manage the session in flex 3 with LCDS Hi, I’m using Flex3 and I want to check Memory Profiling in a Flex Application. where I can get ‘Configure Profiler window’ in flex3? please help me Hi Sujith, Firstly thanks for hosting such a wonderful blog. I have a query regarding executing a perl script or an executable(.exe) from Air. I have searched for around 2 days and was not sucesssful. Can you please provide me a mechanisam to achieve this. Thanks Much Cheers Sridhar Hi Sujit, Do you know where can I get certifications for Flex in India(Mumbai)? Hi Sridhar, This isn’t inbuilt. You might need to communicate through sockets. Hi Sundeep, Please find details at this URL I am big fan of you and continously reading your blogs. i need a help we have a databse in mysql user name and password is there with me, how do i connect to get those datas and display in flex , i have blazeds but i not sure which service to use i used http connector its not working.. please help me eg of my server how the data i have is asdaasdsa.in.example.com/sql124324 username – asdasda passsword – asdasda There is a sql server which has all dataes currently we can query using excel by using connect to database, but i wanted to use flashbuilder to connect and display datas and graphs please please please help me in this atleast if u can redirect me where i can get the info i ll be much more happier… Hi Suresh, You have to create a Java class which will connect to your database and return the data. Once you have this class you can use Remoting to invoke the Java class developed to get the data from the database as explained in this URL If you are using HTTPService then you should create a JSP/Servlet which will invoke the Java class created above and return the data as XML/JSON. If you are using Flash Builder 4 try articles at this URL to access Remoting destinations and JSP/Servlet easily Hope this helps. Sir, I am an ENGG Student , and I had geard of a boot camp On Adobe Flex by Adobe Systems Bangalore, in one of ma nearby college.. So i was just wondering what is this flex thing , its capabilities.. Hi Sujit Reddy garu.. how are you.. i want integrate AIR and BLAZEDS.. i’m getting stuck with this from 2days plx help me… thanks in advance Hi Sujit Reddy, Ultimate Blog on Flex….Keep it up!.. I’m new to Flex…where can i find jobs in flex in india.And what is future job market… Thanks in advance…. Regards, Hi Sujit, I am big fan of you and continously reading your blogs. I have developed a application which does the server push using BlazeDS. The application is pushing the messages to client when we browse the applocation from server where the flex application is deployed. But we have introduced a Clustering (Load Balance) server, which routes the request to the deployed servers. Using this Clustring server the client is not recieving the messages. Do you have any guidence to resolve this issue? Your answer will help me a lot. hai reddy, i am suresh kumar reddy from mumbai.Are you having Flex3 with AIR certification.i am going to give that certification next week.please give any suggestions about the materials for Interacting with data sources and servers regards, suresh kumar reddy Hi Sujit,'” What should i have to do in order to solve my problem. Regards, Naveen. hello Mr.sujit i have question for u, i’m follow your tutorial and i get problem… this my web.xml, setting : BlazeDS BlazeDS Application flex.messaging.HttpFlexSession MessageBrokerServlet MessageBrokerServlet flex.messaging.MessageBrokerServlet services.configuration.file /WEB-INF/flex/services-config.xml 1 MessageBrokerServlet /messagebroker/* index.html index.htm RDSDispatchServlet RDSDispatchServlet flex.rds.server.servlet.FrontEndServlet useAppserverSecurity false 10 RDSDispatchServlet /CFIDE/main/ide.cfm and this the error message…. RDS server message: Error executing RDS command. Status Code : 404, Reason: /blazeds/CFIDE/main/ide.cfm can you explain it thx …. Hi Sujit, I am new to FLEX. Can you plz tel me difference between Flex-Config.xml,Remote-config.xml,Services-Confige.xml and Proxy-Config.xml.. Hi Sujith, i.Can you please explain n detail the difference between array and Array collection (if possible with examples) ii. What is a bindable tag? Regards, Chandra Hi Suresh, Please find details along with sample application source code at this URL Hope this helps. Hi Chandra, Please find details at the URLs below. Hope this helps. Hi Seetha, services-config.xml is used for defining configuring remoting/messaging/proxy/data management services, channels and lots more; which will be used by AMF libraries like BlazeDS/LCDS. remoting-config.xml/messaging-config.xml etc are actually being referred from services-config.xml. Instead of including all configurations in services-config.xml, its distributed in multiple files and referenced in services-config.xml. flex-config.xml is used for configuring compiler options. Please find more details at the URL below. Hope this helps. Hi agung, Please share the version number of the BlazeDS you are using. Thanks. Hi Naveen, Please try the steps explained in the URL below. Hope this helps. Hi Sujit, first of all thank you for helping so many developpers! Thank you! There is a very interesting article on The backend with spring is generated from a tool from a database. And now the question: Can it be a problem, if a bean manged by spring is directly connected to blazeDS mapping (I do not know if that is the correct expression for it, I hope you can understand it. If not please read the comments under the mentioned URL) Thanks for a comment on this. Regards! Martin hi sujit, thank you for the good work. Same problem with agung. ie; —————– rds server message error in executing rds command status code 404 ———— my blazeds version is blazeds-turnkey-3.2.0.3978.( i have tried with different versions , but same result.) flashbuilder is version 4.0 build(253292) Any suggestion? Thank you Hi Shyju, Please download BlazeDS 4 or higher and enable RDS Servlet as explained in the URL below If you want use Flash Builder 4 with earlier versions of BlazeDS, please set up RDS Servlet as explained in the URL below Hope this helps. Thank you very much. i got it solved with blazeds 4 version. Shyju I have a situation where :- GUI producer sends message to destination1 -> The message from destination1 is read by java class and a new message is generated and sent to destination2 -> Later GUI consumer reads from destination2 and dump in GUI. I found an example at your blog. but it doesn’t work . Can u send me the working example at kumarajeya@gmail.com. Thanks in Advance. Also any better approach is highly appreciated. Hi Sujit, The link is not working 😦 hi sujit, I had attended the PHP camp held in Symbioisis, pune this month. There they gave a DVD of flex 3, i did the steps printed at the backside of the DVD cover, i havent recieved any licene Email till now, it has been already 14 days i have entered the promo code. Do you have any idea about this. thanks, naresh Hi Sujit, Iam naresh from pune, iam new to flex development, i have one problem with flex-3 application, My flex application have calls to 2 webservices which are set as virtual directories(i use the webservices’ urls which are set in the iis in my flex app) in my iis, i have creted a virtual directory for my flex app in the iis, when i run my flex application on my local machine, i get this error for the webservice urls “RPC Fault faultString=”Security error accessing url” faultCode=”Channel.Security.Error” faultDetail=”Unable to load WSDL”. This works fine when i run the swf file created at application’s path, I have searched this in the net but havent found any right solution, can you pls help me in this matter. Hi Sujith, I am an avid follower of your blog on flex. I got an issue in flex.Can you please throw some light on how to create a flex calender with events. Regards, Sita. Hi Sujit, I’m having an issue with IE8/7 while using SecureAMFChannel for one Remote object call. I have posted for some help on Adobe forum also. If you have any solution top of your mind, let me know Below is the link Thanks in advance. Feel free to forward if you know any of your colleagues who can help me with this issue Thanks Amar Hi Sujit, I am A.Bhargav Teja, 2 nd year BITS,Pilani.I attended your Boot Camp and am quite excited about Flex. I am trying to build a small app. I’ve succeeded partly but am struck at a crucial part and am unable to figure things out. It would be very helpful if you could answer my query or point to someone who could help me. Thank You in advance. My Problem:- I am trying to build an application that would make movie ticket booking easy. But I am unable to pass the parameters from flex to the database to verify whether a field is true or not. I’ve attached the .MXML file. In the file after I click FIND the application should be able to verify the movie, date, show, tickets with the database and give back if they are available or not. Is this possible. Can multiple parameters be passed at once. If not is there any other approach that would make my work easier. I would be also thankful if you could send me the link to access the airport app you demoed. Thank you once again. Hi, I am trying to retrieve mails from gmail server using Flex. By looking at your code we are trying to get similar url for retrieving mails rather than contacts but have not really succedded..Can u extend some help in case u have idea regarding the same. Hi, I had a query as to how you found out about the format for the contacts because i m trying to retrieve emails from url “” but cannot google as to the format in which objects are being returned.. Hoping for a reply soon Hi sujith, I am trying to integrate adobe flex with IBM Data Power which is a kind of ESB.I am using data power to create web service proxies for my actual end points.From flex how can hit this proxy end point.I am able to hit from soap ui.I can t use the as I can t specift the actual wsdl end point because I only expose the proxy not the actual end point and when I use httpservice it says stream error.Can you please help me. Thanks Hi Sujit, The previous post was skipped by the Advanced Data Grid Content. I am pasting the same in this comment.. ######################################### This is my AdvancedData Grid with Grouped Columns ########################################## ************************************************************************************************************************************************************************************ Hi Sujith, I’m java developer and i want to learn Flex, could you please tell me how the future for it. Thanks in advance. Hi Sujith, I am having a doubt regarding proxy-config.xml in lcds/blazeds. My requirement is to get data from one REST webservice(url looks like:http://{localhost:portno}/context-root?number=5&division=first&userName=Username-1). I did everything fine by calling and meanwhile in proxy-config.xml, i was hardcoded this url under tag. Totally, i got the data displayed in datagrid. But now as per requirement,(if you look at url,it consists of parameters “number”,”division”,”username”), -> if we enter some integer value in textinput box,and after hitting the search button,depending upon the number we entered,corresponding number of rows to be displayed. Now, My Problem is earlier i hardcoded the url in proxy-config.xml.But now proxy-config.xml has to get parameters from flex front end and also have to display accordingly. Can you help me about this issue… Thanks in advance for helping so…. hi i playing with flash builder 4 and blazeds and jpa on server on my crud the update and delete work fine using the service generated by flash builder i put autocommit false on mx.data.RPCDataManager and work great i delete and update and when i ready just make commit But my problem is when add new record on the server with @GeneratedValue the database set the id but on the client side RPCDataManager dont know the id after commit any idea Hi Sujit, Thanks for yesterday’s seminar…its awesome…good to hear from you most of valuable and coming rich internet applications. It is usefull for our application and as well as for me. Thanks Nataraj Javvaji JP Morgan Employee Hi Sujit, Thanks for yesterday’s seminar…its awesome…good to hear from you most of valuable and coming rich internet applications. It is usefull for our application and as well as for me. Thanks Nataraj Javvaji JP Morgan, Mumbai Hi sujit, It is very nice to see such a good blog for flex learners,i have one doubt,i want call struts action class from .swf file before it loading into the webpage,can you please tell how can i do it in action script file. Thanks in advance Hi Chandu, Try the articles in the URLs below: Hope this helps 🙂 Hi Nataraj, Thanks 🙂 glad you liked the session and the Flash Platform products (Flex 4 and Flash Builder 4) 🙂 Hi Eneldo, Can you please make sure, you are invoking getAll/fetchAll to get get all objects on to the client. Hope this helps. Hi Teja, Please try passing parameters from the Flex application using HTTPService to the proxy destination and the same should be passed on to the configured server. Hope this helps. hi Sujit Reddy G Thanks for your respose the solution i get ir work was assing idcolum = int++ on flex for RPCDataManager have local id managment and after commit callresponder lastresult again and work ok now i will try you sugestion thank Hi Sujit Reddy G, I am new with blazeds,active-mq, i am trying one chat example using active-mq and blazeds. First i was starts the activemq.bat then started the tomcat, after run mxml file on flex side. but problem showing when i was run the application showing below error how can i rectify the error. Client.Error.MessageSend—Send failed—Channel.Connect.Failed error NetConnection.Call.Failed: HTTP: Status 404: url: ‘’ —— Client.Error.Subscribe—Consumer subscribe error—The consumer was not able to subscribe to its target destination please help me. thanks in adv.. Nagesh I am building a Tree component which has checkbox in it. Well I will explain it clearly. Say myTree consists of Branches like US, India and Sub-branches like California,Washington and Delhi, Bangalore respectively. All the branches and sub-brances will have checkboxes beside them and all these are created dynamically using ArrayCollection. Now my requirement is if the checkbox of main branch is checked, all the check boxes of sub-branches should be checked automatically. For Example: If the checkbox of US is checked, the checkboxes of sub-branches corresponding to US i.e., California and Washington should also be checked. And if we remove the checkbox of main branch, all the checkboxes corresponding to that branch should be removed. And another condition is if the checkbox of one of the sub branches is clicked, other checks should disappear. For Example: If I click India, both Delhi and Bangalore will be checked. Now if I click on Bangalore, the check should be at Bangalore only. The checks at Delhi and India should disappear. Can you help me in this respect. Hi Nagesh, Please try following the steps in the article below: Hope this helps. Hi Sujit I am using the AdvanceDataGrid to display the record. When try to use the FlexPrintJob object to print the AdvanceDataGrid, It is just the printing the first page and rest of page are getting ignored. Also some time the below error is showing Error:Error #1502: A script has executed for longer than the default timeout period of 15 seconds. at flash.printing::PrintJob/get pageWidth() at mx.printing::FlexPrintJob/start() at index/btnPrint_click_handler() Code is given below public function btnPrint_click_handler ( e:MouseEvent ) : void { // Create an instance of the FlexPrintJob class. var printJob:FlexPrintJob = new FlexPrintJob(); // Initialize the PrintAdvancedDataGrid control. var printADG:PrintAdvancedDataGrid = new PrintAdvancedDataGrid(); // Exclude the PrintAdvancedDataGrid control from layout. printADG.includeInLayout = false; adg1.validateNow(); adg1.expandAll(); printADG.source = adg1; // Add the print-specific control to the application. addChild(printADG); // Start the print job. if (printJob.start() == false) { // User cancelled print job. // Remove the print-specific control to free memory. removeChild(printADG); return; } // Add the object to print. Do not scale it. printJob.addObject(printADG, FlexPrintJobScaleType.NONE); // Send the job to the printer. printJob.send(); // Remove the print-specific control to free memory. removeChild(printADG); } Can you please guide me regards, Rajeesh Hi Sujit, I am mapping AS object properties with,Flex input controls.Once i enter data in form and submit the form ,the values which i entered in the form are not implicitly being setted in to the AS object properties. Do i need to set them manually or is there any way to set them implicitly Thanks I am working in flex (beginner), wanted to know the component life cycle in flex?? Hi Sujit, are there any issues with Mac OS while accessing Flex based web application. let us know if you are availble to train people in our organization on flex. Hi Sujit, Can you comment on this? Also, What could be the future of Flex when HTML5 will come into reality. Also, would like to have some comparison on HTML5 & Flex for the future from your end, if possible. Thanks. Hi Sujit, Can you plz give a comparison of BlazeDS with GraniteDS and WebORB. Which is better in terms of features and performance. I want to start flex-spring-hibernate project. I need to have lazy loading as GraniteDS provides (is there any alternative in blazeDS or other DS) and data push facility (is blazeDS faster then other two in this case or not) Thanks in advance and hope to have your reply soon. Hi Sujit….ur tutorial on Integrating flex and java helped me a lot.I was struggling on the xml file configuration..ur tutorial really helped me on exactly wad i needed..now i would like to know is there any way to host this project on google app engine through Java??….i mean i need a way to host my flex project on Google App Engine I can seem to integrate BlazeDS in websphere. What version of BlazeDS I download? Every post I see is tomcat based. Can you kindly direct me to a post that uses step by step instruction (like above) of How to use BlazeDS from websphere and flex in front end. I have a JSF/JPA simple proof of concept app which I want to turn it to JPA/Flex app. We have to use websphere as app server. Can you help me please? Thanks When porting the application from Flex 3.0 to Flash Builder 4.0 the IFrame is not rendering. May I know we have similair component for Flash Builder 4.0 or do we need to make changes in code Hi sujit, I want to implement LCDS for my application, but I cannot use JAVA, I am using flex-3 and php, to do this I downloaded amfphp and I cofigured it, Its working fine, and I created a test script using remote object, and it is also working fine, now I need to know to implement all features of LCDS like synchronous, automatic refreshing if table updated etc, please help me out, Thanks in advance Karthik Sujit .. could you please let me know possibilities of desktop sharing and remote desktop access through Flex application. I need that in my next project … or we have to use Java for that. Hi is there any way to load a website in Flex Web application. Hi Sujit , I am new to flex. I want to convert my spring mvc web application to Flex. Please suggest me the good docs to start with. Thank you Hi Sujit, If there is a third party server communicating with action script objects to a Flex app client and I do not have access to the server and know nothing about the objects, other than what i can see on the wire using Firebug, is it possible to create a java client that can send and receive action script requests and responses to the server just as their own Flex app does? I believe a starting point is to set WebService.useProxy = “true” since I do not have access to the third party’s server crossdomain.xml. However, is there some introspection that can be used to reveal the object structures and commands that are needed to communicate ?? Hi, thank you for your articls about flex and java, it was wery helpfull for me! Can you say me where i can download BlazeDS 4 while adobe site is down? Or may be some one could email it to me? (tezqatlipoca@gmail.com) Pleaaaaaseee! Good stuff! Hi, I am making a paintbrush like app in flex, and need a functionality where user can fill colors using the inbuilt color picker component. But that color picker is missing the NO COLOR color to remove the fill, is there any way we can use the existing color picker component with NO Color. Thanks for your help. I have been struggling for Flex and LCDS setup but you brilliant article has solved it in minutes. So, Thank you for posting such useful material. I am stuck at one point and struggling from last 3 days. When I am trying to connect to a dataservice then after Selecting No Password checkbox for RDS and when I click next it gives this error: RDS server message: Error executing RDS command.Status Code: 500, Reason:Internal Server Error. Note: I have started Apache Tomcat 7 as well and its running fine apparently. I am waiting for your reply. Thanks. Annappa HI, sujit I want to create a chat room for chatting application using LCDS it uses producer and consumer component pls help we out.if you have sample source code pls send me Hi Sujith I am new baby to learn about Flex and Blazed Data Services. I got some good knowledge on Flex and have very much interest on it. Could you please explain the need of Data Services to communicate Server using Blazed Data Services. Hi, Thanks for you contributions as a Flex evangelist. We need more folks like you to keep Flex alive as an alternative to SilverLight. I’m not a big fan of Adobe’s developer support but you certainly are helping to fill the gap. Keep up the great postings. Regards, John Hi sujit, I am creating one chat application. I got this error(The consumer was not able to subscribe to its target destination.), while running thru servername.If i use like this means(), its working. otherwise i got a error like this “The consumer was not able to subscribe to its target destination”. Pls help me to find out the solution. Here is the code: var cs:ChannelSet = new ChannelSet(); var customChannel:Channel = new StreamingAMFChannel(“my-streaming-amf”,””); cs.addChannel(customChannel); consumer.channelSet = cs; consumer.subscribe(); hi sujit, when am trying to include the folowing in my code var mydate:Date=new Date; am getting 1046: Type was not found or was not a compile-time constant: Date y is it so?? Hi Asha, Can you please share the code to reproduce this. Hi Nasurudeen, You might have to add a crossdomain file. Please find more details here Hope this helps. Hi John, Thanks for kind words John 🙂 Hi Subbarayulu, I am sorry, I didn’t get your question. When you said Data Services, did you mean Data management services? Hi Annappa, Please check this article Its the same with LCDS as well. Hi Annappa, Please make sure the RDSDispatchServlet is uncommented. Please try sending a request to the RDSDispatchServlet from your browser and see if the servlet is getting invoked. Hope this helps. Hi Mayura, Please check if the article in the URL below helps. In the articles below, Struts is being used but you can get an idea on how to go about with Spring. Hope this helps. Hi Shyam, See if this helps Hi sujith, Thanks for ur reply sujith. The date issue worked fine. Its came coz i used date as a variable which is a keyword. How to populate the datagrid with values that are returned by java code in array list form. I tried every way but ntg worked. I have no time plz help me out. am returning an array list from java class as while(rs.next()) {System.out.println(“hai stupid”); B.add(rs.getInt(“Ticket_ID”)); C.add(rs.getString(“MODIFIED_ON”)); D.add(rs.getString(“SEVERITY”)); E.add(rs.getString(“E_MAIL”)); F.add(rs.getString(“IP”)); System.out.println(“hai “); abc.add(0,B); abc.add(1,C); abc.add(2,D); abc.add(3,E); abc.add(4,F); } where b,c,d,e,f are arraylist. and in flex prg am calling those values by [Bindable] public var dp:ArrayCollection; . . . in reult handler dp = (event.result as ArrayCollection); and dp is the dataprovider for my datagrid. Hi, First of all lot of thanks for wonderful blog. I am new to flex, spring and blazeds. I have managed to configure them and get working for my first project of this sort all is fine. I am able to execute services on server and get results in Flex and display them. I want to add a functionality of detecting session expiry at server side and automatically terminate flex application. Is it possible ? If yes how shall I proceed ? any link, reading material etc. etc will be a great help Thanks and regards Raja Hi Sujit, Is it possible to call java class which has overloaded methods in it using blazeds. Sujit, We are using blaze 4 and weblogic 10.3 We are using 1 polling amf channel for all destinations (about 8). we do not have any netwrok bandwith crunch and have about 20 users using the system at peak. The problem is channel disconnects. one point worth mentioing is that one destination fetches message of size – 50kb every 10 seconds. We see channel diconnects for over 7 minutes, following which we kill the client session, and request users to log back in. The problem occurs mostly when most users login at once. please note that the weblogic attains at peak 140MB of perm gen size – to give you an idea of the server side load. The max mem is set to 6g but on the whole the utilization is aboiut 2.5g. Also please note note that we have set time to live for these destinations as about 2-3 mins only so that no unnessesary build up happens on server. If you could please throw some light on this issue of polling amf disconnect it would be really helpful. Hi Sujit, we have an internal webservice developed in our company and i have connected that web service using flex and am able to get all the methods/operations from that service. but wen i try to get data from methods i get the following error msg while running the application Security error accessing url Unable to load WSDL. If currently online, please verify the URI and/or format of the WSDL () am not able to figure out what the problem is? Hi Sujith, I need to test my java services which uses Blazeds from Java. So for that I am using AMFConnection class. By invoking AMFConnection.call(method,param) is giving me the response properly but its throwing an exception only when my service method encounters a FlexContext.getFlexClient(). I can understand that Java AMF Client which uses AMFConnection cannot have multiple clients over a single interface. But I badly want to test all my services using AMFConnection and most of my services will have a FlexClient usage. I also tried using SoapUI and tested my services which in turn uses the same AMFConnection but in groovy. SoapUI also throws the same null pointer exception. Is there any way to trick the FlexClient and fill it and test my services fully… It will very nice if i can get a solution to test all my services which uses FlexClient from Java…. What I think is somewhere the FlexContext is getting primed with FlexClient so can i able to set seomthing on the static class. I might be wrong but just a wild guess…. Please help me to resolve this issue… I build a chat application using blazeds+red5+flex.video chating works fine,bt text chatting work only in IE,it doesnt work in any other browser Hello Sujit, We have created a web conference application using LCDS developer version and FMS 3.5. Now we have stuck with licensing issues of LCDS. So can we shift the whole project to BlazeDS without any major code changes ? Please this is very crucial for us. At least give some hint or directions. Thanks. Hi Asha, Try to add a debug point and check the data type of event.result. Hope this helps. Hi Sid, Yes, you can. But you will have difference in performance based on the services and channels used in your application. Please find details in the URL below. If you are not using any features of LCDS, its very simple. Please find the feature difference between LCDS and BlazeDS in the URL below. LCDS supports NIO based endpoints like RTMP, if you are using NIO based endpoints, you might have to change the same. Hope this helps. Hi Sushma, You might have to place a crossdomain policy file. Try to share more details on the error. Hi Sushma, Please check this Hi Raja, You can send a request to server and required interval to check if the session is valid. You can find details on how to access session data in the URL below. Hope this helps. and xml file as how do i pass upperLimit=””, dial value=”” and maxValue=”” values to xml file dynamically from the flex side. i need these 3 values to plot on the angle gauge fusion chart hi..your bolg has been really helpful.i am currently working a project in which i need to play a youtube video backwards. can u help out in the sense that how do i do that? and can i embed external free open source apps in my RIA building with flex? Thanks in advance! Hi sujit, how do i pass values to xml file from flex? I am having issue with Flash Builder 4 – Connect to Data service. I am trying to use the Remote Serive. When i click on Connect to Data Service i do see a list of available Remote Services. But when i select one and click Finish i get following error – Unable to save data model Reason – An error occured while trying to resolve the existing data model. Error: Actionscript generation is not supported for entities whose names clash with with Actionscript keywords. Entity “Class” clashes with AS keyword. Hi Sujit, I have a VBOX comprising of several components.I want to print the VBOX on multiple pages.I am able to do that using FlexPrintJobScaleType class.But I dont know how to set margins on all pages.Padding is of no use.Can you please explain how to achieve this? Thanks, Meenakshi i need to know benefit of using ESB over Blazeds or LCDS with a clear clarity .
https://sujitreddyg.wordpress.com/about/
CC-MAIN-2018-34
refinedweb
8,402
65.73
Hi ( im a beginning programmer), I always found myself trying to figure out what percent a number is of another number, and rather then using a program online to always do this calculation for me i wrote a simple program in c. I want to make it so i can access this program from the command line, for example: jacob@jacob-laptop:~$ percent 55 390 where its: command arg1 arg2 :: where arg1 is the number to be found the percent of the number (arg2) then I want the program to display the answer. if this is not possible without changing a whole bunch of code then I would also be happy if i could invoke the program from the command line, for example: jacob@jacob-laptop:~$ percent and then the percent program will run its course then return to the command line. any suggestions? Heres the code for my program: #include <stdio.h> main() { float answer, FACTOR, get1, get2; FACTOR = 100; printf("\n\n\n"); printf("What percent is a number of a number?\n\n"); printf("What is __ percent of?\n"); printf("Please enter number:\n"); scanf(" %f", &get1 ); printf("\n"); printf("this number?\n"); printf("Please enter number:\n"); scanf(" %f", &get2 ); answer = (get1/get2) * FACTOR; printf("\n"); printf("%3.2f is %3.2f percent of %3.2f\n\n\n", get1, answer, get2); } if you need me to clarify anything just post, i will include the source in an attached file as well. [file name=percent.txt size=454][/file]
http://www.linux.com/community/forums/software-development/add-program-i-made-to-cmdline
CC-MAIN-2014-15
refinedweb
254
67.99
Hello, as a part of a bachelor's thesis in computer science, I've been experimenting with creating a different frontend for SDCC. In short, I've split SDCC in half, removing the AST stuff, and created new functions for creating iCode instructions, operands and sym_links (the SDCC equivalent of types). Then this library version of SDCC was merged with an existing Java frontend, so SDCC iCode could be generated from Java source code. As the Java frontend was written in Java, the interface to SDCC is JNI (Java Native Interface). Sounds interesting? Bear in mind though, that this is just a prototype so far, and far from alpha, as only a small subset of the Java language is supported (everything must be static, new operator is not supported, no arrays, no exceptions, etc). I've also, for simplicity, commented out every backend architecture except pic14 - bringing them back online shouldn't be much work though. Nevertheless, I think my work could be a good starting point for anyone who is thinking of doing something similar, or is trying to understand the internals of SDCC iCode. (Presuming I've done at least approximately right when interfacing the SDCC code! ;-) ) The SDCC code was taken from a daily build some day in February, 2008. Unfortunately, I don't have the time to continue working on this project (unless someone would be willing to pay me for doing so). But SDCC is GPL, the Java frontend is a mix of GPL and BSD licensed code, and I'm also willing to share my code under GPL, if anyone would be interested in continuing my work, or use it for study. Then I also think I have to write some documentation of how to get things up and running, specifically as the Java frontend requires some extra tools to make it work properly. If I should do this - let me know. As a demo, below is some example Java code that works in my prototype, and plays a melody on the PWM output (if you connect a speaker to it). import piclibrary.Pic; public class PWM { public static void init() { Pic.setTRISB((byte) (Pic.getTRISB() & 0xF7)); Pic.setPORTB((byte) (Pic.getPORTB() & 0xF7)); Pic.setCCP1CON((byte) 0x0C); } public static void start(int period, int dutycycle) { Pic.setPR2((byte) period); Pic.setCCPR1L((byte) dutycycle); Pic.setT2CON((byte) 0x7); } public static void stop() { Pic.setT2CON((byte) 0x0); } } public class SoundMain { public static void delay(int delms) { for (int i=0; i < delms; i++) for (int j=0; j < 35; j++) Pic.getPORTB(); } public static void play(int period, int delayms) { PWM.start(period+period, period); delay(delayms); } public static void quiet(int delayms) { PWM.stop(); delay(delayms); } public static void main() { PWM.init(); while (true) { play(110, 100); play(85, 100); play(65, 100); play(55, 100); quiet(100); play(65, 100); play(55, 100); quiet(300); } } }
http://sourceforge.net/p/sdcc/mailman/message/19541482/
CC-MAIN-2014-52
refinedweb
481
54.52
Hi, Python crashes on one of my computers when I execute: import pylab All I need to do is execute this one line of code and poof. A dialog pops up stating that "python.exe has encountered a problem and needs to close. We are sorry for the inconvenience… I installed matplotlib version 0.99.1 using python xy. However I encountered this same problem when I installed using the python 2.6.4 and matplotlib-0.99.1.win32-py2.6 installers. Running python using verbose output shows that a problem is encountered when the statement import matplotlib.transforms # precompiled from C:\Python26\lib\site-packages\matplotlib\transforms.pyc is reached. This may be the culprit. Thanks for any help, Scott
https://discourse.matplotlib.org/t/import-pylab-error/13318
CC-MAIN-2019-51
refinedweb
122
71.21
Pre-choose the OS to boot, even before turning on the computer by toggling a switch. Now you don’t have to wait to select the os. Story. He has documented his entire journey through the research and implementation of the project in hackaday post(click). Please go through his post to get a better understanding of the implementations. In this project, I will show how I managed to port the changes to Raspberry Pi Pico. You can find my version in this GitHub Repo (Click). Concept GNU GRUB is a program that runs before any Operating Systems are loaded. Through this menu, we can select which OS to load. GRUB offers very limited modules to work with. This means it cannot read data from a microcontroller connected via USB. But it can read data from storage disks. So we can trick GRUB to read data from the microcontroller, by enumerating our micro as a mass-storage device. Hence we enumerate our raspberry pi pico as a mass-storage device, via tinyUSB library, which will be having a file switch.cfg file, to which pico will write the switch position i.e 1 for ON 0 for OFF. We have to add a script in GRUB, that’s functions to read switch.cfg file and set the default to 0(Ubuntu )/2(Windows). GRUB when loads, runs our custom scripts, which in turn searches for our device by its UUID identifiers, and if exits read the switch.cfg file. After getting the switch position it sets the default os selection respectively. In summary, - pico will configure itself as a mass-storage device. - grub menu calls our script and asks for the particular file. - Pico responds to the read request by adding the switch position in the switch.cfg file. - the script in grub extracts the info from the file and sets the default option from the extracted data. Configuring Pico as a Mass-storage device I have used the cdc_mscexample by tinyUSB to achieve this. The example configures the pico as a mass-storage device and creates a FAT12 filesystem and enumerates a README.txt file. I changed the README.txt to switch.cfg and added the line “set os_hw_switch=0\n” to the file. #define SWITCH_CFG_CONTENTS \ "set os_hw_switch=0\n" ... //------------- Block3: Readme Content -------------// SWITCH_CFG_CONTENTS Now we have configured pico as a mass-storage device. After copying the uf2 file to pico, it enumerates as a storage device. We will be needing the UUID id of the device for the GRUB script, which is UUID=”0000-1234″. $ sudo blkid ... /dev/sda: SEC_TYPE="msdos" LABEL_FATBOOT="TinyUSB MSC" LABEL="TinyUSB MSC" UUID="0000-1234" BLOCK_SIZE="512" TYPE="vfat" Circuit Reading switch position and writing to file Now we need to read the switch position and change the content of the switch.cfg file accordingly i.e - if the switch is ON: set os_hw_switch=1\n - if the switch is OFF: set os_hw_switch=0\n I have used GPIO_PIN 28 as the switch pin, which is set to pull down. read_switch_value return the switch position i.e ‘1’ is on (pulled high) and ‘0’ is off (pulled low). //-------------------------main.c--------------------- #define SWITCH_PIN 28 // read switch value uint8_t read_switch_value() { return gpio_get(SWITCH_PIN) ? '1' : '0'; } int main(void) { gpio_init(SWITCH_PIN); //configure pin as INPUT gpio_set_dir(SWITCH_PIN, false); //configure pin as PULL_DOWN gpio_set_pulls (SWITCH_PIN,false,true); To write switch position to switch.cfg, I have used readGRUBConfig() which calls the read_switch_value function, and set the output buffer with the switch position. I found that when reading the third block3 lba is set to 3, hence intercepting the call and calling readGrubConfig and passing the buffer where the content of the file will be copied. //-------------------------msc_disk.c--------------------- static char grubConfigStr[] = "set os_hw_switch=0\n"; static void readGrubConfig(uint8_t* output) { // Modify config string with current switch value grubConfigStr[sizeof(grubConfigStr)-3] = read_switch_value(); memcpy(output, &grubConfigStr, sizeof(grubConfigStr)); } // Callback invoked when received READ10 command. // Copy disk's data to buffer (up to bufsize) and return number of copied bytes. int32_t tud_msc_read10_cb(uint8_t lun, uint32_t lba, uint32_t offset, void* buffer, uint32_t bufsize) { (void) lun; // when reading the file if(lba == 3){ readGrubConfig(buffer); return bufsize; } ... ... } Compile the Pico code We need to add pico stdlib to our code to get the gpio pin access. //-------------------------main.c----------------------------------- #include <stdlib.h> #include <stdio.h> #include <string.h> #include "bsp/board.h" #include "tusb.h" ... #include "pico/stdlib.h" To make the project: $ mkdir build $ cd build $ cmake .. $ make Configuring GRUB to read the file content I have added these changes in my Ubuntu 20.10. $ sudo vim /etc/grub.d/40_custom .... # Look for hardware switch device by its hard-coded filesystem ID search --no-floppy --fs-uuid --set hdswitch 0000-1234 # If found, read dynamic config file and select appropriate entry for each position if [ "${hdswitch}" ] ; then source ($hdswitch)/switch.cfg if [ "${os_hw_switch}" == 0 ] ; then # Boot Linux set default="0" elif [ "${os_hw_switch}" == 1 ] ; then # Boot Windows set default="2" else # Fallback to default set default="${GRUB_DEFAULT}" fi else set default="${GRUB_DEFAULT}" fi First, we search for our filesystem. GRUB has a subcommand search just for this. - -no-floppy option prevents searching floppy devices - -fs–uuid 0000-1234 searches a file system with UUID of 0000-1234. If any device is found, the first device found is set as the value of the environment variable. –set hdswitchhdswitch is our environment variable and is set with disk name if found. Next, we source the switch.cfg file if the hdswitch variable is set, which creates another environment variable os_hw_switch with the switch position i.e either 0/1. We read the value of the os_hw_switch and set the default to 0 or 2 respectively. 0 because Ubuntu is at 0th position and windows at 2nd position in the GRUB menu. Lastly, if hdswitch was not set, we set the default to GRUB_DEFAULT. Now we need to update our grub: $ sudo update-grub Source: Hardware Boot Select Switch Using Pico Low cost PCB at PCBWay - only $5 for 10 PCBs and FREE first order for new members PCB Assembly service starts from $30 with Free shipping all around world + Free stencil Extra 15% off for flex and rigid-flex PCB
https://projects-raspberry.com/hardware-boot-select-switch-using-pico/
CC-MAIN-2021-25
refinedweb
1,035
65.42
Known Issues and Limitations in Cloudera Data Science Workbench 1.8.1 - Known Issues in Cloudera Data Science Workbench 1.7.x -. Upgrades Please read the following upgrade issues before you being the upgrade process: Upgrades supported from CDSW 1.6.x (and higher) to CDSW 1.8.x Cloudera Data Science Workbench only supports upgrades to version 1.8.0 from version 1.6.x and 1.7.x. If you are using an earlier version, you must first upgrade to version 1.6.x or 1.7.x, and then upgrade to version 1.8.0. Domain name resolution issues after upgrading to CDSW 1.7.x; Pods stuck in CrashLoopBackOff state After upgrading to CDSW 1.7.x, certain application pods (s2i-registry and image-puller) get stuck in CrashLoopBackOff state. This is due to an issue with the DNS resolver. Workaround: Remove or comment out the search entry from the /etc/resolv.conf file. # cat /etc/resolv.conf ..... # search example.com nameserver 192.0.2.1 nameserver 192.0.2.2 Post-upgrade error: Pods cannot be deleted After upgrading to CDSW 1.8.0, when trying to restart an application, you may see an error that pods cannot be deleted. The application may appear to be in the “Stopping” state, and clicking the Restart button has no effect. Workaround: First, launch a session, job, model, or experiment. After the engine-based workload starts, you can restart the application. After the application is in a running state, the session, job, or experiment can be terminated. CDSW Restart-repo append '/jobs' after the URL. For example, if your engineID is tb0z9ydiua5q9v2d and the DOMAIN is example.com then view the Spark UI at: Alternative workaround: To view running Spark jobs, navigate to - CDH 5: CDS 2.4 release 2 (and lower) - CDH 6: Versions of Spark that ship with CDH 6.0.x, CDH 6.1.x, CDH 6.2.1 (and lower), CDH 6.3.2 (and lower) - CDH version 6.4.0, 6.2.2, 6.3.3 or higher - CDH 5 with Spark 2.4 release 3 Monitoring Spark Applications invoked from CDSW To monitor spark_on_yarn applications invoked from CDSW, an embedded Spark UI is displayed right next to the session/job. This was achieved by disabling RM proxy. However, with this change, attempts to access the same Spark application using the RM UI will result in Error 500 (connection refused). Affected Versions: CDSW 1.6 and higher. Workaround: If the Administrator wants to troubleshoot a running spark-on-yarn application invoked by an end-user from the workbench, the user must share their session using the Share button on the right side of the console. An alternate workaround which will not provide realtime updates is to access the Spark Application UI from the Spark History Server UI > Incomplete Applications. Cloudera Bug: DSE-4979 Crashes and Hangs - If CDSW is using HTTP or HTTPS_PROXY settings the following will occur: - The _Terminal will spin forever. - The applications will not reach a started state. Cloudera Bug: DSE-12898 The CDSW terminal remains active even after the CDSW web session times out. Cloudera Bug: DSE-12064 The CDSW web UI might freeze while updating the job schedule to Dependant if there is no other job to be depended on. Workaround: If there are no jobs to be dependent on, then refresh the page and select the appropriate setting from the Schedule field before saving other changes on the page. Cloudera Bug: DSE-12032 Restarting an application from Cloudera Manager crashes the kubelet process on a kernel older than 4.3 and CDSW 1.8 running on the Kubernetes cluster 1.14.x because of an existing Kubernetes bug. This happens because the kernel version does not support cgroups pids controller.Workaround: Install CDSW 1.8 on nodes that have the kernels having cgroups for pids feature enabled. To check whether the kernel has the pids feature enabled, run the following command: cat /proc/cgroups/ If the subsystem (subsys_name) in the output does not contain pids, then do not install CDSW 1.8 on that node.Sample output showing subsystem does not list pids: subsys_name hierarchy num_cgroups enabled cpuset 8 17 1 cpu 9 17 1 cpuacct 9 17 1 memory 10 17 1 devices 2 30 1 freezer 6 17 1 net_cls 3 17 1 blkio 4 17 1 perf_event 5 17 1 hugetlb 7 17 1Sample output showing subsystem that lists pids: #subsys_name hierarchy num_cgroups enabled cpuset 5 91 1 cpu 9 91 1 cpuacct 9 91 1 memory 2 91 1 devices 8 91 1 freezer 7 91 1 net_cls 3 91 1 blkio 10 91 1 perf_event 4 91 1 hugetlb 11 91 1 pids 6 91 1 net_prio 3 91 1 Cloudera Bug: DSE-11750 You cannot disable file upload and download when using the Jupyter Notebook. Cloudera Bug: DSE-12065 You may see the following message if you try to open a file in CDSW that contains Chinese characters in the filename: An error occurred while trying to open the file /filepath/filename.py.info. The file could not be found.. Workaround: From the CDSW UI, click the file that you are trying to open and then click Open in Workbench. Cloudera Bug: DSE-11891 The lack of a ROOT CA certificate can cause issues with terminals and the Jupyter editor after upgrading CDSW. Problem: After upgrading from CDSW version 1.5 to version 1.7.1, the terminal does not open for any kernel, and the Jupyter notebook does not work. Workaround: In CDSW, go to Root CA configuration field. You should be able to launch a new session and start the terminal or launch the Jupyter editor. It is not necessary to restart CDSW. This procedure is described at Configuring Custom Root CA Certificate, and paste the internal CA root certificate file contents directly into the Engines The CDSW web UI does not display any acknowledgment message when you update the shared memory and save the change. Cloudera Bug: DSE-12034 When you create a job with a non-default engine profile, the job overview page displays the Engine Profile value as 1 vCPU / 2 GiB Memory instead of the actual engine profile that was selected while creating a CDSW project. Cloudera Bug: DSE-12033 The output of the terminal commands including the curl command may wrap incorrectly, resulting in a terminal output that is difficult to read. Workaround: Resize the terminal to a bigger size. Cloudera Bug: DSE-11956 and track_file functions are not supported with Scala experiments. The UI does not display a confirmation when you start an experiment or any alerts when experiments fail. GPU Support Only CUDA-enabled NVIDIA GPU hardware is supported Cloudera Data Science Workbench only supports CUDA-enabled NVIDIA GPU cards. Heterogeneous GPU hardware is not supported You must use the same GPU hardware across a single Cloudera Data Science Workbench deployment. GPU image for CDSW does not work with TensorFlow The LD_LIBRARY_PATH environment variable is not set properly in the technical preview GPU image (docker.repository.cloudera.com/cdsw/cuda-engine:10) which is needed for the TensorFlow framework to work. - Install TensorFlow by running the following command: pip3 install tensorflow - Add the following to the LD_LIBRARY_PATH environment variable: LD_LIBRARY_PATH=/usr/local/cuda/lib64:/usr/local/cuda/lib:/usr/lib/hadoop/lib/native Jobs When you start a job that has a dependent job, CDSW does not log the job start event for the dependent job in the user_events table. Cloudera Bug: DSE-11855 Unable to create a model with the name of a deleted Model. Workaround: For now, Models shall have unique names across the lifespan of the cluster installation. Cloudera Bug: DSE-4237 Re-deploying or re-building models results in model downtime (usually brief). Data Science Workbench may restart a replica at any time it is deemed necessary (such as bad input to the model). - The use_model_metrics.py file which is available within the CDSW Templates misses the code for setting the user_api_key and is not up-to-date. Use the following code instead: import cdsw import time from sklearn import datasets import numpy as np # This script demonstrates the usage of several model metrics- # related functions: # - call_model: Calls a model deployed on CDSW as an HTTP endpoint. # - read_metrics: Reads metrics tracked for all model predictions # made within a time window. This is useful for doing analytics # on the tracked metrics. # - track_delayed_metrics: Adds metrics for a given prediction # retrospectively, after the prediction has already been made. # Common examples of such metrics are ground truth and various # per-prediction accuracy metrics. # - track_aggregate_metrics: Adds metrics for a set or batch of # predictions within a given time window, not an individual # prediction. Common examples of such metrics are mean or # median accuracy, and various measures of drift. # This script can be used in a local development mode, or in # deployment mode. To use it in deployment mode, please: # - Set dev = False # - Create a model deployment from the function 'predict' in # predict_with_metrics.py # - Obtain the model deployment's CRN from the model's overview # page and the model's access key from its settings page and # paste them below. # - If you selected "Enable Authentication" when creating the # model, then create a model API key from your user settings # page and paste it below as well. dev = True # Conditionally import the predict function only if we are in # dev mode try: if dev: raise RuntimeError("In dev mode") except: from predict_with_metrics import predict if dev: model_deployment_crn=cdsw.dev_model_deployment_crn # update modelDeploymentCrn model_access_key=None else: # The model deployment CRN can be obtained from the model overview # page. model_deployment_crn=None if model_deployment_crn is None: raise ValueError("Please set a valid model deployment Crn") # The model access key can be obtained from the model settings page. model_access_key=None if model_access_key is None: raise ValueError("Please set the model's access key") # You can create a models API key from your user settings page. # Not required if you did not select "Enable Authentication" # when deploying the model. In that case, anyone with the # model's access key can call the model. user_api_key = None # First, we use the call_model function to make predictions for # the held-out portion of the dataset in order to populate the # metrics database. iris = datasets.load_iris() test_size = 20 # This is the input data for which we want to make predictions. # Ground truth is generally not yet known at prediction time. score_x = iris.data[:test_size, 2].reshape(-1, 1) # Petal length # Record the current time so we can retrieve the metrics # tracked for these calls. start_timestamp_ms=int(round(time.time() * 1000)) uuids = [] predictions = [] for i in range(len(score_x)): if model_access_key is not None: output = cdsw.call_model(model_access_key, {"petal_length": score_x[i][0]}, api_key=user_api_key)["response"] else: output = predict({"petal_length": score_x[i][0]}) # Record the UUID of each prediction for correlation with ground truth. uuids.append(output["uuid"]) predictions.append(output["prediction"]) # Record the current time. end_timestamp_ms=int(round(time.time() * 1000)) # We can now use the read_metrics function to read the metrics we just # generated into the current session, by querying by time window. data = cdsw.read_metrics(model_deployment_crn=model_deployment_crn, start_timestamp_ms=start_timestamp_ms, end_timestamp_ms=end_timestamp_ms, dev=dev) data = data['metrics'] # Now, ground truth is known and we want to track the true value # corresponding to each prediction above. score_y = iris.data[:test_size, 3].reshape(-1, 1) # Observed petal width # Track the true values alongside the corresponding predictions using # track_delayed_metrics. At the same time, calculate the mean absolute # prediction error. mean_absolute_error = 0 n = len(score_y) for i in range(n): ground_truth = score_x[i][0] cdsw.track_delayed_metrics({"actual_result":ground_truth}, uuids[i], dev=dev) absolute_error = np.abs(ground_truth - predictions[i]) mean_absolute_error += absolute_error / n # Use the track_aggregate_metrics function to record the mean absolute # error within the time window where we made the model calls above. cdsw.track_aggregate_metrics( {"mean_absolute_error": mean_absolute_error}, start_timestamp_ms, end_timestamp_ms, model_deployment_crn=model_deployment_crn, dev=dev ) -. Applications The subdomain names on the Application page has some constraints, but the CDSW UI may not display a complete error message when these are violated. Workaround: Use the characters from the set of ASCII letters, digits, and hyphens (a-z, 0-9, -) to form the subdomain name. Ensure that the subdomain name does not start or end with a hyphen. Cloudera Bug: DSE-11883 Platform In the monitoring view of the Grafana the UI, the values displayed in the Used CPU Usage and the Total CPU Usage are the same when both the Node and the Pod filters are set to All. Workaround: Use a specific filter other than All to overcome this issue. Cloudera Bug: DSE-12072 Deleting the projects through the UI might leave residual files on disk. Workaround: Please contact Cloudera support to remove residual files in case of disk usage issues. Cloudera Bug: DSE-393 Networking CDSW cannot launch sessions due to connection errors resulting from a segfaultSample error: transport: Error while dialing dial tcp 100.77.93.252:20051: connect: connection refusedWorkaround: Enable IPv6 on all CDSW hosts - Double-check that IPv6 is currently disabled during boot time, i.e. ipv6.disable should be equal to 1. $ dmesg [ 0.000000] Kernel command line: BOOT_IMAGE=/boot/vmlinuz-3.10.0-514.el7.x86_64 root=UUID=3e109aa3-f171-4614-ad07-c856f20f9d25 ro console=tty0 crashkernel=auto console=ttyS0,115200 ipv6.disable=1 $ cat /proc/cmdline .....ipv6.disable=1 - Edit /etc/default/grub and delete the ipv6.disable=1 entry from GRUB_CMDLINE_LINUX. For example: GRUB_CMDLINE_LINUX="rd.lvm.lv=rhel/swap crashkernel=auto rd.lvm.lv=rhel/root" - Run the grub2-mkconfig command to regenerate the grub.cfg file: grub2-mkconfig -o /boot/grub2/grub.cfgAlternatively, on UEFI systems, you would run the following command: grub2-mkconfig -o /boot/efi/EFI/redhat/grub.cfg - Follow the above steps for both CDSW Master and Worker nodes. - Stop the Cloudera Data Science Workbench service. - Reboot all the Cloudera Data Science Workbench hosts to enable IPv6 support. - Start the Cloudera Data Science Workbench service. Run dmesg on the CDSW hosts to ensure there are no segfault errors seen. Cloudera Bug: DSE-7238, DSE-7455 Custom /etc/hosts entries on Cloudera Data Science Workbench hosts do not propagate to sessions and jobs running in containers. Cloudera Bug: DSE-2598 Initialisation of Cloudera Data Science Workbench (cdsw init) will fail if localhost does not resolve to 127.0.0.1. -. - Kubernetes throws the following error when /etc/resolv.conf. Security Working in the terminal or an editor should not count as idle session If a user opens a workbench and is either working exclusively in the terminal or just editing files, Cloudera Data Science Workbench counts that time as idle time and the user gets kicked out after the configured max idle timeout. - Increase the idle session timeout by adding a new environmental variable IDLE_MAXIMUM_MINUTES. Click. You can set the value of the variables IDLE_MAXIMUM_MINUTES or SESSION_MAXIMUM_MINUTES to their maximum allowed value, which is 35000 (~3 weeks). - Alternatively, run a simple script inside CDSW session to keep the session alive. Opening the Cloudera Data Science Workbench and create a file as shown here (assuming Python project), and then run it in the Workbench. import time time.sleep(10000) Cloudera Bug: DSE-3080 Environment variables with the dollar ($) character are not parsed correctly by CDSW. For example, if you set PASSWORD="pass$123" in the project environment variables, and then try to read it using the echo command, you see the following output: pass23Workaround: Use one of the following commands to print the $ sign: echo 24 | xxd -r -p or echo JAo= | base64 -dInsert the value of the environment variable by wrapping it in the command substitution using $() or ``. For example, if you want to set the environment variable to ABC$123, specify: ABC$(echo 24 | xxd -r -p)123 or ABC`echo 24 | xxd -r -p`123 You see the HTTP 404 error on navigating to other tabs within the CDSW web UI after updating the project name on the Project Settings page. This is because the backend API still uses the older project name. Workaround: After you save the new project name, manually reload the webpage before navigating to the other tabs or pages within the CDSW web UI. Cloudera Bug: DSE-11911 In some cases, the application switcher (grid icon) does not show any other applications, such as Hue or Ranger. Cloudera Bug: DSE-865
https://docs.cloudera.com/documentation/data-science-workbench/1-8-x/topics/cdsw_known_issues.html
CC-MAIN-2021-10
refinedweb
2,727
55.24
score:1 without paying attention to the readability of the chart, one solution might be to first add a function: function find_max_date(max,values) { for (i=0;i<values.length;i++) { if (values[i].temperature==max) { return i; break; } } } and to use this code: city.append("text") .datum(function(d) {return {name: d.name, max: d3.max(d.values,function(d){return d.temperature}), max_date: d.values[find_max_date(d3.max(d.values,function(d){return d.temperature}),d.values)].date };}) .attr("transform", function(d) {return "translate(" + x(d.max_date) + "," + y(d.max) + ")"; }) .attr("x", 3) .attr("dy", ".35em") .text(function(d) { return d.name; }).attr("fill",function(d) {return color(d.name);}); so basically, this adds max and max_data to the data-object - max by simply using the d3.max-method to find the highest temperature, and max_data by looping through the original data per city and returning the position of the maximum temperature in the array, which is used to access the corresponding date. the color is added the same way as it is added to the lines. edit: not sure about the "bonus"-question, what should the result look like? lines pointing at the maximum value for each city? edit2: a possible solution for the bonus-question as i was curious if it was doable, but there might be better ways to do it. i changed different parts of the code, so you can delete the function find_max_date. at the start of the script i added a global variable var offset=20; which serves as variable to control the distance of the labels between each other and the border. then, between the cities-color-domain-part and the scale-domains, i added the following code: for (i=0;i<cities.length;i++) { cities[i].max=0; cities[i].label_off=0; for (j=0;j<cities[i].values.length;j++) { if (cities[i].values[j].temperature>cities[i].max) { cities[i].max=cities[i].values[j].temperature; cities[i].max_date=cities[i].values[j].date; } } } this does basically the same as we did before with d3.max and the custom function to find the date of the maximum temperature, only this time i would suggest to add the values directly into the cities-variable. cities.label_off will be a value to put some space between labels which would otherwise be overlapping. next, i added another loop to compare values on the x-scale to check if they overlap. simply put, if the distance between two x-values is smaller than 100 pixels, the label_off-value is set to the offset-value (in this case 20 pixel), otherwise the label_off-value remains at 0. you might want to adjust that, depending on how short/long your labels are. for (i=0;i<cities.length;i++) { for (j=i+1;j<cities.length;j++) { if (Math.abs(x(cities[i].max_date)-x(cities[j].max_date))>0 && Math.abs(x(cities[i].max_date)-x(cities[j].max_date))<100) cities[j].label_off=offset; } } next, i added the offset-variable to the y-domain, just to have a little more space to put the labels in place: y.domain([ d3.min(cities, function(c) { return d3.min(c.values, function(v) { return v.temperature; }); }), d3.max(cities, function(c) { return d3.max(c.values, function(v) { return v.temperature; })+offset; }) ]); and finally the part to add the labels and the lines. as the cities-variable already contains all the necessary information you don't need to use another datum and can just adress them using the property name: city.append("text") .attr("transform", function(d) {return "translate(" + (x(d.max_date)+30+d.label_off) + "," + (offset+d.label_off) + ")"; }) .attr("x", 3) .attr("dy", ".35em") .text(function(d) { return d.name; }) .attr("fill",function(d) {return color(d.name);}); city.append("line") .attr("class","line_con") .attr("x1",function(d){return x(d.max_date);}) .attr("y1",function(d){return y(d.max);}) .attr("x2",function(d){return (x(d.max_date)+30+d.label_off);}) .attr("y2",function(d){return (offset+d.label_off);}) .attr("stroke",function(d) {return color(d.name);}); as you can see, the transform just puts the labels on the x-scale at the position of the date of the maximum temperature. then it adds 30, which is an arbitrary value just to move them slightly to the right so they don't sit directly above the value. d.label_off adds 0 if there is no overlapping, and in our case 20 if there is. on the y-scale i positioned them at the top of the chart with some space between them and the border using the offset. again, if there is overlapping, they are moved down a little bit. for the lines, it's just connecting the maximum value and the starting point of the label. they use a different css-class to allow for the correspondning color: .line_con { fill: none; stroke: none; stroke-width: 1.5px; again, there might be better ways to accomplish it and i'm not sure if this works fine on all sorts of data, but it might give you an idea how to handle it. Source: stackoverflow.com Related Query - Show labels conditionally on multi series line chart - D3 line chart axis text labels in multi line - dc.js Series Chart multi line - nvd3.js-Line Chart with View Finder: rotate axis labels and show line values when mouse over - d3: tooltips on multi series line chart at each line when mouse hover event - nvd3 - force all xaxis labels to show on line chart - Error displaying dots on a multi series line - dots chart - D3 Multi Series Line chart not working with correct xAxis values - dc.js multi line series chart filtering - How to create a interactive d3 line chart to show data plots / labels on hover - d3.js - Multi series line chart tool tip issue - Animated Path multi series line chart in D3.Js - D3 Multi Series Line Chart with Clickable Legend - D3 Multi Series Line Chart - D3 Multi Series Line chart with non time x axis - X axis not displaying on Multi Series Line Chart using d3.js - MultiBar chart with nvd3 / d3 only shows labels for every other tick on the x-axis. How can I get them all to show up? - Multi series chart (D3) with missing values - d3 line chart labels overlap - Multi Line Ordinal d3 chart - d3 show labels only for ticks with data in a bar chart - Dimple.js line chart with composite axis, no links between points on series - C3js - combination chart with data labels only for line - D3: how to show lone point in a line chart - D3 multi line chart - strange animation - simple multi line chart with D3 - d3.js multi y-axis line chart - D3 - Single and Multi Line chart tooltips - D3: Add data value labels to multi line graph - Legend in Multi line chart - d3 More Query from same tag - Can't access array in Javascript/d3 - Does Force-Directed Layout of d3-js support image as node? - JSON parsing in d3 based on date - d3.js Multi-series line chart interactive (tsv into literal data) - Should this code override the default d3 version in use by Juypyter notebooks? - d3.js - jasmine test to invoke a click on an svg element - How to watch an attribute in an angularjs directive? - How to Dynamically Append Custom D3/SVG Element in Angular - Asynchronous Function in Iteration - javascript - CSV to HTML table using d3 and an external javascript file - Load a Geojson to AP.NET MVC 5 - Is there a D3 v4 version of Collapsible Indented Tree? - D3 custom text label axis - How to add keys to data that is used to display pie chart in D3? - Vertical d3.svg.area? - d3 js highlight nodes containing given string - Parsing string to date in d3.js - Summing based on multiple rows - How to calculate SVG Linear Gradient - d3.js select by id not working. Not sure why not - Ordinal scatterplot in D3 - Four color theorem in D3js for neighbors polygons coloring? - d3 v4 X-axis ticks - How to apply tooltips for dc.js chart after chart is rendered - D3 - Add background fill to rect - D3.js does not render SVG in ASP MVC app - Programmatically Zooming in D3? - Dynamically update treemap elements with D3.js - change the style with 'selectAll' and 'select' problems - Placing the nodes in the center of screen in d3 force layout
https://www.appsloveworld.com/d3js/100/54/show-labels-conditionally-on-multi-series-line-chart
CC-MAIN-2022-40
refinedweb
1,404
55.74
thanks a lot for your effort to help me (even though I didnt like a part of the last message). Cheers Nikos thanks a lot for your effort to help me (even though I didnt like a part of the last message). Cheers Nikos the earlierst date is the first day of the first year so propably 1/1/1 we can ask the user to say what name is the first date of the present but he said it's not necessary and had to allow us to do it since lots of people asked for it I cannot use any date I want there are some restrictions.I actually cant use any date what If I dont have a given date? I mean if I dont know what day it is for any day do you have any reccomendations about the part of the leap year and the part of december and such?Also I didnt really get the day calculation thing I have come ro realize that possibly this problem only occurs when of the given months is december.I think that if the months given are not december it works perfectly fine So here is the program I have created in order to solve this. import acm.program.*; public class ask2 extends Program { public void run() { println ("Give the first date.Year,Month,Day");... Hello everyone I am new to this site I have recently joined the university of Computer science in Greece and although we have never used java before our teacher in ''programming with java'' has given...
http://www.javaprogrammingforums.com/search.php?s=1a49b4f5f349a1cab780691b7c76523e&searchid=837102
CC-MAIN-2014-15
refinedweb
263
68.33
24831/$-in-a-variable-name-in-java I am a beginner in Java. While looking at the naming conventions for variables it was mentioned that we can use "$" symbol in the variable name. Along with it, there was this line which said "Java does allow the dollar sign symbol $ to appear in an identifier, but these identifiers have a special meaning, so you should not use the $ symbol in your identifiers." "Java does allow the dollar sign symbol $ to appear in an identifier, but these identifiers have a special meaning, so you should not use the $ symbol in your identifiers." So can someone explain what is the special meaning behind $ symbol? Java compiler uses "$" symbol internally to decorate certain names. For Example: public class demo { class test { public int x; } public void myTrial () { Object obj = new Object () { public String toString() { return "hello world!"; } }; } } Compiling this program will produce three .class files: The javac uses $ in some automatically-generated variable names for the implicitly referencing from the inner classes to their outer classes. Here are two ways illustrating this: Integer x ...READ MORE int[][] multi = new int[5][]; multi[0] = new ...READ MORE You can use readAllLines and the join method to ...READ MORE Java 8 Lambda Expression is used: String someString ...READ MORE You can use Java Runtime.exec() to run python script, ...READ MORE First, find an XPath which will return ...READ MORE See, both are used to retrieve something ...READ MORE Nothing to worry about here. In the ...READ MORE I guess, for deep copying you will ...READ MORE Let me give you the complete explanation ...READ MORE OR Already have an account? Sign in.
https://www.edureka.co/community/24831/$-in-a-variable-name-in-java
CC-MAIN-2019-47
refinedweb
277
67.04
Dear All, Is it possible to use C++ string and sstream in a MATLAB MEX file? The following is a part of my code in which I am having problem: string VariableNames; ostringstream strout( VariableNames ); strout << "x y z "; for( int i = 0; i<N; i++) strout << GetComponentName( i ) << " "; VariableNames = strout.str(); Although I have included string and sstream header files, MATLAB complains with the following error message: error C2065: 'string' : undeclared identifier Could someone tell me if using C++ string is usable in MEX. Thanks, Ahmad: Did you ? Kaustubha Govind (view profile) Direct link to this comment: You probably also need to add "using namespace std;", and ensure that your MEX-file has a .cpp extension. AP (view profile) Direct link to this comment: Thanks @Kaustubha. Excellent catch. namespace was the problem.
http://www.mathworks.com/matlabcentral/answers/64044-is-it-possible-to-use-c-string-and-sstream-in-matlab-mex?requestedDomain=www.mathworks.com&nocookie=true
CC-MAIN-2016-36
refinedweb
133
61.06
While working on a classification model, we feel a need of a metric which can show us how our model is performing. A metric which can also give a graphical representation of the performance will be very helpful. ROC curve can efficiently give us the score that how our model is performing in classifing the labels. We can also plot graph between False Positive Rate and True Positive Rate with this ROC(Receiving Operating Characteristic) curve. The area under the ROC curve give is also a metric. Greater the area means better the performance. Note that we can use ROC curve for a classification problem with two classes in the target. For Data having more than two classes we have to plot ROC curve with respect to each class taking rest of the combination of other classes as False Class. So this recipe is a short example of how to use ROC and AUC to see the performance of our model.Here we will use it on two models for better understanding. Get Closer To Your Dream of Becoming a Data Scientist with 70+ Solved End-to-End ML Projects from sklearn import datasets from sklearn.tree import DecisionTreeClassifier from sklearn.linear_model import LogisticRegression from sklearn.metrics import roc_curve, roc_auc_score from sklearn.model_selection import train_test_split import matplotlib.pyplot as plt Here we have imported various modules like: datasets from which we will get the dataset, DecisionTreeClassifier and LogisticRegression which we will use a models, roc_curve and roc_auc_score will be used to get the score and help us to plot the graph, train_test_split will split the data into two parts train and test and plt will be used to plot the graph. Here we have used datasets to load the inbuilt wine dataset and we have created objects X and y to store the data and the target value respectively. dataset = datasets.load_wine() X = dataset.data y = dataset.target The module. X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3) Now we are creating objects for classifier and training the classifier with the train split of the dataset i.e x_train and y_train. clf_tree = DecisionTreeClassifier(); clf_reg = LogisticRegression(); clf_tree.fit(X_train, y_train); clf_reg.fit(X_train, y_train); After traing the classifier on test dataset, we are using the model to predict the target values for test dataset. We are storing the predicted class by both of the models and we will use it to get the ROC AUC score y_score1 = clf_tree.predict_proba(X_test)[:,1] y_score2 = clf_reg.predict_proba(X_test)[:,1] We have to get False Positive Rates and True Postive rates for the Classifiers because these will be used to plot the ROC Curve. This can be done by roc_curve module by passing the test dataset and the predicted data through it. Here we are doing this for both the classifier. false_positive_rate1, true_positive_rate1, threshold1 = roc_curve(y_test, y_score1) false_positive_rate2, true_positive_rate2, threshold2 = roc_curve(y_test, y_score2) Now, For getting ROC_AUC score we can simply pass the test data and the predected data into the function ruc_auc_score. We are printing it with print statements for better understanding. print('roc_auc_score for DecisionTree: ', roc_auc_score(y_test, y_score1)) print('roc_auc_score for Logistic Regression: ', roc_auc_score(y_test, y_score2)) Explore More Data Science and Machine Learning Projects for Practice. Fast-Track Your Career Transition with ProjectPro We are ploting two ROC Curve as subplots one for DecisionTreeClassifier and another for LogisticRegression. Both have their respective False Positive Rate on X-axis and True Positive Rate on Y-axis. plt.subplots(1, figsize=(10,10)) plt.title('Receiver Operating Characteristic - DecisionTree') plt.plot(false_positive_rate1, true_positive_rate1) plt.plot([0, 1], ls="--") plt.plot([0, 0], [1, 0] , c=".7"), plt.plot([1, 1] , c=".7") plt.ylabel('True Positive Rate') plt.xlabel('False Positive Rate') plt.show() plt.subplots(1, figsize=(10,10)) plt.title('Receiver Operating Characteristic - Logistic regression') plt.plot(false_positive_rate2, true_positive_rate2) plt.plot([0, 1], ls="--") plt.plot([0, 0], [1, 0] , c=".7"), plt.plot([1, 1] , c=".7") plt.ylabel('True Positive Rate') plt.xlabel('False Positive Rate') plt.show() As an output we get: roc_auc_score for DecisionTree: 0.9539141414141414 roc_auc_score for Logistic Regression: 0.9875140291806959
https://www.projectpro.io/recipes/plot-roc-curve-in-python
CC-MAIN-2021-43
refinedweb
685
51.65
Jupyter Notebook pyecharts support show charts and export to some file formats in the Jupyter Notebook. Installation When install the pyecharts package using the following command, a jupyter nbextension named echarts/main will be installed if jupyter exists.Or the nbextension installation will be skipped. pip install pyecharts In the development, you can also use the command to install manually jupyter nbextension. $ pip install jupyter-echarts-pypkg You can check the jupyter nbextension using the list command. $ jupyter nbextension list Known nbextensions: config dir: /Users/jaska/.jupyter/nbconfig notebook section echarts/main enabled - Validating: OK Show Charts In the Notebook cell ,you can simply call the instance itself to diplay the chart. All chart classes in pyecharts implement the _repr_html_ interface about IPython Rich Display . Export html function You can use Notebook's default "download as" to export other forms of files, such as ipynb or images. NOTE: Since the exported file is out of the original Jupyter Notebook environment, in order to be able to display the chart completely, you should use the remote jshost library. from pyecharts import online online(host='') # use remote jshost If the exported HTML file needs to display the image without a network, consider the introduction below. Export PDF function Users can use pyecharts-snapshot to generate static images and then output them. There are two steps that need to be performed. - Install pyecharts-snapshot 0.1.4+ 和 phanomjs-prebuilt - Add a statement at the beginning of the notebook. This will output the image as a PDF. from pyecharts import Bar, configure configure(output_image='pdf') # Display as a pdf file in jupyter and not as a local pdf file. Please see this example: test.pdf Show charts in HTML offline Users need to install pyecharts-snapshot 0.1.4+ and use the renderer parameter to generate svg images by pyecharts 0.4.2+. from pyecharts import configure configure(output_image='svg') NOTE: svg is also possible to output a PDF. But the output image not only requires Inkscape but the image is not very good. Therefore, it is not recommended to use output_image='svg' to output as PDF. Example Refer to pyecharts示例. Theme Since pyecharts 0.5.2+, users configure the theme of a single chart through the use_theme function. If you want to configure the theme of all the charts in your environment, you can add the following statement at the very beginning of the notebook: from pyecharts import configure configure(global_theme='dark') Then re-run, you can see that the theme has been replaced. nteract From pyecharts 0.5.5+, nteract can also use pyecharts. For now, nteract users must declare enable_nteract() at the very beginning. Otherwise, just call enable_nteract() when you need to generate html(js) output. However, if you need to output an image, the method is the same as the jupyter notebook mentioned above. jupyterlab jupyterlab is the next generation for Jupyter Notebook,and this is a very early preview, and is not suitable for general usage yet. We will pay Continuous attention to the development and make adapter with pyecharts.
https://pyecharts.readthedocs.io/projects/pyecharts-en/zh/latest/en-us/jupyter_notebook/
CC-MAIN-2022-40
refinedweb
512
65.73
Hi Everyone. Consider this part two after solving part one of my output window issie basically 7zip i needed to output its text to a output window i had created inside my main menu where the button "backup" exists. The window within the window code looks like this. outputLabel = Label(root,text="7Zip Output Window") outputLabel.place(x=500,y=425) outputWindow = Text(root) outputWindow.config(relief=SUNKEN, bg='beige',width=51,height=17) outputWindow.place(x=350,y=130) and when you click the backup button this piece of code executes def picbackup(): source = ['-ir!"%USERPROFILE%\*.bmp"', '-ir!"%USERPROFILE%\*.tif"', ': # can a progress bar be implemented or EBC anim ????? print('Successful backup to', target) else: print('Backup FAILED') ok ... this is great cause it works ... but i have niggly issues i would like to solve. 1. The output only appears AFTER 7zip has completed. (i would like to see it happen in real time 2. No scroll bars (i have extensive researched this and found when i try to put the working source code in .. it puts scroll bars on the ENTIRE MAIN MENE (root?) window .. NOT the small output window. 3. the output that is show is showing the TOP of the output and not the bottom .... ii do have code for this embedded in my scroll bar code BUT like above ... the scroll bars are attaching to the wrong window. If anyone can help me .. the code i have been using to help me is here. this works great cause it has scrolls, shows the bottom of the text instantly ... i'm not sure how it works in a live continous output situation but i guess we'll see. # searching a long text for a string and scrolling to it # use ctrl+c to copy, ctrl+x to cut selected text, # ctrl+v to paste, and ctrl+/ to select all import tkinter as tk def display(data): """creates a text display area with a vertical scrollbar""" scrollbar = tk.Scrollbar(root) text1 = tk.Text(root, yscrollcommand=scrollbar.set) text1.insert(0.0, data) scrollbar.config(command=text1.yview) scrollbar.pack(side='right', fill='y') text1.pack(side='left', expand=0, fill='both') # could bring the search string in from a listbox selectionscroll</strong> text until index line is visible # might move to the top line of text field text1.see(index) root = tk.Tk() str1 = """\ Chapter 1 . . . . . . . Chapter 2 . . . . . . . . Chapter 3 . . . . . . . . The End """ display(str1) root.mainloop() Thankyou for your time ... and so far .. thansk to everyone as i have gained heaps using these forums to seek out answers, snippet code .. all great stuff.
https://www.daniweb.com/programming/software-development/threads/206803/output-window-not-behaving
CC-MAIN-2018-30
refinedweb
436
68.77
Like most developers, I always have about a hundred ideas for little tools or apps I wish existed. Every once in a while I get the time and energy to magic one of them into existence. Clojure is my language of choice these days, but at first glance it's not super well suited to building little command-line apps (which is usually what I start with). Some things that make it not an obvious first choice: Slow JVM startup time. It usually takes a second or two or more to fire up a JVM, which is an unacceptable startup penalty if your whole app is just a little utility meant to run fast. No coherent ecosystem. The Clojure community is very averse to batteries-included solutions. There are good reasons why, a main one being that we spend vastly more time maintaining apps than setting them up so we should aggressively avoid including non-essential dependencies, which add to our maintenance burden. This is fair and does work out really well for long-running projects (which is most Clojure projects). But, this means it's often frustrating and slow to get a new project started, compared to some languages at least. There's no clojure new-cli-apptype command you can just run to get a new app that works in 1 second. This post is about how to build a command-line app with Clojure, using tools.deps and GraalVM. I assume you already have Clojure (including the CLI) and GraalVM installed. I use jabba to manage JVMs on my machine, and installed and setup a GraalVM by running jabba install graalvm-ce-java11@20.3.0 and then jabba use graalvm-ce-java11@20.3. You also need the GraalVM native image utility, which I installed with gu install native-image. GraalVM and Clojure community to the rescue GraalVM is basically a super fast JVM, which solves the problem of slow startup time. You can use it to build a standalone executable out of your Clojure app that will run instantly. Even though there's no batteries-included way to manage Clojure projects, the community has put together a lot of great tools and guides the cover all the bases. The community seems to be converging around the official Clojure CLI and associated tooling as the preferred way to manage Clojure projects. It's extremely well designed, like most things Clojure, but, also like most things Clojure, it's very bare-bones. It's not an all-in-one command-line utility you can use to manage your whole project, like the angular or rails CLIs (which I didn't appreciate nearly enough in my former life 😢). You need to configure the Clojure CLI itself for it to be useful, but luckily that's really straightforward to do. What follows are the steps I did to make a new skeleton command-line app in Clojure. It follows the steps from this great guide, but I included the actual commands here because I use the Clojure CLI ( clj) instead of lein to run things. 1. Make a new Clojure project I use Sean Corfield's clj-new project to initialize new Clojure projects. Install it for your environment according the instructions in his README, then run clj -X:new :template app :name kiramclean/test-cli to generate a new Clojure project (but replace kiramclean/test-cli with <your-name>/<project-name>). 2. Make an uberjar The app template from clj-new includes a default namespace that just prints "Hello, World!" and an alias for building an uberjar, which is just a java app that includes all the dependencies it needs so it can run on its own without worrying about what's installed or not on the host. Run clj -X:uberjar in your app directory, which should build a test-cli.jar. You can run your app now like java -jar test-cli.jar, and cry about how slow it is. 3. Make a standalone executable with GraalVM Now you can use GraalVM to turn your uberjar into a snappy CLI. Run this magic command (note the names -- the -jar option is the location of the uberjar you just made and -H:Name= is the name of your future executable). native-image --report-unsupported-elements-at-runtime \ --initialize-at-build-time \ --no-server \ -jar test-cli.jar \ -H:Name=test-cli It takes a while on my machine for that to finish, but once it does you're good to go! You should have a standalone executable now that you can run from your terminal, which executes your Clojure app natively, and is way faster than running the jar on a regular JVM! Cool. ❯ time java -jar test-cli.jar Hello, World! java -jar test-cli.jar 4.31s user 1.10s system 113% cpu 4.792 total ❯ time ./test-cli Hello, World! ./test-cli 0.05s user 0.01s system 70% cpu 0.086 total That's all for now I made an executable bin/build script in my project with this in it to make the two steps above simpler: #!/bin/bash echo "Build jar..." clj -X:uberjar echo "Nativize it..." native-image --report-unsupported-elements-at-runtime \ --initialize-at-build-time \ --no-server \ --no-fallback \ -jar test-cli.jar \ -H:Name=./test-cli echo "Success! Good to run ./test-cli" The next thing I want to do is add some command-line options and a help menu, but this is already getting kind of long, so I'll leave it here for now. Happy coding 🙂 Discussion (3) This is very simple (literally a single command to run) and I like this solution a lot for it. Thank you for sharing! This was super useful, thank you! This is an interest guide as well: github.com/lread/clj-graal-docs
https://dev.to/kiraemclean/building-a-fast-command-line-app-with-clojure-1kc8
CC-MAIN-2021-39
refinedweb
975
64.71
The QXmlSimpleReader class provides an implementation of a simple XML reader (parser). More... #include <qxml.h> Inherits QXmlReader. List of all member functions. This XML reader is sufficient for simple parsing tasks. The reader: Documents are parsed with a call to parse(). See also XML. More information about features can be found in the Qt SAX2 overview. See also setFeature(). If incremental is TRUE, the parser does not return FALSE when it reaches the end of the input without reaching the end of the XML file. Instead it stores the state of the parser so that parsing can be continued at a later stage when more data is available. You can use the function parseContinue() to continue with parsing. This class stores a pointer to the input source input and the parseContinue() tries to read from that input souce. This means you should not delete the input source input until you've finished your calls to parseContinue(). If you call this function with incremental TRUE whilst an incremental parse is in progress a new parsing session will be started and the previous session lost. If incremental is FALSE, this function behaves like the normal parse function, i.e. it returns FALSE when the end of input is reached without reaching the end of the XML file and the parsing cannot be continued. See also parseContinue() and QSocket. Returns FALSE if a parsing error occurs; otherwise returns TRUE. If the input source returns an empty string for the function QXmlInputSource::data(), then this means that the end of the XML file has been reached; this is quite important, especially if you want to use the reader to parse more than one XML file. The case of the end of the XML file being reached without having finished parsing is not considered to be an error: you can continue parsing at a later stage by calling this function again when there is more data available to parse. This function assumes that the end of the XML document is reached if the QXmlInputSource::next() function returns QXmlInputSource::EndOfDocument. If the parser has not finished parsing when it encounters this symbol, it is an error and FALSE is returned. See also parse() and QXmlInputSource::next(). This file is part of the Qt toolkit. Copyright © 1995-2003 Trolltech. All Rights Reserved.
http://doc.trolltech.com/3.1/qxmlsimplereader.html
crawl-001
refinedweb
386
65.22
Running a Perl module in Qt Hello, I am trying to use a perl module called WordNet : : Similarity module that implements a variety of semantic similarity and relatedness measures based on information found in the lexical database. I have managed to install this module in Ubuntu,Linux. However, my Perl knowledge is limited. I would like to use this module in my C++ application. I have searched for the way of doing it and I found that QProcess or perlembed can be used for my purpose. Perlembed seemed rather complicated. I believe in Qt and I am hoping that there is an easier way to use the module with C++. Could you give me a small code snippet which achieves what I want. The basic use of the module is below. @"; @ I just need to invoke getRelatedness function and use the output in my application. Here is the "link ": WordNet : : Similarity module. Please help me because I have already started tearing my hair off. You can adapt the sample code on "Call an Applescript from Qt":/wiki/Call_an_AppleScript_from_Qt wiki page for your needs. If you have the script on your file system, the easiest way is to call [[Doc:QProcess]]. The docs have an example that should be easy to adapt too. The command line to use should be something like @ perl /path/to/your/script.pl @ which would result in calling QProcess like this: @ QProcess perl; perl.start("perl", QStringList() << "/path/to/your/script.pl"); @ Then connect to the signals or use the synchronous API. The other option is to embed a perl interpreter into your application. I don't have experience with that. Hello, thank for the response, I have followed the steps you suggested. However, I have some problems. As far as I understood, in the code below. @ QProcess perl; perl.start("perl /Desktop/WordNet-Similarity-2.05/samples/sample.pl vehicle#n#1 car#n#1"); perl.waitForFinished(-1); QString p_stdout = perl.readAllStandardOutput(); QString p_stderr = perl.readAllStandardError(); qDebug() << p_stderr;@ @ perl.start("perl /Desktop/WordNet-Similarity-2.05/samples/sample.pl vehicle#n#1 car#n#1");@ is supposed to do the same thing when you run the command below in the terminal . @perl /Desktop/WordNet-Similarity-2.05/samples/sample.pl vehicle#n#1 car#n#1@ I will try to explain the problemI got thoroughly. Pederson's Wordnet : : Similarity module requires min Wordnet 3.0 and Perl 5 installed. When I run the command in terminal, it works properly and it can locate perl libraries. However, when I run exactly the same code in QProcess : : start(), it can locate the libraries. I have no idea why I get this problem. Could you elaborate what QProcess: : start() does with the given arguments ? Thanks Maybe some missing environment variables? That might be the reason but since I am kinda unfamiliar with Perl, I am not exactly sure which libraries should I add. I only added the followings. DEPENDPATH += /usr/local/lib/perl5 INCLUDEPATH += /usr/local/lib/perl5 I thought it's enough. Do you have any suggestions? Remove that stuff from the .pro file since it's not relevant at all to your problem. Does the "perl" executable starts if you run it from QProcess? Do you really have the "/Desktop/WordNet-Similarity-2.05/samples/sample.pl" file? (Sounds a very strange path to me) No that's not the absolute path. Here is the code: @#include <QtCore/QCoreApplication> #include <QProcess> #include <QDebug> int main(int argc, char **argv) { QProcess perl; perl.start("perl /home/kirbac/Desktop/WordNet-Similarity-2.05/samples/sample.pl vehicle#n#1 car#n#1"); perl.waitForFinished(-1); QString p_stdout = perl.readAllStandardOutput(); QString p_stderr = perl.readAllStandardError(); qDebug() << p_stderr; return 0; }@ And the error I get is the following: @Can't locate Wordnet/QueryData.pm in @INC (@INC contains: /etc/perl /usr/local/lib/perl/5.10.1 /usr/local/share/perl/5.10.1 /usr/lib/perl5 /usr/share/perl5 /usr/lib/perl/5.10 ) at /home/kirbac/Desktop/WordNet-Similarity-2.05/samples/sample.pl line 11 BEGIN failed-- compilation aborted at /home/kirbac/Desktop/WordNet-Similarity-2.05/samples/sample.pl line 111@ And "WordNet-Similarity-2.05" doesn't look like the required version 3.0. [quote author="Volker" date="1326116617"]And "WordNet-Similarity-2.05" doesn't look like the required version 3.0.[/quote] WordNet-Similarity-2.05 is a module written in Perl. However, WordNet is a large lexical database of English. WordNet-Similarity-2.05 uses WordNet database to measure semantic relatedness between words. I would say you need to actually install the perl module. calling @ make install @ usually is sufficient. I'm pretty sure, your program does not work if you call if from the command line outside its build directory as it will be unable to finde the module then too. You can try to add a perl library path to the command line: @ perl -I /home/path/lib script.pl @ bq. I would say you need to actually install the perl module. calling Actually I have already installed the module and am able to run it on terminal Here are the command I used when I ran it on terminal and outcome. @kirbac@ubuntu:~/Desktop/WordNet-Similarity-2.05$ perl samples/sample.pl vehicle#n#1 car#n#1 Loading WordNet... done..679238561464479 RES Similarity = 5.5313491229262 LIN Similarity = 0.882549308265133 WUP Similarity = 0.818181818181818 LCH Similarity = 2.07944154167984 HSO Similarity = 4 @ I think I am calling it from the command line outside its build directory. I am kinda puzzled here. You run it inside the build directory. Read the whole sentence! Because it runs in a specific directory does not mean it runs everywhere. cd to /tmp and try to run your script again... @kirbac@ubuntu:~/Desktop/Alternative$ perl /home/kirbac/Desktop/Dene-build-desktop-Desktop_Qt_4_7_4_for_GCC__Qt_SDK__Release/sample.pl banana#n#1 apple#n#1.0480946368308077 RES Similarity = 1.36959027657875 LIN Similarity = 0.1164047451416 WUP Similarity = 0.434782608695652 LCH Similarity = 1.04982212449868 HSO Similarity = 2 @ I created an alternative folder and I can run it again. I am curious about the exact command the below generates. @ QProcess perl; perl.start("perl /home/kirbac/Desktop/WordNet-Similarity-2.05/samples/sample.pl vehicle#n#1 car#n#1");@ Doesn't look like a Qt problem - something with calling the perl script is screwed up. Most probably some environment variables or the wrong perl interpreter running the script. Try to use the full path to a perl interpreter. Or check the version of "perl -v" of the QProcess. I agree with you not being a Qt problem. I believe what Qt is capable of and that's why I am trying to find a solution. It's so awkward. Everything seems to be normal. I also suspect that I am missing qmake variables. Here is the last question before I fall into despair and give up. Which variables would you use in the project file? [quote author="magpielover" date="1326119505" Which variables would you use in the project file? [/quote] NONE! Your project builds and runs just fine! The only problem you have is how to setup the command line for the perl interpreter. There's nothing in a .pro file that can you help here. The state of affairs is quite clear: Perl shows you the include paths, and it cannot find the requested module in there. Go to that directories and check manually. Check that the version of perl called by QProcess is the same as on the command line (depending on the PATH env variable this can differ!). Add the installation directory using -I switch. Ask some Perl gurus... As a last resort, use the WordNet libraries directly, it seems to be standard C or C++. I appreciate your effort. I'd better get familiar with perlembed. Thanks Despite using perlembed (which introduces another library) you should try to use the WordNet library directly, without using perl at all. [quote author="Volker" date="1326120811"]Despite using perlembed (which introduces another library) you should try to use the WordNet library directly, without using perl at all. [/quote] English lexical database WordNet written in C has nothing to do with similarity measurement algorithms. In WordNet database Nouns, verbs, adjectives and adverbs are grouped into sets of cognitive synonyms (synsets), each expressing a distinct concept. Synsets are interlinked by means of conceptual-semantic and lexical relations. However, there exist some algorithms which use WordNet tools to measure the semantic relatedness. The module I have been struggling with is a Perl module that implements a variety of semantic similarity and relatedness measures based on information found in the lexical database WordNet. In particular, it supports the measures of Resnik, Lin, Jiang-Conrath, Leacock-Chodorow, Hirst-St.Onge, Wu-Palmer, Banerjee-Pedersen, and Patwardhan-Pedersen. Therefore, I cannot use WordNet C code directly for my purpose. I need the implementation of the algorithms I mentioned above. I will try to implement the algorithms myself in C++ and release the code for people's good. Thanks I would simply avoid embedding the Perl interpreter. It's much more complicated than simply running the perl interpreter. Just double check that the working directory is the same, the env variables are the same, etcetera. You need to gain some knowledge about how Perl finds its modules. Read perldoc perlmod, perldoc -f require, perldoc -f use. I've used QProcess to access external applications on my linux box multiple times without flaw. I also had issues like you are having right now being that I could run the application on the command line with no errors, and then I tried using QProcess and had issues all around. My solution was following the exact example on the QProcess page using the argument string lists, checking for errors, and all that jazz. For example (right from the QProcess documentation) @ QObject *parent; ... QString program = "./path/to/Qt/examples/widgets/analogclock"; QStringList arguments; arguments << "-style" << "motif"; QProcess *myProcess = new QProcess(parent); myProcess->start(program, arguments); @ Just a thought though. Here's the docs if you haven't already been there. I think when I was having issues, the QProcess line recognized some characters differently then what the command line does. So an argument string list was absolutely required for my case. Also, put ' ' around your arguments as well. Best of luck.
https://forum.qt.io/topic/12869/running-a-perl-module-in-qt
CC-MAIN-2018-09
refinedweb
1,728
52.36
/* I received some feedback on my earlier code snippet regarding generating unique random numbers and someone suggested I make a shorter, easier example, so here it is. This example simply generates the integers from 0 to 9 in random order without any repeats. It is basically the function GenerateRandomIntegers2 from my earlier snippet. srand, rand, and time appear to be part of the iostream library, but I have included ctime and cstdlib because you need them for the srand, time, and rand functions if you are not including iostream. */ #include <iostream> #include <ctime> #include <cstdlib> using namespace std; int main () { srand (time (NULL)); bool picked[10]; for (int i = 0; i < 10; i++) picked[i] = false; int array[10]; int value; for (int i = 0; i < 10; i++) { value = rand () % 10; if (picked[value]) i--; // already picked. for-loop increments, so decrement here else { array[i] = value; picked[value] = true; // hasn't been picked yet. Assign to array, // flag as picked. } } // display for (int i = 0; i < 10; i++) cout << array[i] << endl; return 0; } Are you able to help answer this sponsored question? Questions asked by members who have earned a lot of community kudos are featured in order to give back and encourage quality replies.
https://www.daniweb.com/programming/software-development/code/217217/generating-random-numbers-without-repeats-part-two
CC-MAIN-2018-30
refinedweb
207
57.61
No Shit Sherlock Comments A no shit sherlock comment looks like this: def get_range(x): """ gets the range """ It's comments like these that lead many developers to think that comments should be banned. Comments like these don't help and people don't like them and are often very vocal about not liking them. Yet they still appear. This is largely because of the mindset developers have when they write the code - when your [head is in the code], context is obvious and why is obvious, but it is not obvious that they are not obvious. However, it is obvious that you must write something as a comment so most developers write something obvious. Communal code commenting can help cut down on this type of comment. - What is a no shit Sherlock comment - Some people want to ban comments - Some people think that you should only write why - Capture conversations about code.
https://hitchdev.com/tropes/no-shit-sherlock-comments/
CC-MAIN-2022-21
refinedweb
153
66.78
UWP-064 - Album Cover Match Game - Setup and Working with Files and System Folders In this second video, Bob turns his attention to the layout in order to display the album covers for the randomly selected songs. He also works on the logic for the game setup to get all the controls and variables in to a valid starting state. Lesson source code: Full series source code: PDF: Coming Soon Got an error > The type or namespace name 'AdMediatorControl' does not exist in the namespace 'Microsoft.AdMediator.Universal' (are you missing an assembly reference?) And do I have to take care of the Songs file? @Hemanzt: I assume that you are running the completed version of this project, correct? If so, you will need to restore the NuGet packages. Right-click on the Solution in the Solution Explorer, select "Restore NuGet Packages". As far as songs go ... it will look at your own library of songs! If you don't have any music, I believe you can download the ones I'm using (just copy them into your Music folder in Windows 10). It isn't enough to just copy the example music folders to the Music folder on your desktop. After copying, you then need to right click, and select "include in library", select "Music". Else they are never found.
https://channel9.msdn.com/Series/Windows-10-development-for-absolute-beginners/UWP-065-Album-Cover-Match-Game-Layout-Data-Binding-and-Game-Setup
CC-MAIN-2018-47
refinedweb
221
72.87
I'm very new to Rust. How would I return a String use std::ffi::CString; #[no_mangle] pub extern fn query() -> CString { let s = CString::new("Hello!").unwrap(); return s; } from ctypes import cdll, c_char_p lib = cdll.LoadLibrary("target/release/libtest.so") result = lib.query() print(c_char_p(result).value) from ctypes import * lib = cdll.LoadLibrary("target/release/libtest.so") lib.query.restype = c_char_p result = lib.query() print cast(result, c_char_p).value lib.free_query(result) The most direct version would be this: use libc::c_char; use std::ffi::CString; use std::mem; #[no_mangle] pub extern fn query() -> *mut c_char { let s = CString::new("Hello!").unwrap(); s.into_raw() } Here we return a pointer to a zero-terminated sequence of chars which can be passed to Python's c_char_p. You can't return just CString because it is Rust structure which is not supposed to be used in C code directly - it wraps Vec<u8> and actually consists of three pointer-sized integers. It is not compatible with C's char* directly. We need to obtain a raw pointer out of it. CString::into_raw() method does this - it consumes the CString by value, "forgets" it so its allocation won't be destroyed, and returns a *mut c_char pointer to the beginning of the array. However, this way the string will be leaked because we forget its allocation on the Rust side, and it is never going to get freed. I don't know Python's FFI enough, but the most direct way to fix this problem is to create two functions, one for producing the data and one for freeing it. Then you need to free the data from Python side by calling this freeing function: // above function #[no_mangle] pub extern fn query() -> *mut c_char { ... } #[no_mangle] pub extern fn free_query(c: *mut c_char) { // convert the pointer back to `CString` // it will be automatically dropped immediately unsafe { CString::from_raw(c); } } CString::from_raw() method accepts a *mut c_char pointer and creates a CString instance out of it, computing the length of the underlying zero-terminated string in the process. This operation implies ownership transfer, so the resulting CString value will own the allocation, and when it is dropped, the allocation gets freed. This is exactly what we want.
https://codedump.io/share/CYHR5DvefFqY/1/returning-a-string-from-rust-function-to-python
CC-MAIN-2017-34
refinedweb
373
62.68
Hello: I already finished my program, but i cannot print out the result on the screen, and i think there have a few logical problems. Here is the instruction: Write a program to read a maze from a text file into your array, print the unsolved maze, solve the maze, and then print the solution. You may assume the maze will fit in a 24-row by 80-column array. The maze will be in a file with the number of rows and columns on the first line, followed by the lines defining the maze, with '*' representing a wall and ' ' (space) representing a corridor. For example, here is a small (8-by-12) maze (on my web site as maze8-12.txt): 8 12 ********** * * * * ****** * ***** * * ****** *** *** * * ** * ********** You may assume that the maze will always have a solution. The program is easily generalized to show if there is no solution, but this is not required for this assignment. For an n-by-m maze held in a char array a[n][m], the starting point (at the top left) is a[0][0], and the ending point (at the bottom right) is at a[n-1][m-1]. When you print the solved maze, show the path through the maze by marking all points in the solution set with '#'. For example, here is the same maze printed showing the solution: ##********** *#*########* *###******#* *****######* * ###****** ***#***####* * #####**#* **********## Notice, moves down "blind alleys" are left off the solution. I will discuss the algorithm for this in class, and you must use the recursive backtracking algorithm I give you for this program. This is not a large program- about two pages of code.Here is my code:Here is my code:8 12 ********** * * * * ****** * ***** * * ****** *** *** * * ** * ********** Code:#include <iostream> #include <fstream> #include <string> using namespace std; char map[24][80]; bool nnew[24][80]; int n, m; // print maze solution void print() { cout << endl << "Solution = " << endl; int i, j; for (i = 0; i < n; ++i, cout << endl) for (j = 0; j < m; ++j) cout << map[i][j]; exit(0); } void dfs(int i, int j) { // range coordinates check if (!(i >= 0 && i < n && j >= 0 && j < m)) return; // do not processing walls and earlier marked cells if (map[i][j] == '*' || nnew[i][j]) return; // memorize char of the map char ch = map[i][j]; // put in this cell segment of our future path map[i][j] = '#'; // marked cell, we only moved to the unmarked positions nnew[i][j] = 1; // yes! if (i == n - 1 && j == m - 1) print(); // process all 4 directions dfs(i - 1, j); dfs(i, j + 1); dfs(i + 1, j); dfs(i, j - 1); // restore map map[i][j] = ch; nnew[i][j] = 0; } int main() { ifstream cin("c:\maze8-12.txt"); cin >> n >> m; int i, j; string str; // ignore \n symbol cin.ignore(); for (i = 0; i < n; ++i) { // read string describing new row of the map getline(cin, str); for (j = 0; j < m; ++j) // construct current cell of the map map[i][j] = str[j]; cout << str << endl; } // recursive search from upper-left corner dfs(0, 0); return 0; }
http://cboard.cprogramming.com/cplusplus-programming/90094-help-my-cplusplus-program.html
CC-MAIN-2015-48
refinedweb
512
69.65
dataset: databases for lazy people# Although managing data in relational databases! dataset provides a simple abstraction layer that removes most direct SQL statements without the necessity for a full ORM model - essentially, databases can be used like a JSON file or NoSQL store. A simple data loading script using dataset might look like this: import dataset db = dataset.connect('sqlite:///:memory:') table = db['sometable'] table.insert(dict(name='John Doe', age=37)) table.insert(dict(name='Jane Doe', age=34, gender='female')) john = table.find_one(name='John Doe') Here is similar code, without dataset. Features#. Contents# Contributors# dataset is written and maintained by Friedrich Lindenberg, Gregor Aisch and Stefan Wehrmeyer. Its code is largely based on the preceding libraries sqlaload and datafreeze. And of course, we’re standing on the shoulders of giants. Our cute little naked mole rat was drawn by Johannes Koch.
https://dataset.readthedocs.io/en/latest/
CC-MAIN-2022-40
refinedweb
144
59.9
java.lang.Object org.netlib.lapack.SLAQGEorg.netlib.lapack.SLAQGE public class SLAQGE SLAQGE is a simplified interface to the JLAPACK routine slaq * ======= * * SLAQ) REAL) REAL array, dimension (M) * The row scale factors for A. * * C (input) REAL array, dimension (N) * The column scale factors for A. * * ROWCND (input) REAL * Ratio of the smallest R(i) to the largest R(i). * * COLCND (input) REAL * Ratio of the smallest C(i) to the largest C(i). * * AMAX (input) REAL * Absolute value of largest matrix entry. * * EQUED (output) CHARACTER*1 * * =================== * *. * * ===================================================================== * * .. Parameters .. public SLAQGE() public static void SLAQGE(int m, int n, float[][] a, float[] r, float[] c, float rowcnd, float colcnd, float amax, StringW equed)
http://icl.cs.utk.edu/projectsfiles/f2j/javadoc/org/netlib/lapack/SLAQGE.html
CC-MAIN-2017-51
refinedweb
113
57.16
Why can't raw strings (r-strings) end with a backslash? Raw string literals are parsed in exactly the same way as ordinary string literals; it’s just the conversion from string literal to string object that’s different. This means that all string literals must end with an even number of backslashes; otherwise, the unpaired backslash at the end escapes the closing quote character, leaving an unterminated string. Raw strings were designed to ease creating input for processors, such as use raw strings to build Windows path names, note that all Windows system calls accept forward slashes too: f = open("/mydir/file.txt") # works fine! The exception is commands passed to the Windows command interpreter (command.com or cmd.exe). The easiest way to handle that is to run the filename through os.path.normpath before passing it to the command interpreter: arg = os.path.normpath("/this/is/my/dos/dir/") os.system("myapp " + arg) Note that getting the slashes right before you call os.system still won’t help you with spaces and other special characters. To write robust code, you can use the subprocess.list2cmdline helper function. It takes a list of arguments, and turns them into a properly quoted command line: import os import subprocess def mysystem(command, *files): files = map(os.path.normpath, files) files = subprocess.list2cmdline(files) return os.system(command + " " + files) mysystem("more", "/program files/subversion/readme.txt") But then you might as well use subprocess.call and the shell option, of course. But back to the raw strings; if you really want to add a backslash to the end of a raw string, you can work around the parser limitation by doing: arg = r"\this\is\my\dos\dir" "\\" or arg = r"\this\is\my\dos\dir\ "[:-1]
http://www.effbot.org/pyfaq/why-can-t-raw-strings-r-strings-end-with-a-backslash.htm
CC-MAIN-2014-52
refinedweb
296
58.79
Will AOO 4.0 conform to the latest & greatest version? (I'm limited to a dialup link at the moment, and searching the 'net is almost painful User community support forum for Apache OpenOffice, LibreOffice and all the OpenOffice.org derivatives That namespace works for all versions of MathML, i.e., 1.0, 1.01, 2.0 & 3.0.That namespace works for all versions of MathML, i.e., 1.0, 1.01, 2.0 & 3.0.acknak wrote:... namespace declaration ... <math xmlns=""> ... ODF uses the MathML standard and Apache OpenOffice touts its support of ODF. But is Apache OpenOffice even compatible with MathML (ignore conform for the moment)?ODF uses the MathML standard and Apache OpenOffice touts its support of ODF. But is Apache OpenOffice even compatible with MathML (ignore conform for the moment)?acknak wrote:If you want to get some substantive discussion over this, or communicate a specific suggestion, you'll need to use the project email list. There are few developers here and all decisions are discussed on the mailing list. "... MathML, a web standard for displaying mathematical equations. I will show how well established it is on the web, how it is integrated into ODF ..." "... MathML was the only logical choice for us to use to support equations in OpenDocument Format (ODF). ..." "... But the choice of MathML is more than just a fashion statement. It has practical significance and enables opportunities for innovative workflows around mathematical document production. ..." "... strictly speaking the ODF specification allows MathML 2.0, including the non-marking characters. ..." "... Let’s demonstrate the value of open standards working together." "... we standards geeks ... ... ODF is very much built on top of web and internet standards from the W3C and IETF. ..."" "... A request to support MathML 2.0 for import/export ..." "... this would be a load of work, there are loads of features in mathml2.0 which are not supported by our starmath at all, and some which are likely not to map well to the new mathml 2.0 without a lot of effort on our side. ..." "... Since OpenOffice.org is working as to be XML compliant, MathML should be rendered correctly. ..." ." "... Full MathMl 2.0 supoprt entails a lot of work , and can be expected to be a rather middle to long term goal. The trouble with current state of affairs is that if one writes an ODF compliant mathMl object ( by eg directly editing the XML file) OOO will wipe it clean on load/save. This destructive behaviour is rather problematic..." Users browsing this forum: No registered users and 2 guests
https://user.services.openoffice.org/en/forum/viewtopic.php?f=12&t=59546
CC-MAIN-2020-40
refinedweb
430
67.25
Gábor Lehel schrieb: > On Tue, Jan 4, 2011 at 1:25 PM, Ian Lynagh <igloo at earth.li> wrote: >> On Mon, Jan 03, 2011 at 11:30:44PM +0100, Bas van Dijk wrote: >>> >>> 2) Make 'join' a method of Monad. >> Why? > > Of course I'm only a sample size of one, but I find join a lot easier > to think about and implement than (>>=). Even trying to look at it > objectively and factor out my own potential idiosyncracies, it's > obvious that it only has one argument to (>>=)'s two, and the type > signature looks a lot more straightforward any way I slice it. I was > very glad to see this proposal to make it possible to define a Monad > using return (pure), fmap, and join, rather than return and (>>=). Mathematically I like 'join' more than '>>=', but for RMonads like StorableVector you will in general be able to define a '>>=' but not 'join'. Of course, you can ignore this reason, because Monad is not RMonad, but for reasons of consistency it might count.
http://www.haskell.org/pipermail/libraries/2011-January/015587.html
CC-MAIN-2014-23
refinedweb
173
72.6
Express killers, part IV First, quick reminder: what will be result when you execute following code? public class Loader { { System.out.println("a"); } X x; static { System.out.println("b"); } Loader() { System.out.println("c"); } { System.out.println("d"); } static class X { static { System.out.println("e"); } } public static void main(String[] args) { System.out.println("f"); new Loader(); } } When we get into this piece of code we realized (surprisingly!) that it doesn't compile, but it is simple and fixing doesn't take a lot of time. However, what if we have following restrictions in code manipulation: - It is academic example and ternary operator can't be changed (it means main()method can't be changed), - classes A and B are used in other projects and, besides they do nothing, API can't be changed (methods' signatures and inheritance hierarchy). What can you do, to make this code able to compile without changing the result? class Parent { } class A extends Parent { public boolean test() { return false; } } class B extends Parent { public boolean test() { return true; } } public class X { public static void main(String[] args) { A a = new A(); B b = new B(); boolean t = (true ? a : b).test(); } } Results: First example: Result will be: b – after class is loaded, static blocks are executed, f – execution of main() method, a, d – creation object of class Loader will execute subsequent (ordered by position in class) class initializations blocks, c – execution of class constructor. Letter e will not be printed because static inner class is loaded at the time of first usage. In above example this class is not created, so it will not be loaded as well. Even despite the fact, that it is attribute in class Loader, because it is just type declaration and object is not created. Second example: Tenary operator can't be used as it is, because compiler: - will be looking for first common super class for classes A and B, - will check, if found class has method that is called, and if not, will return an error. Compiler at the compile phase can't define what will be the result of the ternary operator (even though in this example, optimizer can figure out resulting type), so we have to be sure that in both cases calling method test() will be possible. Besides that in this example, both types have test() method, compiler will look for common super class, so it will find Parent class, that doesn't have test() method. What can we do about it? If ternary operator can't be changed, it means we have to assure that Parent class has test() method. We can do it: - by changing Parentclass to abstract class and add abstract test()method, but it will break possibility to call new Parent(); - by adding test()method to class Parent, that will throw an exception that it is not implemented yet. It means that derived classes should overwrite this method. The best solution would be to remove ternary operator and replace it with if-else statement. In this case modification of Parent class will be not needed. Nobody has commented it yet.
http://www.javaexpress.pl/article/show/Express_killers_part_IV
CC-MAIN-2020-16
refinedweb
522
60.14
connor hoarePro Student 7,932 Points Where am i going wrong here? functions return complex values // Enter your code below func coordinates (for location: String) -> (Double, Double) { switch location { case "Eiffel Tower": return (48.8582,2.2945) case "Great Pyramid": return (29.9792,31.1344) case "Syndey Opera House": return (33.8587,151.2140) default: return (0,0) } return (location) } 1 Answer Matthew Long28,363 Points You pretty much have the correct answer except for a couple issues. Primarily, you don't need to return the location. The switch statement is returning the tuple for you. Your function is expecting you to return a tuple of types Double, not the location parameter. Also, make sure you spell Sydney Opera House correctly. func coordinates (for location: String) -> (Double, Double) { switch location { case "Eiffel Tower": return (48.8582, 2.2945) case "Great Pyramid": return (29.9792, 31.1344) case "Sydney Opera House": return (33.8587, 151.2140) default: return (0,0) } }
https://teamtreehouse.com/community/where-am-i-going-wrong-here-8
CC-MAIN-2020-24
refinedweb
159
60.61
haptic and vibration feedback I was just playing around, and thought this might be useful to others as well. So I signed up to GitHub. Feelback (didn't know how else to call it, I know it's a bit cringey) makes it fairly easy to get vibrations and haptic feedback, assuming your device has a haptic engine built in. The oldest supported iPhone is the 6s (mine), and it only works with a little workaround. I don't know which iPads work (my iPad mini 2 is just way too old), or if they have a haptic engine at all. Does anyone know if there are other SystemSounds than these? Because even this list doesn't include the ids for haptic feedback (1519, 1520, 1521) , so there may be more. @omz used a slightly different code here. What's the advantage of his code over this? import ctypes import time c = ctypes.CDLL(None) vibrate = c.AudioServicesPlaySystemSound if __name__ == '__main__': for i in range(3): vibrate(4095) time.sleep(0.5) @cvp jup, they are too old :) I was so relieved when I found out that at least my phone supports the haptic stuff! But I guess it's not really a feature that will be used often @Drizzel, thanks. Now we know how to do it for that game that really needs it. For example, my draw-in-the-dark game caves sure could use this for that moment when you hit the wall. @Drizzel @omz's code is identical, excep that he specifies the argtypes on the playaudiosystemsound, which you should also do, otherwise you risk crashing (say on a 32 bit vs 64 bit device). I think ctypes defaults to 32 bit argtypes even on 64 bit devices, so you are safe in this case.
https://forum.omz-software.com/topic/6321/haptic-and-vibration-feedback/2
CC-MAIN-2021-49
refinedweb
299
81.02
Couch (IoT) environments, Couchbase Lite runs native on-device and manages sync to Couchbase Server. Couchbase Server 4.5 was recently announced. Flexible data model, SQL-like query language (N1QL), simple administration, high availability, full-text search, Role Based Access Control (RBAC), Enterprise Backup and Restore are some of the features that makes it an excellent choice for your web, mobile and IoT applications. Read What’s New in Couchbase 4.5. One of the key features in this release is production certified support for Docker. There are multiple orchestration frameworks for Docker containers, such as Kubernetes, Docker Swarm and Mesos. Red Hat OpenShift provides Enterprise-ready Kubernetes for Devs and Ops. This blog will explain how to get started with Couchbase on OpenShift. This blog was written using OSX 10.10.5, Vagrant 1.7.4 and VirtualBox 5.0.18 r106667. Getting Started with OpenShift OpenShift can be started using a Docker container, All-in-one VM, or binary release. These options are easily described on openshift.org. This blog will use an All-in-one VM and the complete instructions for that are described at openshift.org/vm/. Create a new directory and in that directory do the following commands: vagrant init thesteve0/openshift-origin vagrant up It should show output similar to this: /Users/arungupta/.vagrant.d/boxes/thesteve0-VAGRANTSLASH-openshift-origin/1.2.0/virtualbox/include/_Vagrantfile:5: warning: already initialized constant VAGRANTFILE_API_VERSION /Users/arungupta/tools/openshift/1.2/Vagrantfile:5: warning: previous definition of VAGRANTFILE_API_VERSION was here Bringing machine 'default' up with 'virtualbox' provider... ==> default: Importing base box 'thesteve0/openshift-origin'... ==> default: Matching MAC address for NAT networking... ==> default: Setting the name of the VM: origin-1.1.1 ==> default: Clearing any previously set network interfaces... ==> default: Preparing network interfaces based on configuration... default: Adapter 1: nat default: Adapter 2: hostonly default: Adapter 3: hostonly ==> default: Forwarding ports... default: 8443 => 8443 (adapter 1) default: 22 => 2222 (adapter 1) ==> default: Running 'pre-boot' VM customizations... ==>... The following SSH command responded with a non-zero exit status. Vagrant assumes that this means the command failed! /sbin/ifup eth2 Stdout from the command: ERROR : [/etc/sysconfig/network-scripts/ifup-eth] Error, some other host already uses address 10.2.2.2. Stderr from the command: This downloads the OpenShift Vagrant box definition, starts and configures the Virtual Machine. Download and Configure the OpenShift Client Download Mac 64-bit Client Tools. Clients for other operating systems are available from openshift.org/vm/#downloads. Create a new directory and extract the downloaded zip file. The directory will have the following contents: LICENSE README.md oc Verify the client version: oc version oc v1.2.0 kubernetes v1.2.0-36-g4a3f9c5 Login to OpenShift: Use test as login and choose a password that you’ll remember, it can be anything you want. oc login Server []: The server uses a certificate signed by an unknown authority. You can bypass the certificate check, but any data you send to the server could be intercepted by others. Use insecure connections? (y/n): y Authentication required for (openshift) Username: test Password: Login successful. You don't have any projects. You can try to create a new project, by running $ oc new-project Welcome! See 'oc help' to get started. This displays the list of projects for that user. Each OpenShift project is created in a Kubernetes namespace with additional annotations. This allows a community of users to organize and manage their content in isolation from other communities. Learn more about OpenShift Users, Namespaces and Projects. Create Couchbase Application in OpenShift Let’s make a project for our Couchbase example: oc new-project couchbase Now using project "couchbase" on server "". You can add applications to this project with the 'new-app' command. For example, try: $ oc new-app centos/ruby-22-centos7~ to build a new hello-world application in Ruby. This creates the project and automatically selects it as well. OpenShift Application allows to create an application in a project using source code from a repository, a Docker image or a previously stored template. Let’s create an application that will start a Couchbase database using a Docker image. We’ll use arungupta/couchbase Docker image. This image is built from github.com/arun-gupta/docker-images/tree/master/couchbase. It uses Couchbase base image and configures it using the Couchbase REST API. Note that the chosen project is couchbase, and so the application will be created in this project. Create a new Couchbase application: oc new-app arungupta/couchbase --> Found Docker image 69f3ad9 (10 hours old) from Docker Hub for "arungupta/couchbase" * An image stream will be created as "couchbase:latest" that will track this image * This image will be deployed in deployment config "couchbase" * Ports 11207/tcp, 11210/tcp, 11211/tcp, 18091/tcp, 18092/tcp, 18093/tcp, 8091/tcp, 8092/tcp, 8093/tcp, 8094/tcp will be load balanced by service "couchbase" * Other containers can access this service through the hostname "couchbase" * This image declares volumes and will default to use non-persistent, host-local storage. You can add persistent volumes later by running 'volume dc/couchbase --add ...' * WARNING: Image "couchbase" runs as the 'root' user which may not be permitted by your cluster administrator --> Creating resources with label app=couchbase ... imagestream "couchbase" created deploymentconfig "couchbase" created service "couchbase" created --> Success Run 'oc status' to view your app. This will download arungupta/couchbase image in OpenShift and start a Pod, a Service, an Image Stream, and a Deployment Configuration. . Check status of the application: oc status In project couchbase on server svc/couchbase - 172.30.75.85 ports 8091, 8092, 8093, 8094, 11207, 11210, 11211, 18091, 18092, 18093 dc/couchbase deploys istag/couchbase:latest deployment #1 running for 17 seconds - 1 pod 1 warning identified, use 'oc status -v' to see details. Get the list of pods running: oc get po NAME READY STATUS RESTARTS AGE couchbase-1-deploy 1/1 Running 0 27s couchbase-1-rg6zn 0/1 ContainerCreating 0 24s -w switch can be used to check for change in status of pod creation. oc get po -w NAME READY STATUS RESTARTS AGE couchbase-1-deploy 1/1 Running 0 30s couchbase-1-rg6zn 0/1 ContainerCreating 0 27s NAME READY STATUS RESTARTS AGE couchbase-1-rg6zn 1/1 Running 0 1m couchbase-1-deploy 0/1 Completed 0 1m couchbase-1-deploy 0/1 Terminating 0 1m couchbase-1-deploy 0/1 Terminating 0 1m It shows that Couchbase image is downloaded and pod created. A container is used to deploy the application and is terminated after the job is accomplished. The time to start the Couchbase pod would vary based upon your network speed, as we are waiting for download of the image from Docker Hub. More details about the pod can be found as: c describe po couchbase-1-rg6zn Name: couchbase-1-rg6zn Namespace: couchbase Node: origin/10.0.2.15 Start Time: Thu, 23 Jun 2016 16:52:10 -0700 Labels: app=couchbase,deployment=couchbase-1,deploymentconfig=couchbase Status: Running IP: 172.17.0.14 Controllers: ReplicationController/couchbase-1 Containers: couchbase: Container ID: docker://648dac7e00fd6234e602ab04c5419c0d0b40089acda4d115125f5d26b2f49a35 Image: arungupta/couchbase@sha256:6c909014126d312949bb552f31682fe173749c7e0902305033d7d72511a2907c Image ID: docker://7aa00979751477146b54e33a9ffac804874d88abd7d503355c22b4162d978faa Ports: 8091/TCP, 8092/TCP, 8093/TCP, 8094/TCP, 11207/TCP, 11210/TCP, 11211/TCP, 18091/TCP, 18092/TCP, 18093/TCP QoS Tier: cpu: BestEffort memory: BestEffort State: Running Started: Thu, 23 Jun 2016 16:53:16 -0700 Ready: True Restart Count: 0 Environment Variables: Conditions: Type Status Ready True Volumes: couchbase-volume-1: Type: EmptyDir (a temporary directory that shares a pod's lifetime) Medium: default-token-te2o1: Type: Secret (a volume populated by a Secret) SecretName: default-token-te2o1 Events: FirstSeen LastSeen Count From SubobjectPath Type Reason Message --------- -------- ----- ---- ------------- -------- ------ ------- 6m 6m 1 {default-scheduler } Normal Scheduled Successfully assigned couchbase-1-rg6zn to origin 5m 5m 1 {kubelet origin} spec.containers{couchbase} Normal Pulling pulling Pulled Successfully pulled Created Created container with docker id 648dac7e00fd 4m 4m 1 {kubelet origin} spec.containers{couchbase} Normal Started Started container with docker id 648dac7e00fd It shows that the pod is actually created inside a DeploymentConfiguration as shown by the label “deploymentconfig=couchbase”. This Deployment Configuration wraps the Kubernetes Replication Controller, whose job it is to insure your Couchbase pod always has the correct number of replicas running. By default, only one instance is running. A subsequent blog will show how to run a Couchbase cluster. Couchbase on OpenShift Web Console OpenShift provides a Web Console that allows developers to visualize, browse, and manage the contents of projects. Login to OpenShift Web Console at: Your browser may give a warning as this is running on localhost and no verified security certificates are installed. It’s OK to ignore those warnings. This would not be an issue when running OpenShift in production as appropriate certificates will be installed. Enter the username and password as test and the chosen password. Click on the Log In button to login. This shows the complete list of projects: This list shows only a single project that was created earlier. Click on the project to see the list of deployed applications: Click on the big pod (big blue circle with the number 1 inside it) to see more details the pod: Click on the pod name to see more details: Note down IP address of the pod, 172.17.0.14 in this case. Click on Terminal to open a terminal into the pod. Connect to Couchbase Query Tool to query over the JSON documents stored in Couchbase bucket. In the terminal, give the command is: cbq -u Administrator -p password Note that that the pod’s IP address is specified here. Now query over the JSON documents by giving the N1QL query: select * from `travel-sample` limit 1; You can learn more about N1QL or learn the SQL-like syntax in an interactive tutorial. You can create an index on this bucket and then the query will return accurate results. Finally, let’s go ahead and make a route to the Couchbase web server so we can access it from our local machine using the web console. Routes in OpenShift provide a way to route traffic from outside the cluster to a service inside the cluster. Back on the overview page for your project, up in the top right you should see a “create route” link, go ahead and click it. On the following page you can just accept all the defaults (which basically says to auto-generate the URL to take incoming traffic from port 80 and reroute to 8091 on the service named Couchbase. Click “create” which will bring you back to the overview page, but now there is a URL under the service. When you click the link you will be brought to the login for the Couchbase web console. Use the username and password of Administrator and password as you did above on the command line. These passwords are baked into the arungupta/couchbase Docker image. Once you hit the sign in button you should be looking at the normal Couchbase Web Console. You could even make another route to expose port 8093 traffic for the CBQ. You can see I made both of these routes and they both work at the same time. In this blog, you deployed a Couchbase server on OpenShift.
https://blog.openshift.com/openshift-ecosystem-couchbase-openshift-nosql-applications/
CC-MAIN-2017-13
refinedweb
1,889
54.73
On Sun, 13 Aug 2000, Alan Cox wrote:> > But "tar" won't even _see_ the thing. Unless "tar" starts to know about> > S_IFCOMPLEX. In which case it's a non-issue.> > oh wonderful. So you've just broken my backup scripts. Congratulations.Alan. Calm down a moment, and THINK.How hard do you think it is to make the tar-test that does if (S_ISDIR(st->st_mode)) { ... traverse into directories .. }instead be #ifdef S_ISCOMPLEX #define CAN_TRAVERSE(x) (S_ISCOMPLEX(x) || S_ISDIR(x)) #else #define CAN_TRAVERSE(x) (S_ISDIR(x)) #endif ... if (CAN_TRAVERSE(st->st_mode)) { .. traverse into directories .. }and suddenly tar _can_ handle resource forks. Sure, you'll need some extralogic to handle the complex files data too, but really, Alan.What's the advantage, I hear you say?The above will work on HFS. But so will the current "tar". Resource forksand all.The above will -also- work on NTFS. And the current setup will never dothat.> tar is already backing up my HFS test partition, including the resource> forks. ..and it can do so. The thing is, right now resource forks are only exported on HFS. As far asI know, the Linux NTFS driver doesn't even try. But people are starting tobe more and more interested in supporting NTFS in a real way, rather thanthe partial support it has now. You-know-who etc.Quite frankly, _eventually_ we'll have to bite the bullet and handleresource forks. Maybe HFS will continue to use the current setup. Whoknows? But wouldn't it be nice to have a unified way of handling it? Andcomplain all you like, but the HFS way just cannot be the unified way.There are actually problems with the current HFS hackery: one of theproblems is that because it splits things up in different directories, youhave multiple dentries pointing to the same inode. That's fine: the dentrycode has no trouble with that per se (hard links), but I suspect it causesraces on create/remove.At the very least, I hope the virtual ".resource" directory is the samephysical inode as the directory it resides in, because otherwise the basic"dir->i_sem" concurrency protection simply won't work.(To me it looks like that isn't the case. Race city. Nobody probablycares, but it's an example of the fact that HFS is actually buggy as it isimplemented right now. Exactly because the VFS layer doesn't understandwhat it is that HFS is trying to do).Do you see the problem now? Is pointing you to a real bug enough? Linus-To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.rutgers.eduPlease read the FAQ at
http://lkml.org/lkml/2000/8/13/126
CC-MAIN-2014-52
refinedweb
447
68.87
I am trying to load time.h directly with Cython instead of Python's import time Call with wrong number of arguments (expected 1, got 0) cdef extern from "time.h" nogil: ctypedef int time_t time_t time(time_t*) def test(): cdef int ts ts = time() return ts Cannot assign type 'long' to 'time_t *' cdef extern from "time.h" nogil: ctypedef int time_t time_t time(time_t*) def test(): cdef int ts ts = time(1) return ts cdef extern from "math.h": double log10(double x) The parameter to time is the address (i.e.: "pointer") of a time_t value to fill or NULL. To quote man 2 time: time_t time(time_t *t); [...] If t is non-NULL, the return value is also stored in the memory pointed to by t. It is an oddity of some standard functions to both return a value and (possibly) store the same value in a provided address. It is perfectly safe to pass 0 as parameter as in most architecture NULL is equivalent to ((void*)0). In that case, time will only return the result, and will not attempt to store it in the provided address.
https://codedump.io/share/AbdNINVC3gOL/1/how-to-call-time-from-timeh-with-cython-i-can39t-get-it-to-work
CC-MAIN-2016-44
refinedweb
191
71.95
LifecycleListener equivalentBechara Hitti Feb 24, 2014 2:52 PM Hello, I am contemplating a cross-over from glassfish v4 (reasons beyond the scope of this question). The application I am porting is mostly standard compliant except for the initialization part which relies on com.sun.appserv.server.LifecycleListener public class Init implements com.sun.appserv.server.LifecycleListener { @Override public void handleEvent(LifecycleEvent le) throws ServerLifecycleException { whatever initialization code I need goes here.... } } While wildfly is getting downloaded, I have been trying to research a way to accomplish the same. Basically, what I need is a way to make sure the code initialization sequence is performed once and only once in the event of a server startup (even when following a crash or ungraceful reboot). I am not a fan of using server specific code but with glassfish, I had previously tried a Singleton with a @PostConstruct... which resulted with the code getting initiated twice... afaik java ee 7 specifications do not guarantee that the @PostContruct method is only called once. Any suggestions would be appreciated. Thanks, 1. Re: LifecycleListener equivalentTomaz Cerar Feb 24, 2014 3:36 PM (in response to Bechara Hitti) You need servlet events? As you can achieve what you want in completely standard way. by having @Singleton @Startup ejb bean with @PostConstruct method. 2. Re: LifecycleListener equivalentBechara Hitti Feb 24, 2014 3:57 PM (in response to Tomaz Cerar) Thank you for your reply! Unfortunately, as stated above, last time I tried this approach the method got called twice during startup. Afaik, there is no guarantee that the @PostConstruct gets called only once. It is absurd I know, but it seems that's the way things are designed. See EJB 3.2 spec section "3.4.4Session Bean's No-Interface View":class constructor. (Got my information from) 3. Re: Re: LifecycleListener equivalentStephen Coy Feb 24, 2014 9:32 PM (in response to Bechara Hitti) This: The developer of an enterprise bean that exposes a no-interface view must not make any assumptions about the number of times the bean class no-arg constructor will be called does not imply that @PostConstruct will be called multiple times. In fact the JIRA that you referenced says this as well. Therefore, if this is indeed happening to you then we would need to see more details. 4. Re: LifecycleListener equivalentBechara Hitti Feb 25, 2014 5:36 AM (in response to Stephen Coy) Thank you for the feedback. So you mean that the multiple calls apply to the no-arg constructor rather than the @PostContruct method My experience with Glassfish tells me otherwise. I had the @PostConstructor called twice during startup which after a lot of research prompted me to switch to the LicecycleListener. Since I am trying to migrate to wildfly, I do not feel that elaborating on the glassfish issue is relevant to this forum. Perhaps it would be best if I made a test implementation using wildfly an shared my findings here. It will probably do so and report success of failure. Thanks again! 5. Re: LifecycleListener equivalentRich DiCroce Feb 25, 2014 5:05 PM (in response to Bechara Hitti)1 of 1 people found this helpful If you're okay with using CDI, there's a new feature in CDI 1.1 that may do what you want. Basically, the CDI container now fires a CDI event whenever any scope is initialized or destroyed. So you can effectively get "run on startup" behavior by creating an observer method like so: void myStartupMethod(@Observes @Initialized(ApplicationScoped.class) Object event) { ...your init code here... } I'm using this in a new project right now, and I'm happy with it so far. For you, I do see one caveat. Technically, this is not tied to the lifecycle of the application server but rather the lifecycle of the deployment. So if you deployed the application, then undeployed it (without stopping WildFly), and then redeployed it, the method would get invoked again. 6. Re: LifecycleListener equivalentBechara Hitti Feb 26, 2014 6:44 AM (in response to Rich DiCroce) That sounds like a delightful solution and standard compliant too! Thank you! I am currently running into the much expected migration trouble.. netbeans 7.4 refusing to connect to wildfly etc ... and still have not been able to find the time needed to get a test environment running. Will get back to you with my findings asap! 7. Re: Re: LifecycleListener equivalentBechara Hitti Feb 26, 2014 8:07 AM (in response to Rich DiCroce) @ApplicationScoped public class Init { private static final Logger LOG = Logger.getLogger(Init.class.getName()); public Init() { LOG.info("###In init"); } public void start(@Observes @Initialized(ApplicationScoped.class) Object o) { LOG.info("## Startup"); } public void stop(@Observes @Destroyed(ApplicationScoped.class) Object o) { LOG.info("Goodbye cruel World!"); } } I tested the code above in glassfish while setting up WildFly, the code above worked like a charm but only when the class was decorated with @ApplicationScoped are you observing the same behavior? Thanks! 8. Re: LifecycleListener equivalentTomaz Cerar Feb 26, 2014 8:23 AM (in response to Bechara Hitti)1 of 1 people found this helpful Bechara Hitti wrote: I am currently running into the much expected migration trouble.. netbeans 7.4 refusing to connect to wildfly etc ... and still have not been able to find the time needed to get a test environment running. You should try NetBeans 8 see: 9. Re: Re: LifecycleListener equivalentRich DiCroce Feb 26, 2014 10:17 AM (in response to Bechara Hitti) Yes, I've observed that behavior as well. The reason is because of another change in CDI 1.1. In CDI 1.0, any archive containing a beans.xml file was CDI-enabled, and any class in such an archive that didn't have a scope annotation was implicitly @Dependent scoped. That caused headaches for a variety of reasons, so in CDI 1.1, a new bean discovery mode was introduced (and is also the default, if memory serves) that only looks at classes with an explicit scope annotation. You can change the bean discovery mode in beans.xml like so: <beans xmlns="" xmlns:xsi="" xsi: bean-discovery-mode can be annotated, all (equivalent to CDI 1.0), or none. @Dependent is a scope annotation, so you can still have dependent-scoped beans when using annotated bean-discovery-mode. 10. Re: Re: LifecycleListener equivalentBechara Hitti Feb 26, 2014 4:00 PM (in response to Rich DiCroce) Thanks for the thorough explanation!
https://developer.jboss.org/thread/237436
CC-MAIN-2017-47
refinedweb
1,078
56.66
This project appears to have gone dormant. It will be removed from the list soon unless new activity is noted. Object-oriented scripting language mixing Python, PHP, and Ruby. Saffire is a new, scripting language, based primarily on Python, PHP, and Ruby. Our goal is to blend all the good things of those languages into a new one. Saffire primary selling points: - Everything is an object. - Unicode support out of the box. - CLI & FastCGI interfaces. - Operator and method overloading. import io; class Foo { const FOOBAR = "foobar"; protected property a = 1; public method ctor() { // Constructor } public method foo() { return self.a; } } f = Foo(); io.print ("The value is: ", f.foo()); Information updated 11/11/17
http://fll.presidentbeef.com/lang/saffire
CC-MAIN-2019-13
refinedweb
114
63.05
A namespace for classes internal to the triangulation classes and helpers. Determine the neighbors of all cells. con_cf connectivity cell-face con_cc connectivity cell-cell (for each cell-face it contains the index of the neighboring cell or -1 for boundary face) Definition at line 946 of file connectivity.h. Build entities of dimension d (with 0<d<dim). Entities are described by a set of vertices. Furthermore, the function determines for each cell of which d-dimensional entity it consists of and its orientation relative to the cell. Definition at line 999 of file connectivity.h. Call the right templated function to be able to use std::array instead of std::vector. Definition at line 1183 of file connectivity.h. Build surface lines described by: Furthermore, the type of the quad is determined. Definition at line 1244 of file connectivity.h. Build the reduced connectivity table for the given dimension dim. This function is inspired by the publication Anders Logg "Efficient Representation of Computational Meshes" and the FEniCS's DOLFIN mesh implementation. It has been strongly adjusted to efficiently solely meet our connectivity needs while sacrificing some of the flexibility there. Definition at line 1359 of file connectivity.h. Preprocessing step to remove the template argument dim. Definition at line 1445 of file connectivity.h. Reserve space for TriaLevel. Details: Reserve enough space to accommodate total_cells cells on this level. Since there are no used flags on this level, you have to give the total number of cells, not only the number of newly to accommodate ones, like in the TriaLevel<N>::reserve_space functions, with N>0. Since the number of neighbors per cell depends on the dimensions, you have to pass that additionally. Definition at line 1205 of file tria.cc. Reserve space for TriaObjects. Details: Assert that enough space is allocated to accommodate new_objs_in_pairs new objects, stored in pairs, plus new_obj_single stored individually. This function does not only call vector::reserve(), but does really append the needed elements. In 2D e.g. refined lines have to be stored in pairs, whereas new lines in the interior of refined cells can be stored as single lines. Definition at line 1351 of file tria.cc.
https://www.dealii.org/developer/doxygen/deal.II/namespaceinternal_1_1TriangulationImplementation.html
CC-MAIN-2021-25
refinedweb
366
50.53
Adventures in Scala Have you discovered Scala? I did and I'm keeping track of it here, recording my experiments and lessons learned. -- Steve Posted by Steve Yen on January 24, 2008 at 11:40pm — 1 Comment package scalanateimport scala.xml._… Continue import java.util.Date import org.hibernate._ import org.hibernate.cfg._ class Event { var id: Long = 0L var title: String = null var date: Date = null var p Posted by Steve Yen on January 24, 2008 at 7:08pm object User extends User with MetaMegaProtoUser[User, User with KeyedMetaMapper[Long, User]] Posted by Steve Yen on December 28, 2007 at 10:16am "a calculator" should { "provide an add operation" in { "a" | "b" | "result" |> 1 ! 2 ! 3 | 5 ! 2 ! 7 | 3 ! 0 ! 3 | { (a: Int, b: Int, result: Int) => { calc.add(a, b) must_== result } } } } Posted by Steve Yen on December 20, 2007 at 9:54am mvn archetype:create -U \… Continue -DarchetypeGroupId=net.liftweb \ -DarchetypeArtifactId=lift-archetype-blank \ -DarchetypeVersion=0.3.0 \ -DremoteRepositories= \ -DgroupId=com.test \ -DartifactId Posted by Steve Yen on December 19, 2007 at 9:30pm Create your own social network! © 2009 Created by Steve Yen on Ning. Create Your Own Social Network Badges | Report an Issue | Privacy | Terms of Service
http://scalabase.ning.com/
crawl-002
refinedweb
206
67.15
What gives SBUX its edge over competition? Savvy shoppers know how to get good deals Join the NASDAQ Community today and get free, instant access to portfolios, stock ratings, real-time alerts, and more! Oromin Explorations Ltd. (OLE.TO) today announced the positive results of its 2013 Carbon-in-Leach (CIL) Feasibility Study (FS) and Mineral Reserve update for its OJVG Gold Project in Senegal, West Africa. All figures are in US Dollars. HIGHLIGHTS Net present value ( NPV ) pre-tax of $740 million and after-tax of $558 million at a 5% discount rate and evaluation price of $1550 per ounce of gold, generating an after-tax internal rate of return ( IRR ) of 27.7% with a 23 month payback Average annual gold production for first three years of full production at 182,000 payable ounces per year at a $489 operating cash cost per ounce Average annual life of mine (LOM) gold production of 144,000 ounces per full milling year at an LOM operating cash cost of $654 per ounce Open pit and underground gold mining complex with a current mine life of 17 years Probable mineral reserves increase by 64% to 2.335 million ounces of contained gold since the 2010 FS - the OJVG Gold Project now hosts the largest gold reserve in Senegal Average LOM gold recovery of 90.8% Estimated start-up capital cost of $297.1 million, including $27.9 million contingency All capital and operating expenditures in the FS have been updated to Q1 2013 The FS does not include the results of the upcoming January 2013 Preliminary Economic Assessment ("PEA") of the Project's heap leach deposits which have potential to outline additional contained gold ounces within the?
http://www.nasdaq.com/article/oromin-reports-cil-feasibility-study-results-at-the-ojvg-gold-project-in-senegal-cm212723
CC-MAIN-2015-40
refinedweb
286
55.07
with it. Lastly comes the enclosure. Some of you may be aware that I've created a new Raspberry Pi B+, a clear acrylic enclosure for the Raspberry Pi B+ that is also stackable and modular and has room comfortably for the ePaper Display HAT. It is clear and sturdy and also has rubber feet to slightly elevate it and protect the surface of your table or nightstand, so you can display your weather station and have it easily accessible by your nightstand or coffee table to get the weather information to plan your day! 😊 You can, of course, use any Raspberry Pi, compatible ePaper display or enclosure and just use the code in this project. Ok, let's get started! Step 1 - Mount the Raspberry Pi B+ to the Enclosure Base Plate Let us first mount the Raspberry Pi to the enclosure's base plate. This gives it protection while offering full open access to it to configure and setup the RPi and play around with it. When you are ready to close it up, It is easy to add the side walls and top plate and secure everything with screws. Mount the Raspberry Pi to the base plate, and add feet and other hardware to prepare the enclosure in Platform Configuration. See steps below in the slideshow - the caption for each image is numbered and gives additional explanation for each step. Here are all the steps as an animated gif: Step 2 - Plug the Waveshare ePaper HAT into the Raspberry Pi Next step is to plug the Waveshare ePaper HAT into the Raspberry Pi. Its female header fits into the GPIO pins of the Raspberry Pi. It comes with standoffs to attach it more firmly to the Raspberry Pi. Since we are using it inside a protected enclosure, this step is not necessary and I skipped it. Reuse the standoffs for any later projects! 😉 Step 3 - Configure the Raspberry Pi The ePaper display uses SPI for communication. We therefore need to enable SPI on the Raspberry Pi, if you haven't already done so. Steps to Enable SPI Launch raspi-config. Go to "Interfacing Options". Navigate to SPI and press enter. Say yes when asked if you would like the SPI interface to be enabled. See steps below in the slideshow - the caption for each image is numbered and gives additional explanation for each step. Next, we will need to install the necessary software packages PyOWM You can choose to make calls to the Open Weather Map REST APIs and process the JSON object that it returns to extract the fields of choice directly. Or alternately, you can use the PyOWM library - it is an elegant client Python wrapper for the OpenWeatherMap web APIs. You can very quickly make calls to the OWM APIs and consume the data easily using a more object-oriented approach. This is what I went with! Thanks to Claudio Sparpaglione for the PyOWM library! To install PyOWM on your Raspberry Pi, do the following: $ pip install pyowm Read the PyOWM documentation to know more and to see their examples - ProtoStax Weather Station Demo Code Grab the weather station demo code from the ProtoStax GitHub repository. You can clone it to your Raspberry Pi using the following command: $ git clone You will need git on your Raspberry Pi of course! Use the following to install git if required: $ sudo apt-get install git You can also directly download it in zip format and unzip it. [Note: The example also uses Waveshare's e-Paper python3 library. You can find the library on Github at, but it has the libraries and code for a multitude of displays. I've taken the two files that are needed for my e-Paper display and have incorporated them into my own code base, so you don't need to additionally get and install that library from GitHub. You can refer to the aboveGithub link, and if you are using a different sized display, you can always grab the requisite library files from the above repository! ] Step 4 - Get Open Weather Map API Key Generate an API key. Note the API key generated - you will use it later in the Weather Station python program. See steps below in the slideshow - the caption for each image is numbered and gives additional explanation for each step. Step 5 - Demo Code Let's take a look at the demo code and see what it is doing. To do that, we can split it up into two main parts. - Open Weather Map - ePaper display You can quickly reference the demo code here: ePaper Display You initialize your instance of the ePaper display using the following: epd = epd2in7b.EPD() init() and Clear() methods are used to initialize the object, and clear the contents of the display, respectively. epd.init() epd.Clear() You can draw on the display using Python PIL's Image, ImageDraw and ImageFont. The epd library uses two images, one for black and one for red, to display black and red images on top of a white background. You first create two Images as shown: # Drawing on the Horizontal image HBlackimage = Image.new('1', (epd2in7b.EPD_HEIGHT, epd2in7b.EPD_WIDTH), 255) # 298*126 HRedimage = Image.new('1', (epd2in7b.EPD_HEIGHT, epd2in7b.EPD_WIDTH), 255) # 298*126 After drawing on the individual black and white Images all the text and icons and stuff you want to display (we'll look at this later), you make the ePaper display it using epd.display(epd.getbuffer(HBlackimage), epd.getbuffer(HRedimage)) The actual formatting of the Images will be discussed in the section below. Open Weather Map - Getting and Displaying the Data Firstly, you will need to replace the placeholder string below with your own OWM API Key that you generated in the previous step: owm = pyowm.OWM('REPLACE_WITH_YOUR_OWM_API_KEY') With the owm object thus initialized, you can invoke methods on it that will in turn call the APIs and return the results as objects. You can invoke the weather APIs by either City Name, City ID, Lat/Lon or Zip Code. According to Open Weather Map, "We recommend to call API by city ID to get unambiguous result for your city. " You can find your own city id by downloading, unzipping and checking the JSON file from the following: Locate your city there and note the city ID. You can replace it in the code below. In the example, the city ID for Mountain View, CA is used. # REPLACE WITH YOUR CITY ID city_id = 5375480 # Mountain View, CA, USA You can, of course, play around with other modes of invoking the APIs, like Lat/Lon, for example. In the main function, we start with getting the current weather data for the city specified by the city_id. def main(): epd = epd2in7b.EPD() while True: # Get Weather data from OWM obs = owm.weather_at_id(city_id) location = obs.get_location().get_name() weather = obs.get_weather() reftime = weather.get_reference_time() description = weather.get_detailed_status() temperature = weather.get_temperature(unit='fahrenheit') humidity = weather.get_humidity() pressure = weather.get_pressure() clouds = weather.get_clouds() wind = weather.get_wind() rain = weather.get_rain() sunrise = weather.get_sunrise_time() sunset = weather.get_sunset_time() ... It is fairly self-explanatory. We get the weather (obs.weather_at_id()) for the specified city_id. From that returned observation object, we can get the location information (e.g. Mountain View), as well as the weather object. The weather object has details like reference time when the observation was made, temperature, humidity, pressure, clouds, rain, sunrise time, sunset time, and so on. Next, we would like to take that information and present it in a human-readable format. For example, temperature readings are good enough to round up to the nearest integer, as is the humidity. We would like to present the sunrise and sunset times in the local time, with AM/PM identifiers. We would also like to use icons and images to spruce up the interface and break the visual monotony. An easy way to display icons and artwork on your ePaper display is to use a font like Meteocons, which maps font letters to specific icons, so by printing a character "B" you can print a Sunny icon! Open Weather Map has weather codes for the current weather report, that correspond to different conditions like sunny, cloudy, etc. Check Weather Condition Codes under for the full list of weather codes. I have created a weather_icon_dict dictionary that maps the weather codes from OWM to suitable icons from Meteocons. This enables us to easily use artwork and icons for display by simply using the character corresponding to that icon! For example, I take the weather_code that I receive from OWM, and use the weather_icon_dict to get the mapping to the corresponding Meteocons icon, and then display that icon by just printing that character with the Meteocons font as shown below: drawred.text((264 - w3 - 10, 0), weather_icon_dict[weather.get_weather_code()], font = fontweatherbig, fill = 0) This will display icons for weather codes, like Sunny or Partly Cloudy etc. You can always modify the weather_icon_dict to the change the mapping to your taste! Refer to for the mapping of meteocons to characters, and modify the dictionary below to change icons you want to use for different weather conditions! Meteocons is free to use - you can customize the icons - do consider contributing back to Meteocons! Because of the usage of Meteocons icons, every bit of information in the display below is just a text string, and the font size can be easily changed to play around with proportions. I played around with the information and the layout until I was satisfied with the look and feel, and showing the fields that were important to me. This is what I finally settled on: At the top is the location name, so you are reassured the weather data is for the right place. This is also useful if you end up displaying multiple locations (perhaps triggered by the switches that come with the ePaper display!) location = obs.get_location().get_name() Below that is the description of the weather, such as "few clouds" in the example above. description = weather.get_detailed_status() Following that is information about when the observation was made. This also helps to reassure the user that they are not looking at stale data. reftime = weather.get_reference_time() The next entry is displaying the Meteocons icon corresponding to the weather_code as I described above. I present all icons in red for visual relief: drawred.text((264 - w3 - 10, 0), weather_icon_dict[weather.get_weather_code()], font = fontweatherbig, fill = 0) The next entry is the current temperature, as well as the high and low for the day. temperature = weather.get_temperature(unit='fahrenheit') This returns a temperature object, which has several fields: temperature: {'temp_kf': None, 'temp_max': 77.0, 'temp_min': 62.01, 'temp': 70.93} I use the "temp", "temp_max" and "temp_min" fields in displaying current, max and min temperatures. I then get the pressure information pressure = weather.get_pressure() which returns a pressure object pressure: {'sea_level': None, 'press': 1011} The next field is humidity humidity = weather.get_humidity() which returns the relative humidity in percent. Pressure and humidity are shown as simple text strings in black using the ImageDraw library drawblack.text((10, 100), str("{} hPA".format(int(round(pressure['press'])))), font = font20, fill = 0) drawblack.text((150, 100), str("{}% RH".format(int(round(humidity)))), font = font20, fill = 0) I also like to know the sunrise and sunset times. sunrise = weather.get_sunrise_time() sunset = weather.get_sunset_time() These fields are unix timestamps and need to be converted to human readable format. I chose to display them in the local time zone, in AM/PM format. I also used Meteocons to display icons representing sunrise and sunset, for some visual relief. These icons are displayed in red. drawred.text((20, 120), "A", font = fontweather, fill = 0) drawred.text((160, 120), "J", font = fontweather, fill = 0) drawblack.text((10, 150), time.strftime( '%I:%M %p', time.localtime(sunrise)), font = font20, fill = 0) drawblack.text((150, 150), time.strftime( '%I:%M %p', time.localtime(sunset)), font = font20, fill = 0) Once the Image objects are rendered, we use epd.display as I describe above to display the contents of the two Image objects on the ePaper display. After displaying, we call epd.sleep() to put the ePaper display in low power mode/turned off. epd.display(epd.getbuffer(HBlackimage), epd.getbuffer(HRedimage)) time.sleep(2) epd.sleep() We then sleep for 10 minutes, before waking up and repeating the process in an endless while loop, until a Control C is pressed or the program is killed. Step 5 - Test everything out You can test the program out by running it with python (I used python3.5 - the epd library and my code assume python 3) cd ProtoStax_Weather_Station_Demo python3.5 main.py The program connects to OWM, gets the weather data and displays it on the ePaper Screen. It then goes to sleep for 10 minutes, wakes up again and refreshes the data and the screen. You can of course modify the amount of time it sleeps. Upon quitting the program, it cuts power to the ePaper Display. The ePaper display should not be powered on for extended periods of time. After rendering the image, it is advisable to make the device go into sleep mode (low power consumption), before waking it up and re-rendering. The latest version of the ePaper library also cuts power to the module when you invoke sleep. You can, of course, play around with this as well and change the behavior. Another point to bear in mind is that the ePaper display, when not in use for extended periods, should ideally have its display cleared to white before storage. This will help prevent burn-in. The demo code has a python script cleardisplay.py that you can use to clear the display before storing it. python3.5 cleardisplay.py Step 6 - Close It Up Install the top bracing elements, side walls, and top. See steps below in the slideshow - the caption for each image is numbered and gives additional explanation for each step. Here are all the steps in a single animated gif: Step 7 - Display the Weather! You can now always be able to see the current weather - keep it by your nightstand or coffee table and access the weather any time to plan your day! 😊 Going Forward Here are some ideas to take the project even further. If you want to run your weather station headless and all the time without having to log in and launch the program, then you will want to make sure your program runs in the background. Otherwise, the moment you log out or exit your ssh session, the program will be terminated. You can do that by specifying nohup when invoking the command: nohup python3.5 main.py & This will make the program run in the background, as well as not terminate when you exit your shell. Even better, you can make sure that the program runs on boot-up, so any time you plug in your device, it will boot up and start the weather station program. There are many ways to do this. There are many pointers on the web, but feel free to ask questions in the comments below! 😊 You can play around with the OWM APIs to get and display different types of weather data on your weather station other than the ones mentioned in this example. You can use different Meteocon icons to get more graphics on the display. You can even modify Meteocons to create your own icon (check their page link above - they give pointers as to how to do that), and give your contribution back to Meteocons! You can use the switches on the ePaper display to toggle the display between different locations, or different views showing different data for the same location. The switches are connected to BCM pins 5, 6, 13 and 19. Check the Waveshare schematic here - You can laser cut holes for the switches and mounting holes for the ePaper display to the top of the enclosure, and mount the ePaper display on the top of the enclosure, and plug in the Raspberry Pi B+ below it. If you don't have access to a laser cutter, it is relatively easy to drill mounting (and switch access) holes into the acrylic plate using some painters tape (to protect the surface and keep everything clean and spiffy) and a drill to make the holes. If the holes are not small, it is recommended to use a step drill bit. Can you think of any more? Write a comment below to let us know! 😊 Feel free to also ask any questions you may have! 😊 Happy making! 😊
https://www.hackster.io/sridhar-rajagopal/weather-station-with-epaper-and-raspberry-pi-c26a70
CC-MAIN-2020-10
refinedweb
2,770
64
Return to where it all began Document options requiring JavaScript are not displayed Help us improve this content Level: Introductory Elliotte Rusty Harold (elharo@metalab.unc.edu), Adjunct Professor, Polytechnic University 19 Dec 2006 The annual IDEAlliance XML conference took place the first week in December in Boston MA. Markup was generated, specifications were debated, and much Samuel Adams was quaffed. Looking back, a few topics stand out, including XQuery, native XML databases, the Atom Publishing Protocol, Web 2.0, and the extraction of implicit metadata from data. Last month marked ten years since the World Wide Web Consortium (W3C) Standard Generalized Markup Language (SGML) on the Web Editorial Review Board publicly unveiled the first draft of Extensible Markup Language (XML) 1.0 at the SGML 96 conference. In November 1996, in the same hotel, Tim Bray threw the printed 27-page XML spec into the audience from the stage, from whence it fluttered lightly down; then, he said, "If that had been the SGML spec, it would have taken out the first three rows." The point was made. Although SGML remains in production to this day, as a couple of sessions reminded attendees, the markup community rapidly moved on to XML and never looked back. Ten years later, IDEAlliance's annual conference is still going strong, although today it's called XML 2006. It's the major North American XML conference and the largest pure XML show still running. However, many of the players remain the same. Quite a few attendees (and one keynoter) could and did give first-hand reports of the early days to others like myself who only discovered the power of descriptive markup from XML. The conference was smaller than in previous years (as almost all conferences are, post-dotcom implosion) -- about 400 people. However, repeat attendees reported that this was the most exciting and active iteration in several years. Despite running four concurrent tracks over three days, limiting speakers to somewhere between 400 seconds (for the least interesting subjects) and 45 minutes (for the most interesting subjects), and not covering speakers' travel expenses, the referees still had to choose from about four times as many submissions as they had slots for. For the six late-breaking sessions, that ratio was more like 10:1. It looks like the XML world is accelerating once again. In addition to the final emergence from the post dot-bomb malaise and the possible expansion of Bubble 2.0, several factors converged to make this one of the most interesting XML conferences since the late 90s: XQuery Without a doubt,. That the W3C XQuery and Extensible Stylesheet Language Transformation (XSLT) working groups released eight proposed recommendations two weeks before the conference (after years of development) didn't hurt. Barring any last-minute spec bugs, the final recommendations are expected to be released within weeks, not months. There are already over a dozen mostly conformant implementations of the specs, and four of them were represented at the show: IBM® DB2® 9, Oracle Database 10g Release2, Mark Logic, and Data Direct XQuery. On Wednesday morning, Darin McBeath of Reed Elsevier gave a keynote address titled "Unleashing the Power of XML" in which he described numerous cases of publishers like Oxford University Press, O'Reilly, and even JetBlue implementing successful XQuery projects on top of either hybrid or pure XML databases. Hybrid XML databases are those such as DB2 and Oracle that support both Structured Query Language (SQL) and XQuery. Native XML databases are those such as Mark Logic that support only XQuery. I talked to several database vendors on the exhibit floor and attended several more XQuery presentations to try to make some sense of this. In brief, hybrid databases are still composed of relational tables. However, fields aren't limited to the usual SQL types like INT and DATE. They can also be declared to have type XML. An XML-type field contains a complete, well-formed, optionally schema-valid document (or null). You can select, insert, and update the XML values using SQL statements with embedded XQuery subqueries. For example, the code in Listing 1 inserts an Extensible Hypertext Markup Language (XHTML) formatted comment into the comments table. This table has two fields, a CHAR(16) username and an XML comment. INT DATE XML CHAR(16) Listing 1: Inserting XML into a hybrid SQL-XML database INSERT INTO comments (username, comment) VALUES ("FP", "<div xmlns='' class='comment'> <p> The relational model rules <strong>supreme</strong>. It can do anything an XML model can do. Unfortunately, no one's ever listened to me and implemented a true relational database. </p> <p> I will now go sulk in my corner until the world accepts Codd and the <a href=''>12 commandments</a>. </p> </div>"); The database parses the XML data before insertion and stores it in a form that's amenable to searching and querying without having to reparse the data for every query. Indexes can even be defined on particular paths in the XML trees to improve performance. To SQL, this data looks like one CLOB. However, XQuery expressions can exploit the structure of the XML. For example, Listing 2 shows a query that extracts img elements from the comments table. img Listing 2: An XQuery select XQUERY declare namespace html = "" for $img in db2-fn:xmlcolumn('comments.comment')//html:img return $img; Some parts of this process are standardized in either the XQuery specs, JSR 225: XQuery API for Java, or SQL/XML. A few pieces are still in development, notably updates and full-text search. However, many pieces remain deliberately unspecified. Consequently, most applications will use some vendor-specific code. Listing 2 uses the DB2-specific function xmlcolumn to find the right field. xmlcolumn All of this violates the relational model in about half a dozen different ways. On the other hand, no major production database has ever fully implemented the relational model anyway, the cries of the relational purists not withstanding. Normalization is also left by the wayside (as it usually is in any large database in which performance is a major concern). Despite the ideological impurity, this is an incredibly useful way to organize data. In particular, publishing and Web applications that need to store large documents rather than small fields and unmarked-up strings should see major benefits from this approach. The current strategy of storing marked-up text in BLOBs, CLOBs, and VARCHARs isn't nearly as natural or efficient. Shredding the document into individual nodes to be stored in separate records is even nastier. Allowing the document to be stored as a single unit in one field in one record while still letting it be searched with XQuery fits the structure of most traditional and Web publishing applications much more neatly. Authoring As Jon Bosak reminded listeners in the closing keynote, we still struggle with issues that go back to the SGML days and even earlier. Not surprisingly, a lot of these problems are people issues masquerading as technical issues. Many of these problems revolve around authoring: Who creates the markup, and how do they create it? The three traditional approaches are: Although option 3 is my preferred method (it's how I'm writing this article, for instance) it's a little too simple to justify conference presentations and probably not appropriate for nonprogrammer end users. This year, the competition between Microsoft's Office Open XML Formats and OpenOffice's OpenDoc format (ODF) focused attention on option 1. ODF versus OpenXML Both Microsoft and the open-document partisans seem to believe they're involved in a struggle to the death. They see themselves as waging nothing less than a war for truth, justice, and the American way on the one hand and liberté, égalité, and fraternité on the other. Consequently, neither side distinguished itself at this show. Both could benefit from toning down the hype several notches and recognizing their own limits. When teased out from the invective, most of the technical discussion this year focused on the Microsoft formats -- probably because they're newer, and this conference thrives on the new. The critical factor seems to be that Microsoft is dead-set on maintaining pixel-perfect compatibility with at least 10 years of legacy Microsoft Office binary formats. This means the newly minted ECMA Open XML standard is really just an XML encoding of a legacy format. Consequently, the specification was severely constrained by the requirements of compatibility. The result is a specification that's about 6,000 pages long. It's almost 10 times as large as the OpenDoc specification, for pretty much the same functionality. It's possibly the single largest XML specification I've ever encountered. I'm not sure even the combined family of WS-* specs matches it. This is more complete than any similar spec Microsoft has published in the past, and it will help anyone who needs to read or generate Microsoft Office documents. However, I can't see that any other project will ever adopt this format for anything other than exchange with Microsoft Office. It's too big and too full of legacy detail. If you don't already have 10 years of legacy code that reads, writes, and displays something close to this, you have no hope of implementing it. By contrast, the competing OpenDoc format, although originally derived from StarOffice legacy formats, is much simpler and more independent of its ancestry. It's already been adopted as the native file format by separate office suites and programs with independent code bases. I'd be surprised if anyone besides Microsoft tried that with Office Open XML and even more surprised if they succeeded. Even Microsoft itself hasn't yet been able to implement this format in Microsoft Office for the Mac -- and that's not an independent code base. By the way: An extra demerit goes to Microsoft for naming its format Office Open XML, thereby thoroughly confusing it with OpenOffice's OpenDoc format. DITA Another ongoing development in the XML world is Darwin Information Typing Architecture (DITA), an XML format for modular documentation. Rather than books and articles, DITA documents are divided into topics, concepts, and tasks. Map documents indicate how the different topics are rearranged to make magazine articles, Web pages, tutorials, conference presentations, man pages, and more. Different map documents can reuse the same topics to make new and different collections of documentation. Even individual paragraphs, sentences, and words can be pointed to and transcluded into output documents. For technical authors like myself, this sounds like a godsend. I don't have to keep rewriting or cutting and pasting the same content. After all, how many different ways can I explain a linked list? This is the writer's version of structured programming and the DRY principle (Don't Repeat Yourself). At least, that's the theory. The reality might fail to meet expectations. Without mentioning DITA by name, Jon Bosak shot it down pretty conclusively in his closing keynote. As he pointed out, we've been here before. He first encountered this idea in the late 1970s and was very enamored of it for a time. The problem is that you can't cut and paste topics freely between documents. Doing so produces frankenbooks that don't have a consistent authorial voice, target audience, or flow. One of the worst problems is that when you write a topic, you don't know what you can or can't assume the reader already understands from previous chapters, because the chapters are always moving. Thus you end up either constantly repeating all prerequisites or leaving out necessary prerequisites. Bosak noted that this technique was invented several times before, and it hasn't worked yet. Sprinkling magic XML pixie dust on a flawed concept won't make it work now. He suspects that writers like this approach because it helps them be treated like important, exciting software developers rather than lowly, boring tech writers. (It worked for him.) That's why this bad idea keeps getting reinvented as soon as its previous failure is forgotten. The Web In 2006, it's hard to find a technical conference or subject that doesn't involve the Web. XML 2006 was no exception. An entire track was devoted to XML and the Web. Web 2.0 themes like mashups, Asynchronous JavaScript and XML (Ajax), and user interactivity were especially prominent; but this part of the conference ranged widely from cell phones to servers, from RSS to Atom to HTML. Atom and APP Atom might be old hat for the markup geeks at this show, but the newer Atom Publishing Protocol (APP) is bleeding-edge enough to attract a lot of interest. APP may be a sleeper technology like XML was 10 years ago. Like XML, it's starting small with a simple use case. (For XML, the use case was putting SGML on the Web. For APP, it's posting blog entries.). Not all the players in this space were present at this conference, but IBM was there with the Abdera library. Abdera is an Apache Incubator project that implements APP as a Java™ class library that other applications can invoke on either the client or server side. Wrap a user interface around this, and you have a blog editor. Attach a database to the backend, and you have a content management system. Abdera looks promising; but even if it doesn't pan out, numerous other developers are working on similar libraries in many languages and environments. REST APP is also the poster child for Representational State Transfer (REST), the architecture on which Hypertext Transfer Protocol (HTTP) and the Web are based. REST wasn't specifically on the program, but it kept coming up. For instance, in a session on the Google Checkout API, Google evangelist Patrick Chanezon mentioned that only the earliest public APIs they designed were done with the WS-* stack in mind. These days, they try to design their APIs RESTfully. Maybe they implement a SOAP gateway somewhere for the developers who prefer those tools, but behind the scenes it's all REST. I also noted that the distinction between WS-* and REST is blurring. REST seems to be winning in actual code, even if not yet in developers' minds. A lot of people are doing REST even when they don't have any idea that's what it's called. More than once, I saw "WS-*" or equivalent on a speaker's slides, only to find out in further conversation that all they were doing was sending plain old XML over HTTP -- not even using SOAP or Web Services Description Language (WSDL), much less the whole family of specs that sit on top of that. I suppose I don't care what they call their designs, as long as they're doing it the right way. Web services has always been a fuzzy term. However, going forward, developers need to be aware that unqualified terms like Web services can have very different meanings to different people. Metadata Metadata might be another classic people problem masquerading as a technical problem. In brief, how do you get authors to create and enter reliable metadata for their content? Google has created one of the world's most effective search engines by ignoring metadata completely and focusing exclusively on the data. The Semantic Web zealots aren't ready to give up on Resource Description Framework (RDF) yet (although topic maps were conspicuous by their absence), so several presentations focused on means of deriving RDF metadata from HTML data, relational databases, and other unannotated systems. The most promising approach (probably because it promised the least) was a W3C effort called Gleaning Resource Descriptions from Dialects of Languages (GRDDL), presented by Harry Halpin. He's developing XSL transforms that produce RDF metadata from a variety of XML, HTML, and microformats. Ronald Reck and Ken Sall's effort to infer metadata from the CIA World Factbook, Wikipedia, and Project Gutenberg aimed for more but achieved less, in my opinion. What was shocking about both these proposals, compared to earlier years, was that neither required any effort by or even cooperation from the original document authors. I wonder if this means the metadata community is finally coming to learn Google's lesson? If they can extract the implicit metadata embedded in the documents rather than ask authors to add explicit metadata outside the documents, they can get both more and better metadata. Summary XML 2006 was one of the most exciting and active conferences I've been to in several years. Every time slot had at least two and often three or four presentations I wanted to see. Hallway conversations and the exhibit floor were equally active. Even after the official end of the conference for the day, a lot of activity continued in the hotel lobby and bar. (Cold Boston weather may have contributed to this.) Looking forward to 2007, I think XQuery and native XML databases will be very, very hot. Many large publishing businesses have already successfully implemented XQuery systems to excellent effect. Smaller publishers might want to wait until simpler, cheaper, possibly open source solutions become available; but they might not have to wait long. The biggest rumor at the conference was that principals from one of the largest pure XML database players and one of the largest hybrid XML database players have joined forces to create a new open source XQuery engine that will be competitive with the big boys.. Resources About the author Elliotte Rusty Harold is originally from New Orleans, to which he returns periodically in search of a decent bowl of gumbo. However, he resides in the Prospect Heights neighborhood of Brooklyn with his wife Beth, their dog Shayna and cats Charm and Marjorie. talking about Web Forms 2.0 at the SD West 2007 conference in Santa Clara in March. Rate this page Please take a moment to complete this form to help us better serve you. Did the information help you to achieve your goal? Please provide us with comments to help improve this page: How useful is the information?
http://www.ibm.com/developerworks/library/x-xml2006conf.html
crawl-001
refinedweb
3,022
52.8