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 |
|---|---|---|---|---|---|
Red Hat Bugzilla – Full Text Bug Listing
Spec URL:
SRPM URL:
Description: Python 3.x (backwards incompatible with the 2.x series)
Python 3.x is somewhat controversial in the Fedora community. Since so many of the system tools are written in Python, it may be a very long time before Fedora can be migrated from Python 2.x to Python 3.x. Unlike previous updates to Python, it will be impossible to switch over to a new version in one day.
I believe it will be important to have a Python 3.x RPM available. Note that I do NOT propose creating any separate library RPMs for Python 3. There are several reasons for creating an early RPM for Python 3.x without creating new RPMs for all of the various Python packages. First, Fedora developers will eventually need to experiment with Python 3.x, and having an RPM available would help with this. Second, people learning Python are now finding resources that are specific to Python 3.x (for example, the famous book "Dive Into Python" is now available for Python 3.x). Third, Python developers (like myself) may wish to use Python 3.x for simple scripts that don't rely on third-party libraries (there are plenty of batteries included in the standard library).
This new Python 3.x RPM is loosely based on the current Python 2.x RPMs. I'm sure it still isn't perfect, but I'm at the point where I would appreciate feedback. I really think that this RPM will be helpful for many people.
By the way, this is my first Fedora package, so I would greatly appreciate help from a sponsor. Thanks.
The files are not available. An reviewer can't review it ;)
And i can't review it because it's to big for me.
Some work has already been done
Might want to compare.
Thomas, I've tried downloading the files from a few different places, and everywhere has worked. What problem are you seeing?
Ah i see now it works :)
I also had a go at packaging 3.1.1, before I saw either of your efforts, so we now have 3 separate SRPMS... I'll have a look and compare the 3 SRPMs.
To liven things up further, I think it would be good if the python 3 specfile closely resembled the python 2 specfile. (It may be necessary to clean up the python 2 specfile to do this, see bug 226342).
I've written up some thoughts about getting Python 3 into Fedora here:
Adding ivazquez to the CC list. Ignacio: I hope that's OK.
Andrew: thanks for your work on packaging Python 3
I feel a little awkward about reviewing this. As far as I can see based on the link in comment #3, ivazquez has been packaging Python 3000 since 2007-09-01, with "3.0-0.a1.1":
Sat Sep 1 2007 Ignacio Vazquez-Abrams <ivazqueznet+rpm@gmail.com> 3.0-0.a1.1
and he's been steadily updating his rpms since then. However, I don't think he ever filed a package review request on those rpms. (Please correct me if I'm wrong!) Ignacio: is there a reason you didn't file a review request?
I've posted a proposal on Python 3 in Fedora 13. See this proposed feature page:
I'm very keen to see a python 3 package in Fedora, either based on Andrew's srpm, or on Ignacio's. I also tried packaging it, but I'm happy to abandon my specfile in favor of your work. I would like to be a comaintainer of the resulting package.
For me, the most important thing is that the python 3 rpms should be installable in parallel with the python 2 rpms. I hope I captured the other kinds of expected behavior on the feature page above.
I'd be happy to review your package (though we need to find a sponsor for you), but I'm worried that Ignacio may feel put out if we use your package rather than his (and likewise, vice versa). I'm curious why Ignacio never filed a package review request on his packages.
Thoughts?
I tried generating a pure textual "diff" of the two specfiles (Andrew's vs Ignacio's), but too much is different for the result to be meaningful.
So I tried comparing individual aspects of the packaging (no doubt omitting much):
= Name =
"python3" vs "python3000"
I prefer "python3"; I feel that "python 3000" was a good development codename during the development towards 3.0, but now that it's been released, "3" seems to be the name. I'd prefer us to use "python3-" as a naming prefix throughout.
= Source and Patches =
ivazquez's srpm makes use of various ".list" source files to control various parts of the build/install/etc, and I think this approach works well.
amcnabb's patches:
Patch0: python-3.1.1-config.patch
This heavily patches Modules/Setup.dist, like we do on the python 2 rpm. I haven't gone though and checked the various modules in detail yet, but it looks reasonable, a "batteries-included" approach.
Patch102: python-3.1.1-lib64.patch
It's only applied on 64-bit archs; it reworks lib to lib64 in many places.
# -- fixed in r75062
Patch200: python-3.1.1-pathfix.patch
Fixes an encoding issue with the pathfix script, used when fixing up shebangs. Good to see that you upstreamed it.
ivazquez's patches:
Patch0: Python-3.1.1-rpath.patch
Removes standard library path from rpath.
Patch1: Python-3.0a5-libprep.patch
Ignacio's version fix up the shebangs uses sed (see "sedcmd" in the specfile), rather than fixing the broken "pathfix" tool.
= BuildRequires =
Both have BuildRequires on:
bzip2-devel
db4-devel (amcnabb's has a ">= 4.7" here)
gdbm-devel
openssl-devel
ncurses-devel
readline-devel
sqlite-devel
tk-devel
(alphabetized them for ease of comparison)
amcnabb's has an additional:
BuildRequires: gmp-devel
BuildRequires: zlib-devel, expat-devel
BuildRequires: libGL-devel tk tix gcc-c++ libX11-devel glibc-devel
BuildRequires: bzip2 tar /usr/bin/find pkgconfig tcl-devel
BuildRequires: tix-devel
BuildRequires: autoconf
BuildRequires: libffi-devel
Some of these are implicitly assumed in the buildroot, and don't need to be explicitly listed. The others presumably reflect the very broad batteries-included approach taken when patching Modules/Setup.dist
ivazquez's has an additional:
BuildRequires: gdbm-devel
BuildRequires: python
= Description =
amcnabb's seems to be taken directly from our python 2 specfile; I think the one in ivazquez's specfile is better (although as I said, I feel we should refer to Python 3 not to Python 3000). In particular, the description in ivazquez' specfile deprecates the use of TkInter, which I think is wise advice!
= Subpacakages =
amcnabb's specfile has a -test subpackage, whereas ivazquez's is -tests. Our python 2 specfile uses the singular form, so perhaps we should use the singular form for consistency (also, the main component of it is the "Lib/test" directory from the upstream tarball, again a singular)
= Configuration =
Both specfiles have %configure with:
--enable-ipv6
--enable-shared
amcnabb's adds: --with-wide-unicode --with-system-ffi
ivazquez's adds: --enable-unicode=ucs4
I definitely want us to have "--with-system-ffi"
I hope that's a useful start on reviewing this.
Should I begin a formal package review of Andrew's package?
Dave, thank you very much for your insightful thoughts. I agree with you on almost all points. The important thing for me is getting a working RPM that can be installed alongside Python 2. As you noticed, a lot of things in my specfile exist purely to be similar to Python 2 (although I changed anything that seemed wrong or inapplicable). I wouldn't have any hard feelings over which specfile is used. However, there are some areas where I think mine is more "right" and other areas where I think ivazquez's is probably better. Obviously, we should want to combine the best of both. Here are a few specific thoughts:
1) I think that the name python3 is clearly preferable to python3000.
2) I'm confused by the .list thing. The .list files are really short, and I don't see how they make it any more clear. In fact, I think they make the specfile more difficult to read. Is this a standard way to do things?
3) The patch python-3.1.1-config.patch follows the approach of Python 2. This is really important (whoever did Python 2 really knew what they were doing). Python's default build configuration (without the patch applied) will fail silently if a module can't be built. This is really evil. It means that if a dependency is missing, then files will just disappear. This patch gets rid of silent failures by explicitly specifying which modules must be built.
4) The patch python-3.1.1-lib64.patch ensures that Python is installed into /usr/lib64 (as per Fedora's packaging guidelines). It looks like the python3000 specfile does the same work with sed instead of a patch. I don't know which approach is better, and I could be easily persuaded either way. I picked to make a patch to more closely match the Python 2 specfile, but I can definitely see some advantages to using sed.
5) I have no strong feelings on the package description or build dependencies. However, I don't get the disparaging remarks about Tkinter. Not that I have any attachment to Tkinter, but I'm not aware of it being considered in any way deprecated.
6) The configure option --with-wide-unicode seems to be the correct spelling for the option, where --enable-unicode=ucs4 is the old way to say it.
7) By the way, the python3000 package defines a python3000-libs subpackage, but the python3 package just includes the .so file in the main package. When I tried to have a python3-libs package, it ended up being a prerequisite for python3 anyway, so I couldn't see the point in keeping it separate. However, it's entirely possible that I did something wrong to make this happen. :)
ivazquez, do you have any thoughts on these issues? Is there any particular reason that you didn't submit your package for review? Thanks for your work!
I'm pretty worried about multiple installable python's, so I've tried to keep out of this (hey, it's David's problem now when he breaks the world anyway ... I just get to complain :)
Anyway, I think I can clear some stuff up:
4) IMO use a patch instead of sed, the advantage of sed is that a patch often breaks as new upstreams of python are done. The disadvantage of sed is that it'll keep almost working, silently, when new upstreams of python change something.
5) The problems with TK are that it looks like gack, and has no i18n support. So pygtk2 is _much_ prefered.
7) python-libs is separate for multilib, x86_64 has just:
python-devel.i586 2.6-9.fc11 updates
python-libs.i586 2.6-9.fc11 updates
James, thanks for your thoughts. By the way, why are you worried about multiple installable pythons? Unless someone runs "python3", they will get the normal (python2) system python. The python3 package would never install a binary named "python". Anyway, I would love to understand the concerns.
In response to your comments:
4) Thanks for clarifying the difference. I'm already using patches instead of sed in my specfile, so I'll just keep on doing that.
5) I agree that Tk isn't the prettiest thing in the world, but upstream hasn't deprecated it (and it's the only GUI in the stdlib). I don't think we have to like it, but that doesn't mean we should make misleading comments in the package descriptions.
7) Thanks for the clarification about multilib (this is one of those areas where I still make lots of mistakes). I'll plan on putting a libs package back in.
2) The .list thing was experimental. Feel free to ignore it if you find it impedes progress.
4) My SRPM uses both a patch and sed. The patch annotates where files should be poked in order to enable multilib, and sed does the actual poking.
5) I do understand that TkInter is still available, regardless of the fact that I want it to die a flaming, screaming death. However, I do not believe that my description is in any way misleading.
Ignacio, thanks for your help. For the record, I'm really not trying to step on your toes with this specfile. What are your thoughts on combining and merging our efforts?
> James, thanks for your thoughts. By the way, why are you worried about
multiple installable pythons?
I think I've written down all of the big concerns, but I reserve the right to have forgotten things:)
James, thanks for the informative link.
One of the concerns was: "Of course humans are lazy, so to get around doing some of this work someone will decide it's a good idea to have a single python-blah package that works with either/both versions of python ... and then you'll have more problems." A package that works with both python2 and python3 would have to write files to both /usr/lib/python2.6/site-packages and /usr/lib/python3.1/site-packages. This is clearly a bad idea, and it seems reasonable to ban it in the packaging guidelines.
There is also the worry about having to support two versions of each package. For right now, we're just doing the interpreter, and you make a great argument for waiting to package libraries for Python 3. However, this will eventually be unavoidable, and ignoring Python 3 won't make it go away.
Is it inaccurate to summarize the rest of your concerns as: "two versions of Python will lead to user complaints"? I think all of the complaints that you enumerated are unavoidable and not particularly severe. I could see an argument for making some additions to the release notes.
For comment #14 and the problem of two versions of say, SOAPpy for
2.6 and 3.0 I think we just need to have standard variable so a package content
can just be swinged and duplicated from default to special e.g 3.0 in
this context.
... As you say it all comes down to guidelines basically.
Steve...
P.S I would love to see python3 available.
> A package that works with both python2 and python3 ... is clearly a bad idea, and it seems reasonable to ban it in the packaging guidelines.
Well it's clear to you because you don't have to do 3x the work :) ... but, yeh, in Fedora the obvious solution to this is to ban it (I've seen 3rd party repos. do it for php modules so they work with the RHEL-5 version and a php-5.3 version).
> For right now, we're just doing the interpreter, and you make a great argument
> for waiting to package libraries for Python 3.
Right, as I said ... the problem with just doing the interpreter is that it doesn't really help anyway because very few things use no extra modules. For this reason alone I don't think you can pretend this will be a one off, it's very likely to avalanche into RFEs for everything possible to be available in both versions. So, again IMO, you need to start from that assumption not assume that you can just do a py2k package.
> However, this will eventually be unavoidable ignoring Python 3 won't make it go away.
I'm not saying to ignore it, we do semi-significant GCC updates every few releases which break things ... yes, python3 breaks pretty much every piece of python ever. But I'd still hope we could do all the bits that needed to be done during a single release (esp. with time to prepare for it). But as I also said, it's kinda David's problem as he gets to keep all the pieces if/when it breaks.
> Is it inaccurate to summarize the rest of your concerns as: "two versions of
Python will lead to user complaints"
Well there was the minor bit about how everyone has to do 3x the testing :).
Created attachment 365267 [details]
Script to locate collisions between python 2 and python 3 rpms
The python 2 and python 3 packages must be parallel-installable.
In order to verify this, I've written a script to attempt to identify areas where the two sets of packages could interfere with each other.
Specifically, the attached script takes the locally-installed set of python (2) rpms as one PackageSet, and a locally-built set of python3 rpms as another PackageSet, and attempts to locate
- names listed in the "Provides" in one set of packages that also occur in the "Provides" of a package in the other set
- paths owned by packages in both sets
Is the script a reasonable test of the parallel-installability of the rpms? Is there anything else it should test for?
Running this script on my F11 machine's python rpms, together with a local build of the candidate python3 rpms outputs some collisions:
== Colliding "Provides" items: ==
Lots of "foo.so" lines appear (e.g. "_bisectmodule.so"), but probably shouldn't. The python modules have numerous auto-generated lines e.g. "Provides: _bisectmodule.so". I believe they're coming from the SONAME entries in the built c extension modules, from the script "/usr/lib/rpm/find-provides".
Does anything actually use these provides lines? My feeling is that they should be suppressed for the Python 3 rpms, and probably for Python 2 rpms also: the .so files aren't in the regular system search path for DSOs (instead, being loaded by Python's module loading mechanism).
Looking at /usr/lib/rpm/macros, it looks like this can be overridden by setting __find_provides to another script, or empty, though we probably shouldn't do this; don't want to hide the python library itself.
== Colliding filesystem items: ==
I see the following collisions; duplicate ownership within the -debuginfo packages. I believe that these aren't a problem:
/usr/lib/debug
/usr/lib/debug/.build-id
/usr/lib/debug/.build-id/00
/usr/lib/debug/.build-id/0c
/usr/lib/debug/.build-id/2b
/usr/lib/debug/.build-id/39
/usr/lib/debug/.build-id/47
/usr/lib/debug/.build-id/61
/usr/lib/debug/.build-id/76
/usr/lib/debug/.build-id/7b
/usr/lib/debug/.build-id/94
/usr/lib/debug/.build-id/9b
/usr/lib/debug/.build-id/a1
/usr/lib/debug/.build-id/ba
/usr/lib/debug/.build-id/d3
/usr/lib/debug/.build-id/d4
/usr/lib/debug/.build-id/eb
/usr/lib/debug/.build-id/ed
/usr/lib/debug/.build-id/fd
/usr/lib/debug/usr
/usr/lib/debug/usr/bin
/usr/lib/debug/usr/lib
Created attachment 365268 [details]
Output from the script
Dave, I think it makes sense to block the private libraries from being added to provides, but I'm not experienced enough to know the best way to do this.
I've had a go at merging Andrew and Ignacio's specfiles, using Andrew's specfile as a base. I've also attempted to address some of the issues already raised in this review.
Specfile:
SRPM:
To ease review, a diff from Andrew's 3.1.1-1 specfile to my 3.1.1-2 specfile can be seen here:
I wrote a custom __find_provides hook, filtering away paths matching /usr/lib/python (which appears to require setting _use_internal_dependency_generator to 0). See
This successfully gets rid of the various _collectionsmodule.so etc provides lines:
$ rpm -q --provides python3
python3 = 3.1.1-2.fc11
python3(x86-32) = 3.1.1-2.fc11
and thus my script to find collisions with the regular "python" rpms no longer detects any "Provides" collisions .
Note that SONAME provides still work for regular libraries:
$ rpm -q --provides python3-libs
libpython3.1.so.1.0
python3-libs = 3.1.1-2.fc11
python3-libs(x86-32) = 3.1.1-2.fc11
See the %changelog in the specfile for the other changes.
rpmlint output isn't clean yet (but it's getting late: E: script-without-shebang /usr/lib/python3.1/distutils/tests/Setup.sample
python3-test.i586: W: uncompressed-zip /usr/lib/python3.1/test/zipdir.zip
python3-tkinter.i586: W: no-documentation
python3-tools.i586: E: script-without-shebang /usr/lib/python3.1/Demo/comparisons/patterns
python3-tools.i586: E: script-without-shebang /usr/lib/python3.1/Demo/rpc/test
python3-tools.i586: W: file-not-utf8 /usr/lib/python3.1/Demo/distutils/test2to3/setup.py
python3-tools.i586: E: zero-length /usr/lib/python3.1/Tools/modulator/Templates/copyright
python3-tools.i586: W: wrong-file-end-of-line-encoding /usr/lib/python3.1/Demo/turtle/tdemo_round_dance.py
python3-tools.i586: W: file-not-utf8 /usr/lib/python3.1/Demo/rpc/README
python3-tools.i586: E: script-without-shebang /usr/lib/python3.1/Tools/README
python3-tools.i586: E: script-without-shebang /usr/lib/python3.1/Demo/scripts/newslist.doc
python3-tools.i586: E: script-without-shebang /usr/lib/python3.1/Demo/md5test/foo
python3-tools.i586: W: wrong-file-end-of-line-encoding /usr/lib/python3.1/Demo/turtle/tdemo_nim.py
7 packages and 0 specfiles checked; 10 errors, 8 warnings.
I've fixed some of the rpmlint issues.
Updated specfile here:
Updated SRPM here:
Diff of specfile since comment #20 can be seen here:
rpmlint output is; 4 errors, 5 warnings.
Since Dave is working so hard on this, I think it would be great to switch to him as the submitter. Ignacio, would you have any complaints with this?
Dave, would you need to clone this bug report, or is there some way to switch the reporter field?
> Since Dave is working so hard on this, I think it would be great to switch to
> him as the submitter. Ignacio, would you have any complaints with this?
From my point-of-view, I'm happy to take over as the "requester" role within this review request; I have plenty of time to work on this package.
> Dave, would you need to clone this bug report, or is there some way to switch
> the reporter field?
I don't think it's possible to switch the "reporter" field via the web UI.
I have a preference for not cloning: we'd lose the handy links for all of the comments so far. But if you'd prefer me to go that route, I'll do it (potentially we could continue the review here, but if the import process requires a fresh clone we could do the clone at that point, to avoid splitting the conversation).
The review process does depend on the reporter field to be set correctly so just before you import, you can clone, file this as a duplicate and then request cvs access.
Updated specfile:
Updated SRPM:
Diff between 3.1.1-3 and 3.1.1-4:
The above fixes a couple of compiled modules that were broken (spotted whilst running regrtest.py)
"import crypt" was failing with this error:
/usr/lib/python3.1/lib-dynload/cryptmodule.so: undefined symbol: crypt
"import datetime" was failing with this error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: /usr/lib/python3.1/lib-dynload/datetimemodule.so: undefined symbol: _PyTime_DoubleToTimet
The latter symbol is defined in timemodule.c; the fix is to build that module using "setup.py".
The updated srpm fixes both of these issues.
rpmlint output is the same as in comment #21
Dave, I've downloaded your new specfile and taken a look at it.
1) I love the description for __os_install_post. It explains the problem clearly and is very helpful..
3) The %description probably shouldn't refer to Python 3000, since that was just a code name and hasn't been used recently. I would recommend rephrasing to "Python 3 is a new version of...".
I think you're making great progress. This spec file is looking better and better all the time.
(Andrew, thanks; I'll respond to comment #26, but here's what I've done in the meantime)
Updated specfile:
Updated SRPM:
Diff between 3.1.1-4 and 3.1.1-5:
This version:
(a) adds a patch to fix what appears to be an upstream bug in permissions handling of .pyc files, which shows up during the regression test suite; I've sent the patch upstream ()
This improves the results of the regression test suite (/usr/lib/python3.1/test/regrtest.py)
Results with 3.1.1-4:
Results with 3.1.1-5:
304 tests OK.
10 tests failed:
test_email test_httpservers test_imp test_lib2to3 test_linecache
test_socket test_tk test_ttk_guionly test_ttk_textonly
test_zipfile
(b) actually applies ivazquez's patch to fixup RPATH directives, fixing one error found by rpmlint:
binary-or-shlib-defines-rpath /usr/lib/python3.1/lib-dynload/_sqlite3.so ['/usr/lib']
The remaining rpmlint errors are:; 3 errors, 5 warnings.
Of the rpmlint warnings, I think that the following are ignorable:
- 3 "zero-length" errors: I believe these are deliberate:
- I believe that "build_class.py" must exist for legacy compat reasons (so that "import build_class" succeeds)
- nullcert.pem is a test datafile
- Templates/copyright is an empty placeholder file
- 1 "uncompressed-zip" warning: this is an upstream test data file for exercising the zip handling code. It seems better to me to leave it as is.
- 1 "file-not-utf8" warning:.
That leaves the 3 subpackages that show "no-documentation" warnings. These aren't especially serious IMHO, but I can fix them if others perceive them as a problem.
(In reply to comment #26)
> Dave, I've downloaded your new specfile and taken a look at it.
>
> 1) I love the description for __os_install_post. It explains the problem
> clearly and is very helpful
Thanks..
Probably..
> 3) The %description probably shouldn't refer to Python 3000, since that was
> just a code name and hasn't been used recently. I would recommend rephrasing
> to "Python 3 is a new version of...".
Sounds good
> I think you're making great progress. This spec file is looking better and
> better all the time.
Thanks! FWIW I think the biggest remaining issue will be to figure out a sane way of building out a python3- stack on top of this package, which will involve thinking through packaging practices/guidelines (and probably just trying it for some packages).
(In reply to comment #29)
>
>?
I think that sounds like a good idea. The only problem is that within the python3.spec, we couldn't just set `RPMBUILD_PYTHON_INTERPRETER=./python` because this interpreter also needs to be called with `LD_LIBRARY_PATH=.`. And it would be a shame to change brp-python-bytecompile in a way that didn't help at all for python3.spec. Hmm.
> :-(
> )
Hmm. Is it really necessary to remove the shebang lines from .py files that aren't executable? I think it's a complicated (and error-prone) step that doesn't have any tangible value.
>.
If this step is really necessary, the only way to embed "head -n1 |grep" is to offload it into a standalone shell script. Alternatively, you could use sed:
sed -e '/^#!/Q 0' -e 'Q 1' {}
It will return 0 if the shebang is found and 1 otherwise. Hey, that's actually pretty cool, in a sick way. :)
)
(In reply to comment #31)
> didn't like this approach, as it would restrict us to having all .py files within one srpm build be for the same python implementation.
I've created a patch for rpmbuild which doesn't have this restriction, and it thus can support e.g. both a python-foo and python3-foo subpackage emitted from the same build. I don't yet know if this is sane, but I don't want to rule it out due to tool bugs.
See bug 531117 for the gory details.
I've also created an rpmlint test to verify timestamps and ABI versions of .pyc/.pyo files (this is bug 531102).
Finally, I've patched "file" so it can identify Python 3 bytecode files (see bug 531082).
(all of the above bugs along with this review are on a Python 3 tracker bug; bug 530636).
>)
FWIW I think this is still true with my patch; IIRC "make install" does the byte-compilation using the freshly built python binary; I just need to sort out the timestamps.
(In reply to comment #32)
>
> FWIW I think this is still true with my patch; IIRC "make install" does the
> byte-compilation using the freshly built python binary; I just need to sort out
> the timestamps.
The install target doesn't do byte-compilation. This step is performed manually, with the following line (on line 289 of my slightly outdated download of the spec file):
LD_LIBRARY_PATH=. /usr/lib/rpm/brp-python-bytecompile ./python
Updated specfile:
Updated SRPM:
Diff between 3.1.1-5 and 3.1.1-6:
This incorporates Andrew's description suggestion from comment #26 and his "sed" suggestion from comment #30.
This version improves the regrtest results. When run as root, the only failures I get are now "test_httpservers" and "test_socket" (the latter due to not having my hostname set up properly in DNS/hosts) Some additional tests fail when run as non-root due to permissions issues. I don't intend to fix the latter.
rpmlint errors are as before (see comment #27 and comment #28).
Wow. You've made tremendous progress. The remaining rpmlint warnings/errors seem to all be false positives, and it looks like it's passing almost all of the regression tests. You mentioned why "test_socket" is failing, but do you know why "test_httpservers" is failing?
What's the justification for removing the shebang lines from .py files that
aren't executable?
In Comment #26, I mentioned a few changes made in the spec file that look upstreamable. Although it's doesn't seem like a high priority issue, upstreaming would probably declutter the spec file a bit.
Whenever you think everything looks good, I'd be happy to do some more testing and come up with any final suggestions. However, I'm not an official reviewer. Do we have anyone lined up for the reviewer role? I think the package is just about ready.
I'm fine with switching it to whoever come the appropriate time.
As for the spec, it looks sane to me; I haven't really tried building it yet
due to lack of time, but I trust your observations. The only things I really
pick up on are style/cosmetic things, such as find -exec vs. find |
xargs; I think one should be picked and stuck with throughout the entire spec..
(In reply to comment #37)
>.
(For reference, Andrew also filed a report about this for the main python package as bug 531901)
Thanks; I've fixed this in the latest version of the file:
Updated specfile:
Updated SRPM:
Diff between 3.1.1-6 and 3.1.1-7:
This adds an additional rpmlint warning:
python3.i686: W: devel-file-in-non-devel-package /usr/include/python3.1/pyconfig-32.h
but clearly this is deliberate, to address the issue in comment #37/bug 531901
Python 3.* isn't very standard across packages. Since we're saying that python2 and python3 are different language versions, I think we should use Python 3 (or Python3) in the descriptions.
We're unconditionally BuildRequireing openssl-devel so why are we conditionalizing this:
if pkg-config openssl ; then
export CFLAGS="$CFLAGS `pkg-config --cflags openssl`"
export LDFLAGS="$LDFLAGS `pkg-config --libs-only-L openssl`"
fi
We don't need this::
[ -d $RPM_BUILD_ROOT ] && rm -fr $RPM_BUILD_ROOT
Change this::
- mkdir -p $RPM_BUILD_ROOT/usr $RPM_BUILD_ROOT%{_mandir}
+ mkdir -p $RPM_BUILD_ROOT%{_prefix} $RPM_BUILD_ROOT%{_mandir}
Why do we still have this in the spec file? there's more and more work being done on utilizing the information in the egg-info metadata so I don't think we can keep removing it and stay compatible with upstream's intentions::
# Get rid of egg-info files (core python modules are installed through rpms)
rm $RPM_BUILD_ROOT%{pylibdir}/*.egg-info
Unless there's a good reason we probably want to make this change::
# Switch all shebangs to refer to the specific Python version.
- LD_LIBRARY_PATH=. ./python Tools/scripts/pathfix.py -i "%{_bindir}/env python%{pybasever}" $RPM_BUILD_ROOT
+ LD_LIBRARY_PATH=. ./python Tools/scripts/pathfix.py -i "%{_bindir}/python%{pybasever}" $RPM_BUILD_ROOT
What files are affected here?
# Remove shebang lines from .py files that aren't executable
I just glanced at python2.6 and saw several different kinds of files that this falls to:
difflib.py - can run a unittest.. no harm done
unittest.py - can be run as a script and do something useful
For find out which this is you have to check what the file does when run as a script.
.cvsignore removal shouldn't be needed anymore as upstream hasswitched to svn and then to hg. remove lines like this::
find $RPM_BUILD_ROOT/ -name ".cvsignore"|xargs rm -f
find . -name ".cvsignore"|xargs rm -f
Fedora standard has %post and %postun before %files.
I'd like us to think about installing rpm macros like python_sitelib from this and the main python package so we don't have to add it as boilerplate to each spec file.
Clarification:
> We don't need this::
> [ -d $RPM_BUILD_ROOT ] && rm -fr $RPM_BUILD_ROOT
Change it to::
rm -fr $RPM_BUILD_ROOT
Also, we should probably do work on the python2 merge review as well.
Thanks; I've addressed most of the above; here's the latest work-in-progress:
Updated specfile:
Updated SRPM:
Diff between 3.1.1-7 and 3.1.1-8:
rpmlint results are as before.
Still to do:
(i) analysis of shebang files still
(ii) installation of rpm macros
(iii) anything else I've missed
Re (ii), is there a standard way for a -devel package to drop macros into a directory (e.g. /usr/lib/rpm ) in such a way that rpm will automatically use them? Is this acceptable practice?
.
(In reply to comment #42)
> .
Updated specfile:
Updated SRPM:
Diff between 3.1.1-8 and 3.1.1-9:
I've tested this with a sample specfile and it works.
One possible drawback is that the macro files are read (with rpmInitMacros) and expanded on every rpm operation, which means that when python3-devel is installed, every "rpm" invocation is going to be quietly invoking /usr/bin/python3 twice on startup. None of the existing macro files seem to invoke subprocess during expansion.
Having said that, it only affects systems with python-devel installed, so I don't see this as a problem.
I'll look at doing something similar for the main "python-devel" package.
rpmlint output is as before (see comment #38)
> Having said that, it only affects systems with python-devel installed, so I
"python3-devel", rather than "python-devel", obviously
(In reply to comment #43)
> I'll look at doing something similar for the main "python-devel" package.
Filed as bug 533022
I read through the history here, and tried to summarize the remaining review issues.
Here's what I think remains:
- a reviewer needs to go through the full review guidelines on this
- fixup the factual errors in the comment describing redefinition of __os_install_post
-
- cosmetic issue: exec vs find | xargs noted in comment #36
- what files are affected when modifying shebangs, and how (see commment #39)
- anything else I've missed
Created attachment 369966 [details]
patch to version 9 of the spec file
(In reply to comment #46)
> - fixup the factual errors in the comment describing redefinition of
> __os_install_post
> - cosmetic issue: exec vs find | xargs noted in comment #36
These two issues should be fixed in python3-10.patch, which I just attached.
> - what files are affected when modifying shebangs, and how (see commment #39)
I wouldn't worry too much about this problem. The shebang doesn't actually do anything for a file without executable permissions, so removing the shebang line doesn't make it any less executable than it already was.
(In reply to comment #48)
>
> I wouldn't worry too much about this problem. The shebang doesn't actually do
> anything for a file without executable permissions, so removing the shebang
> line doesn't make it any less executable than it already was.
I forgot to mention that leaving the shebang lines in doesn't make a file any more executable than it already was. It probably wouldn't hurt to just remove the shebang removal.
(In reply to comment #47)
> Created an attachment (id=369966) [details]
> patch to version 9 of the spec file
Thanks Andrew!
Updated specfile:
Updated SRPM:
Diff: purely the changes from your attachment
rpmlint output as before
hmm i am curious why not call python3 -> python and the old version python-compat2.6 or whatever?
(In reply to comment #51)
> hmm i am curious why not call python3 -> python and the old version
> python-compat2.6 or whatever?
Python 3 is intended by upstream to be the future of Python, but we have many critical components that use Python 2. Python 2 and Python 3 are sufficiently different that we need both (try writing "print" in each). Python 2 will be around for a long time.
Changing the meaning of "python" to mean python 3 rather than python 2 in specfiles/yum/rpmdb would have a very high chance of breaking something during updates, and I don't see any real benefit.
Hence the plan is to continue to use "python-" to mean the existing python 2 stack, and "python3-" for the new parallel-installable python3 stack.
For more information see
I can't get runtests.sh working...
When running, all tests are failing because of:
"./python: error while loading shared libraries: libpython3.1.so.1.0: cannot open shared object file: No such file or directory"
If this is fixed, you could add a %check section and run the tests there.
(In reply to comment #53)
> I can't get runtests.sh working...
I'm not sure what you mean by "runtests.sh" here.
> When running, all tests are failing because of:
> "./python: error while loading shared libraries: libpython3.1.so.1.0: cannot
> open shared object file: No such file or directory"
>
> If this is fixed, you could add a %check section and run the tests there.
I think you need to prefix the invocation of "./python" with this:
LD_LIBRARY_PATH=.
so that it can find the libpython library from the build.
Sorry for the delay:
You could add a %check section:
%check
LD_LIBRARY_PATH=. ./runtests.sh
This runs the python3 testsuite on each build to verify nothing is broken.
Currently here on my pc:
18 BAD
296 GOOD
23 SKIPPED
337 insgesamt
Replying to comment #55:
Thanks! I've added a %check to the specfile. I used
LD_LIBRARY_PATH=$(pwd)
rather than
LD_LIBRARY_PATH=.
as I ran into problems that appeared to occur when a subprocess had changed working directory and could no longer find libpython. See the diff below for more info.
Updated specfile:
Updated SRPM:
Diff:
rpmlint output as before (see comment #27, comment #28, and comment #38)
Koji scratch build into dist-f13 here:
Following up on comment #46:
Issues addressed in release 10:
> - fixup the factual errors in the comment describing redefinition of
>__os_install_post
> - cosmetic issue: exec vs find | xargs noted in comment #36
Remaining issues:
> - a reviewer needs to go through the full review guidelines on this
TODO
> -
> - what files are affected when modifying shebangs, and how (see commment #39)
> - anything else I've missed
The remaining issues from comment #56:
> - a reviewer needs to go through the full review guidelines on this
Looking for a volunteer here.
> - perhaps fixup rpm-build to avoid needing
> find-provides-without-python-sonames.sh
Deferred: I don't think this is needed before package import.
> - fixup macros.python3 to bake in the definitions, avoid invoking python3
> each time
Deferred: currently the script is arch-independent and goes in sysconfdir; it will lead to different results on 32-bit vs 64-bit archs. It's not clear to me how to "bake in" the result at build time in a way that works in a cross-arch way. Suggestions welcome. So I plan to punt this for now: I don't think it's necessary to fix this to pass package review, something to be fixed after package import.
> - verify the script in comment #17 still works and that it verifies the 2 and
> 3 packages are independent
I'm working on this
> - what files are affected when modifying shebangs, and how (see commment #39)
I'm working on this
> - anything else I've missed
Does anyone have other concerns?
> how to "bake in" the result at build time in a way that works in a cross-arch
"cross-arch" should read "multilib-safe" here
...
> > - anything else I've missed
> Does anyone have other concerns?
- BR tix tk not needed, because both -devel packages are in BR
- %global vs %define:
- tools and tkinter contain tests -> should go into tests
-.
- Why do you force gcc?
And by the way: because you are not the requester of this review request, you need to open your own one and close this as dublicate.
I will give it a try, but it is a very complex .spec, so second opinions are welcome.
rpmlint output:
$ rpmlint python3-3.1.1-11.fc12.src.rpm
python3.src: W: strange-permission find-provides-without-python-sonames.sh 0775
python3.src:220: E: hardcoded-library-path in $RPM_BUILD_ROOT/usr/lib/python%{pybasever}/site-packages
python3.src:416: E: hardcoded-library-path in /usr/lib/python%{pybasever}
python3.src:417: E: hardcoded-library-path in /usr/lib/python%{pybasever}/site-packages
1 packages and 0 specfiles checked; 3 errors, 1 warnings.
rpmlint ~/rpmbuild/RPMS/i686/python3-*
python3.i686: E: zero-length /usr/lib/python3.1/build_class.py
python3.i686: W: devel-file-in-non-devel-package /usr/include/python3.1/pyconfig-32.h
python3-libs.i686: W: no-documentation
python3-test.i686: W: no-documentation
python3-test.i686: E: zero-length /usr/lib/python3.1/test/nullcert.pem
python3-test.i686: W: uncompressed-zip /usr/lib/python3.1/test/zipdir.zip
python3-tkinter.i686: W: no-documentation
python3-tools.i686: W: file-not-utf8 /usr/lib/python3.1/Demo/distutils/test2to3/setup.py
python3-tools.i686: E: zero-length /usr/lib/python3.1/Tools/modulator/Templates/copyright
7 packages and 0 specfiles checked; 3 errors, 6 warnings.
python3.src: W: strange-permission find-provides-without-python-sonames.sh 0775
Should this be 755 ?
python3-tools.i686: W: file-not-utf8
/usr/lib/python3.1/Demo/distutils/test2to3/setup.py
python3.i686: W: devel-file-in-non-devel-package
/usr/include/python3.1/pyconfig-32.h
Please comment on these ones.
MUST:
* package is named according to the Package Naming Guidelines .
* spec file name match base package
* package meet Packaging Guidelines .
* package is licensed with a Fedora approved license and meet the Licensing Guidelines .
* License field match the actual license.
* available license(s) file(s) is included in %doc.
* spec file is written in American English.
* spec file is legible.
* sources match upstream (md5sum)
d1ddd9f16e3c6a51c7208f33518cd674 Python-3.1.1.tar.bz2 (upstream)
d1ddd9f16e3c6a51c7208f33518cd674 Python-3.1.1.tar.bz2 (srpm)
* package compile on x86
* build dependencies is listed in BuildRequires
* no locales
* available shared library files calls ldconfig in %post and %postun.
* package not relocatable
* package own all directories that it creates.
* no duplicate files in the %files listing.
* Permissions on files must be set properly. (%defattr(...) line)
* %clean section present and contains rm -rf %{buildroot} (or $RPM_BUILD_ROOT)
* package is consistently using macros
* package contain code, or permissable content
* no large doc
* %doc does not affect runtime
? available Header files go into -devel package.
What about this one ?
python3.i686: W: devel-file-in-non-devel-package /usr/include/python3.1/pyconfig-32.h
* no static libs
X available pkgconfig(.pc) files 'Requires: pkgconfig'
There is a buildrequire on pkgconfig, but no Requires:
* no unversioned *.so.* libs
* available devel packages uses fully versioned dependency: Requires: %{name} = %{version}-%{release}
* package dont contain .la libtool archives.
* not a GUI app.
* no files or directories already owned by other packages.
* %install begins with rm -rf %{buildroot} (or $RPM_BUILD_ROOT)
* filenames is valid UTF-8
SHOULD:
* source package include license text(s) in separate file from upstream
* builds in mock.
Not tried, but koji build has been done so it should be ok
* compile and build into binary rpms on all supported architectures.
* package functions as described.
* scriptlets is sane.
* subpackages require the base package using a fully versioned dependency.
Fix/comment on the X/? and i will approve it, i nobody has any issues i have mixed
i nobody = if nobody :)
have mixed = have missed :)
(In reply to comment #59)
> ...
Bravo! Thanks for the feedback!
> > > - anything else I've missed
> > Does anyone have other concerns?
>
> - BR tix tk not needed, because both -devel packages are in BR
I've removed these two.
> - %global vs %define:
>
>
Fixed; I did a search-and-replace throughout the specfile
> - tools and tkinter contain tests -> should go into tests
"rpm -qlv python3-tools|grep test" shows the majority of these files in these subidrectories:
- /usr/lib/python3.1/lib2to3/tests subdirectory
- /usr/lib/python3.1/Demo/distutils with just a test2to3 (the latter with many files)
- /usr/lib/python3.1/Demo/md5test
and a few other files
"rpm -qlv python3-tkinter|grep test" shows the tests in this subpackage are all below "/usr/lib/python3.1/tkinter/test"
In both cases I've moved the ones listed above into the "test" subpackage. I've added a requirement to the "test" subpackage for the "tools" subpackage due to the way the directory hierarchy is set up.
> -.
This sounds like bug 543756. We've lived with this for Python 2. I'd prefer to leave dealing with this as an open RFE, rather than block package import on it.
> - Why do you force gcc?
These lines:
# Force CC
export CC=gcc
came from Python 2's python.spec, and was introduced in this version
* Wed Nov 12 2003 Mihai Ibanescu <misa@redhat.com> 2.3.2-5
- force CC (#109268)
(way back in the Fedora Core 2 days)
If I'm reading that bug correctly, it appears that what happened was that the Makefile (generated by "configure" during the build) would include a reference to "x86_64-redhat-linux-gcc", rather than to "gcc". This generated Makefile is shipped in the RPM (originally in the -devel subpackage, more recently in the main subpackage; see bug 531901) and is parsed by the "distutils" module. It appears that a generated libtool script specialcased detection for "gcc" and couldn't handle such compiler names.
I've tried removing the lines, and it seems to work fine. We can reinstate them if it causes trouble. (Also, if in the future Unladen Swallow gets merged into Python 3.x, we may want to build Python 3 with LLVM's compiler instead of gcc).
Updated specfile:
Updated SRPM:
Diff:
rpmlint output as before (see comment #27, comment #28, and comment #38)
Successful scratch build here:
(In reply to comment #61)
> I will give it a try, but it is a very complex .spec, so second opinions are
Thanks!
(In reply to comment #63)
> python3.src: W: strange-permission find-provides-without-python-sonames.sh 0775
>
> Should this be 755 ?
Fixed in -13
Updated specfile here:
updated SRPM here:
Updated scratch build here:
No change to specfile other than to %changelog
> python3-tools.i686: W: file-not-utf8
> /usr/lib/python3.1/Demo/distutils/test2to3/setup.py
From comment #28:.
> python3.i686: W: devel-file-in-non-devel-package
> /usr/include/python3.1/pyconfig-32.h
This is deliberate, as the file is actually used at run-time by the distutils package (as well as the more normal usage at build-time) - see comment #37, bug 531901, and upstream issue
From comment #57
> - verify the script in comment #17 still works and that it verifies the 2 and
> 3 packages are independent
I slightly reworked my script, to compare scratch builds.
"koki download-build" can't download scratch builds, as they only have a task_id, not a build_id.
mbonnet has a script for this:
and I use this to download all of the files into the PWD
Created attachment 383125 [details]
Updated version of script to locate collisions between python2/python3
The output of this script contains:
(i) the various /usr/lib/debug filesystem collisions described in comment #17, which aren't a problem
(ii) Provides: "python(abi)", which could be a problem
$ rpm -q --provides python | grep abi
python(abi) = 2.6
python-abi = 2.6
$ rpm -q --provides python3 | grep abi
python(abi) = 3.1
Both python and python3 provide "python(abi)", with different values. Add-on Python rpms will have a Requires on "python(abi)", some requiring this to equal "2.6", others requiring it to equal "3.1"
Is this a problem? IIRC I was able to install both sets of packages during my testing.
James: is this a no-no from the point of view of Yum?
It's probably not been tested much in the wild, but it will almost certainly work. Just ignore the warning.
But don't do "obviously" insane stuff like:
Conflicts: python(abi) < 3.1
...because that has to be true for all providers.
Also note:
% cat /tmp/python-abi-wtf.py
#! /usr/bin/python -tt
import yum
yb=yum.YumBase()
for pkg in sorted(yb.pkgSack.returnPackages()):
for req in pkg.requires_print:
if not req.startswith("python(abi)"): continue
if req == "python(abi) = 2.6": continue
print pkg.repo.id,pkg,req
% sudo python /tmp/python-abi-wtf.py
Loaded plugins: local, presto
fedora cobbler-2.0.0-1.fc12.noarch python(abi) >= 2.6
fedora cobbler-web-2.0.0-1.fc12.noarch python(abi) >= 2.6
rpmfusion-free compat-python24-imaging-1.1.6-4.fc11.x86_64 python(abi) = 2.4
rpmfusion-free compat-python24-libxml2-2.7.6-1.fc12.x86_64 python(abi) = 2.4
fedora koan-2.0.0-1.fc12.noarch python(abi) >= 2.6
fedora revisor-cli-2.1.8-1.fc12.noarch python(abi) >= 2.4
updates revisor-cli-2.1.10-3.fc12.noarch python(abi) >= 2.4
fedora ris-linux-0.4-6.fc12.noarch python(abi) >= 2.1
...what yum does with >= is much less well defined, but you'll probably be fine ... and most of the above are probably bugs anyway (Eg. revisor-cli also has a Requires: python(abi) = 2.6).
But I'd save the above script and run it periodically to make sure no one does anything weird you aren't expecting (being a trail blazer and all :).
David:
What about this one ?
X available pkgconfig(.pc) files 'Requires: pkgconfig'
There is a buildrequire on pkgconfig, but no Requires:
Rpm adds pkgconfig dependencies automatically, no need to duplicate it manually.
OK, Fine with me, maybe this path of the guidelines is outdated.
APPROVED
path = part :)
(In reply to comment #76)
> OK, Fine with me, maybe this path of the guidelines is outdated.
>
It is.
I think ratification by FESCo/FPC writeup has gotten lost in the holiday-vacation-no-meeting shuffle. I'll look into it.
Tim, thanks for taking on a large and complex review!
Something I noticed, can be changed after import:
%if "%{_lib}" == "lib64"
%attr(0755,root,root) %dir /usr/lib/python%{pybasever}
%attr(0755,root,root) %dir /usr/lib/python%{pybasever}/site-packages
%endif
[..]
%dir /usr/include/python%{pybasever}
/usr/include/python%{pybasever}/%{_pyconfig_h}
Those should be:
%attr(0755,root,root) %dir %{_prefix}/lib/python%{pybasever}
%attr(0755,root,root) %dir %{_prefix}/lib/python%{pybasever}/site-packages
%dir %{_includedir}/python%{pybasever}
%{_includedir}/python%{pybasever}/%{_pyconfig_h}
Tim: thanks for reviewing this.
James: thanks for doublechecking the python(abi) question
Toshio: yes, I'll fix the issue in comment #79 after import
As discussed in:
I'm opening a fresh review in order to set myself as "Reporter", and I'll mark the old review as a duplicate of this one.
*** This bug has been marked as a duplicate of bug 554799 ***
The package review in bug 554799 is now done; the package is in CVS and I've built the package into dist-f13 (yay!)
If anyone wants to be added as a comaintainer etc, please let me know.
Thanks Andrew, Ignacio, James, Steve, Toshio, Tim, and everyone else for your work on this! (hope I didn't miss anyone) | https://bugzilla.redhat.com/show_bug.cgi?format=multiple&id=526126 | CC-MAIN-2017-13 | refinedweb | 8,835 | 66.03 |
In the past few months, I’ve learned a lot about WebAPI and using Kendo UI with ASP.NET by creating the HTML5 Development For ASP.NET Developers series. While the company behind Kendo UI has a distinguished .NET pedigree, Kendo UI itself is completely server agnostic. That means it doesn’t lean one way or the other in terms of catering to a specific server language. It’s all about HTML5, and that’s the way it should be.
When I did Hello Kendo UI Part 1, I got a few comments asking me if I could show some additional server actions, like sorting. Actually, the exact comment was
And then there was another vote for the same thing.
So, naturally, I said…
In the interest of full disclosure, I just want you all to know that this one was indeed as the commenter suggested it might be in terms of not being necessarily easy to decipher. The end solution is by no means complicated, but the trick is knowing your way around WebAPI. There was a lot of trial and error, a bit of crying and a small amount of swearing, but today I would like to publicly declare victory.
While I have a very good understanding of Kendo UI, my expertise in WebAPI is not nearly as matched. It’s a newer technology, and it’s got a few things in it that can keep you guessing. Fortunately for me, I was able to enlist of the help of the Jonathan Creamer (AKA “The Prodigy”) of AppendTo His knowledge of WebAPI (and many other things) far exceeds my own and he was a valuable source of direction when trying to navigate the sometimes murky waters.
You can download the complete source for this article here.
I will be using the last Hello Kendo UI example and applying sorting to the same project that already has paging and editing in it. There are only 3 records on a page, but we’ll pretend we have a bunch.
The first order of business is for you to open up the Default.aspx page and in the Grid initialization you need to turn on sorting.
selectable: true,
...
sortable: true,
...
change: function (e) {
With that change, the grid is now sortable. However it’s happening client side. Of course this is fine when your grid hold 9 records but we’re trying to prove a point here. We need to get this on the server. To do that, set the serverSorting property on the DataSource to true
// do paging on the server
serverPaging: true,
...
// do sorting on the server
serverSorting: true
...
}),
Now you can sort the columns, and if you inspect the network request in the developer tools you will see that a sort parameter is being sent across.
One of the things that Jonathan had me change was to use the Default Parameter Binding in WebAPI. It turns out that you can pass any parameter into the Get request in the Controller Method and as long as it’s present, it will be automatically bound. For instance, we could now get the take and skip paging parameters directly. We do have to provide defaults though. If no values are passed, WebAPI will bark about not getting the parameter its expecting
public Models.Response Get(int take = 10, int skip = 0)
{
...
}
That’s a whole lot nicer isn’t it!?!
Now you would think that you could reference the sort parameter the same way. However, this is not the case. For starters, lets look at the structure of the object being passed.
sort[0][field]:LastName
sort[0][dir]:asc
This object is actually rather complex. It’s an array of objects that contain a field and dir property. Right now, WebAPI sees both of these sort parameters as separate parameters that have a key of sort[0][field] and sort[0][dir]. That’s not exactly what we want at all.
What we need to do here is get Kendo UI and WebAPI on the same page. This is all about serialization. JSON is going to be the middle ground here. Kendo UI and WebAPI both read and speak JSON fluently. We essentially have two options now. We could convert just the sort objects to JSON, or we could convert the entire request to JSON and expect a single Request object in the Get controller method.
I opted for the later as it’s a bit less verbose and I think makes more sense when you go back to debug or some other pour soul gets handed your code.
Kendo UI has a whole plethora of framework methods. One of them is stringify. This is a pollyfill for the JSON2 object. It takes an object and converts it to JSON. Most browsers support the JSON2 stringify natively, but older ones don’t. By using the kendo.stringify method, you will be safe in knowing that Kendo will take care of things if your browser can’t serialize to JSON.
HTML5 is about making sure things work across browsers. Kendo UI fills in the gaps (like missing JSON serialization support) for you and automatically provides fallbacks when functionality is missing. See how Kendo UI makes your life so much easier?!?
HTML5 is about making sure things work across browsers. Kendo UI fills in the gaps (like missing JSON serialization support) for you and automatically provides fallbacks when functionality is missing. See how Kendo UI makes your life so much easier?!?
In the parameterMap, you need to convert the parameters to JSON using kendo.stringify. You can just convert the whole options object.
if (operation === "read") {
return kendo.stringify(options);
}
We now have a different issue. We can’t send parameters like this to WebAPI in a GET. We need to do this in a POST and send the parameters as part of the payload. To tell Kendo UI to do this is quite easy. Just set the type on the read operation to POST.
read: {
url: "api/employees",
type: "POST"
}
In the controller, you now need to have the Get method respond to a POST. By Default, WebAPI is routing it to a GET because it’s assuming that since we called it Get, we would want to do a GET. Makes sense right?
To get around this, you need to make some routing changes. Right now, you have one simple route in the Global.asax application start event. You are again at a cross roads. On the one hand, you can create a route specific for this scenario the same way you created the default route. By now though, you can see that creating a new route every time you have something other than a super simple set of CRUD operations is not going to scale very well. I wasn’t satisfied with this answer so I did some soul searching. There has to be a better way.
It turns out that I’m not the only one who had this concern. Tim McCall created an Attribute Based Routing framework for MVC and then ported it for WebAPI as well. This allows you to decorate your methods with what routes you want them available at. This is frankly brilliant, and I would love to see this baked into the framework.
For now, head out to NuGet and get the AttributeRouting package. Make sure you get the WebAPI one, NOT the MVC one. They are not interchangeable.
Once you have installed this package, you can get rid of that nasty route table in the Global.asax file. Open the EmployeesController and add a reference to the AttributeRouting library.
using AttributeRouting.Web.Http;
If this namespace isn’t available for you, then you probably installed the MVC version instead of the WebAPI version.
If this namespace isn’t available for you, then you probably installed the MVC version instead of the WebAPI version.
Now decorate your methods as shown:
public Models.Response Get(){
...
}
public HTTPResponseMessage Post() {
...
}
[DELETE("api/employees/{id}")]
public HTTPResponseMessage Delete() {
...
}
The Get will respond to a POST and the update method will only respond to a POST when an ID is passed in on the URI (i.e.).
If you wanted to make this id parameter optional like it was before, you can simply put a “?” in front of it - POST(“api/employees/{?id}”). For a completely syntactical reference, have a look at this article.
If you wanted to make this id parameter optional like it was before, you can simply put a “?” in front of it - POST(“api/employees/{?id}”). For a completely syntactical reference, have a look at this article.
If you remember, in the parameterMap method you serialized the entire option object to JSON. This means that in the Get, you are now expecting a single object. You need to create an object that WebAPI can use to map the request parameters to. In the Models folder, create a Request class. Give it the following structure.
namespace hello_kendo_ui.Models {
public class Request {
public int take { get; set; }
public int skip { get; set; }
public int page { get; set; }
public List<Sort> sort { get; set; }
}
public class Sort {
public string field { get; set; }
public string dir { get; set; }
}
}
OK, so it’s actually two classes in the same file. You can now expect one Request parameter in the Get method and all of the parameters coming from the DataSource (i.e. take, skip, page, sort) will be available off of this object. The take and skip parameters are gone and the LINQ query now references the request object. I also moved the Take and Skip into the body of the LINQ query for reasons I will explain shortly.
public Models.Response Get(Models.Request request) {
// get all of the records from the employees table in the
// northwind database. return them in a collection of user
// defined model objects for easy serialization. skip and then
// take the appropriate number of records for paging.
var employees = (from e in _context.Employees
.Skip(request.skip)
.Take(request.take)
select new Models.Employee(e)).ToArray();
// returns the generic response object which will contain the
// employees array and the total count
return new Models.Response(employees, _context.Employees.Count());
}
At this point, you can test the application and you will see that it’s returning an empty dataset and a count of 9? What happened?
As it turns out, since you are sending a JSON payload to WebAPI, you need to specify that you are doing that. You need to set the contentType in the header of the AJAX request. That sounds complicated, but since at it’s core the Kendo UI DataSource calls jQuery.ajax(), you can pass virtually any valid $.ajax parameter in to the transport methods. Simply set the contentType to application/json.
read: {
url: "api/employees",
type: "POST",
contentType: "application/json"
},
This will give you data back. If you click on a column heading and break into the EmployeesController Get method, you will see that the sort property is now populated! You are well on your way at this point.
Since you don’t know what the sort will be at runtime, you need to be able to pass in a dynamic OrderBy clause to in your LINQ query. To do this, you are going to need the Dynamic LINQ library that comes with the Visual Studio 2008 samples.
It’s just a class that you add to your project. It extends off the System.Linq namespace so no worries on where you put it in your project.
Once you have added it, you can import the System.Linq.Dynamic namespace in the EmployeesController.
using System.Linq.Dynamic;
This will allow you to pass a string to the OrderBy method. A string like “LastName asc”. It’s a standard SQL order by syntax. You do need to translate this out of the sort object and into a single string. Right now you are only passing one sort value in the 0 position of the sort object, but should you turn on multiple sorting, you will be passing 1 to many sort objects. You might do this any number of ways, but I simply iterated over the list of incoming sort objects and composed a string using the string.join method.
// compose the order by for sorting
string order = "EmployeeID";
// order the results
if (request.sort != null && request.sort.Count > 0) {
List<string> sorts = new List<string>();
request.sort.ForEach(x => {
sorts.Add(string.Format("{0} {1}", x.field, x.dir));
});
order = string.Join(",", sorts.ToArray());
}
Notice that I gave the sort a default value. This is because the Dynamic LINQ query won’t respect null or empty string as a valid OrderBy. Also, check for a null sort object and make sure that it has a length. Before you sort, Kendo UI sends no value. On the first click, it sorts Ascending. On the second click, it sorts Descending. On the third click it turns sorting completely off, but passes a zero length object.
You have an interesting scenario here if you stop to think about it. You are paging and sorting. That means that you need to do both of these, but in what order? The grid will display the current page of data. This means that when a user sorts, it should sort only the current page of data. Consequently, you need to page and then sort.
Fortunately for you, this is quite easy. This is also the reason that I earlier moved the Skip and Take into the body of the LINQ query right off of the _context.Empolyees object. Just add the OrderBy clause after the Skip and Take. This will get the right page of data, and then sort it. This is what the user expects would happen in the grid. If you sort and then page, you will be providing an unexpected user experience.
// get all of the records from the employees table in the
// northwind database. return them in a collection of user
// defined model objects for easy serialization. skip and then
// take the appropriate number of records for paging. Then order
// that dataset with the dynamic linq query library
var employees = (from e in _context.Employees
.Skip(request.skip)
.Take(request.take)
.OrderBy(order.ToString())
select new Models.Employee(e)).ToArray();
That’s it! You’ve now got server sorting and paging in your grid. Lets kick it up a notch and set the sorting to multiple on the DataSource.
editable: "inline",
selectable: true,
...
sortable: {
mode: "multiple"
},
...
Thanks to the fact that you have already accounted for the fact that the sort object is a collection, you don’t need to make any additional changes.
As you can see, Kendo UI plays really nicely with WebAPI. You get the utility methods you need - like stringify - and the DataSource is super flexible in what it will let you do to the outgoing request.
Hopefully between this and the previous HTML5 For ASP.NET Developer articles, you have all the info you need to wire Kendo UI up to ASP.NET. If not, I would love to hear what would be helpful for you to see in addition to what’s already been provided.
As always, if you haven’t downloaded Kendo UI yet, make sure you do and see how HTML5 goes from frustrating to fun!
Grab the complete project for this article. | http://www.telerik.com/blogs/ask-kendo-ui-ndash-server-side-sorting-with-webapi | CC-MAIN-2017-39 | refinedweb | 2,571 | 74.69 |
In case you haven’t heard the news, Mobile Services now has a service backend that is implemented as a Web API project. This “.NET backend” relies heavily on the Code First features of Entity Framework, where you specify on the data model as a DbContext and Entity Framework will automagically generate the database for you. This make the .NET backend quickstart projects work super easy on first try, both on the local machine (using localdb) and after you publish to Azure (using SQL Database).
If you dig into a .NET backend project, you will find the static WebApiConfig class, which is called when the service is first initialized. In the Register method, the following method is called to create the database:
Database.SetInitializer(new my_mobile_serviceInitializer());
And in the same code page you can see that the generated my_mobile_serviceInitializer class inherits from DropCreateDatabaseIfModelChanges:
public class my_mobile_serviceInitializer :
DropCreateDatabaseIfModelChanges<my_mobile_serviceContext>
{
protected override void Seed(my_mobile_service);
}
}
The first time the project runs, Code First (by default) creates the database automatically. With this initializer, EF also tries to drop and recreate the database whenever it detects a model change. The Seed method provides the set of default data in the new database (both local and in Azure).
If the good news is how easy it is to get the service up and running with a database created for you automatically in Azure by Entity Framework. The bad news is that the mobile service runtime doesn’t have permissions to drop a SQL Database in Azure (as it does for the local DB). This means that the default initializer will continue to work great locally (dropping and recreating the DB and reseeding every time you mess with the data model) but things will break when you try to publish changes with an existing database schema. (But this is actually a good thing…just think of the havoc it would wreak if it did drop your DB in Azure).
This means, of course, that you need to disable the call to SetInitializer when publishing model changes to Azure. At this point, there are really two options for publishing data model changes up to Azure:
The rest of this topic will deal with option #2 (and bonus—we also get to do #1 in the process).
Before you can get going with Code First Migrations, we need to drop any existing tables in Azure that belong to the mobile service’s “schema.” You need to do this if you have already published your mobile service to Azure (and accessed the data, that’s when Code First goes to work) before you configure Code First Migrations. The one exception to this is if the database schema already matches your current model, then you are good to go.
Depending on when you created your .NET backend project, you may have to make some recent updates for everything to work correctly.
string schema = ServiceSettingsDictionary.GetSchemaName();
if (!string.IsNullOrEmpty(schema))
{
modelBuilder.HasDefaultSchema(schema);
}
Now we have finally come to the fun Code First Migrations stuff….
Make sure that your mobile service is the startup project, open the Package Manager Console, and run the following command:
PM> Enable-Migrations
PM> Add-Migration Initial
Open the App_Start\WebApiConfig.cs file and add the following using statements, where todolistService is your project’s namespace:
using System.Data.Entity.Migrations;
using todolistService.Migrations;
var migrator = new DbMigrator(new Configuration());
migrator.Update();
This disables the default Code First database initializer that drops and recreates the database and replaces it with an explicit request to apply the latest migration. At this point, any data model changes will result in an InvalidOperationException when the data is accessed, unless a migration has been created for it. Going forward, your service must use Code First Migrations to migrate data model changes to the database.
Press F5 to start the mobile service project on the local computer. At this point, the database is in sync with the data model.
Now make a change to your data model, such as adding a new UserId property to the TodoItem type, rebuild the project, and then in the Package Manager, run the following command:
PM> Add-Migration NewUserId
This creates a new migration named NewUserId. A new code file, which implements this change, is added in the Migrations folder.
Press F5 again to restart the mobile service project on the local computer.
The migration is applied to the database and the database is again in sync with the data model. If you didn’t add seed data in the Seed override method in Configure.cs, then there will be no data to return.
Republish the mobile service to Azure, then run the client app to access the data and verify that data loads and no error occur.
If you haven’t already figured it out—it’s much better to pretty-much nail down your data model before you publish your mobile service to Azure, and definitively before you fill the database with valuable data. That way, you can keep using the default initializer
Instead of 'Dropping existing tables', I am trying 'Enable Code-first' option
Enabled Migrations for the downloaded service project, it was already enabled for my existing EF project. Also, ran Add-migration -Initialize command on the zumo service project.
but when try to run the service, I get this weird error -
Additional information: Column names in each table must be unique. Column name 'Id' in table 'SomeTable' is specified more than once ---(1)
So, I checked the scaffolded "up" method of my new migration class that was created when I ran PM>Add-Migration Initialize. In the up method, I noticed it is trying to add a new column 'Id' for all my tables, in addition to my existing 'id' columns. So I commented the 'AddColumn('Id'......) that were there for all my tables (along with other related code like adding new key based on that column). Ran the project again, but keep getting the same error as in (1) above. I rolled back the 'Initialize' migration, commented the whole 'up' method, but keep getting the same error?
scratching my head, do you see anything I am doing wrong, or missing anything? appreciate your help, thanks
For code-based migration, I tried the steps from your new blog post, there also, I get the same exception as in (1) above.
@kkap
No, I haven't seen this behavior, but I have always deleted existing tables before starting to use migrations, so...
Have you tried creating the initial migration using the -IgnoreChanges switch?
Glenn.
thanks, figured it out, the error was because I had 'id' property defined in my model class. When upgrading to mobile services, I changed the inheritance of this model class to inherit from 'EntityData', which has an 'Id' property defined.
This was causing that error when running the migration - Column names in each table must be unique.
thank you, the service is running now.
@Glenn, how can I make the 'Id' and 'createdDate' fields of 'Microsoft.WindowsAzure.Mobile.Service.EntityData'( from which my model classes are derived), to be AutoGenerated and default SQL value 'GetDate()' respectively. otherwise when I do a 'Http Post' of a new record to my table, I need to provide these values in my json object.
I tried below in migration,
AlterColumn("dbo.Table1", "Id", c => c.String(defaultValueSql: "newid()"));
AlterColumn("dbo.Table1", "CreatedAt", c => c.DateTime(defaultValueSql: "GETDATE()"));
AlterColumn("dbo.Table1", "Deleted", c => c.Boolean(defaultValue: false));
but the migration update fails saying Object DF_<tablename>_Id/DF_<tablename>_createdDate or constraint key PK_<tablename>_Id is dependent on these columns.
I can try dropping the PK constraint and re-create it later, but I am not sure of that DF_<tablename>_Id object. I believe this object may have been provided by Mobile.Service.EntityData for giving some default values to these columns, but then why it asks to provide values for these columns in the Http POST request body when I try to add a new record?
any idea?
My first concern is why your table belongs to the dbo schema. The schema name should be the same as the mobile service name. Make sure that you are using the latest version of the DbContext from the portal quickstart (it has some recent fixes that prevent the dbo problem).
@glenn, sorry for the confusion the code in my previous post created, the schema name for the tables is in fact the name of the mobile service, not dbo. I just put dbo as I didn't want to put the actual name of my mobile service.
Hi Glenn, unfortunately this does not work for me at all. The only solution that is really working (found on SO) stackoverflow.com/.../error-while-enabling-code-first-migrations-on-mobile-services-database - works without any code-changes. I only updated the three packages.
Thanks a lot Glenn! Great article. Saved me a lot of time. I wish the demos refer to it, because in all demos I have seen so far, they move from local DB to azure and magic happens and it works :).
Thanks aelswify,
Notice that the default initializers have changed somewhat now that .NET backend has reached the "general availability" milestone. This topic has the latest info: azure.microsoft.com/.../mobile-services-dotnet-backend-how-to-use-code-first-migrations | http://blogs.msdn.com/b/writingdata_services/archive/2014/03/28/mobile-services-net-backend-initializers-and-model-updates.aspx | CC-MAIN-2014-52 | refinedweb | 1,560 | 62.38 |
Selenium Tutorial using C# and NUnit
Mon 13 Apr 2009
In previous tutorials you would have seen how to create your Selenium Scripts in Selenese and then run them using Selenium Remote Control. You would have noticed how good Selenium Remote Control is for running tests against your web application using any browser without having to move your test scripts onto the webserver.
In this tutorial we are going to learn how to create your first test script using the language that I most commonly use, c#. Since most languages are semantically the same, if you do not use c# it shouldn't be too difficult to translate the tutorial into your language of choice. You will to download NUnit and at least Visual Studio Express c# edition to complete this tutorial. They are free to download and use.
- Follow steps 1-4 of Selenium Remote Control HTML Suite Tutorial. This will get the Selenium Remote Control Running.
- In Visual Studio lets create a new project. You will have to create a new class library by going New> New Solution> Class Library and call it TheAutomatedTester
- Add a reference to the NUnit Framework by rightclicking on the solution and clicking add reference. Click on the browse tab and navigate to <%nunithome%>\bin and select nunit.framework.dll . This allows you now to create your first NUnit test.
- Now in the *.cs file put the code below into it. The code below will call Selenium Remote and say that it needs an instance on Firefox Chrome.
[TestFixture] public class TheAutomatedTester { private ISelenium selenium; private StringBuilder verificationErrors; [SetUp] public void SetupTest() { selenium = new DefaultSelenium("localhost", 4444, "*chrome", ""); selenium.Start(); verificationErrors = new StringBuilder(); }
- Now Lets create a test:
[Test] public void AutomatedTester_Test() { selenium.Open("/index.htm"); selenium.Click("buttonName"); selenium.WaitForPageToLoad("30000"); }
The code above would open the page index.htm for the root of your local web server then click on a button and wait for a page to load. If you want to see how to the other commands look I would suggest creating your command in Selenium IDE and then converting them to c# using the Options > Format commands.
- Once your test has run you will need to clean up Selenium object. The best way to do this is to create a teardown function in your test. It should look like something like the code below.
[TearDown] public void TeardownTest() { try { selenium.Stop(); } catch (Exception) {// Ignore errors if unable to close the browser } Assert.AreEqual("", verificationErrors.ToString()); }
If you make sure that your code has this teardown then you will be able to reuse the Selenium Remote Control.
- Now compile the code into a DLL and Open it with NUnit. When you click the Run button in NUnit it will run your Selenium Test.
If you would like to make your test data driven put all the code to pull the data in the SetUp. | http://www.theautomatedtester.co.uk/tutorials/selenium/selenium_csharp_nunit.htm | CC-MAIN-2014-41 | refinedweb | 485 | 55.13 |
Splitting Datasets into Training/Testing/Validating¶
This example shows how to split a single dataset into two datasets, one used for training and the other used for testing.
Note that when splitting frames, H2O does not give an exact split. It’s designed to be efficient on big data using a probabilistic splitting method rather than an exact split. For example, when specifying a 0.75/0.25 split, H2O will produce a test/train split with an expected value of 0.75/0.25 rather than exactly 0.75/0.25. On small datasets, the sizes of the resulting splits will deviate from the expected value more than on big data, where they will be very close to exact.
library(h2o) h2o.init() # Import the prostate dataset prostate.hex <- h2o.importFile(path = "", destination_frame = "prostate.hex") print(dim(prostate.hex)) [1] 380 9 # Split dataset giving the training dataset 75% of the data prostate.split <- h2o.splitFrame(data=prostate.hex, ratios=0.75) print(dim(prostate.split[[1]])) [1] 291 9 print(dim(prostate.split[[2]])) [1] 89 9 # Create a training set from the 1st dataset in the split prostate.train <- prostate.split[[1]] # Create a testing set from the 2nd dataset in the split prostate.test <- prostate.split[[2]] # Generate a GLM model using the training dataset. x represesnts the predictor column, and y represents the target index. prostate.glm <- h2o.glm(y = "CAPSULE", x = c("AGE", "RACE", "PSA", "DCAPS"), training_frame=prostate.train, family="binomial", nfolds=10, alpha=0.5) # Predict using the GLM model and the testing dataset pred = h2o.predict(object=prostate.glm, newdata=prostate.test) # View a summary of the prediction with a probability of TRUE summary(pred$p1, exact_quantiles=TRUE) p1 Min. :0.1560 1st Qu.:0.2954 Median :0.3535 Mean :0.4111 3rd Qu.:0.4369 Max. :0.9989
import h2o from h2o.estimators.glm import H2OGeneralizedLinearEstimator h2o.init() # Import the prostate dataset prostate = "" prostate_df = h2o.import_file(path=prostate) # Split the data into Train/Test/Validation with Train having 70% and test and validation 15% each train,test,valid = prostate_df.split_frame(ratios=[.7, .15]) # Generate a GLM model using the training dataset glm_classifier = H2OGeneralizedLinearEstimator(family="binomial", nfolds=10, alpha=0.5) glm_classifier.train(y="CAPSULE", x=["AGE", "RACE", "PSA", "DCAPS"], training_frame=train) # Predict using the GLM model and the testing dataset predict = glm_classifier.predict(test) # View a summary of the prediction predict.head() predict p0 p1 --------- -------- -------- 1 0.366189 0.633811 1 0.351269 0.648731 1 0.69012 0.30988 0 0.762335 0.237665 1 0.680127 0.319873 1 0.687736 0.312264 1 0.676753 0.323247 1 0.685876 0.314124 1 0.707027 0.292973 0 0.74706 0.25294 [10 rows x 3 columns] | http://docs.h2o.ai/h2o/latest-stable/h2o-docs/data-munging/splitting-datasets.html | CC-MAIN-2019-26 | refinedweb | 459 | 54.49 |
.
>.
Warning: The code below uses a Rect based on the image size (m_FrameSize) to define the vignetting region. Depending on the architecture of your app this may be available directly where you're defining the filter, or indirectly from the source. This is discussed further in #How to use the filter.
// Instagram
black.R = 0;
black.G = 0;
black.B = 0;
// NOTE: How m_FrameSize is obtained depends on the architecture
Rect region = new Rect();
region.X = 0.1 * m_FrameSize.Width;
region.Y = 0.1 * m_FrameSize.Height;
region.Width = m_FrameSize.Width - (2 * region.X);
region.Height = m_FrameSize.Height - (2 * region.Y);
filters.Add(new VignettingFilter(1();
}
The recipe uses a Rect based on the image size (m_FrameSize) to define the vignetting region. In the code fragment above we have access to the source as a StreamImage, and so can get the ImageSize using the following asynchronous function call:
//Get image size from stream to use in vignetting. Note is asynchronous call.
ImageProviderInfo imageInformation = await StreamImage.GetInfoAsync();
Size m_FrameSize= imageInformation.ImageSize;
Depending on the application architecture it may be possible to get hold of frames directly. It is also possible to define vignetting without a region, and this might be an area for further exploration.
Testing the filter
The easiest way to test the recipes is to add them to the Test Apps for Viewing Custom Filters (Nokia Imaging SDK) (a fork of the Real Time Filter Demo). Simply to add the filter source above to both RealtimeFilterDemo and StaticFilterViewer test apps in their respective switch statements. You may also need to add the line:
using Windows.UI;
Note that the code for both test apps makes the frame size available as m_FrameSize (as used in the recipe snippets).
License
The code has been released with the standard MIT License.
Performance
This section lists the approximate frame rate range (in frames-per-second) obtained by using the recipe in the Test framework.
Gallery
-
-
-
-
- Hop LoFi Instagram.jpg
-
-
-
-
-
-
- | http://developer.nokia.com/community/wiki/Instagram_Lo-Fi_Filter_Recipe_-_Mk1_(Nokia_Imaging_SDK) | CC-MAIN-2014-49 | refinedweb | 325 | 57.67 |
19 May 15:36
Re: Poem extension revealing faults
From: Robert Murphy <mrandmrsmurphy@...>
Subject: Re: Poem extension revealing faults
Newsgroups: gmane.comp.web.wiki.semediawiki.devel
Date: 2008-05-19 13:36:45 GMT
Subject: Re: Poem extension revealing faults
Newsgroups: gmane.comp.web.wiki.semediawiki.devel
Date: 2008-05-19 13:36:45 GMT
Thanks, Markus. I'm glad to know I was dumb for not being able to figure out a way to do that. I think the way around it in my case involves using __NOFACTBOX__ and then making a query to extract the semantic data from the transcluded pages. I appreciate you looking into this. -Robert On Mon, May 19, 2008 at 6:16 AM, Markus Krötzsch <mak <at> aifb.uni-karlsruhe.de> wrote: > On Freitag, 16. Mai 2008, Robert Murphy wrote: >> Dear Developers, >> >> I have successfully installed the Poem extension >> () on my wiki and it >> has been running fine. However, I just discovered too faults with it, >> that I now think may be due to Semantic MediaWiki. >> >> First, on the talk pages of custom namespaces, use of the <poem> tag >> makes the error >> UNIQ583c33685170dbcd-poem-00000000-QINU >> (for an example, see >>) >>. >> >> Second, it makes the factbox right after the </poem>, in the middle of >> the page, and the values aren't on the page's main factbox, at the >> bottom. (see). >> >> While I know some PHP, I don't know the mediawiki framework well >> enough to know why either of these might be. I posed this question on >> the extension's page on mediawiki.org and got no reply. I wrote on >> the talk page of Poem's creator >> () and he suggested >> I contact Steve Sanberg (). >> His reply was: >> >> The UNIQ.. problem seems to be unrelated to the poem extension. >> Basically, the preprocessor hides XML-style tags with strings like >> that to prevent them from being treated as wikitext, then unhides them >> later on; something in the state of your parser must be getting messed >> up. I looked at your wiki, and I get the same result with poem, cite >> and nowiki. It's probably best to try disabling some extensions to see >> which one is causing that. I'm not sure about semantic mediawiki; I'd >> guess that it's using the wrong hook to detect when the page is ends, >> so the recursive parse triggers the fact box. That sounds like a bug >> in semantic mediawiki. -Steve Sanbeg (talk) 15:23, 15 May 2008 (UTC) >> >> I've disabled Cite to no avail. Now I can accept that the talk_page >> problem might be mine alone, but the factboxes (pl.) in the middle of >> the pages seems like a SMW error. > > The whole thing is due to the way MediaWiki works, and one cannot really blame > either SMW or Poem here. MediaWiki replaces certain parts of input text with > that "UNIQ..." stuff. This happens *before* any extension gets to see the > code -- i.e. extensions do not know what was there before (at least I do not > know how, and in any case it this stuff usually cannot be understood as > normal wiki text). Not only poem, but also <!--
...-->, <math>, and <nowiki> > are examples for that. See also bug 13011 > <> > > One way to improve the situation might be to have a parser function > {{#poem:... instead of a parser hook <poem> (similar to our #ask that > replaced <ask>). It is really the way in which MW processes <parserhooks> > that creates problems here. Parser functions return not UNIQ... but normal > wiki code, and that would be workable input for SMW. > > The other stuff (Factbox in page) happens for other reasons. The problem is > that SMW uses MW hooks during parsing, i.e. functions that the parser > triggers when parsing wiki articles. Unfortunately, MediaWiki uses more than > one parser, and any hook in the parser code is used by all of those. Thus, > whenever MediaWiki uses a second parser for some part of text, SMW will do > the same as if this text was the only input. I know of no way of detecting > whether SMW runs in a subparser or in the "real" parser. Normally, however, > subparsers are triggered before or after the main page was parsed, and no > semantic data is found then -- thus the Factbox is empty and remains hidden. > You can try __NOFACTBOX__ to not display the Factbox, or you can check > whether it suffices to avoid semantic annotations in certain environments. > > -- Markus > > -- > Markus Krötzsch > Institut AIFB, Universität Karlsruhe (TH), 76128 Karlsruhe > phone +49 (0)721 608 7362 fax +49 (0)721 608 5998 > mak <at> aifb.uni-karlsruhe.de www > -- -- Roses are red,Violets are blue,I'm schizophrenic,and so am I. ------------------------------------------------------------------------- This SF.net email is sponsored by: Microsoft Defy all challenges. Microsoft(R) Visual Studio 2008. _______________________________________________ Semediawiki-devel mailing list Semediawiki-devel <at> lists.sourceforge.net | http://permalink.gmane.org/gmane.comp.web.wiki.semediawiki.devel/788 | crawl-002 | refinedweb | 807 | 65.01 |
1265/selenium-testing-server-something-headless-browser-testing
Yes, you are indeed rigth. For Selenium WebDriver testing on servers or on machines where you do not have a GUI, use either HTMLUnit Driver or PhanthomJS driver. So you will have to similarly download the driver.exe from SeleniumHQ's website, provide the path in your code and most importantly import the required packages in your code. For python, you will do it something like this:
from selenium import webdriver
dr = webdriver.PhantomJS()
This is a flaw with ChromeDriver. Tried ...READ MORE
Along with the --headless option, you should ...READ MORE
Hello @Nishant, follow these steps to use ...READ MORE
Hey @Misha,
I'm guessing you've tried Selenium IDE already. ...READ MORE
OR
Already have an account? Sign in. | https://www.edureka.co/community/1265/selenium-testing-server-something-headless-browser-testing?show=1275 | CC-MAIN-2020-24 | refinedweb | 129 | 68.06 |
There simply are no other Crossword or
Word Search software programs on the market today that allow you to:
make your own puzzles
play them onscreen
and/or print them out
make your own puzzles
play them onscreen
and/or print them out
Our
version is XP & Vista compatible.
Works on Windows 95/98/Me and Mac 8/9 as well.
On Sale during May 2008
approximately 20% off!
See the
online order form
for sale pricing.
Each CD has a generous set
of ready-made Bible puzzles you can
PLAY ONSCREEN
or PRINT
out.
All puzzles are fully editable,
...or you can create your
own to play onscreen or print.
It's easy to do with the built-in
puzzle editor.
You're
in control. You can print puzzles with or without clues and word lists.
You can edit the ready-made puzzles, or create your own. You can change
the puzzle layout and complexity to serve your needs. You can select
from included Bible artwork or import your own.
Bible Crosswords and Word
Search CDs come with
Bible
artwork on the CD
which you can select to accompany
your puzzles onscreen or on the printout. You can also
import your own graphics.
You can create puzzles on
one computer, and easily copy them to another if it also has a copy of the
puzzle program installed. Or you can print them out.
How is this program being used?
$28 for one 2 CD set
(includes one copy of Bible Crosswords CD
and one copy of Bible Word Search CD)
$23 ea. for two to four
2 CD sets
$20 ea. for five or more
2 CD sets
$16.00 per set for 8 or more
Need some extra help working with the Editor and Puzzles?
This graphic above shows you some of the pop-up controls in
the puzzle editor. | http://www.sundaysoftware.com/wordgame.htm | crawl-001 | refinedweb | 312 | 83.66 |
You need to sign in to do that
Don't have an account?
namespace hands-on org
So are start doing some beginner trailheads and try a challenge but it won't let me use my dev org as it has a namespace (I was messing around with Lighning components a while back). So it lets me create a new hands-on org curious-racoon ... I do some beginning trailheads in that org. Then I do a Lightning Trailhead and it says to create a namespace so I do. The challenges in that Trailhead work fine. Then I go back to a beginner Trailhead and do a simple challenge to create two custom fields. The check fails. I strongly suspect it's because it's looking for a field with an API name Description__c but my field has an API Name, myNameSpace_Description__c.
Is there a way to have a hands-on org that's compatible with all Trailhead Modules?
Is there a way to have a hands-on org that's compatible with all Trailhead Modules?
When you have any trailhead modules with a namespace to be created in order to validate the challenge its always recommended to connect to a trailhead playground.Connecting a developer edition org would not be a good idea as there are other modules which don't need any namespace requirement. As namespace gets created for the org you will not be able to validate other trailhead challenges.So you need to create a new developer instance for the trailhead challenges in order to validate them.
Please let us know if you are looking for something else.
Thanks,
Nagendra. | https://developer.salesforce.com/forums/ForumsMain?id=9060G000000IBbHQAW | CC-MAIN-2021-04 | refinedweb | 274 | 71.85 |
Andrew Glover started writing about Groovy for developerWorks in 2004, starting with his introductory "Feeling Groovy" article in the alt.lang.jre series, and continuing with the long-running Practically Groovy series. That was before there was a single book on the market about Groovy (there are now more than a dozen), and years before the Groovy 1.0 release in January 2007. Much has changed since the last Practically Groovy installment was published in late 2006.
Groovy now averages roughly 35,000 downloads a month. Conservative companies like Mutual of Omaha have more than 70,000 lines of Groovy code in production. Groovy has one of the busiest mailing lists at Codehaus.org, where the project is hosted (see Resources). The only project that has more downloads and a busier mailing list is Grails, a popular Web framework implemented in Groovy (see Resources).
Running non-Java™ languages on the JVM is not only commonplace, it's a core part of Sun's strategy for the JVM. Groovy joins Sun-supported languages like JavaScript, JavaFX, JRuby, and Jython in the alternative-languages cavalcade. What was experimental in 2004 is now state-of-the-art.
Writing about Groovy in 2009 is, in many ways, much the same as it was when Andy started. The syntax stabilized in 2005 and remains the same today. New, compelling features are added with each release, but preserving backward compatibility is paramount to the project leaders. This solid foundation makes Groovy an easy choice for Java development shops that have come to rely on technologies that will be around for as long as their applications are in production.
This article aims to get experienced Java developers up to speed quickly as Groovy developers. Don't be fooled by its primer-ish aspect. This series, as its name implies, is all about practical uses for Groovy know-how. After you say "Hello, World" in this gentle beginning, prepare to enter the real world posthaste.
Installing Groovy
If you've never worked with Groovy before, the first thing you need to do is get it installed. The installation steps are pretty straightforward. They're the same steps you use to install common Java applications like Ant and Tomcat, and even the Java platform itself:
- Download the latest Groovy ZIP file or tarball.
- Unzip the archive to the directory of your choice. (You should avoid directories with spaces in the name.)
- Create a
GROOVY_HOMEenvironment variable.
- Add GROOVY_HOME/bin to the
PATH.
Groovy runs best on Java 5 or 6. Type
java -version at a command prompt to confirm that you are up-to-date. Then type
groovy -version to make sure that Groovy is properly installed.
All of the major IDEs (Eclipse, IntelliJ, and NetBeans) have a Groovy plug-in that supports features like autocomplete and step-debugging. Although a good IDE is almost a requirement for writing Java code these days, the same isn't necessarily true when it comes to Groovy. Thanks to the conciseness of the Groovy language, many people choose to use a simple text editor instead. Popular open source editors like vi and Emacs offer Groovy support, as do inexpensive commercial text editors like Textpad (for Windows®) and TextMate (for Mac OS X). (See Resources for more information.)
As you'll see later in the article, incorporating Groovy with an existing Java project is easy. All you need to do is add a single Groovy JAR from GROOVY_HOME/embeddable to the classpath and wrap the existing
javac Ant task in a
groovyc task. (Maven offers similar support.)
But before you get too far ahead of yourself, I'll start you off with the obligatory "Hello World" example.
Hello Groovy World
You know what a "Hello World" example is supposed to demonstrate — it's the simplest possible program that you can write in a given language. What's interesting about "Hello World" in Java code, shown in Listing 1, is how much intermediate language knowledge you need in order to understand fully what's going on:
Listing 1. A "Hello World" example written in Java code
public class HelloJavaWorld{ public static void main(String[] args){ System.out.println("Hello Java World"); } }
You start by creating a file named HelloJavaWorld.java and typing
public class HelloJavaWorld. The first hard lesson many beginning Java developers learn is that if the class name and file name don't match exactly (including upper- and lowercase), the class won't compile. Also, curious students begin asking about access modifiers like
public and
private at this point.
The next line —
public static void main(String[] args)— generally unleashes an avalanche of questions about implementation details: What is
static? What is
void? Why does the method need to be named
main? What is a
String array? And finally, try explaining to a first-time Java developer that
out is a
public,
static,
final instance of a
PrintStream object on the
System class. I'll never forget the student who said, "Sheesh! All I wanted to do was say 'Hello.'"
Contrast this with "Hello World" in Groovy. Create a file named HelloGroovyWorld.groovy and type the line shown in Listing 2:
Listing 2. A "Hello World" example written in Groovy
println "Hello Groovy World"
Yes, this is the equivalent in Groovy to the Java example in Listing 1. In this case, all of the implementation details — the "baggage" that doesn't immediately contribute to solving the problem at hand — fade into the background, leaving you with code that simply says, "Hello." Type
groovy HelloGroovyWorld to confirm that it works.
This trivial example demonstrates the twin value propositions of Groovy: it dramatically reduces the lines of code you need to write while it preserves the semantics of the Java equivalent. In the next section, you'll explore this idea further.
Digging deeper into Hello World
Experienced Java developers know that you must compile your code before it will run on the JVM. Yet, there doesn't appear to be a class file for the Groovy script anywhere. Does that mean that you can execute Groovy source code directly? The answer is, "Not really, but it sure looks that way, doesn't it?"
The Groovy interpreter compiles the source code in-memory before handing it off to the JVM. You can manually perform this step by typing
groovyc HelloGroovyWorld.groovy. However, if you try to run the resulting class using
java, you'll be greeted with the exception shown in Listing 3:
Listing 3. Trying to run a compiled Groovy class without the Groovy JAR on the
CLASSPATH
$ java HelloGroovyWorld Exception in thread "main" java.lang.NoClassDefFoundError: groovy/lang/Script
As I mentioned earlier, the Groovy JAR must be included in the
CLASSPATH. Try it again, this time passing in the
-classpath argument to
java, as shown in Listing 4:
Listing 4. Successfully running a compiled Groovy class with the
java command
//For UNIX, Linux, and Mac OS X $ java -classpath $GROOVY_HOME/embeddable/groovy-all-x.y.z.jar:. HelloGroovyWorld Hello Groovy World //For Windows $ java -classpath %GROOVY_HOME%/embeddable/groovy-all-x.y.z.jar;. HelloGroovyWorld Hello Groovy World
Now you're getting somewhere. But to prove that the Groovy script really is preserving the semantics of the Java example, you need to dig deeper into the bytecode. To start, type
javap HelloJavaWorld, as shown in Listing 5:
Listing 5. Examining the Java bytecode
$ javap HelloJavaWorld Compiled from "HelloJavaWorld.java" public class HelloJavaWorld extends java.lang.Object{ public HelloJavaWorld(); public static void main(java.lang.String[]); }
There shouldn't be too many surprises here, other than some of the niceties that the
javac compiler added on your behalf. You didn't need to type
extends java.lang.Object explicitly or provide a default constructor for the class.
Now, type
javap HelloGroovyWorld, as shown in Listing 6:
Listing 6. Examining the Groovy bytecode
$ javap HelloGroovyWorld Compiled from "HelloGroovyWorld.groovy" public class HelloGroovyWorld extends groovy.lang.Script{ ... public static void main(java.lang.String[]); ... }
Here, you can see that the
groovyc compiler took the name of your source file and created a class of the same name. (The fact that the class extends
groovy.lang.Script instead of
java.lang.Object should help you understand why trying to run the file without the Groovy JAR on the
CLASSPATH threw the
NoClassDefFoundError exception.) Amidst all of the other compiler-provided methods, you should be able to find a good old
public static void main(String[] args) method. The
groovyc compiler wrapped the lines of your script in this method to preserve Java semantics. This means that you can take advantage of all of your existing Java knowledge when it comes to Groovy.
For example, here's how you can accept command-line input in a Groovy script. Create a new file named Hello.groovy and add the line in Listing 7:
Listing 7. A Groovy script that accepts command-line input
println "Hello, " + args[0]
Now type
groovy Hello Jane from the command line. The
args
String array is there, as any Java developer would expect. Using
args here might not make sense to the uninitiated, but it makes perfect sense to seasoned Java developers.
Groovy boils Java code down to its bare essence. The Groovy script that you just wrote is almost like executable pseudocode. It is simple enough on the surface for novices to understand, but it doesn't strip away the underlying power of the Java language for experienced developers. This is what leads me to call Groovy a domain-specific language (DSL) for the Java platform. (See the "What is a DSL? sidebar.)
Plain Old Groovy Objects
JavaBeans — or more casually Plain Old Java Objects (POJOs) — are a mainstay of Java development. You should follow a well-defined set of expectations when you create a POJO to represent a domain object. The class should be
public, and the fields should be
private with a corresponding set of
public getter and setter methods. Listing 8 shows a typical Java POJO:
Listing 8. A Java POJO
public class JavaPerson{; } }
Plain Old Groovy Objects (POGOs) are a drop-in replacement for POJOs. They perfectly retain the semantics of the POJO while drastically reducing the amount of code you need to write. Listing 9 shows a "shorthand" person class written in Groovy:
Listing 9. A Groovy POGO
class GroovyPerson{ String firstName String lastName }
All classes in Groovy are
public unless you specify otherwise. All properties are
private, and all methods are
public. The compiler provides a set of
public getter and setter methods for each property automatically. Compile
JavaPerson with
javac and
GroovyPerson with
groovyc. Now run them both through
javap to confirm that the Groovy example has everything that the Java example does, right down to extending
java.lang.Object. (You didn't specify a class in the earlier
HelloGroovyWorld example, so Groovy created a class that extended
groovy.lang.Script instead.)
All of this means that you can immediately begin using POGOs as a replacement for your POJOs. The Groovy class is the Java class boiled down to its bare essence. Once the Groovy class is compiled, other Java classes can use it as easily as if it had been written in Java code. To prove this, create a file named JavaTest.java and add the code in Listing 10:
Listing 10. Calling Groovy classes from Java code
public class JavaTest{ public static void main(String[] args){ JavaPerson jp = new JavaPerson(); jp.setFirstName("John"); jp.setLastName("Doe"); System.out.println("Hello " + jp.getFirstName()); GroovyPerson gp = new GroovyPerson(); gp.setFirstName("Jane"); gp.setLastName("Smith"); System.out.println("Hello " + gp.getFirstName()); } }
Even though the getters and setters don't appear in the Groovy source code, this test proves that they are there and fully functional in the compiled Groovy class. But this example wouldn't be complete if I didn't show you the corresponding test in Groovy. Create a file named TestGroovy.groovy and add the code in Listing 11:
Listing 11. Calling Java classes from Groovy
JavaPerson jp = new JavaPerson(firstName:"John", lastName:"Doe") println "Greetings, " + jp.getFirstName() + ". It is a pleasure to make your acquaintance." GroovyPerson gp = new GroovyPerson(lastName:"Smith", firstName:"Jane") println "Howdy, ${gp.firstName}. How the heck are you?"
The first thing you probably notice is the new constructor that Groovy offers, allowing you to name the fields and specify them in any order you'd like. Even more interesting is the fact that you can use this constructor on either Java or Groovy classes. How is this possible? In reality, Groovy calls the default no-argument constructor first and then calls the appropriate setter for each field. You could approximate similar behavior in the Java language, but because the Java language lacks named arguments and both fields are
Strings, you can't pass in the first- and last-name fields in any order.
Next, notice that Groovy supports the traditional, Java way to do
String concatenation, as well as the Groovy way by embedding code surrounded by
${} directly in the
String. (These are called
GStrings, short for Groovy Strings.)
Finally, you see one more bit of Groovy syntactic sugar you can use when calling getters on a class. Instead of using the more verbose
gp.getFirstName(), you can simply call
gp.firstName. It may look like you are directly accessing the field, but in reality you are calling the corresponding getter method behind the scenes. Setters work the same way:
gp.setLastName("Jones") and
gp.lastName = "Jones" are equivalent, with the latter calling the former under the covers.
I expect that you'll agree that in each case, Groovy feels like a shorthand version of the Java language — one that "domain experts" might use to "communicate effectively with their peers," or something akin to casual banter among old friends.
Groovy is Java code at the end of the day
One of the most underappreciated aspects of Groovy is the fact that it fully supports Java syntax. As I mentioned earlier, you don't need to unlearn a bit of your Java knowledge when working with Groovy. When you are getting started with Groovy, much of your code will end up looking just like traditional Java code. But as you get more comfortable with the newer syntax, your code will gradually evolve to embrace the more concise, expressive Groovy style.
To prove that your Groovy code can look exactly like your Java code, copy JavaTest.java to JavaTestInGroovy.groovy, and type
groovy JavaTestInGroovy. You should see identical output, but notice that you didn't need to compile the Groovy class before running it.
This demonstration should make Groovy an almost no-brainer choice for experienced Java
developers. Because Java syntax is valid Groovy syntax as well, the initial learning curve is practically nonexistent. You can use your existing Java version with Groovy, your existing IDE, and your existing production environment. This means that the disruption to your daily routine is minimal. All you need to do is ensure that the Groovy JAR is somewhere on your
CLASSPATH and tweak your build script so that the Groovy classes are compiled along with the Java ones. The next section shows you how to add the
groovyc task to your Ant build.xml file.
Compiling Groovy code with Ant
If
javac were a pluggable compiler, you could instruct it to
compile both your Groovy and Java files at the same time. Because it's not, you can simply wrap the
javac task in Ant with a
groovyc task. This allows
groovyc to compile the Groovy source code, and
javac to compile the Java source code as it always did.
Of course,
groovyc can compile both Java and Groovy files, but remember the additional convenience methods that
groovyc added to
HelloGroovyWorld and
GroovyPerson? These additional methods would also be added to the Java classes. It's probably best to let
groovyc compile the Groovy files and let
javac compile the Java ones.
To call
groovyc from Ant, define the task using
taskdef and then use the
groovyc task as you would normally use the
javac task (see Resources for more information). Listing 12 shows the Ant build script:
Listing 12. Compiling Groovy and Java code with Ant
<taskdef name="groovyc" classname="org.codehaus.groovy.ant.Groovyc" classpathref="my.classpath"/> <groovyc srcdir="${testSourceDirectory}" destdir="${testClassesDirectory}"> <classpath> <pathelement path="${mainClassesDirectory}"/> <pathelement path="${testClassesDirectory}"/> <path refid="testPath"/> </classpath> <javac debug="on" /> </groovyc>
By the way, those
Strings with
${} inside them look suspiciously like
GStrings, don't they? Groovy is a best-of-breed language, shamelessly borrowing syntax and features from a variety of other languages and libraries. This isn't the last time you'll see something in Groovy that makes you say, "Hmm, haven't I seen that somewhere before?"
Conclusion
This has been a whirlwind tour of Groovy. You learned a bit about where Groovy has been and where it stands today. You got Groovy installed on your system, and through a couple of simple examples you caught just a glimpse of the power that Groovy offers Java developers.
Groovy isn't the only alternate language that runs on the JVM. JRuby is a great solution for Java developers who already know Ruby. Jython is a great solution for Java developers who already know Python. But as you saw, Groovy is a great solution for Java developers who already know the Java language. The fact that Groovy offers a concise Java-like syntax that also preserves Java semantics is pretty compelling. And, a new language whose path to adoption doesn't involve
del *.* or
rm -Rf * is a nice change, wouldn't you say?
Next time, you'll learn about iteration in Groovy. Your code often needs to walk through things item by item, whether it's a list, a file, or an XML document. You'll see the pervasive
each closure up close. Until then, I hope that you find plenty of practical uses for Groovy.
Resources
Learn
- Groovy: Learn more about Groovy at the project Web site.
-.
- Groovy stats: Check out download statistics for Groovy and Grails.
- Groovy mailing list: Browse, search, or subscribe to the Groovy mailing list.
- Groovy IDE Support: Read about IDEs and text editors that support Groovy.
- Using Domain Specific Languages: Find out what Martin Fowler has to say about DSLs.
- "The 'Language' in Domain-Specific Language Doesn't Mean English (or French, or Japanese, or ...)" (Dave Thomas, PragDave, March 2008): DSL fan Thomas weighs in.
- The
groovycAnt Task: Learn more about using Ant to compile Groovy code.
- Technology bookstore: Browse. | http://www.ibm.com/developerworks/library/j-pg02179/ | CC-MAIN-2015-06 | refinedweb | 3,090 | 64.91 |
.
First, watch the video intro below
Project Overview.
Parts Required
Here’s a list of the required components for this project:
- Arduino UNO – read Best Arduino Starter Kits
- MFRC522 RFID reader + tags
- SD card module
- Micro SD card
- SD1307 RTC module
- 2x LEDs (1x red + 1x green)
- 2x 220 Ohm resistor
- Breadboard
- Jumper wires
You can use the preceding links or go directly to MakerAdvisor.com/tools to find all the parts for your projects at the best price!
MFRC522 RFID Reader
In this project we’re using the MFRC522 RFID reader and that’s the one we recommend you to get (although this project may also be compatible with other RFID readers).
RFID means radio-frequency identification. RFID uses electromagnetic fields to transfer data over short distances and it’s useful to identify people, to make transactions, etc.
An RFID system needs tags and a reader:
- Tags are attached to the object to be identified, in this example we have a keychain and an electromagnetic card. Some stores also use RFID tags in their products’ labels to identify them. Each tag has its own unique identification (UID).
- Reader is a two-way radio transmitter-receiver that sends a signal to the tag and reads its response.
.
To learn more about the RFID reader with the Arduino read: Security Access using MFRC522 RFID Reader with Arduino
Installing the MFRC522 library
This project uses the MFRC522.h library to control the RFID reader. This library doesn’t come installed in Arduino IDE by default, so you need to install it. Go to Sketch > Include library > Manage libraries and search for MFRC522 or follow the next steps:
- Click here to download the MFRC522 library. You should have a .zip folder in your Downloads folder.
- Unzip the .zip folder and you should get RFID-master folder
- Rename your folder from
RFID-masterto RFID
- Move the RFID folder to your Arduino IDE installation libraries folder
- Finally, re-open your Arduino IDE
MFRC522 RFID reader pinout
The following table shows the reader pinout for a future reference:
Note: different Arduino boards have different SPI pins. If you’re using another Arduino board, check the Arduino documentation.
SD card module
When a tag is read, its UID and time are saved on an SD card so that you can keep track of check ins. There are different ways to use an SD card with the Arduino. In this project we’re using the SD card module shown in figure below – it works with micro SD card.
There are different models from different suppliers, but they all work in a similar way, using the SPI communication protocol. To communicate with the SD card we’re going to use a library called SD.h, that comes already installed in Arduino IDE by default.
To learn more about the SD card module with the Arduino read: Guide to SD Card Module with Arduino
SD card module pinout
The following table shows the SD card module pinout for a future reference:
Note: different Arduino boards have different SPI pins. If you’re using another Arduino board, check the Arduino.
2) A new window pops up. Select FAT32, press Start to initialize the formatting process and follow the onscreen instructions.
Testing the SD card module
(This step is optional. This is an additional step to make sure the SD card module is working properly.)
Insert the formatted SD card in the SD card module.
Connect the SD card module to the Arduino as shown in the circuit schematics below or check the pinout table.
Note: depending on the module you’re using, the pins may be placed in a different location.
Uploading CardInfo sketch the SD card information will be displayed. If everything is working properly you’ll see a similar message on the serial monitor.
RTC (Real Time Clock) module
To keep track of time, we’re using the SD1307 RTC module. However, this project works just fine with the DS3231, which is very similar. One main difference between them is the accuracy. The DS3231 is much more accurate than the DS1307. The figure below shows the SD1307 model.
The module has a backup battery installed. This allows the module to retain the time, even when it’s not being powered up.
This module uses I2C communication and we’ll use the RTCLib.h library to read the time from the RTC.
To learn more about the DS1307 real time clock with the Arduino read: Guide for Real Time Clock (RTC) Module with Arduino (DS1307 and DS3231)
RTC module pinout
The following table shows the RTC module pinout for a future reference:
Note: different Arduino boards have different I2C pins. If you’re using another Arduino board, check the Arduino documentation.
Installing the RTCLib library
To install the RTCLib.h go to Sketch > Include library > Manage libraries and search for RTCLib or follow the next steps:
- Click here to download the RTCLib library. You should have a .zip folder in your Downloads folder.
- Unzip the .zip folder and you should get RTCLib-master folder
- Rename your folder from
RTCLib-masterto RTCLib
- Move the RTCLib folder to your Arduino IDE installation libraries folder
- Finally, re-open your Arduino IDE
Schematics
The circuit for this project is shown in the circuit schematics below.
In this circuit there are 3.3V and 5V devices, make sure you wire them correctly. Also, if you’re using different modules, check the recommend voltage before powering the circuit. Wire one module at a time and follow the pinout tables if needed.
Here’s how your circuit should look like after assembling.
Code
Upload the following code to your Arduino. Make sure you have the right Board and COM Port selected.
/* * Rui Santos * Complete Project Details */ #include <MFRC522.h> // for the RFID #include <SPI.h> // for the RFID and SD card module #include <SD.h> // for the SD card #include <RTClib.h> // for the RTC // define pins for RFID #define CS_RFID 10 #define RST_RFID 9 // define select pin for SD card module #define CS_SD 4 // Create a file to store the data File myFile; // Instance of the class for RFID MFRC522 rfid(CS_RFID, RST_RFID); // Variable to hold the tag's UID String uidString; // Instance of the class for RTC RTC_DS1307 rtc; // Define check in time const int checkInHour = 9; const int checkInMinute = 5; //Variable to hold user check in int userCheckInHour; int userCheckInMinute; // Pins for LEDs and buzzer const int redLED = 6; const int greenLED = 7; const int buzzer = 5; void setup() { // Set LEDs and buzzer as outputs pinMode(redLED, OUTPUT); pinMode(greenLED, OUTPUT); pinMode(buzzer, OUTPUT); // Init Serial port Serial.begin(9600); while(!Serial); // for Leonardo/Micro/Zero // Init SPI bus SPI.begin(); // Init MFRC522 rfid.PCD_Init(); // Setup for the SD card Serial.print("Initializing SD card..."); if(!SD.begin(CS_SD)) { Serial.println("initialization failed!"); return; } Serial.println("initialization done."); // Setup for the RTC if(!rtc.begin()) { Serial.println("Couldn't find RTC"); while(1); } else { // following line sets the RTC to the date & time this sketch was compiled rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); } if(!rtc.isrunning()) { Serial.println("RTC is NOT running!"); } } void loop() { //look for new cards if(rfid.PICC_IsNewCardPresent()) { readRFID(); logCard(); verifyCheckIn(); } delay(10); } void readRFID() { rfid.PICC_ReadCardSerial(); Serial.print("Tag UID: "); uidString = String(rfid.uid.uidByte[0]) + " " + String(rfid.uid.uidByte[1]) + " " + String(rfid.uid.uidByte[2]) + " " + String(rfid.uid.uidByte[3]); Serial.println(uidString); // Sound the buzzer when a card is read tone(buzzer, 2000); delay(100); noTone(buzzer); delay(100); } void logCard() { // Enables SD card chip select pin digitalWrite(CS_SD,LOW); // Open file myFile=SD.open("DATA.txt", FILE_WRITE); // If the file opened ok, write to it if (myFile) { Serial.println("File opened ok"); myFile.print(uidString); myFile.print(", "); // Save time on SD card DateTime now = rtc.now(); myFile.print(now.year(), DEC); myFile.print('/'); myFile.print(now.month(), DEC); myFile.print('/'); myFile.print(now.day(), DEC); myFile.print(','); myFile.print(now.hour(), DEC); myFile.print(':'); myFile.println(now.minute(), DEC); // Print time on Serial monitor Serial.print(now.year(), DEC); Serial.print('/'); Serial.print(now.month(), DEC); Serial.print('/'); Serial.print(now.day(), DEC); Serial.print(' '); Serial.print(now.hour(), DEC); Serial.print(':'); Serial.println(now.minute(), DEC); Serial.println("sucessfully written on SD card"); myFile.close(); // Save check in time; userCheckInHour = now.hour(); userCheckInMinute = now.minute(); } else { Serial.println("error opening data.txt"); } // Disables SD card chip select pin digitalWrite(CS_SD,HIGH); } void verifyCheckIn(){ if((userCheckInHour < checkInHour)||((userCheckInHour==checkInHour) && (userCheckInMinute <= checkInMinute))){ digitalWrite(greenLED, HIGH); delay(2000); digitalWrite(greenLED,LOW); Serial.println("You're welcome!"); } else{ digitalWrite(redLED, HIGH); delay(2000); digitalWrite(redLED,LOW); Serial.println("You are late..."); } }
Note: double-check that you have the needed libraries installed.
Importing libraries
The code starts by importing the needed libraries. The MFRC522 for the RFID reader, the SD for the SD card module and the RTClib for the RTC. You also include the SPI library for SPI communication with the RFID and SD card module.
#include <MFRC522.h> // for the RFID #include <SPI.h> // for the RFID and SD card module #include <SD.h> // for the SD card #include <RTClib.h> // for the RTC
Preparing RFID reader, SD card and RTC
Then, you define the pins for the RFID reader and the SD card module. For the RFID, the SCK pin (CS_RFID) is connected to pin 10 and the RST pin (RST_RFID) is connected to pin 9. For the SD card module, the Chip Select pin (CS_SD) is connected to pin 4.
// define pins for RFID #define CS_RFID 10 #define RST_RFID 9 // define chip select pin for SD card module #define CS_SD 4
You create a File called myFile to store your data.
File myFile;
Then, you create an instance for the RFID and for the RTC:
// Instance of the class for RFID MFRC522 rfid(CS_RFID, RST_RFID); // Instance of the class for RTC RTC_DS1307 rtc;
Variables
You create a string variable uidString that holds the UID tags.
String uidString;
The following lines create variables to define the check in time hour and minute. In this case, we’re defining the check in hour to 9h05m AM. You can change the check in time by changing these values:
// Define check in time const int checkInHour = 9; const int checkInMinute = 5;
You also need to create variables to hold the user’s check in hour. These variables will save the hour a certain UID tag was read. The following variables hold the check in hour and the check in minute.
//Variable to hold user check in int userCheckInHour; int userCheckInMinute;
Finally you attribute the pin numbers to the LEDs and buzzer.
// Pins for LEDs and buzzer const int redLED = 6; const int greenLED = 7; const int buzzer = 5;
setup()
Next, in the setup() you set the LEDs and buzzer as outputs.
// Set LEDs and buzzer as outputs pinMode(redLED, OUTPUT); pinMode(greenLED, OUTPUT); pinMode(buzzer, OUTPUT);
After that, each module is initialed.
Functions
In this code you create 3 functions: readRFID(), logCard() and verifyCheckIn().
The readRFID() function reads the tag UID, saves it in the uidString variable and displays it on the serial monitor. Also, when it reads the tag, the buzzer makes a beep sound.
The logCard() function creates a file on your SD card called DATA.txt. You can edit the name of the file, if you want, on the following line.
myFile=SD.open("DATA.txt", FILE_WRITE);
Then, it saves the uidString (that holds the UID of the tag) on the SD card and the current time.
myFile.print(uidString);
// Save time on SD card DateTime now = rtc.now(); myFile.print(now.year(), DEC); myFile.print('/'); myFile.print(now.month(), DEC); myFile.print('/'); myFile.print(now.day(), DEC); myFile.print(','); myFile.print(now.hour(), DEC); myFile.print(':'); myFile.print(now.minute(), DEC);
It also saves the user check In hour and minute in the following variables for further comparison with the predefined check in time.
userCheckInHour = now.hour(); userCheckInMinute = now.minute();
The verifyCheckIn() function simply compares the user check in time with the predefined check in hour and gives feedback accordingly. If the user is late, the red LED lights up; if the user is on time, the green LED lights up.
loop()
After studying the created functions, the loop() is pretty straightforward to understand.
First, the code checks if an RFID tag was swiped. If yes, it will read the RFID UID, log the UID and the time into the SD card, and then it will give feedback to the user by lighting up one of the LEDs.
Grabbing the SD Card data
To check the data saved on the SD card, remove it from the SD card module and insert it on your computer.
Open the SD card folder and you should have a file called DATA.txt.
Open the file using a text editor. You’ll have something as follows:
Notice that each value is separated by commas. This makes it easier if you want to import this data to Excel, Google Sheets, or other data processing software.
Wrapping up
In this project you’ve learned how to use an RFID card reader and the SD card module with Arduino. You can modify this project to your own needs or you can use the functions created here in other projects that require data logging or reading RFID tags.
You can take this project further and add a display to give extra feedback to the user. You can associate a name with each UID and display the user name when the tag is read. You may want to take a look at some tutorials with the Arduino using displays:
This is an excerpt from our course “Arduino Step-by-step Projects“. If you like Arduino and you want to make more projects, we recommend downloading our course: Arduino Step-by-step Projects.
46 thoughts on “Arduino Time Attendance System with RFID”
how to send or save data to mysql server? thank you very much
Hi Abu,
Thanks for the project suggestion and I’ll try to make something like that in the future.
Regards,
Rui
Nice tutorial, an enhancement would be to do this with a ES8266 or ESP32 and send data direkt o a Database
Thanks for the project suggestion Rainer!
Good day. We have a project like that but inour project we have a Mobile application. May i ask how to conect it to Arduino?
Hi. We don’t have any specific project with that.
But we have some tutorials with Arduino and MIT App Inventor that can get you started build mobile applications to connect with Arduino.
You can get started with the following article:
I hope this helps,
Regards,
Sara 🙂
good
There is a problem in the schematic and article. This will only work we connect a 330-ohm resistor from MISO of RFID to MISO of SD card, otherwise, we are getting the SD card initialization error.
Hi.
Our project worked just fine as it is (at least for us). Maybe you’re using another sd card module or something. But thank you for sharing your solution, it can help others with the same problem.
Regards,
Sara 🙂
Can you share your schema and code pls? i connect a 330-ohm resistor like you say and nothing happend just error to initialize the SD card
Can you plz tell me a code for RTC DS3231. This code is not working properly for me.
Hi.
What do you mean?
Do you get any errors on the serial monitor?
Yes its only say that SD card initialization done and nothing happens
same error for me also plz help
Hi! How do i directly send data to database? Thank you so much!
Unfortunately I don’t have any tutorials on that exact subject.
Thanks for asking. Regards,
Rui
HI,
I HAVE DS3231 RTC, KINDLY LET ME KNOW THE CHANGE WHICH I HAVE TO MAKE IN THIS CODE..OR KINDLY POST THE COMPLETE CODE WITH DS3231.
Hi.
I think you just need to replace line 27 on the code (github.com/RuiSantosdotme/Arduino-Projects/blob/master/code/25_Time_Attendance_System_with_RFID.ino) with the following:
RTC_DS3231 rtc;
I haven’t tested this. If it doesn’t work and you need more information on how to make it work with the DS3231 RTC, take a look at the following code:
github.com/adafruit/RTClib/blob/master/examples/ds3231/ds3231.ino
or this tutorial:
Regards,
Sara
i have 5v sd card module , it is not working with rfid , kindly help
What do you mean by “it is not working with rfid”?
Regards,
Sara
Same problem, with 5v sd after “initialization done.” the RFID-module does not read the rfid tags
Hi, I have the same problem. Any solutions?
Im having the same issue. The serial monitor shows the SD card initializing but the RFID module will not read the UIDS. I also have 5v SD card and a 3.3 RFID card. Spent 2 days troubleshooting
Hi.
What are the exact components you are using?
The project works just fine for me. Maybe the newer modules are a bit different?
Hi,
i had se same problem with my project, it helped in my case to put a 330 ohm resistor between MISO RFID and MISO SD, as Surya Saini suggested
Hii, may I know how can I use LCD Display in this project?? please kindly reply
Hi.
This tutorial can be integrated with the LCD.
However, we don’t have any tutorial about that subject.
Regards,
Sara
Hi, thank you so much for sharing this project! My question is how much would it cost to buy all the required parts for this solution ?
Hi.
It really depends on where you get your parts from.
You can click the links on the Parts Required section and compare the prices on several stores like Amazon, ebay, aliexpress, Banggood, etc…
Or you can go to Maker Advisor tools to compare the prices.
Regards,
Sara 🙂
SD card initialization failed. is there a workaround without using a 330-ohm resistor?
Hi.
I’ve tested this project again and it works great with my SD card module.
Which SD card module are you using?
I’m using this one, as shown in this image: and it works great.
Maybe there are some incompatibilities with your SD card module.
Besides that error, are you getting other errors?
Regards,
Sara
I have the same situation, just show “initialization failed!” , somebody help me
Hi Andrew.
Which SD card module are you using?
Hi, I’m having problems to test the circuit. I am using a 5v SD card module, when I run de program the initializaction works but after that it doesn´t reads or whites anything. Do you know why?
Hi Giovanna.
Do you get any errors on the serial monitor?
Is your RFID reader working properly? If it doesn’t read properly, the microSD card will not be written.
I want to do something similar but just to know who is IN or OUT and time stamps. (In case of emergencies I need proper head count.)
I want to link 2 of these and be able to view logs remotely like ssh ir something. Can this be done with arduino or should I lean towards raspberry pi?
Hi.
It really depends on your project requirements. But taking into account what you’ve described, I would recommend a Raspberry Pi.
But it will depend on the functionalities you want in your project.
Regards,
Sara
Thanks for your sharing. I dont know why my RC522 not working together with SD card module.
What is the error that you are getting?
“Initializing SD card…initialization done” but RFID read nothing. RFID just read when i removed SD card module.
I use Catalex MicroSD card adapter, and it only works with 5V DC.
Hi all!
I was working on this project on my own, and after getting lost with the Slave Selection I decided to give a try to this one.
Here is my feedback:
1/ Problem: My SD card system sent me “initialisation failed” Solution: It worked after I formated the card and power it with 5V. Even if written 3.3V.
I have the CATALEX micro SD Card Adapter V1.0 11/01/13.
I heard that All SD Card modul can/should be plugged on 5V as they have stepdown integrated and may not work on 3.3V.
2/ I am using the DS3231 Problem: THere is not “is running” in the lib. So I replaced “RTC_DS1307 rtc;” by “RTC_DS3231 rtc;” and ” if(!rtc.isrunning()) {
Serial.println(“RTC is NOT running!”);
}” by /*if(!rtc.isrunning()) {
Serial.println(“RTC is NOT running!”);
}*/
3/ Problem, I get in void look (I added a srial print to see if i am in:
void loop() {
Serial.println(“Here 3”);
//look for new cards
and… I am in but my RFID module don’t detect my card. So I guess there is probable a problem with the Slave selection. I am Using a NanoV3.
I am stuck here. If you have a hint for me It’s welcome
Hi Elias.
Thank you for your feedback.
It can be helpful for other readers.
I think you’ve already found the answer for your problem. Thank you so much for sharing.
Regards,
Sara
Hey,
Ive the same problem. I’ve connected sd card to 5V but still “initialization failed!” and my rfid mfrs522 cant detect.
For RTClib.h it worked after changed to “RTC_DS3231 rtc.”
Hey,
I got it working by adding a 330Ohm between the SDCard Reader Miso and the Arduino 12 Pin. The RFID still is connected to 12 without Resistor.
Would be good to get feedbak from you all Nerds about this 🙂
Cheers!
hello ,
elias it’s work thank you
nerd 1
Hello,
I connected 3.3K resistor between SD card MISO and MISO of MEGA,but still not detecting card.
Your help will be appreciated! | https://randomnerdtutorials.com/arduino-time-attendance-system-with-rfid/?replytocom=359834 | CC-MAIN-2021-31 | refinedweb | 3,654 | 66.23 |
Created on 2008-01-09 23:19 by AchimGaedke, last changed 2010-09-21 03:03 by benjamin.peterson.
The value SyntaxError.offset is for most SyntaxErrors an offset from
beginning of line SyntaxError.lineno. In case of an triple-quoted string
which is not at all closed, offset seems to be the offset from beginning
of the buffer.
sometimes offset is None...
Example:
def blub(bla, blub=None, blabla):
bla
causes:
non-default argument follows default argument
Confirmed in trunk and py3k.
This will go nowhere until someone supplies a patch. I'm assuming unit tests can be built using the attached test file.
None offsets gone in r84931. | http://bugs.python.org/issue1778 | crawl-003 | refinedweb | 110 | 60.61 |
Problem Statement
Suppose you have an array of integers of size n. The problem statement asks to find out the minimum number of subsets with distinct elements, that is subsets that can be formed which contain all the different/distinct elements from the array.
Example
arr[] = {2,4,6,2,1,4,2}
3
Explanation: {1, 2, 4, 6}, {2, 4} and {2} can be the subsets.
arr[] = {2,5,6,7,5,4,2}
3
Explanation: {2, 5, 6, 7} and {2, 4} can be the two subsets.
Algorithm to find the minimum number of subsets with distinct elements
1. Declare a map and count and store the frequency of each element of the array into the map. 2. Set output to 0. 3. Traverse the map and find out the maximum between the output and each value of key in the map and store it into the output. 4. Return the value of output.
Explanation
We have given an integer array in which positive numbers are stored. We have asked to find out the count of minimum possible subsets that can be formed from the given array and has all distinct elements in the subset. For this we are going to use Hashing, Hashing provides an efficient solution in which we can achieve good time complexity instead of a naive approach.
We are going to declare a map, count, and store the frequencies of each element of an array. If we have a new entry in a map for some element we make a place for it and for the next time if the same element occurs we will just get that value and increase its frequency by 1. In C++, it itself picks up the element and then we just perform increment operation but in java, we to check for that element in particular. We are storing up the count of frequencies because we are going to find out the maximum frequency among all the elements and results in our answer.
We will set the output to 0, and then we will traverse the map in which we have stored the frequencies of each element. With this, we need not sort the array because with the map we have the elements inside it already sorted. We will pick up each element and get its frequency and compare it with the output. We need to find out the maximum of those two values, the output, and the frequency of picked elements. And that is the required answer to find minimum number of subsets with distinct elements.
Code to find the minimum number of subsets with distinct elements
C++ code
#include <iostream> #include<unordered_map> using namespace std; int getMinSubset(int arr[], int n) { unordered_map<int, int> mp; for (int i = 0; i < n; i++) mp[arr[i]]++; int output = 0; for (auto x : mp) output = max(output, x.second); return output; } int main() { int arr[] = {2,4,6,2,1,4,2}; int n = sizeof(arr) / sizeof(arr[0]); cout << getMinSubset(arr, n); return 0; }
3
Java Code
import java.util.HashMap; import java.util.Map; class MinimumSubsets { public static int getMinSubset(int arr[], int n) { HashMap<Integer, Integer> mp = new HashMap<>(); for (int i = 0; i < n; i++) mp.put(arr[i],mp.get(arr[i]) == null?1:mp.get(arr[i])+1); int output = 0; for (Map.Entry<Integer,Integer> entry : mp.entrySet()) output = Math.max(output, entry.getValue()); return output; } public static void main(String[] args) { int arr[] = { 2,4,6,2,1,4,2}; int n = arr.length; System.out.println( getMinSubset(arr, n)); } }
3
Complexity Analysis
Time Complexity
Here, we have used unordered_map or hash map which makes insertion, deletion, and updation in O(1). Thus, we have a linear complexity of O(n) where “n” is the number of elements in the array.
Space Complexity
Since we are storing key and value pairs, so at max, there will be n pairs that give us O(n) space complexity where “n” is the number of elements in the array. Thus we can say algorithm to find minimum number of subsets with distinct elements has linear space complexity solution. | https://www.tutorialcup.com/interview/hashing/minimum-number-of-subsets-with-distinct-elements.htm | CC-MAIN-2021-49 | refinedweb | 694 | 60.75 |
From: Jens Maurer (Jens.Maurer_at_[hidden])
Date: 2004-12-31 10:51:14
Doug Gregor wrote:
> I'm having a few problems dealing with uniform_real and uniform_01.
>
> The basic issue is that uniform_real does not always produce values
> between its min and its max.
uniform_real was meant to be used with variate_generate<> only.
Reviewing the language in the ISO C++ TR draft seems to miss
one requirement: That the Engine used as input for uniform_real()
always returns numbers in the range [0..1[, if floating-point numbers
are requested. This is one of the features of variate_generate<>:
it wraps the original Engine so that this is always the case.
Note that the current ISO C++ TR draft already requires
that the input Engine produce numbers of the "correct" type
(floating-point or integer).
> Looking at the source to uniform_real, the problem is obvious:
>
> result_type operator()(Engine& eng) { return eng() * (_max - _min) +
> _min; }
Yes. Fixed.
> However, uniform_01 is also broken in several ways:
uniform_01, at this time, is just an implementation helper
for variate_generator<> and thus should move to the details
namespace ASAP. Since it's hideously broken for general
use right now, I'm inclined to perform the move without
any deprecation period.
Jens Maurer
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/2004/12/78254.php | CC-MAIN-2021-21 | refinedweb | 227 | 57.37 |
camelCase is a string whose second word’s starting letter is Capital, Example is employeeList.
This is a short tutorial on Converting camelCase to/from hyphen in JavaScript.
you can
For example, given a string is employeeList, Output converted to dashes. i.e employee-list. so, we have to split the camel case string into words and replace the second word onwards with a hyphen, and update the first letter to a small case.
You can check my other tutorials on string case conversion.
Convert camelCase to hyphens in JavaScript
Following are multiple ways that can be implemented to do the conversion in JavaScript/typescript.
using regular expression
Regular expressions to split into words and convert the first letter of each word into small cases except the first string.
let str = 'employeeListOne'; console.log(str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase());
Output:
employee-list-one
param-case npm library
Instead of writing custom logic for this, we can use the
param-case npm package to do the conversion. It is a very popular package and the most downloaded utility in NodeJS projects.
You can use it in Angular,React, Vuejs applications for camel case to hyphen case.
First, Install the package using the npm command.
npm install param-case --save
you can import the
paramCase class as follows
In javascript,
const paramCase=require("param-case");
In typescript
import { paramCase } from "param-case";
you can see pass string to paramCase class as follows
paramCase("emptyString"); //=> "empty-string" paramCase("twoWords"); //=> "two-words"
Convert Hyphen to camelcase in javascript
For example, given input string is in the dashed string,
array-list and output is in camel case. i.e ArrayList.
lodash camelCase method
camelCase is a simple utility method in lodash library that converts given dashed or space string converts into camelcase. Syntax:
camelCase(string)
The input parameter is a string output is the string returned in camelCase
var dashString = 'array-list'; result = _.camelCase(dashString); // arrayList | https://www.cloudhadoop.com/javascript-camel-hyphen/ | CC-MAIN-2022-21 | refinedweb | 327 | 51.68 |
Qt Quick 3D QML Types
This is the QML frontend for using the spatial renderer and scenegraph. For the time being, all 3D content goes through offscreen textures (FBO)s so that they can be composed into Qt Quick scenes (as a QQuickItem).
Qt Quick 3D provides the following QML types:
QtQuick3D QML Types
Import the QtQuick3D module with the following statement:
import QtQuick3D 1.14
QtQuick3D.Materials QML Types
Import the QtQuick3D.Materials module with the following statement:
import QtQuick3D.Materials 1.14
QtQuick3D.Helpers QML Types
Import the QtQuick3D.Helpers module with the following statement:
import QtQuick3D.Helpers 1. | https://doc.qt.io/qt-5.14/qtquick3d-qmlmodule.html | CC-MAIN-2021-04 | refinedweb | 101 | 58.18 |
Idiomatic Ruby: writing beautiful code
TK
Dec 4 '18
・1 min read
Ruby is a beautiful programming language.
According to Ruby’s official web page, Ruby is a:
“dynamic, open source programming language with a focus on simplicity and productivity. It has an elegant syntax that is natural to read and easy to write.”
Ruby was created by Yukihiro Matsumoto, a Japanese software engineer. Since 2011, he has been the chief designer & software engineer for Ruby at Heroku.
Matsumoto has often said that he tries to make Ruby natural, not simple, in a way that mirrors life.
“Ruby is simple in appearance, but is very complex inside, just like our human body” — Yukihiro Matsumoto
I feel the same way about Ruby. It is a complex but very natural programming language, with a beautiful and intuitive syntax.
With more intuitive and faster code, we are able to build better software. In this post, I will show you how I express my thoughts (aka code) with Ruby, by using snippets of code.
Expressing my thoughts with array methods
Map
Use the map method to simplify your code and get what you want.
The method map returns a new array with the results of running a block once for every element in enum.
Let’s try it:
an_array.map { |element| element * element }
Simple as that.
But when you begin coding with Ruby, it is easy to always use the each iterator.
The each iterator as shown below
user_ids = [] users.each { |user| user_ids << user.id }
Can be simplified with map in a single beautiful line of code:
user_ids = users.map { |user| user.id }
Or even better (and faster):
user_ids = users.map(&:id)
And when you’re used to coding with map, sometimes your code can be like this:
even_numbers = [1, 2, 3, 4, 5].map { |element| element if element.even? } # [ni, 2, nil, 4, nil] even_numbers = even_numbers.compact # [2, 4]
nil object as well. Use the compact method to remove all nil objects.
And ta-da, you’ve selected all the even numbers.
Mission accomplished.
Come on, we can do better than this! Did you hear about the select method from enumerable module?
[1, 2, 3, 4, 5].select { |element| element.even? }
Just one line. Simple code. Easy to understand.
Bonus
[1, 2, 3, 4, 5].select(&:even?)
Sample
Imagine that you need to get a random element from an array. You just started learning Ruby, so your first thought will be, “Let’s use the random method,” and that’s what happens:
[1, 2, 3][rand(3)]
Well, we can understand the code, but I’m not sure if it is good enough. And what if we use the shuffle method?
[1, 2, 3].shuffle.first
Hmm. I actually prefer to use shuffle over rand. But when I discovered the sample method, it made so much more sense:
[1, 2, 3].sample
Really, really simple.
Pretty natural and intuitive. We ask a sample from an array and the method returns it. Now I’m happy.
What about you?
Expressing my thoughts with Ruby syntax
As I mentioned before, I love the way Ruby lets me code. It’s really natural for me. I’ll show parts of the beautiful Ruby syntax.
Implicit return
Any statement in Ruby returns the value of the last evaluated expression. A simple example is the **getter **method. We call a method and expect some value in return.
Let’s see:
def get_user_ids(users) return users.map(&:id) end
But as we know, Ruby always returns the last evaluated expression. Why use the return statement?
def get_user_ids(users) users.map(&:id) end
After using Ruby for 3 years, I feel great using almost every method without the return statement.
Multiple assignments
Ruby allows me to assign multiple variables at the same time. When you begin, you may be coding like this:
def values [1, 2, 3] end one = values[0] two = values[1] three = values[2]
But why not assign multiple variables at the same time?
def values [1, 2, 3] end one, two, three = values
Pretty awesome.
Methods that ask questions (also called predicates)
One feature that caught my attention when I was learning Ruby was the question mark (?) method, also called the **predicates **methods. It was weird to see at first, but now it makes so much sense. You can write code like this:
movie.awesome # => true
Ok… nothing wrong with that. But let’s use the question mark:
movie.awesome? # => true
This code is much more expressive, and I expect the method’s answer to return either a true or false value.
A method that I commonly use is any? It’s like asking an array if it has anything inside it.
[].any? # => false [1, 2, 3].any? # => true
Interpolation
For me string interpolation is more intuitive than string concatenation. Period. Let’s see it in action.
An example of a string concatenation:
programming_language = "Ruby" programming_language + " is a beautiful programming_language" # => "Ruby is a beautiful programming_language"
An example of a string interpolation:
programming_language = "Ruby" "#{programming_language} is a beautiful programming_language" # => "Ruby is a beautiful programming_language"
I prefer string interpolation.
What do you think?
The if statement
I like to use the if statement:
def hey_ho? true end puts "let’s go" if hey_ho?
Pretty nice to code like that.
Feels really natural.
The try method (with Rails mode on)
The try method invokes the method identified by the symbol, passing it any arguments and/or the block specified. This is similar to Ruby’s Object#send. Unlike that method, nil will be returned if the receiving object is a nil object or NilClass.
Using if and unless condition statement:
user.id unless user.nil?
Using the **try **method:
user.try(:id)
Since Ruby 2.3, we can use Ruby’s safe navigation operator** (&.)** instead of Rails **try **method.
user&.id
Double pipe equals (||=) / memoization
This feature is so C-O-O-L. It’s like caching a value in a variable.
some_variable ||= 10 puts some_variable # => 10 some_variable ||= 99 puts some_variable # => 10
You don’t need to use the if statement ever. Just use double pipe equals (||=) and it’s done.
Simple and easy.
Class static method
One way I like to write Ruby classes is to define a **static **method (class method).
GetSearchResult.call(params)
Simple. Beautiful. Intuitive.
What happens in the background?
class GetSearchResult def self.call(params) new(params).call end def initialize(params) @params = params end def call # ... your code here ... end end
The self.call method initializes an instance, and this object calls the **call **method. Interactor design pattern uses it.
Getters and setters
For the same GetSearchResult class, if we want to use the params, we can use the @params
class GetSearchResult def self.call(params) new(params).call end def initialize(params) @params = params end def call # ... your code here ... @params # do something with @params end end
We define a setter **and **getter:
class GetSearchResult def self.call(params) new(params).call end def initialize(params) @params = params end def call # ... your code here ... params # do something with params method here end private def params @params end def params=(parameters) @params = parameters end end
Or we can define attr_reader, attr_writer, or attr_accessor
class GetSearchResult attr_reader :param def self.call(params) new(params).call end def initialize(params) @params = params end def call # ... your code here ... params # do something with params method here end end
Nice.
We don’t need to define the getter and setter methods. The code just became simpler, just what we want.
Tap
Imagine you want to define a create_user method. This method will instantiate, set the parameters, and save and return the user.
Let’s do it.
def create_user(params) user = User.new user.id = params[:id] user.name = params[:name] user.email = params[:email] # ... user.save user end
Simple. Nothing wrong here.
So now let’s implement it with the tap method
def create_user(params) User.new.tap do |user| user.id = params[:id] user.name = params[:name] user.email = params[:email] # ... user.save end end
You just need to worry about the user parameters, and the tap method will return the user object for you.
That’s it
We learned I write idiomatic Ruby by coding with
array methods
syntax
We also learned how Ruby is beautiful and intuitive, and runs even faster.
And that’s it, guys! I will be updating and including more details to my blog. The idea is to share great content, and the community helps to improve this post! ☺
I hope you guys appreciate the content and learned how to program beautiful code (and better software).
If you want a complete Ruby course, learn real-world coding skills and build projects, try One Month Ruby Bootcamp. See you there ☺
This post appeared first here on my Renaissance Developer publication.
Have fun, keep learning, and always keep coding!
My Medium, Twitter, Github & LinkedIn. ☺
Thanks for stopping by ❤️
Fabulous post. I’m not sure I’ve read a post that expresses the wonder of Ruby so coherently.
Lots of hot tips in here!
I like to use the rubocop gem to watch my back when I'm writing ruby. It will point out a lot of non-idiomatic bits of your code and suggest ways to improve them in line with this great article.
Awesome! I love programming with Ruby too.
Recently discovered that the .any method can be used as an iterator too.
results.any? do |result|
end
Look forward to more.
Nice.
A common problem that I have been enjoying the use of
tapon is populating an array with optional elements.
Instead of:
... (which creates two Array objects) I have switched to ...
... or ...
As is often the case, simple examples don't really do this justice. When you have a lot of complexity about what is going to be added and when, it comes into its own.
Semantically, what I particularly like is the way that
taplets you use a block to say:
Very nice. As a PHP developer, I died once again. :-)
Correct me if I'm wrong, but
[1, 2, 3, 4, 5].select(&:even?)should actually be slower than explicitly writing a block, as it creates a Proc object implicitly by calling
to_procon the Symbol. There might of course be some optimization going on in the background that I don't know about. (EDIT: I totally agree that it looks neater though, and I use it a lot myself)
This is an awesome list of a bunch of great tips you've put together! Thank you for it!
Ruby was (and retrospectively, I'm thankful for it) the first programming language I learned. I've since picked up PHP, JavaScript and am working on Elixir, but I consider myself a proud Ruby programmer.
With the progress being made on the Ruby 3X3 goal, as well as the fact that nothing I have tried comes close to the productivity i get from working with Rails, I don't see that changing anytime soon.
I'm a Rubyist, and your list is a perfect example of why.
Thanks a lot for writing this! I've been looking for ways to use the same filter that ES6 offers but couldn't figure out the syntax in ruby. This post is now bookmarked for reference!
Nice article! It's worth pointing out that safe navigation is not a replacement for try, though. I've made this mistake a few times and had it bite me :D
Tap is my favorite!
Great intro :)
you can as example a programatic lambda
Awesome post!
This really captures why I love Ruby so much: it's really expressive and natural when done right.
totally love this--i came back to programming after something like a 15-year hiatus, and ruby was just what i needed to fall back in love with coding (and see it for the linguistic art it truly is!) | https://practicaldev-herokuapp-com.global.ssl.fastly.net/leandrotk_/idiomatic-ruby-writing-beautiful-code-56ef | CC-MAIN-2019-13 | refinedweb | 1,986 | 68.47 |
.
While loop
The general form of the while loop is
while(condition) statement;
where statement can be a single statement or a block of statements, and condition defines the condition that controls the loop and may be any valid Boolean expression. The statement is performed while the condition is true. When the condition becomes false, program control passes to the line immediately following the loop.
using System; class WhileDemo { static void Main() { int num; int mag; num = 435679; mag = 0; Console.WriteLine("Number: " + num); while(num > 0) { mag++; num = num / 10; }; Console.WriteLine("Magnitude: " + mag); } }
The while loop works like this: The value of num is tested. If num is greater than 0, the mag counter is incremented, and num is divided by 10. As long as the value in num is greater than 0, the loop repeats. When num is 0, the loop terminates and mag contains the order of magnitude of the original value.
Do – While Loop
It is similar to a while loop, except that it tests the condition at the end of the loop body. The Do – While loop executes the loop once irrespective of whether the condition is true or not.
do { executable code; } while (condition);
The do-while loop is used when we want to guarantee that the sequence of operations in it will be executed repeatedly and at least once in the beginning of the loop.
For Loops:
for (initialization; condition; update) { loop's body; }loop:
for ( ; ; ) { // Loop body }
for (int i = 1, sum = 1; i <= 128; i = i * 2, sum += i) { Console.WriteLine("i={0}, sum={1}", i, sum); }
i=1, sum=1 i=2, sum=3 i=4, sum=7 i=8, sum=15 i=16, sum=31 i=32, sum=63 i=64, sum=127 i=128, sum=255
The foreach Loop
The foreach loop cycles through the elements of a collection. A collection is a group of objects. C# defines several types of collections, of which one is an array.
foreach will iterate over any object of a class that implements IEnumerable (take note that IEnumerable inherits from it). Such objects include some built-in ones, but not limit to: List, T[] (arrays of any type), Dictionary, as well as interfaces like IQueryable and ICollection, etc.
foreach(ItemType itemVariable in enumerableObject) statement;
- The type ItemType does not need to match the precise type of the items, it just needs to be assignable from the type of the items
- Instead of ItemType, alternatively var can be used which will infer the items type from the enumerableObject by inspecting the generic argument of the IEnumerable implementation
- The statement can be a block, a single statement or even an empty statement (;)
- If enumerableObject is not implementing IEnumerable, the code will not compile
- During each iteration the current item is cast to ItemType (even if this is not specified but compiler-inferred via var) and if the item cannot be cast an InvalidCastException will be thrown
var list = new List<string>(); list.Add("Ion"); list.Add("Andrei"); foreach(var name in list) { Console.WriteLine("Hello " + name); } | https://blog.codehunger.in/c-loops/ | CC-MAIN-2021-43 | refinedweb | 513 | 55.88 |
Bug #9115open
Logger traps all exceptions; breaks Timeout
Description
Line 577-579 of logger.rb
rescue Exception => ignored warn("log writing failed. #{ignored}") end
Thus, when the system times out in the middle of writing a log message, it warns "log writing failed. execution expired" and just keeps right on running.
This is true in 1.9.3 as well. I haven't looked at older versions.
Pardon me while I go grep "rescue Exception" in the entire Ruby codebase, and see whether I can reliably use Timeout at all...
OK, you might check out C:\Ruby200\lib\ruby\gems\2.0.0\gems\activerecord-3.2.13\lib\active_record\railties\databases.rake
All the other "rescue Exception" seem to re-raise it, except maybe C:\Ruby200\lib\ruby\2.0.0\xmlrpc\server.rb and C:\Ruby200\lib\ruby\gems\2.0.0\gems\activesupport-3.2.13\lib\active_support\callbacks.rb
Updated by cphoenix (Chris Phoenix) over 7 years ago
...I guess my search was broken. I did another and found a whole lot of "rescue exception" that don't seem to always re-raise. But the logger is a big one because it's supposed to be usable everywhere, and someone who logs a lot will run into this bug.
Updated by aaron@serendipity.cx (Aaron Stone) almost 7 years ago
The behavior has changed in Ruby 2.1, and the default rescue no longer rescues Timeout unless Timeout was given an explicit exception class to raise. Could you try Ruby 2.1 and see if it behaves according to your expectation here?
Updated by wpaulson (Bill Paulson) almost 7 years ago
The source code for 2.1.2 doesn't seem to have changed: the LogDevice::write method still does a rescue Exception and ignores the result.
Our application ran into this problem when one thread raises an exception in another thread that's doing a LogDevice::write(). The exception is supposed to be handled at a higher level, so write() rescuing it and ignoring it causes our application to hang.
A write() method without this problem looks like
def write(message) @mutex.synchronize do if @shift_age and @dev.respond_to?(:stat) begin check_shift_log rescue IOError warn("log shifting failed. #{$!}") end end begin @dev.write(message) rescue IOError warn("log writing failed. #{$!}") end end end
Updated by astratto (Stefano Tortarolo) about 6 years ago
I confirm that this bug is reproducible up to 2.2 and it's pretty easy to trigger.
require 'timeout' require 'logger' class MyExc < RuntimeError; end def long_call(logger) Timeout.timeout(3, MyExc) do a = 1 loop do a += 1 logger.warn "Test #{a}" end end end
Aaron Stone is right though that using 2.1+ it would work if you don't provide a custom exception or if your exception inherits from TimeoutError.
Beware that it must inherit from Object::TimeoutError and not Timeout::Error.
Having said that, it'd be nice to have a proper fix at logger.rb level.
@Bill, I don't think your code would fix it though, because the underlying device might throw a different exception.
Updated by astratto (Stefano Tortarolo) about 6 years ago
Correction: providing an exception to Timeout#timeout would break it also in trunk.
It seems that by design inner blocks are able to rescue the exception provided to that method.
Updated by jeremyevans0 (Jeremy Evans) almost 2 years ago
- Backport deleted (
1.9.3: UNKNOWN, 2.0.0: UNKNOWN)
- Assignee set to sonots (Naotoshi Seo)
- Status changed from Open to Assigned
It makes sense for Logger to handle all exceptions by default, as you don't want Logger breaking otherwise working code. So the default behavior is expected and not a bug.
I think the best way to handle this is to allow the user to specify exception classes they would like reraised instead of swallowed. I've added a pull request that implements this:
Updated by ioquatix (Samuel Williams) almost 2 years ago
It makes sense for Logger to handle all exceptions by default
I'm not sure I agree with this. There must be some well-defined set of exceptions that could be raised by the code it's executing that should be handled/ignored, e.g.
IOError, EPERM, ENOSPC, etc. I think it's going to be much better to solve this problem by catching only specific errors that related to the operations that might fail.
Updated by naruse (Yui NARUSE) almost 2 years ago
See the code again before discuss.
def write(message) begin synchronize do if @shift_age and @dev.respond_to?(:stat) begin check_shift_log rescue warn("log shifting failed. #{$!}") end end begin @dev.write(message) rescue warn("log writing failed. #{$!}") end end rescue Exception => ignored warn("log writing failed. #{ignored}") end end
With the code, the intention of
rescue Exception is clear. It wants to rescue exceptions which is raised by
synchronize.
And note that
synchronize is Monitor's and it only raises ThreadError.
I don't understand why it loosely rescues all exceptions.
Updated by naruse (Yui NARUSE) almost 2 years ago
There're also rescue-clauses for
check_shift_log and
@dev.write(message).
They may raise various exceptions and logger.rb never knows that.
Explicitly passing those exceptions are general way, but are there any exceptions other than the family of Timeout::Error?
Also available in: Atom PDF | https://bugs.ruby-lang.org/issues/9115 | CC-MAIN-2021-31 | refinedweb | 891 | 67.55 |
When trying to load csv file data into Scribus it only takes the data of the last row.
I'm using ScribusGenerator.py by Ekkehard Will and my best guess is that the cause of the problem is somewhere in this part of the code:
def replaceVariablesWithCsvData(self, headerRow, row, lines): # lines as list of strings
result = ''
for line in lines:
i = 0
for cell in row:
tmp = ('%VAR_' + headerRow[i] + '%')
line = line.replace(tmp, cell) # string.replace(old, new)
i = i + 1
result = result + line
return result
def getCsvData(self, csvfile):
Read CSV file and return 2-dimensional list containing the data
reader = csv.reader(file(csvfile))
result = []
for row in reader:
rowlist = []
for col in row:
rowlist.append(col)
result.append(rowlist)
return result | https://www.daniweb.com/programming/software-development/threads/440046/csv-file-import-only-takes-values-of-last-row | CC-MAIN-2017-17 | refinedweb | 126 | 64.1 |
In .NET, we can view variables' contents in different ways like local window, quick watch, etc. In System.Diagnostics namespace, we can see a DebuggerDisplayAttribute class that is used to view variables’ contents in debugger window. This attribute can be applied to class, field, property, enum, delegate, struct, etc. Using this attribute, we can easily view variable contents in debug mode, and those contents are easily visible as data tip when we move mouse pointer over that variable. This attribute becomes quite useful when we have to view inner contents of custom type object variable when it has a collection of values.
System.Diagnostics
DebuggerDisplayAttribute
For example, we will apply this attribute to a class and watch the collection values in debug window.
[DebuggerDisplay("Client Name = {CustomerName} Client Type = {CustomerType, nq}")]
class Customer
{
private string _CustomerName;
private string _CustomerType;
public Customer(string strCustomerName, string strCustomerType)
{
_CustomerName = strCustomerName;
_CustomerType = strCustomerType;
}
public string CustomerName
{
get { return _CustomerName; }
}
public string CustomerType
{
get { return _CustomerType; }
}
}
Now after loading a Customer type collection, we see the following view in data tip:
Customer
Had we not used DebuggerDisplayAttribute on Customer class type, we would have to traverse a long hierarchy of tree view of each index value of collection objects to view data contents.
Programmers often override ToString() method in the custom class type method to view data. But still DebuggerDisplayAttribute wins the heart!
ToString()
When ToString() method is overridden inside Customer class, then ToString() method of Customer object will result as:
public new string ToString()
{
return ("Customer Name: " + _CustomerName + "\n" + "Customer Type: " + _CustomerType);
}
DebuggerDisplayAttribute constructor has only one parameter as string. The {} braces contain field or property or method name. In the example above, we have used this way.
string
{}
[DebuggerDisplay("Client Name = {CustomerName} Client Type = {CustomerType, nq}")]
One can also quickly see {CustomerType, nq}. Due to this “nq” specifier, Client Type value is shown without double quotes, whereas Client Name value is still in double quote (see Fig 1). The “nq” specifier is used for string type properties.
CustomerType
nq
string
Happy debugging for next. | https://www.codeproject.com/Articles/117477/Using-DebuggerDisplayAttribute | CC-MAIN-2017-51 | refinedweb | 341 | 50.16 |
Win32::GUI::Reference::Methods - Common Methods
The Win32::GUI package defines a set of methods that apply to most windows and controls. Some of the methods are applicable to resources. See the individual method documentation for more details.
Common methods apply to most windows, controls and resources.
AbsLeft([LEFT])
Gets or sets the absolute left (screen) co-ordinate of a window.
See also Left() See also Move()
AbsTop([TOP])
Gets or sets the absolute top (screen) co-ordinate of a window.
See also Top() See also Move()
AcceptFiles([FLAG])
Gets/sets the -acceptfiles options on a window.
If
FLAG is not provided,
returns the current state.
If FLAG is provided it sets or unsets the state,
returning the previous state.
Animate(%OPTIONS)
Apply special effects when showing or hiding a window. Used instead of Show() or Hide().
OPTIONS can take the following values:
-show => (0|1) default: 1 Hide(0) or Show(1) the window -activate => (0|1) default: 0 Activate the window. Ignored if hiding the window -animation => (roll|slide|blend|center) default: 'roll' Animation type: roll: use roll animation slide: use slide animation blend: use a fade effect. Top-level windows only center: expand out if showing, collapse in when hiding -time => time default: 200 Animation time in milli-seconds -direction => (lr|tlbr|tb|trbl|rl|brtl|bt|bltr) default: 'lr' Animation direction (l=left, r=right, t=top, b=bottom). Ignored for animation types blend and center
Returns a true value on success or a false value on failure
NOTE: blend animation does not work on Win98. It is recomended that you always check the return value from this function and issue a suitable Show() or Hide() on failure.
ArrangeIconicWindows()
Arranges all the minimized child windows of the specified parent window.
AttachThreadInput(FROM, TO, [FLAG])
If you have multiple windows running in different threads, this function allows you to attach one thread's input processor to a different thread.
For example, you can redirect thread A's input to thread B, and then call SetFocus on an object running in thread B to set the keyboard focus to that object. You would not normally be able to do this.
FROM and TO should be thread IDs. FLAG should be non-zero to attach the threads (the default operation if FLAG is not specified), or zero to detach the threads.
see also GetWindowThreadProcessId()
BringWindowToTop()
Brings a window to the foreground (on top of other windows). This does not make the window "always on top". If the window is already on top, it is activated. If the window is a child window, the top-level parent window associated with the child window is activated.
BrowseForFolder(%OPTIONS)
Displays the standard "Browse For Folder" dialog box. Returns the selected item's name, or undef if no item was selected or an error occurred.
Allowed %OPTIONS are:
-title => STRING the title for the dialog -computeronly => 0/1 (default 0) only enable computers to be selected -domainonly => 0/1 (default 0) only enable computers in the current domain or workgroup -driveonly => 0/1 (default 0) only enable drives to be selected -editbox => 0/1 (default 0) if 1, the dialog will include an edit field in which the user can type the name of an item -folderonly => 0/1 (default 0) only enable folders to be selected -includefiles => 0/1 (default 0) the list will include files as well folders -newui => 0/1 (default 0) use the "new" user interface (which has a "New folder" button) -nonewfolder => 0/1 (default 0) hides the "New folder" button (only meaningful with -newui => 1) -owner => WINDOW A Win32::GUI::Window or Win32::GUI::DialogBox object specifiying the owner window for the dialog box -printeronly => 0/1 (default 0) only enable printers to be selected -directory => PATH the default start directory for browsing -root => PATH or CONSTANT the root directory for browsing; this can be either a path or one of the following constants (minimum operating systems or Internet Explorer versions that support the constant are shown in square brackets. NT denotes Windows NT 4.0, Windows 2000, XP, etc.): CSIDL_FLAG_CREATE (0x8000) [2000/ME] Combining this with any of the constants below will create the folder if it does not already exist. CSIDL_ADMINTOOLS (0x0030) [2000/ME] Administrative Tools directory for current user CSIDL_ALTSTARTUP (0x001d) [All] Non-localized Startup directory in the Start menu for current user CSIDL_APPDATA (0x001a) [IE4] Application data directory for current user CSIDL_BITBUCKET (0x000a) [All] Recycle Bin CSIDL_CDBURN_AREA (0x003b) [XP] Windows XP directory for files that will be burned to CD CSIDL_COMMON_ADMINTOOLS (0x002f) [2000/ME] Administrative Tools directory for all users CSIDL_COMMON_ALTSTARTUP (0x001e) [All] Non-localized Startup directory in the Start menu for all users CSIDL_COMMON_APPDATA (0x0023) [2000/ME] Application data directory for all users CSIDL_COMMON_DESKTOPDIRECTORY (0x0019) [NT] Desktop directory for all users CSIDL_COMMON_DOCUMENTS (0x002e) [IE4] My Documents directory for all users CSIDL_COMMON_FAVORITES (0x001f) [NT] Favorites directory for all users CSIDL_COMMON_MUSIC (0x0035) [XP] Music directory for all users CSIDL_COMMON_PICTURES (0x0036) [XP] Image directory for all users CSIDL_COMMON_PROGRAMS (0x0017) [NT] Start menu "Programs" directory for all users CSIDL_COMMON_STARTMENU (0x0016) [NT] Start menu root directory for all users CSIDL_COMMON_STARTUP (0x0018) [NT] Start menu Startup directory for all users CSIDL_COMMON_TEMPLATES (0x002d) [NT] Document templates directory for all users CSIDL_COMMON_VIDEO (0x0037) [XP] Video directory for all users CSIDL_CONTROLS (0x0003) [All] Control Panel applets CSIDL_COOKIES (0x0021) [All] Cookies directory CSIDL_DESKTOP (0x0000) [All] Namespace root (shown as "Desktop", but is parent to my computer, control panel, my documents, etc.) CSIDL_DESKTOPDIRECTORY (0x0010) [All] Desktop directory (for desktop icons, folders, etc.) for the current user CSIDL_DRIVES (0x0011) [All] My Computer (drives and mapped network drives) CSIDL_FAVORITES (0x0006) [All] Favorites directory for the current user CSIDL_FONTS (0x0014) [All] Fonts directory CSIDL_HISTORY (0x0022) [All] Internet Explorer history items for the current user CSIDL_INTERNET (0x0001) [All] Internet root CSIDL_INTERNET_CACHE (0x0020) [IE4] Temporary Internet Files directory for the current user CSIDL_LOCAL_APPDATA (0x001c) [2000/ME] Local (non-roaming) application data directory for the current user CSIDL_MYMUSIC (0x000d) [All] My Music directory for the current user CSIDL_MYPICTURES (0x0027) [2000/ME] Image directory for the current user CSIDL_MYVIDEO (0x000e) [XP] Video directory for the current user CSIDL_NETHOOD (0x0013) [All] My Network Places directory for the current user CSIDL_NETWORK (0x0012) [All] Root of network namespace (Network Neighbourhood) CSIDL_PERSONAL (0x0005) [All] My Documents directory for the current user CSIDL_PRINTERS (0x0004) [All] List of installed printers CSIDL_PRINTHOOD (0x001b) [All] Network printers directory for the current user CSIDL_PROFILE (0x0028) [2000/ME] The current user's profile directory CSIDL_PROFILES (0x003e) [XP] The directory that holds user profiles (see CSDIL_PROFILE) CSIDL_PROGRAM_FILES (0x0026) [2000/ME] Program Files directory CSIDL_PROGRAM_FILES_COMMON (0x002b) [2000] Directory for files that are used by several applications. Usually Program Files\Common CSIDL_PROGRAMS (0x0002) [All] Start menu "Programs" directory for the current user CSIDL_RECENT (0x0008) [All] Recent Documents directory for the current user CSIDL_SENDTO (0x0009) [All] "Send To" directory for the current user CSIDL_STARTMENU (0x000b) [All] Start Menu root for the current user CSIDL_STARTUP (0x0007) [All] Start Menu "Startup" folder for the current user CSIDL_SYSTEM (0x0025) [2000/ME] System directory. Usually \Windows\System32 CSIDL_TEMPLATES (0x0015) [All] Document templates directory for the current user CSIDL_WINDOWS (0x0024) [2000/ME] Windows root directory, can also be accessed via the environment variables %windir% or %SYSTEMROOT%.
Caption([TEXT])
Change(HANDLE, %OPTIONS)
Change most of the options used when the object was created.
ChangeCursor(CURSOR)
Changes the default cursor for a window to CURSOR (a Win32::GUI::Cursor object). Returns the handle of the previous default cursor.
see also new Win32::GUI::Cursor
ChangeIcon(ICON)
Changes the default icon for a window to ICON (a Win32::GUI::Icon object). Returns the handle of the previous default icon.
ChangeSmallIcon(ICON)
Changes the default small icon for a window to ICON (a Win32::GUI::Icon object). Returns the handle of the previous default small icon.
ChooseColor(%OPTIONS)
Allowed %OPTIONS are:
-owner => WINDOW Identifies the window that owns the dialog box. -color => COLOR Initial color selected.
ChooseFont(%OPTIONS)
Allowed %OPTIONS are:
-owner => WINDOW Identifies the window that owns the dialog box. -pointsize -height -width -escapement -orientation -weight -bold -italic -underline -strikeout -charset -outputprecision -clipprecision -quality -family -name -face (== -name) -color -ttonly -fixedonly -effects -script -minsize -maxsize
ClassData([value])
Sets or reads class instance data associated with the window or control.
my $data=$win->ClassData();#retrieve any data associated with the window $win->ClassData('some string');#associate data to the window
Class instance data can be any perl scalar or reference.
When reading returns the stored instance data, or undef if nothing is stored. When setting returns a true value if the instance data is stored correctly, or a false value on error
Class instance data is private to the package that sets the data. I.e. it is only accessable as a method call from within the package that sets the data, not from a sub-class. So, if you wish to make data stored this way accessible to sub-classes you must proved assessor methods in your package.
ClientToScreen(X, Y)
Converts client-area co-ordinates to screen co-ordinates.
ClipCursor([LEFT, TOP, RIGHT, BOTTOM])
Confines the cursor to the specified screen rectangle. Call it without parameters to release the cursor. Returns nonzero on success
CloseEnhMetaFile(HANDLE)
Closes an enhanced-metafile device context and returns a handle that identifies an enhanced-format metafile.
CloseWindow()
Minimizes a window.
CommDlgExtendedError()
Returns the common dialog library error code.
CreateEnhMetaFile(FILENAME, [DESCRIPTION])
Creates a device context for an enhanced-format metafile.
DeleteEnhMetaFile(HANDLE)
Deletes an enhanced-format metafile or an enhanced-format metafile handle.
Dialog()
Enter the GUI dialog phase: the script halts, the user can interact with the created windows and events subroutines are triggered as necessary; note that this function must be called without ANY parameter or instantiation (eg. don't call it as method of a created object):
Win32::GUI::Dialog(); # correct $Window->Dialog(); # !!!WRONG!!!
Win32::GUI::Dialog(); does a similar thing to
while(Win32::GUI::DoEvents() != -1) {};
See also DoEvents() See also DoModal()
DialogUI(HANDLE, [FLAG])
Gets or sets whether a window accepts dialog-box style input (tab between fields, accelerator keys etc). FLAG should be 1 to enable this functionality, or 0 to disable it.
See also new Win32::GUI::DialogBox()
Disable()
Disables a window or control. Disabled widgets cannot be interacted with, and often change appearance to indicate that they are disabled. This is the same as Enable(0).
DoEvents(hwnd=NULL,wMsgFilterMin=0,wMsgFilterMax=0,wRemoveMsg=PM_REMOVE)
Performs all pending GUI events and returns the status. If DoEvents() returns -1, your GUI has normally terminated.
You can call $window->DoEvents() to process pending events relating to a specific window, or Win32::GUI::DoEvents() to process pending events for all windows.
DoModal([DISABLE_ALL=FALSE])
Enter the GUI dialog phase for a specific window: the script halts, the user can interact with the window, events subroutines are triggered as necessary, but no other windows in the application will accept input. DoModal() also brings the window on top of all other windows.
DISABLE_ALL flag can set for deactivate all top window and not only parent/active window.
The correct usage is:
$window->DoModal(1);
To exit from the GUI dialog phase of the modal window, return -1 from the event handler.
See also Dialog() See also DoEvents()
DrawMenuBar()
Forces redrawing of the menu bar.
Enable([FLAG])
Enables (or disables) a window or control. Controls do not accept input when they are disabled.
FLAG should be 0 to disable the control (the same as calling Disable() on a control), or 1 to enable it.
EnumMyWindows()
Returns a list of top-level window handles created by your application.
Usage:
@windows = Win32::GUI::EnumMyWindows();
FindWindow(CLASSNAME, WINDOWNAME)
Returns the handle of the window whose class name and window name match the specified strings; both strings can be empty. Note that the function does not search child windows, only top level windows.
If no matching windows is found, the return value is zero.
FreeLibrary(LIBRARY)
The FreeLibrary function decrements the reference count of the loaded dynamic-link library (DLL) module.
GetAbsClientRect()
Gets the absolute screen co-ordinates of the client rectangle and returns an array of left, top, right, and bottom co-ordinates.
GetActiveWindow()
Returns the handle of the active window.
GetAsyncKeyState(keyCode)
Retrieve the status of the specified virtual key at the time the function is called. The status specifies whether the key is up or down.
keyCode -- If A..Z0..9, use the ASCII code. Otherwise, use a virtual key code. Example: VK_SHIFT
Return 1 if the key is depressed, 0 if it's not.
GetCapture()
Returns the handle of the window that has the captured the mouse. If no window has captured the mouse zero is returned.
GetClassName()
Returns the class name for a window or control.
GetClientRect()
Gets the client area rectangle and returns an array of left, top, right, and bottom co-ordinates if successful. Left and top will always be 0, right and bottom are equivalent to the width and height of the client area.
GetCursor()
Returns the handle of the current cursor.
GetCursorPos()
Gets the absolute mouse cursor position. Returns an array containing x and y co-ordinates.
Usage:
($x, $y) = Win32::GUI::GetCursorPos;
See also ScreenToClient() See also SetCursorPos()
GetDesktopWindow()
Returns the handle of the desktop window.
GetDlgItem(ID)
Returns the handle of a control in the dialog box given its ID.
GetEffectiveClientRect(HANDLE, @CONTROLS)
Returns the left, top, right and bottom co-ordinates of a rectangle that can accommodate all the controls specified. The elements of @CONTROLS should be control identifiers.
GetEvent(NAME)
Retrieves an event. If the New Event Model is being used, this will return the code-reference of the event you named, otherwise it will return undef.
GetFocus()
Returns the handle of the window that has the keyboard focus.
GetFont(FONT)
Gets the font of the window (returns an handle; use to get font details).
$Font = $W->GetFont(); %details = Win32::GUI::Font::Info( $Font );
GetFontName()
Returns the name of the font that is currently assigned to a window or control
GetForegroundWindow()
Returns the handle of the foreground window.
GetKeyboardState()
Return array ref with the status of the 256 virtual keys.
The index in the array is the virtual key code. If the value is true, that key is depressed.
Example:
$key=Win32::GUI::GetKeyboardState; print 'CTRL is down' if $key->[0x11];
GetKeyState(keyCode)
Retrieve the status of the specified virtual key at the time the last keyboard message was retrieved from the message queue.
In scalar context returns a value specifying whether the key is up(0) or down(1). In list context, returns a 2 element list with the first element as in scalar context and the second member specifying whether the key is toggled(1) or not(0) - this is only meaningful for keys that have a toggled state: Caps Lock, Num Lock etc.
keyCode -- If A..Z0..9, use the ASCII code. Otherwise, use a virtual key code. Example: VK_SHIFT
GetMenu()
Returns the handle of the menu associated with the window.
GetMessage([MIN=0, MAX=0])
Retrieves a message sent to the window, optionally considering only messages identifiers in the range MIN..MAX.
If a message is found, the function returns a 7 elements array containing:
- the result code of the message - the message identifier - the wParam argument - the lParam argument - the time when message occurred - the x coordinate at which message occurred - the y coordinate at which message occurred
If the result code of the message was -1 the function returns undef. Note that this function should not be normally used unless you know very well what you're doing.
GetOpen. GetOpen. -multisel => 0/1 (default 0) Allow multiple file selection If the user selects more than one file then return filename with full path. If the user selects more than one file then return an array with the path to the current directory followed by the filenames of the selected files. . -hidereadonly => 0/1 (default 1) Hides the Read Only check box. If -hidereadonly is set to 0, the read only status is return only in array context as last value. does not have the Read Only check box checked and is not in a write-protected directory. -pathmustexist => 0/1 (default 0) Specifies that the user can type only valid paths and filenames. If this flag is used and the user types an invalid path and filename in the File Name entry field, the dialog box function displays a warning in a message box. -readonly => 0/1 (default 0) Causes the Read Only check box to be checked initially when the dialog box is created.
GetParent()
Returns the parent window for this child control/window. If there is no parent window or there has been an error, undef is returned.
GetPerlWindow()
Returns the handle of the command prompt window your perl script is running in; if called in an array context, returns the handle and the HINSTANCE of your perl process.
GetSave. GetSave is not in a write-protected directory. -pathmustexist => 0/1 (default 1) Specifies that the user can type only valid paths and filenames. If this flag is used and the user types an invalid path and filename in the File Name entry field, the dialog box function displays a warning in a message box. -overwriteprompt => 0/1 (default 1) Generate a message box if the selected file already exists. The user must confirm8 whether to overwrite the file.
GetStockObject(OBJECT)
Returns the handle of the specified predefined system object (pen, brush or font).
OBJECT can have one of the following values:
0 WHITE_BRUSH 1 GRAY_BRUSH 2 LTGRAY_BRUSH 3 DKGRAY_BRUSH 4 BLACK_BRUSH 5 NULL_BRUSH (also HOLLOW_BRUSH) 6 WHITE_PEN 7 BLACK_PEN 8 NULL_PEN 10 OEM_FIXED_FONT 11 ANSI_FIXED_FONT 12 ANSI_VAR_FONT 13 SYSTEM_FONT 14 DEVICE_DEFAULT_FONT 15 DEFAULT_PALETTE 16 SYSTEM_FIXED_FONT 17 DEFAULT_GUI_FONT 18 DC_BRUSH (Windows 2000/XP only) 19 DC_PEN (Windows 2000/XP only)
The returned handle can be referenced as if it was a Win32::GUI object (eg. a Win32::GUI::Brush or Win32::GUI::Font), but note that it is not blessed, so you can't directly invoke methods on it:
$Font = Win32::GUI::GetStockObject(17); # DEFAULT_GUI_FONT print $Font->GetMetrics(); # !!!WRONG!!! print Win32::GUI::Font::GetMetrics($Font); # correct $Window->SetFont($Font); # correct
GetSystemMetrics(INDEX)
Retrieves various system metrics (dimensions of display elements) and configuration settings. Too numerous to list here. See WinUser.h for a complete list of SM_* constants that you can use for INDEX.
GetTextExtentPoint32(STRING, [FONT])
Returns a two elements array containing the x and y size of the specified STRING in the window (eventually with the speficied FONT), or undef on errors.
GetTopWindow()
Returns the handle of the foreground window.
GetWindow(COMMAND)
Returns handle of the window that has the specified relationship (given by COMMAND) with the specified window.
Available COMMAND are:
GW_CHILD GW_HWNDFIRST GW_HWNDLAST GW_HWNDNEXT GW_HWNDPREV GW_OWNER
Example:
$Button->GetWindow(GW_OWNER);
GetWindowLong(INDEX)
Retrieves a windows property; for more info consult the original API documentation.
GetWindowRect()
Returns a four elements array defining the windows rectangle (left, top, right, bottom) in screen co-ordinates or undef on errors.
GetWindowThreadProcessId()
Returns a two elements array containing the thread and the process identifier for the specified window.
Height([HEIGHT])
Sets or retrieves the height of a window.
Hide()
Hides a window or control.
Hook(MSG,CODEREF)
Adds a new handler to the list of handlers for a particular window message / command / notification.
Hook() can be used with the New Event Model and the Old Event Model. You can Hook() normal window messages, WM_COMMAND codes and WM_NOTIFY codes. You can add as many hooks for one message as you like. To remove hooks see UnHook().
Here's an example Perl handler routine:
sub click_handler { ($object, $wParam, $lParam, $type, $msgcode) = @_; print "Click handler called!\n"; }
Here, $object is the Perl object for the widget, $wParam and $lParam are the parameters received with the message, $type is the type of message (0, WM_NOTIFY or WM_COMMAND, see below), and $msgcode is the original numeric code for the message.
If you call Hook() on a child widget, such as a button, the Hook will be called if the parent window receives WM_COMMAND and the code given with WM_COMMAND matches the MSG argument you passed to Hook(). Put simply, what this means is that things like
$button->Hook(BN_CLICKED, \&button_clicked);
will work. When your handler is called it will be passed a $type argument of WM_COMMAND (numeric 273).
The same is true for WM_NOTIFY messages, although handlers defined for those are passed a $type argument of WM_NOTIFY (numeric 78).
Any message that was not WM_NOTIFY or WM_COMMAND gets passed a $type of 0. It is important to check your $type argument. Certain codes for WM_COMMAND messages may conflict with codes for WM_NOTIFY messages or regular window messages, meaning the handler you defined for a particular WM_NOTIFY code may get triggered by a WM_COMMAND code. The $type argument is there to allow you to check this. The rule is to just return immediately if $type is not what you were expecting.
If Hook() successfully added a hook for the event, it returns true. If the hook already exists (the coderef you gave is already in the list of hooks for the specified event), or if there was an error in creating the new hook, it returns false.
InvalidateRect(...)
Forces a refresh of a window, or a rectangle of it.
The parameters can be (FLAG) for the whole area of the window, or (LEFT, TOP, RIGHT, BOTTOM, [FLAG]) to specify a rectangle. If the FLAG parameter is set to TRUE, the background is erased before the window is refreshed (this is the default).
See also Redraw() See also Update()
IsEnabled()
Returns TRUE if the window is enabled, FALSE otherwise.
IsIconic()
Returns TRUE if the window is minimized, FALSE otherwise.
IsVisible()
Returns TRUE if the window is visible, FALSE otherwise.
IsWindow()
Returns TRUE if the window is a window, FALSE otherwise.
IsZoomed()
Returns TRUE if the window is maximized, FALSE otherwise.
Left([LEFT])
Gets or sets the left co-ordinate of an object, relative to the object's parent if it has one, or absolute screen co-ordinate if it doesn't.
See also AbsLeft() See also Move()
LoadCursor(ID)
This function loads one of the default cursors. ID can be one of:
32650 IDC_APPSTARTING Standard arrow and small hourglass 32512 IDC_ARROW Standard arrow 32515 IDC_CROSS Crosshair 32649 IDC_HAND Windows 98/Me, Windows 2000/XP: Hand 32651 IDC_HELP Arrow and question mark 32513 IDC_IBEAM I-beam 32641 IDC_ICON Obsolete for applications marked version 4.0 or later. 32648 IDC_NO Slashed circle 32640 IDC_SIZE Obsolete for applications marked version 4.0 or later. Use IDC_SIZEALL. 32646 IDC_SIZEALL Four-pointed arrow pointing north, south, east, and west 32643 IDC_SIZENESW Double-pointed arrow pointing northeast and southwest 32645 IDC_SIZENS Double-pointed arrow pointing north and south 32642 IDC_SIZENWSE Double-pointed arrow pointing northwest and southeast 32644 IDC_SIZEWE Double-pointed arrow pointing west and east 32516 IDC_UPARROW Vertical arrow 32514 IDC_WAIT Hourglass
On success returns a Win32::GUI::Cursor object, on failure undef.
Example:
my $hourglass=Win32::GUI::LoadCursor(32514);
NOTE: it is better to use Win32::GUI::Cursor->new(ID);
LoadLibrary(NAME)
The LoadLibrary function maps the specified executable module into the address space of the calling process.
The return value is a handle to the module, or undef on failure.
Directory seperators are normalised to windows seperators (
\).
Under Cygwin, cygwin paths are converted to windows paths
LoadResource(NAME)
Loads a generic resource from the EXE file that your perl process is running as. This is for use when distributing your application. Resources can be packed into the EXE file using many tools including ResHacker.
Note that packing resources into a PAR executable will not work. You must first pack the resources into par.exe then use PAR to build your executable.
For this routine to work, any resources you wish to load with it must be added to the executable with the RCDATA resource type.
If the resource is not found in the EXE, this function will return NULL, otherwise it will return a scalar containing the raw resource data.
LoadString(ID)
The LoadString method loads a string resource from the executable file
LockWindowUpdate(flag)
The LockWindowUpdate method disables or enables drawing in the specified window. Only one window can be locked at a time.
If an application with a locked window (or any locked child windows) calls the GetDC function, the called function returns a device context with a visible region that is empty. This will occur until the application unlocks the window by calling LockWindowUpdate method specifying a value for the flag. Example: $win->LockWindowUpdate; #Locks window $win->LockWindowUpdate(1); #Unlocks window
Maximize()
Maximizes a window.
MessageBeep([TYPE=MB_OK])
Plays a sound.
TYPE specifies the sound type :
MB_OK : Play SystemDefault sound. MB_ICONASTERISK : Play SystemAsterisk sound. MB_ICONEXCLAMATION : Play SystemExclamation sound. MB_ICONHAND : Play SystemHand sound. MB_ICONQUESTION : Play SystemQuestion sound. 0xFFFFFFFF Play Standard beep using the computer speaker
MessageBox([HANDLE], TEXT, [CAPTION], [TYPE])
Shows a standard Windows message box and waits for the user to dismiss it. You can set the window that the message box corresponds to by passing a specific HANDLE (window handle or object). The given TEXT will appear in the message box client area, and the given CAPTION text will appear in the message box titlebar. TYPE specifies various flags that change the appearance of the message box. These are:
To set which buttons appear on the message box, specify one of the following values:
0x0000 MB_OK show an OK button 0x0001 MB_OKCANCEL show an OK button and a Cancel button 0x0002 MB_ABORTRETRYIGNORE show Abort, Retry and Ignore buttons 0x0003 MB_YESNOCANCEL show Yes, No and Cancel buttons 0x0004 MB_YESNO show Yes and No buttons 0x0005 MB_RETRYCANCEL show Retry and Cancel buttons 0x0006 MB_CANCELTRYCONTINUE show Cancel, Try Again and Continue buttons (2000/XP only)
To add a help button to the message box, specify the following value:
0x4000 MB_HELP
To show an icon in the message box, specify one of these values:
0x0010 MB_ICONHAND show a stop-sign icon (used for errors) 0x0020 MB_ICONQUESTION show a question mark icon 0x0030 MB_ICONEXCLAMATION show an exclamation mark icon (used for warnings) 0x0040 MB_ICONASTERISK show an asterisk icon (the letter "i" in a circle) (used for information)
To set a default button, specify one of these values (if none of these are specified, the first button will be the default button):
0x0100 MB_DEFBUTTON2 The second button is default 0x0200 MB_DEFBUTTON3 The third button is default 0x0300 MB_DEFBUTTON4 The fourth button is default
To specify how the message box affects other windows and various other flags, use one or more of the following values:
0x0000 MB_APPLMODAL The user must dismiss the message box before continuing work in the window specified by HANDLE (this is the default) 0x1000 MB_SYSTEMMODAL Same as MB_APPLMODAL but the window appears on top of all other windows on the desktop. 0x2000 MB_TASKMODAL Same as MB_APPLMODAL except that all the top-level windows belonging to the current thread are disabled if no HANDLE is specified 0x8000 MB_NOFOCUS Does not give the message box input focus 0x10000 MB_SETFOREGROUND Makes the message box become the foreground window 0x20000 MB_DEFAULT_DESKTOP_ONLY If the current desktop is not the default desktop, MessageBox will not return until the user switches to the default desktop 0x40000 MB_TOPMOST Makes the message box become the topmost window 0x80000 MB_RIGHT Makes text in the message box right-aligned 0x100000 MB_RTLREADING Displays message and caption text using right-to-left reading order on Hebrew and Arabic systems. 0x200000 MB_SERVICE_NOTIFICATION Displays the message box even if no user is logged in on Windows NT/2000/XP. You should not specify a HANDLE when using this.
To combine several values together, use a bitwise OR operator (|).
MessageBox will return one of the following values depending on the user's action:
1 IDOK The user clicked the OK button. 2 IDCANCEL The user clicked the Cancel button. 3 IDABORT The user clicked the Abort button. 4 IDRETRY The user clicked the Retry button. 5 IDIGNORE The user clicked the Ignore button. 6 IDYES The user clicked the Yes button. 7 IDNO The user clicked the No button. 8 IDCLOSE The user closed the message box. 9 IDHELP The user clicked the Help button. 10 IDTRYAGAIN The user clicked the Try Again button. 11 IDCONTINUE The user clicked the Continue button.
The default TYPE value is a warning icon with an OK button (MB_ICONEXCLAMATION|MB_OK).
Minimize()
See CloseWindow()
Move(X, Y)
Moves a window to the given X and Y co-ordinates.
OpenIcon()
Restores a minimized window.
PeekMessage([MIN, MAX, MESSAGE])
Inspects the window's message queue and eventually returns data about the message it contains; it can optionally check only for message identifiers in the range MIN..MAX; the last MESSAGE parameter, if specified, must be an array reference.
If a message is found, the function puts in that array 7 elements containing:
- the handle of the window to which the message is addressed - the message identifier - the wParam argument - the lParam argument - the time when message occurs - the x coordinate at which message occurs - the y coordinate at which message occurs
PlayEnhMetaFile(FILENAME)
Displays the picture stored in the specified enhanced-format metafile. This function use current window device context (-DC).
PlayWinMetaFile(FILENAME)
Displays the picture stored in the specified enhanced-format metafile.
PostMessage(MSG, WPARAM, LPARAM)
Posts a message to a window.
PostQuitMessage([EXITCODE])
Sends a quit message to a window, optionally with an EXITCODE; if no EXITCODE is given, it defaults to 0.
Redraw()
Repaints a window
See also Update() See also InvalidateRect()
ReleaseCapture()
Releases the mouse capture.
Resize(WIDTH, HEIGHT)
Resizes a window to the given WIDTH and HEIGHT.
Restore()
See OpenIcon()
Result(HANDLE, RESULT)
Explicitly set the result to be returned from a handler. For safety and backwards compatibility, results returned from Win32::GUI handlers are discarded. You can use this method (with GREAT CARE) to explicitly force a return value for your handler. Consult the API documentation for valid return values as they vary from message to message.
SaveBMP(handle)
Saves the window content to a BMP file.
ScaleHeight()
Returns the windows client area height.
ScaleWidth()
Returns the windows client area width.
ScreenToClient(X, Y)
Converts screen co-ordinates to client-area co-ordinates.
Scroll(scrollbar,operation[,position, [thumbtrack_flag]])
Handles scrollbar scrolling if you don't want to do it yourself. This is most useful in the Scroll event handler for a window or dialog box.
scrollbar can be:
SB_HOR(0) : Horizontal scrollbar SB_VERT(1) : Vertical scrollbar
operation is an identifier for the operation being performed on the scrollbar, this can be:
SB_LINEUP, SB_LINELEFT, SB_LINEDOWN, SB_LINERIGHT, SB_PAGEUP SB_PAGELEFT, SB_PAGEDOWN, SB_PAGERIGHT, SB_THUMBPOSITION, SB_THUMBTRACK, SB_TOP, SB_LEFT, SB_BOTTOM, SB_RIGHT, or SB_ENDSCROLL
position is ignored unless operation is SB_THUMBPOSITION, or operation is SB_THUMBTRACK and thumbtrack_flag is TRUE. If position is not provided (or provided and equal to -1), then the position used is taken from the internal scrollbar structure: this is the prefered method of operation.
thumbtrack_flag indicates whether SB_THUMBTRACK messages are processed (TRUE) or not (FALSE). It defaults to false.
Returns the new position of the scrollbar, or undef on failure.
ScrollPage(scrollbar,[pagesize])
Sets / Gets page size of a window scrollbar (if enabled). scrollbar argument should be set as follows:
0 : Horizontal scrollbar 1 : Vertical scrollbar
Returns the scrollbar page size or undef on failure.
ScrollPos(scrollbar,[pos])
Sets / Gets position of a window scrollbar (if enabled). scrollbar argument should be set as follows:
0 : Horizontal scrollbar 1 : Vertical scrollbar
Returns the scrollbar position or undef on failure.
ScrollRange(scrollbar,[min, max])
Sets / Gets range for a window scrollbar (if enabled). scrollbar argument should be set as follows:
0 : Horizontal scrollbar 1 : Vertical scrollbar
Returns the scrollbar range as an array, or undef on failure.
SendMessage(MSG, WPARAM, LPARAM)
Sends a message to a window.
SendMessageTimeout(MSG, WPARAM, LPARAM, [FLAGS=SMTO_NORMAL], TIMEOUT)
Sends a message to a window and wait for it to be processed or until the specified TIMEOUT (number of milliseconds) elapses.
Returns the result code of the processed message or undef on errors.
If undef is returned and a call to Win32::GetLastError() returns 0, then the window timed out processing the message.
The FLAGS parameter is optional, possible values are:
0 : SMTO_NORMAL The calling thread can process other requests while waiting; this is the default setting. 1 : SMTO_BLOCK The calling thread does not process other requests. 2 : SMTO_ABORTIFHUNG Returns without waiting if the receiving process seems to be "hung".
SetActiveWindow()
Activates a window. Returns the handle of the previously active window or 0.
SetCapture()
Assigns the mouse capture to a window.
SetCursor(CURSOR)
Draws the specified CURSOR (a Win32::GUI::Cursor object). Returns the handle of the previously displayed cursor. Note that the cursor will change back to the default one as soon as the mouse moves or a system command is performed. To change the cursor stablily, use ChangeCursor().
see also ChangeCursor()
SetCursorPos(X, Y)
Moves the mouse cursor to the specified screen coordinates.
see also GetCursorPos()
SetEvent(NAME,HANDLER)
Sets an event. If the New Event Model is being used, this will enable the specified event and set it to be handled by the specified
HANDLER, which should be a code-reference.
SetFocus()
Set focus to a window.
SetFont(FONT)
Sets the font of the window (FONT is a Win32::GUI::Font object).
SetForegroundWindow()
Brings the window to the foreground.
SetIcon(ICON, [TYPE])
Sets the icon of the window; TYPE can be 0 for the small icon, 1 for the big icon. Default is the same icon for small and big.
SetMenu(MENU)
Associates the specified MENU to a window.
SetRedraw(FLAG)
Determines if a window is automatically redrawn when its content changes.
FLAG can be a true value to allow redraw, false to prevent it.
SetWindowLong(INDEX, VALUE)
Sets a windows property; for more info consult the original API documentation.
SetWindowPos(INSERTAFTER,X,Y,cx,cy,FLAGS).
INSERTAFTER - window to precede the positioned window in the Z order. This parameter must be a window object, a window handle or one of the following integer values.
HWND_BOTTOM Places the window at the bottom of the Z order. If the WINDOW.
SetWindowRgn(region,flag)
The SetWindowRgn method sets the window region of a window. The window region determines the area within the window where the system permits drawing. The system does not display any portion of a window that lies outside of the window region
flag : Specifies whether the system redraws the window after setting the window region. If flag is TRUE, the system does so; otherwise, it does not. Typically, you set flag to TRUE if the window is visible.
ShellExecute(window,operation,file,parameters,directory,showcmd)
Performs an operation on a file.
Operation. A string that specifies the action to be performed. The set of available action verbs depends on the particular file or folder. Generally, the actions available from an object's shortcut menu are available verbs.
edit - Launches an editor and opens the document for editing. If File is not a document file, the function will fail. explore - Explores the folder specified by File. find - Initiates a search starting from the specified directory. open - Opens the file specified by the File parameter. The file can be an executable file, a document file, or a folder. print - Prints the document file specified by lpFile. If lpFile is not a document file, the function will fail. ""(NULL) - For systems prior to Microsoft.
File. A string that specifies the file or object on which to execute the specified verb. To specify a Shell namespace object, pass the fully qualified parse name. Note that not all verbs are supported on all objects. For example, not all document types support the "print" verb.
Parameters. If the File parameter specifies an executable file, Parameters is a string that specifies the parameters to be passed to the application. The format of this string is determined by the verb that is to be invoked. If File specifies a document file, Parameters should be NULL.
Directory. A string that specifies the default directory.
ShowCmd. Flags that speciow an application is to be displayed when it is opened. If File specifies a document file, the flag is simply passed to the associated application. It is up to the application to decide how to handle it.
0 SW_HIDE Hides the window and activates another window. 3 SW_MAXIMIZE Maximizes the specified window. 6 SW_MINIMIZE Minimizes the specified window and activates the next top-level window in the z-order. 9 SW_RESTORE Activates and displays the window. If the window is minimized or maximized, Windows restores it to its original size and position. An application should specify this flag when restoring a minimized window. 5 SW_SHOW Activates the window and displays it in its current size and position. 10 SW_SHOWDEFAULT Sets the show state based on the SW_ flag specified in the STARTUPINFO structure passed to the CreateProcess function by the program that started the application. An application should call ShowWindow with this flag to set the initial show state of its main window. 2 SW_SHOWMINIMIZED Activates the window and displays it as a minimized window. 7 SW_SHOWMINNOACTIVE Displays the window as a minimized window. The active window remains active. 8 SW_SHOWNA Displays the window in its current state. The active window remains active. 4 SW_SHOWNOACTIVATE Displays a window in its most recent size and position. The active window remains active. 1 SW_SHOWNORMAL Activates and displays a window. If the window is minimized or maximized, Windows restores it to its original size and position. An application should specify this flag when displaying the window for the first time.
Returns a value greater than 32 if successful, or an error value that is less than or equal to 32 otherwise. The following table lists the error values.
0 The operating system is out of memory or resources. 3 ERROR_PATH_NOT_FOUND The specified path was not found. 11 ERROR_BAD_FORMAT The .exe file is invalid (non-Microsoft Win32 .exe or error in .exe image). 5 SE_ERR_ACCESSDENIED The operating system denied access to the specified file. 27 SE_ERR_ASSOCINCOMPLETE The file name association is incomplete or invalid. 30 SE_ERR_DDEBUSY The Dynamic Data Exchange (DDE) transaction could not be completed because other DDE transactions were being processed. 29 SE_ERR_DDEFAIL The DDE transaction failed. 28 SE_ERR_DDETIMEOUT The DDE transaction could not be completed because the request timed out. 32 SE_ERR_DLLNOTFOUND The specified dynamic-link library (DLL) was not found. 2 SE_ERR_FNF The specified file was not found. 31 SE_ERR_NOASSOC There is no application associated with the given file name extension. This error will also be returned if you attempt to print a file that is not printable. 8 SE_ERR_OOM There was not enough memory to complete the operation. 3 SE_ERR_PNF The specified path was not found. 26 SE_ERR_SHARE A sharing violation occurred.
Examples:
Open a web page in the default browser
my $exitval = $win->ShellExecute('open','','','',1);
Open a text file in nodepad
my $exitval = $win->ShellExecute('open','notepad.exe','readme.txt','',1) ;
Show([COMMAND=SW_SHOWNORMAL])
Shows a window (or change its showing state to COMMAND);
Available COMMAND are:
0 : SW_HIDE 1 : SW_SHOWNORMAL 1 : SW_NORMAL 2 : SW_SHOWMINIMIZED 3 : SW_SHOWMAXIMIZED 3 : SW_MAXIMIZE 4 : SW_SHOWNOACTIVATE 5 : SW_SHOW 6 : SW_MINIMIZE 7 : SW_SHOWMINNOACTIVE 8 : SW_SHOWNA 9 : SW_RESTORE 10 : SW_SHOWDEFAULT 11 : SW_FORCEMINIMIZE 11 : SW_MAX
Text([TEXT])
Sets or gets the text associated with a window or control. For example, for windows, this is the text in the titlebar of the window. For button controls, it's the text on the button, and so on. Text() and Caption() are synonymous with oneanother.
Top([TOP])
Gets or sets the top co-ordinate of an object, relative to the object's parent if it has one, or absolute screen co-ordinate if it doesn't.
See also AbsTop() See also Move()
TrackMouse([TIMEOUT=HOVER_DEFAULT, EVENTS=TME_HOVER|TME_LEAVE])
Causes the window to receive messages when the mouse pointer leaves a window or hovers over a window for a specified amount of time (TIMEOUT, in milliseconds).
EVENTS can be set to one or more of the following values (ORed together):
0x0001 TME_HOVER Makes the window receive WM_MOUSEHOVER messages when the mouse hovers over it. 0x0002 TME_LEAVE Makes the window receive a WM_MOUSELEAVE message when the mouse leaves it. 0x0010 TME_NONCLIENT Specifies that the non-client area should be included when tracking the mouse. The window will receive WM_NCMOUSEHOVER and WM_NCMOUSELEAVE messages depending on whether TME_HOVER and/or TME_LEAVE are set.
See also UntrackMouse()
TrackPopupMenu(MENU [, X, Y [, LEFT, TOP, RIGHT, BOTTOM] [, FLAGS [, CODEREF]]])
Displays the menu MENU at the specified co-ordinates (X,Y) and tracks the selection of items on the menu. X and Y are absolute screen co-ordinates.
If X and Y are not provided, uses the current cursor position.
If LEFT, TOP, RIGHT and BOTTOM are provided they describe a rectangle in absolute screen co-ordinates over which the menu will not be drawn (the excluded rectangle).
The following flags can be set (combine flags with bitwise OR (|) )
0x0000 TPM_LEFTBUTTON Menu items can only be selected with left mouse button 0x0002 TPM_RIGHTBUTTON Menu items can be selected with either left or right mouse button 0x0000 TPM_LEFTALIGN Menu is aligned to the left of the given X co-ordinate 0x0004 TPM_CENTERALIGN Menu is centered on the given X co-ordinate 0x0008 TPM_RIGHTALIGN Menu is aligned to the right of the given X co-ordinate 0x0000 TPM_TOPALIGN Menu is aligned above the given Y co-ordinate 0x0010 TPM_VCENTERALIGN Menu is centered on the given Y co-ordinate 0x0020 TPM_BOTTOMALIGN Menu is aligned below the given Y co-ordinate 0x0100 TPM_RETURNCMD TrackPopupMenu returns the selected menu item identifier in the return value 0x0400 TPM_HORPOSANIMATION Menu will be animated from left to right (ignored if menu fading is on) 0x0800 TPM_HORNEGANIMATION Menu will be animated from right to left (ignored if menu fading is on) 0x1000 TPM_VERPOSANIMATION Menu will be animated from top to bottom (ignored if menu fading is on) 0x2000 TPM_VERNEGANIMATION Menu will be animated from bottom to top (ignored if menu fading is on) 0x4000 TPM_NOANIMATION Menu will not be animated and will not "fade" in and out even if menu fading is enabled 0x0001 TPM_RECURSE Allows you to display a menu when another menu is already displayed. This is intended to support context menus within a menu. (Windows 2000/XP only)
The default flags are
TPM_LEFTALIGN | TPM_TOPALIGN | TPM_LEFTBUTTON
If an excluded rectangle is spefified then the following flags may also be used, and TPM_VERTICAL is added to the default flags:
0x0000 TPM_HORIZONTAL If the menu cannot be shown at the specified location without overlapping the excluded rectangle, the system tries to accommodate the requested horizontal alignment before the requested vertical alignment. 0x0040 TPM_VERTICAL If the menu cannot be shown at the specified location without overlapping the excluded rectangle, the system tries to accommodate the requested vertical alignment before the requested horizontal alignment.
If you specify
TPM_RETURNCMD, then the menu item ID of the selected item is returned. If an error occurs or the user does not select an item, zero is returned. If you do not specify
TPM_RETURNCMD, the return value will be nonzero on success or zero on failure.
If CODEREF is provided, then it is a code reference to a callback procedure that will be called for windows events that occur while the menu is displayed (normally such events are not available, as TrackPopupMenu has its own internal event loop). The callback will recieve a reference to the Win32::GUI object used to call TrackPopupMenu on, and the message code, wParam and lParam of the event that occured. The callback should return nothing or 1 to allow the event to be processed normally, or 0 to prevent the event being passed to the default event handler. See MSDN documentation for SetWindowsHookEx with idHook set to WH_MSGFILTER for the full gore.
The callback prototype is:
sub callback { my ($self, $message, $wParam, $lParam) = @_; # Process messages you are interested in return; }
UnHook(MSG,[CODEREF])
Removes a specific code reference from the hooks listing for the given message, or removes all code references for the given message if no coderef is specified.
Returns true on success, and false on failure (no such hook).
See Hook() documentation for more information on hooks and their usage.
UntrackMouse()
Disables the tracking of mouse hover or leave events for a window.
See also TrackMouse()
Update()
Repaints a window if it's update region is not empty.
see also Redraw() see also InvalidateRect()
UserData([value])
Sets or reads user data associated with the window or control.
my $data=$win->UserData();#retrieve any data associated with the window $win->UserData('some string');#associate user data to the window
User data can be any perl scalar or reference.
When reading returns the stored user data, or undef if nothing is stored. When setting returns a true value if the user data is stored correctly, or a false value on error
If you are writing a class that you expect others to use, then this method should NOT be used to store class instance data. See ClassData() instead.
Version()
Returns the module version number.
WaitMessage()
The WaitMessage function yields control to other threads when a thread has no other messages in its message queue. The WaitMessage function suspends the thread and does not return until a new message is placed in the thread's message queue.
Width([WIDTH])
Sets or retrieves the width of a window.
WindowFromPoint(X, Y)
Returns the handle of the window at the specified screen position.
Common events apply to most windows and controls.
Documentation for Win32::GUI v1.13 created 26 Jul 2016. | http://search.cpan.org/~kmx/Win32-GUI-1.13/GENERATED/Win32/GUI/Reference/Methods.pod | CC-MAIN-2016-36 | refinedweb | 7,586 | 53.31 |
(via.
January 17th, 2006 at 3:25 am
A bit disappointing, but nowhere near as bad as the markup produced by iWeb.
<div class="paragraph Body" style="line-height: 20px; ">This is my paragraph text</div> <div class="paragraph Body" style="line-height: 20px; text-decoration: none;"> </div>
Hmmm… what happened to the good ol’
pelement?
P.S. What’s wrong with the
apple-wallpapers:namespace? I’m not sure they’ve implemented it 100% correctly, but I thought the ability add custom elements via namespaces was the strength of RSS and other XML-based markup languages.
January 17th, 2006 at 7:26 am
The feed validator misses further errors to do with nonstandard tags that have not been marked as such with the apple-wallpapers: namespace prefix
January 17th, 2006 at 7:32 am
I, too, don’t see the error the feedvalidator “missed”.
The RSS 2.0 spec says “A RSS feed may contain elements not described on this page, only if those elements are defined in a namespace.”
What may those elements contain? The RSS 2.0 spec doesn’t say. Nor can I find any documentation on the apple-wallpapers namespace, but suppose for a second that such documentation did exist and specified that apple-wallpapers:meta-data elements are to contain PhotoDate and Comments elements, and these elements are not in any namespace?
What portion of the RSS 2.0 spec would such a definition violate?
If RSS 2.0 had been in a namespace itself, I could have reported that somebody was using an element that wasn’t defined by the owner of that namespace, but who owns the “null” namespace?
Further discussion here.
January 17th, 2006 at 9:21 am
I subscribed just fine using BottomFeeder.
Apple isn’t turning all non-Mac tools away…
January 17th, 2006 at 9:44 am
[...]. Filed under News by Dan Gillmor. Permalink • Print • Email [...]
January 17th, 2006 at 9:56 am
Kevin and Chris B, you say that there are tags being missed that haven’t been included in the apple-wallpapers namespace — what are those tags? I’ve now looked over that feed three times and can’t find what you’re talking about.
And of course, as Sam’s already pointed out, the presence of apple-wallpapers elements in the feed doesn’t make it broken; Apple built its own namespace, just as the RSS 2.0 spec says it needed to do. (Yes, I’d love to see the definition of the namespace, just like Sam, but its absence doesn’t make the resultant RSS invalid, just suboptimally described.)
In the end, this example feed you point to has two real problems — incorrectly-formatted dates (something easily fixed), and the presence of a guid element at the channel level (something that isn’t explicitly excluded in RSS 2.0, and is mandated under a different name in one of the more well-structured syndication standards). None of these prevent the feed from being read by my syndication aggregator, Gregarius; while they’re unquestionably present, they’re also reasonably minor.
January 17th, 2006 at 12:02 pm
Old news.
Ever import Safari bookmarks in to Firefox 1.5? Watch what happens when you try to open a Safari “RSS feed bookmark” in Firefox. Wow - incompatible. So Firefox asks to open it in Safari.
Sad.
January 17th, 2006 at 12:14 pm
Ummm… The feed displays fine in NetNewsWire.
It does fail in Firefox’s sage plug in, however.
January 17th, 2006 at 12:18 pm
I think the PhotoDate and Comments elements, within the apple-wallpaper:metadata element are whatg is being referred to. I’m not sure if sub elements also need to be qualified though?
January 17th, 2006 at 1:28 pm
I notice that your feed doesn’t validate too, and it has far more errors (20, I mean, TWENTY errors!)
So… does this mean that YOU are the new Microsoft? ;-)
Please don’t take this seriously, I’m just pointing out that it’s difficult to find perfectly well-formed RSS feeds on the Internet. Photocasting works for me, it works in Safari, in NetNewsWire and in Vienna (another RSS reader). Apple can make mistakes, they will probably correct them in a later version of iPhoto.
January 17th, 2006 at 1:48 pm
It is pretty obvious that whoever developed the feed just didn’t understand xml namespaces. First of all the apple-wallpaper namespace wasn’t declared with an xmlns attribute anywhere. The x in <x:y> is only a shortcut for the full URI of the namespace. There should be a xmlns:apple-wallpaper=”" someplace.
Second of all, it *is* required to put the namespace prefix on subelements unless you set up a new default namespace. This can only be done (again) with an xmlns attribute. This time it should look like: xmlns=”" on the first element of the subtree in the new namespace.
So not only is this not valid RSS, it isn’t even valid XML.
January 17th, 2006 at 2:01 pm
The feed also displays fine in the Vienna freeware newsreader.
January 17th, 2006 at 2:06 pm shows the feed nicely.
cute kid!
January 17th, 2006 at 2:09 pm
It’s amusing. I don’t find any reply from the author. From what I can see it seems he was incredibly hasty to write this up and now that he’s been called on the errors in the piece (I don’t understand where did the notion that the RSS couldn’t be opened in other readers came from) no correction, update or reply has been made.
January 17th, 2006 at 2:45 pm
I suggest that anyone legitimately concerned about RSS compatibility errors submit feedback at this page:
You might include a link to the validation page referenced in the article, if you feel its results are valid:
January 17th, 2006 at 3:43 pm
NetNewswire would work fine because it’s built on webkit, which is the base of Safari. So any Mac ap that uses webkit (well a current one) should work.
January 17th, 2006 at 4:42 pm
I was writing a tool to view photocasts in a wiki, and I found the workaround for this problem in about five minutes. Any user-agent can download the photocast simply by replacing ‘photocast.mac.com’ with ‘web.mac.com’ in the URL.
January 17th, 2006 at 4:58 pm
If it’s only usable with iPhoto (to view the photos), then why all the complaining? The Macs that can run this version of iPhoto will also have Safari on them for free, so relax. This isn’t an issue for Windows or non-Mac or non-iPhoto users as they can’t get the photos anyway.
January 17th, 2006 at 5:15 pm
Ah!!! Now SitePoint is anti-Opera and anti-Apple. It’s a consipiracy I swear….
I subscribed fine using Opera (just make sure you don’t have it set to supress images, otherwise obviously you cannot see it, obviously).
I have a strong feeling Apple will fix this. You must have forgotten that Safari was the first official browser to release an Acid2 passing browser. They also update their software quite frequently in OS X. You must not keep up Kevin!
January 17th, 2006 at 5:17 pm
(I can’t edit my comments?)
You should also look at this:
Practice what you preach. They have less errors than you all do.
January 17th, 2006 at 6:12 pm
Babya Discoverer RSS’s bView displays photocasts fine.
January 17th, 2006 at 7:30 pm
Joe, your point would be well taken… except for the fact that it doesn’t look like you looked at the RSS file at all. For example, you say that one problem is the lack of a definition of the XML namespace via an xmlns: declaration — except that line 2 of the document DOES have the apple-wallpapers namespace declared, with the statement:
<rss version=”2.0″ xmlns:apple-wallpapers=””>
You also state that another problem is the lack of prefixing of any of Apple’s special XML elements in the document… except that every single one of the special tags — photoDate, cropDate, thumbnail, image, metadata — is prefixed with the apple-wallpapers: tag. Every last one of ‘em.
Kevin, the Atom feed for this very site is much more broken than for Apple’s photocasts; in addition, you seem to have just taken Dave Winer’s claim of a broken Apple spec and republished it without ever validating anything that it contained. Like I said above, the worst thing you can say about the photocast feeds is that they incorrectly format their dates (assuredly a problem, but something that none of my RSS readers have a problem with), and that they include an element at the channel level that isn’t required, but also isn’t explicitly excluded. And looking at the validator link you yourself published would have told you every bit of this, so you should have known better.
January 17th, 2006 at 7:39 pm
I use Firefox 1.5
I’ve added a livebookmark from this link and works fine
January 17th, 2006 at 7:59 pm
So, considering all the ruckus Kevin made about this — and all the other folks who’ve subsequently proved him wrong — shall we expect an apology or retraction any time soon?
–R.J.
January 17th, 2006 at 8:54 pm
John Levine:
Um, no:
PhotoDateand
January 17th, 2006 at 8:59 pm
Moof:
We would be anxious to correct such errors. Can you point any of them out? At a glance, our feed certainly seems valid: feedvalidator.org report.
Update: Found the errors in our Atom feed. We’ll fix them today. Thanks for pointing them out!
January 17th, 2006 at 10:02 pm
charmedlover:
On the one hand, I’d say HTML validation errors are much less severe than RSS validations errors, as the former is not commonly processed as XML while the latter is.
On the other hand, we work hard to keep as much of our site valid XHTML as possible. In this case it looks like one of our advertisers mucked up the works with some bad HTML. Thanks for pointing this out — it’s now fixed.
January 17th, 2006 at 10:10 pm
Jason Levine:
Heh — I could’ve sworn that I it didn’t have that when I looked at the feed right as this story was breaking. If it was always there then I stand corrected. There is still the issue with child elements and such that Kevin points out.
January 17th, 2006 at 10:12 pm
Kevin:
Ummm… not by my read of the XML spec. According to the W3C:
The only possible argument against this is that somehow those two elements belong to the default (null) namespace, despite being underneath elements to which another namespace has been explicitly declared — but as Sam Ruby pointed out, RSS 2.0 itself doesn’t belong to any namespace, so it’s unclear what it means that any element belongs to the null namespace. (As it stands, every RSS 2.0 document has an ambiguous null namespace.)
January 17th, 2006 at 10:27 pm
Jason, you need to understand XML namespaces before you start claiming people have gotten them right or wrong.
Here’s a namespace declaration:
xmlns:apple-wallpapers="..."
Indeed, it applies to the element in which it is specified (
rss) and all elements inside it. It sets up the
apple-wallpapersprefix to indicate Apple’s custom namespace.
That doesn’t change the fact that elements within that namespace all need to have the namespace prefix from that declaration. The only exception would be if you declared Apple’s “wallpapers” namespace as the default namespace for the
metadataelement:
But Apple isn’t doing this either.
Exactly. That’s how XML namespaces work. Just because an element is in a namespace doesn’t mean any of its descendant elements are also in that namespace by default.
The default namespace (or a “null namespace”, as you put it) is not as ambiguous as you make out. Just because an XML document doesn’t have a default namespace URI assigned to it doesn’t mean that it has no rules as to what tags can and cannot be put into it.
RSS processors identify RSS documents by virtue of the fact that they have an
rsselement at their root. Reinforcing this with a standard namespace URI would allow you to differentiate between actual RSS documents and other XML documents that just happen to have an
rsselement at their root. Apparently the writers of the RSS spec decided that wasn’t a big enough concern to warrant requiring a standard namespace URI for the RSS standard.
But that doesn’t change the fact that elements in the default namespace of an RSS document must be valid RSS elements.
There’s nothing ambiguous about the default namespace. RSS just doesn’t mandate a standard URI for it. It does, however, specifically state that non-RSS elements must be delcared to be in a specific namespace.
January 17th, 2006 at 10:45 pm
I’m pretty comfortable taking the reading of those over in Sam Ruby’s thread, that at a minimum the idea of a non-namespaced child of a namespaced child of a non-namespaced child of a non-namespaced element is ambiguous at best. But that being said, it’s hard to say things like “RSS doesn’t mandate a standard URI for [its default namespace]“, and that “just because an XML document doesn’t have a default namespace URI assigned to it doesn’t mean that it has no rules as to what tags can and cannot be put into it” — RSS doesn’t get to change the overarching XML spec, and XML specifically *does* say that if there’s no default namespace declared, there are precious few rules about what tags can and can’t be contained within it. It’s been the complaint since day one that RSS 2.0’s author did not choose to develop a namespace for it, and thus, there are no ways for validators or parsers to actually be able to determine what belongs and does not belong in an RSS 2.0 document.
Obviously, we don’t see eye to eye on this one; I just am not willing to say that we should reject Apple’s photocast feeds because they don’t adhere to the strict rules of XML (again, an ambiguous statement), but we should accept the base of RSS 2.0 despite the fact that it doesn’t adhere to the need for an explicitly-declared, well-defined default namespace. We either need to be consistent in our requirement for well-defined namespaces, or lax in that requirement — in the first case, RSS 2.0 fails, and in the second, there aren’t any problems at all.
January 17th, 2006 at 11:14 pm
Jason,
There are the rules of XML, and there are the rules of RSS. Apple’s photocast feeds are certainly valid XML, because all XML requires is well-formedness. From the beginning, my beef has been with photocast feeds not being valid RSS.
Not at all. The standards are very specific about this, and it is done all the time in XSLT. Consider this common XSLT template that outputs HTML:
Those HTML tags in the template are still HTML, even though they are descendants of an element in the XSLT namespace. The default namespace in this document is HTML.
The only difference between the above example and RSS is that RSS has no standard namespace URI that should be used to identify its tags.
As I mentioned above, the only thing XML requires is well-formedness. Beyond that, the only thing that can specify what can and can’t go into an XML document is a spec like RSS 2.0 (which can be made machine-enforcable through a DTD).
The purpose of namespaces, rather, is to identify elements that belong to a given XML language when they are embedded in an XML document of a different type. Since there is no convincing use case for RSS 2.0 elements to be embedded in another XML document, there was no pressing need to specify a standard namespace URI for it.
Namespaces do not identify what DTD to use to validate a document. That’s what document type declarations (
<!DOCTYPE ...>) are for. A more valid complaint would be that RSS 2.0’s author didn’t develop a formal DTD (or XML Schema) that could be used to validate RSS 2.0 documents. That’s why tools like the Feed Validator are necessary.
I’m not saying anything of the kind. It’s the strict rules of RSS 2.0 that they don’t adhere to.
There is no such need. Not even the XML Namespaces spec itself requires all elements to have an assigned namespace URI. XML documents were being validated long before XML namespaces came along.
January 18th, 2006 at 11:27 am
[...] [...]
January 18th, 2006 at 1:12 pm
Despite the naysayers here who can’t see anything wrong with iPhoto’s RSS implementation, it really is spectacularly bad:
January 18th, 2006 at 3:09 pm
Without too much proof, it takes Apple three releases to get the best of their new technologies. It was pretty much the case for their OS and ITune.
I don’t know if Apple if following Agile development strategy, but putting something on the market, getting feedback and producing upgrade few months later sound like Agile. Get your product on the market have it discuss good or bad and learn from it. Stop the project and save money if this is not good, or improve on the knowledge.
Now for the RSS feed, I’ll leave that to other to discuss if it is incorrect or some readers doesn’t support the standard.
Have a good day.
Hugues Lamy
January 18th, 2006 at 7:47 pm
Thanks for that link, Mark. Though my main concern with iPhoto is the feed generated by their service, the state of their preferred client goes a long way towards explaining it:
January 18th, 2006 at 11:17 pm
My only point here is that you aren’t pefect either. I think the few errors in Apple’s generated feed are not drastic enough to lash out at them to this point. While I agree it should be brought to Apple’s attention you are taking it a level too far, elevating it to an unacceptable level.
I find you are simply looking for a small flaw in Apple’s system to criticize them just for the sake of criticizing them.
As mentioned earlier, Apple is good about fixing flaws such as this and getting them cleaned up. That is why Safari had the first official release of a browser that passed Acid2.
For such a small error you’re making an alwful big deal about it. I haven’t seen any lashing for the HTML generated by FrontPage?
January 18th, 2006 at 11:22 pm
charmedlover:
That’s because there’s still hope for Apple. :)
January 19th, 2006 at 1:48 am
Of course, maybe this is an intelligently written post which is designed just to get attention. And draw attention to the advertising.
Bashing Apple Sells newspapers
January 19th, 2006 at 5:40 am
“the new Microsoft” - Kevin, what ever you are smoking, either cut back on it or blog about it so the rest of us can join in.
January 19th, 2006 at 9:23 pm
[...] Steve Jobs is a salesman. He’s possibly the best salesman on the planet, but that doesn’t make him a god, or even someone worth your attention. It means his purpose in life is to clean your wallet. And guess what? He’s done a respectable job thus far. Not exactly in Bill Gates territory (although Kevin Yank says Apple is the new Microsoft, but it beats the hell out of working for a living. It’s a lot like half the U.S. population bitching about the sinking ship they’re on: Bitch away, Mary, but you created this mess. [...]
January 19th, 2006 at 9:30 pm
Even with a compatible feed reader, the actual feed is not located at photocast.mac.com/… but at the URL that’s specified in the error message. Apple is looking at the User-Agent, and if it’s supported (eg, it contains “NetNewsWire/”) it returns a 302 redirect to the actual feed.
January 19th, 2006 at 11:12 pm
[...] SitePoint Blogs » Apple “photocasting” Mac only, uses invalid RSS Quote: “If I had my doubts before, I stand corrected. Apple is the new Microsoft.” Wow. (tags: apple mac iphoto rss) [...]
January 23rd, 2006 at 7:38 pm
Zeldman’s take on the issue — iPhoto , iTunes, iForgotToTest
February 10th, 2006 at 6:59 pm
Apple has also published invalid examples of RSS 2.0 in the iTunes specification [1]. See “An Example Feed” and note there is no element in the channel. I’m discussing this and other “missing information” in their syndication-dev@lists.apple.com list.
I encourage others to show up in that list and support the concerns I have discussed as well as any you may have yourself.
[1]
April 6th, 2007 at 4:39 am
More a question than a statement.
One of the iPhoto photocasting feeds I subscribe to is
It appears (to me, anyway) to be:
(1) iPhoto compatible and iPhoto RSS sound
(2) Yahoo media RSS compatible
(3) RSS 2.0 valid
(4) .mac independent
Am I right about that? If so, should/could I use it as a template for my own photocast, or is there something here that I’m completely missing?
Tx | http://www.sitepoint.com/blogs/2006/01/17/apple-photocasting-mac-only-uses-invalid-rss/ | crawl-002 | refinedweb | 3,669 | 70.94 |
Hi Stepan, > here is an explanation of your problem: sntp/libopts is a subdir > of both of the packages: ntp-4.0.2b and ntp-4.0.2b/sntp. Yes... > So if you run automake in both of these projects, both runs will > generate sntp/libopts/Makefile.in. Yes, which I agree is probably wrong, but at this time I want to allow people to build ntp and not build sntp. I may have to change my mind on this one! > Well, this is consitent with the fact that both ./configure and > sntp/configure will generate sntp/libopts/Makefile. OK... > To fix this, it's enough to delete (comment out) the line > > AC_CONFIG_FILES(AO_Libopts_Dir/Makefile) > > from m4/libopts.m4 (but not from sntp/m4/libopts.m4 !). That will be Ugly, but I'll talk to Bruce about how we might do this. If this is what we need to do, I suspect we'll have a 2nd argument to the LIBOPTS_CHECK macro. > (Automake processes as config files which have a corresponding .am file.) > > But sntp/libopts is still listed in DIST_SUBDIRS in the root Makefile. > I don't think this is healthy, so I'd delete it. > > Actually, I think it's better if define DIST_SUBDIRS implicitly, like > this: > > if WITH_ARLIB > SUBDIR_arlib = arlib > endif > if WITH_SNTP > SUBDIR_sntp = sntp > edif > if NEED_LIBOPTS > ## We have to omit this from DIST_SUBDIRS, it is handled by the > ## sntp package. > ## HACK: this is achieved by using an AC_SUBSTed variable, which is > ## not known statically. > SUBDIR_libopts = $(LIBOPTS_DIR) > edif > SUBDIRS = \ > $(SUBDIR_libopts) \ > scripts \ > include \ > ElectricFence \ > $(SUBDIR_arlib) \ > libntp \ > libparse \ > ntpd \ > ntpdate \ > ntpdc \ > ntpq \ > parseutil \ > adjtimed \ > clockstuff \ > kernel \ > $(SUBDIR_sntp) \ > util But this solution will only work if we *always* build sntp, as otherwise sntp/libopts/Makefile will not be generated. Again, this may be what I have to do. > BTW: > I have noticed that libopts/Makefile.am contains > MAINTAINERCLEANFILES = Makefile.in > I think this is unfortunate: according to the Coding Standards, > you should still be able to run ./configure after running > "make maintainer-clean". > > I understand that there is a need for a target which would bring > the tree back to the state when it was checked from the CVS, but that > should have a different name, eg. "make mrproper" or "bootstrap --clean". > > Or you can try to change the GCS that the current definition of > maintainer-clean should be changed. Such a change would be nice, but > might be actually a lot of work. That's for Bruce to decide, I suspect. > Have a nice day, You too, and thanks very much! H | http://lists.gnu.org/archive/html/automake/2005-09/msg00075.html | CC-MAIN-2013-20 | refinedweb | 424 | 65.83 |
Seam identity loginguy bashan Jul 4, 2008 8:23 PM
I am having a weird behavior with Seam and identity login.
1) My username is actually an email. I use identity.rememberMe. It seems like the data after the
@ character is being truncated. for example if I use: xx@xxx.com, the username data stored in the cookie is:
xx.
2) After doing a logout, then login again, Seam is persisting a new password to my database (it is possible that by making a login, the user data is being persisted to the database somehow)?
This is my bean code:
@Name("authenticator") public class AuthenticatorAction { @In Session myDatabase; @Out(required = false, scope = SESSION) private User user; @Logger private Log log; @In Identity identity; public boolean authenticate() { String password = DigestUtils.shaHex(identity.getPassword()); log.info("Authenticating user: #{identity.username} with password: #{identity.password}"); List results = nikoniansDatabase.createQuery("select u from User u where " + "u.email=#{identity.username} and u.password=:password").setParameter("password", password).list(); if (results.size() == 0) { log.info("User: #{identity.username} was not found"); return false; } else { user = (User)results.get(0); log.info("User: #{user.email} (user.userId) was authenticated"); return true; } } }
1. Re: Seam identity loginliu lei Jul 5, 2008 11:46 AM (in response to guy bashan)
I meet the same problem.
I checked the cookie directly,it seems that the email was saved correctly in cookie.But when been fetched by the identity for displaying, the email has been truncated.
It seems to be a bug.
Warting for the solution.
2. Re: Seam identity loginguy bashan Jul 5, 2008 4:27 PM (in response to guy bashan)
I have already faced this problem with a non-Seam application. It seems to be a browser specific issue. I think it is related to FireFox 3, since I didn't have it on earlier FireFox versions (but I may be wrong...). Anyway, I simply solved it in the none-Seam application by replacing the @ with ~ . Is there a workaround for this problem in Seam? Is it a reported bug?
3. Re: Seam identity loginliu lei Jul 6, 2008 5:10 AM (in response to guy bashan)
I don't think so.
I get the same problem both in ie/Firefox2/Firefox3.
Other browsers haven't been checked yet.
Besides,I have told that the email saved in cookie is correct.
I'm using SEAM 2.0.2SP1.
4. Re: Seam identity loginmichael pan Jul 6, 2008 9:50 AM (in response to guy bashan)
I have the same question.
5. Re: Seam identity loginguy bashan Jul 7, 2008 12:41 AM (in response to guy bashan)
Hi,
Anything new with this issue?
6. Re: Seam identity loginnathan dennis Jul 7, 2008 2:40 AM (in response to guy bashan)
you guys arent leaving jsf commented out in your xhtml files are you? the interpreter will instantiate things within a comment. it has bit me several times in project i am currently working on..... including but not limited to... over writing my passwords in entity object.
7. Re: Seam identity loginliu lei Jul 7, 2008 8:31 AM (in response to guy bashan)
you means i should remove all the
<!-- comment -->in the jsf file?
That's weird.
Althought I removed all the
commentin the page, the bug is still there.
Waiting for the official reply.
8. Re: Seam identity loginShane Bryzak Jul 9, 2008 5:09 AM (in response to guy bashan)
I can't reproduce this. I tested with the Seamspace example, using shane@test.com as the username, and the cookie was persisted correctly, and also read back correctly into the Identity component. I'm using Firefox 3.
9. Re: Seam identity loginShane Bryzak Jul 9, 2008 5:10 AM (in response to guy bashan)
Oh and I should add that I'm also using latest SVN version of Seam. You may wish to try with the same version and see if the issue is still occurring.
10. Re: Seam identity loginguy bashan Jul 10, 2008 12:30 AM (in response to guy bashan)
I just put the latest version of Seam and it still doesn't work.
This is a weird problem, obviously it is not related to Seam but to the cookie mechanism.
I a non-Seam application that I have it just
startedhappening one day about a month ago. I cannot point out what was changed that caused this behavior. It becomes weirder: when I put the non-Seam application in production, it all works well and cookie information is fetched correctly.
Currently the only think I can thing of is that the Antivirus/Firewall (Bitdefender) may be blocking things there, but it seams like a weak assumption... let me know (the others that have this problem) if you are also using Bitdefender... ;-)
Some other thing I wanted to know about this rememberMe feature: Shouldn't it automatically login the user? I go to login screen, put my details and login. Then I take down the webapp and raise it again. It doesn't do autologin. When I go back to the login screen I see the
usernamefield filled automatically.
Is there a way of making autologin in Seam (assuming the
Thanks,
Guy.
11. Re: Seam identity loginShane Bryzak Jul 10, 2008 4:58 AM (in response to guy bashan)
The auto-login feature will only be available in Seam 2.1.0 (where it is still not a recommended practice due to the possibility of XSS attacks).
12. Re: Seam identity loginguy bashan Jul 10, 2008 9:40 AM (in response to guy bashan)
Is this feature already implemented in 2.1.0 (I am trying it now)?
Thanks,
Guy.
13. Re: Seam identity loginliu lei Jul 10, 2008 10:42 AM (in response to guy bashan)
I have tried this with firefox3.0,the bug is still there.
I will try the
Seamspace example.
14. Re: Seam identity loginguy bashan Jul 10, 2008 9:12 PM (in response to guy bashan)
Anything came up the Seamspace example? | https://developer.jboss.org/thread/182888 | CC-MAIN-2019-18 | refinedweb | 1,008 | 66.64 |
Building a Game with Three.js, React and WebGL
For a high-quality, in-depth introduction to React, you can’t go past Canadian full-stack developer Wes Bos. Try his course here, and use the code SITEPOINT to get 25% off and to help support SitePoint.
I’m making a game titled “Charisma The Chameleon.” It’s built with Three.js, React.
Recommended Courses>
Now we have an empty 3D scene with a camera. Adding a mesh to the scene is as simple as including a
<mesh /> component, and giving it
<geometry /> and a
<material />.
<scene> … <mesh> <boxGeometry width={ 1 } height={ 1 } depth={ 1 } /> <meshBasicMaterial color={ 0x00ff00 } /> </mesh>
Under the hood, this creates a THREE.Scene and automatically adds a mesh with THREE.BoxGeometry. R3R handles diffing the old scene with any changes. If you add a new mesh to the scene, the original mesh won’t be recreated. Just as with vanilla React and the DOM, the 3D scene is only updated with the differences.
Because we’re working in React, we can separate game entities into component files. The Robot.js file in the example repository demonstrates how to represent the main character with pure React view code. It’s a “stateless functional” component, meaning it doesn’t hold any local state:
const Robot = ({ position, rotation }) => <group position={ position } rotation={ rotation } > <mesh rotation={ localRotation }> <geometryResource resourceId="robotGeometry" /> <materialResource resourceId="robotTexture" /> </mesh> </group>;
And now we include the
<Robot /> in our 3D scene!
<scene> … <mesh>…</mesh> <Robot position={…} rotation={…} /> </scene>
You can see more examples of the API on the R3R GitHub repository, or view the complete example setup in the accompanying project.
Organizing Game Logic
The second half of the equation is handling game logic. Let’s give SitePointy, our robot, some simple animation.
How do game loops traditionally work? They accept user input, analyze the old “state of the world,” and return the new state of the world for rendering. For convenience, let’s store our “game state” object in component state. In a more mature project, you could move the game state into a Redux or Flux store.
We’ll use the browser’s
requestAnimationFrame API callback to drive our game loop, and run the loop in GameContainer.js. To animate the robot, let’s calculate a new position based on the timestamp passed to
requestAnimationFrame, then store the new position in state.
// … gameLoop( time ) { this.setState({ robotPosition: new THREE.Vector3( Math.sin( time * 0.01 ), 0, 0 ) }); }
Calling
setState() triggers a re-render of the child components, and the 3D scene updates. We pass the state down from the container component to the presentational
<Game /> component:
render() { const { robotPosition } = this.state; return <Game robotPosition={ robotPosition } />; }
There’s a useful pattern we can apply to help organize this code. Updating the robot position is a simple time-based calculation. In the future, it might also take into account the previous robot position from the previous game state. A function that takes in some data, processes it, and returns new data, is often referred to as a reducer. We can abstract out the movement code into a reducer function!
Now we can write a clean, simple game loop that only has function calls in it:
import robotMovementReducer from './game-reducers/robotMovementReducer.js'; // … gameLoop() { const oldState = this.state; const newState = robotMovementReducer( oldState ); this.setState( newState ); }
To add more logic to the game loop, such as processing physics, create another reducer function and pass it the result of the previous reducer:
const newState = physicsReducer( robotMovementReducer( oldState ) );
As your game engine grows, organizing game logic into separate functions becomes critical. This organization is straightforward with the reducer pattern.
Asset management
This is still an evolving area of R3R. For textures, you specify a
url attribute on the JSX tag. Using Webpack, you can require the local path to the image:
<texture url={ require( '../local/image/path.png' ) } />
With this setup, if you change the image on disk, your 3D scene will live update! This is invaluable for rapidly iterating game design and content.
For other assets like 3D models, you still have to process them using the built-in loaders from Three.js, like the JSONLoader. I experimented with using a custom Webpack loader for loading 3D model files, but in the end it was too much work for no benefit. It’s easier to treat the model as binary data and load them with the file-loader. This still affords live reloading of model data. You can see this in action in the example code.
Debugging
R3R supports the React developer tools extension for both Chrome and Firefox. You can inspect your scene as if it were the vanilla DOM! Hovering over elements in the inspector shows their bounding box in the scene. You can also hover over texture definitions to see which objects in the scene use those textures.
You can also join us in the react-three-renderer Gitter chat room for help debugging your applications.
Performance Considerations
While building Charisma The Chameleon, I’ve run into several performance issues that are unique to this workflow.
- My hot reload time with Webpack was as long as thirty seconds! This is because large assets have to be re-written to the bundle on every reload. The solution was to implement Webpack’s DLLPlugin, which cut down reload times to below five seconds.
- Ideally your scene should only call one
setState()per frame render. After profiling my game, React itself is the main bottleneck. Calling
setState()more than once per frame can cause double renders and reduce performance.
- Past a certain number of objects, R3R will perform worse than vanilla Three.js code. For me this was around 1,000 objects. You can compare R3R to Three.js under “Benchmarks” in the examples.
The Chrome DevTools Timeline feature is an amazing tool for debugging performance. It’s easy to visually inspect your game loop, and it’s more readable than the “Profile” feature of the DevTools.
That’s It!
Check out Charisma The Chameleon to see what’s possible using this setup. While this toolchain is still quite young, I’ve found React with R3R to be integral to organizing my WebGL game code cleanly. You can also check out the small but growing R3R examples page to see some well organized code samples.
This article was peer reviewed by Mark Brown and Kev Zettler. Thanks to all of SitePoint’s peer reviewers for making SitePoint content the best it can be! | https://www.sitepoint.com/building-a-game-reactjs-and-webgl/?utm_source=sitepoint&utm_medium=relatedsidebar&utm_term=javascript | CC-MAIN-2018-05 | refinedweb | 1,084 | 57.27 |
I dont know what has happened to my pc .
I have win xp and borland c++ (3.1) and it is in 2 models ( one is run at windows and the other is run at Dos ) . usually I use the one that is run at win .
for one of my classes I need to get the aski code of a simple program and our teacher told us useing the compiler that is run at Dos is better for undresatnding the aski code (if it be at win , the aski code will have some more codes ), but know I cant use the one that is run at Dos .
when I enter the environment (the blue page that is similar to paskal invironment), both of keyboard and mouse stop working and just the " win " key of my keyboard works .
can any one tell me what is wrong ? I have to solve this problem cause I must get the aski code and bring it for my teacher .
can one of u use this code in his(her) compiler and give me the aski code ?
Code:#include <iostream.h> int f(char,float); int g=1; int main(){ char a='A'; float b=3.2; int k; k=f(a,b); cout << k; return 0;} int f(char a,float b){ static int c=20; int f=6; cout << a <<'\n'; cout << b <<'\n'; cout << g <<'\n'; c+=f; cout << c <<'\n'; return (12);}
thanks alot | http://cboard.cprogramming.com/cplusplus-programming/58777-keyboard-stop-working-dos.html | CC-MAIN-2015-11 | refinedweb | 242 | 84.61 |
In this tutorial you will learn how angular 2 routing and navigation works. On the real example I will show you how to configure routes for our Angular application. Also you will learn what for do you need router-outlet and router-link components in Angular.
So what is frontend routing? When we load frontend application, for example Angular, then it's always the same index.html page which is completely empty. It doesn't matter in what url of the project we are going, it's always the same empty index.html. But inside this html we have javascript which decides what content to show depending on the path in url, parameters and other routing related stuff. Then when we change the page we don't reload the page. Instead javascript removes current page and renders new page. This is why it's a Single Page Application without reloading.
Angular gives us all this stuff out of the box and we can use it right away. Let's look inside app.module.ts. Inside you can see a module AppRoutingModule. Inside you can see a small module with routes on the top. Empty array means that we don't register any routes. And code RouterModule.forRoot(routes) registers this array of routes inside our application.
Normally we have a layout inside the app.component and then we loading different components on different pages. Let's try this now to see how it works. But to make it really correct we need to create 2 modules each for specific page. This is how people normally doing it in the application. Let's create 2 modules login and register.
First of all we need a login folder and a module inside
login/login.module.ts
import {CommonModule} from '@angular/common' import {NgModule} from '@angular/core' import {LoginComponent} from './login.component' @NgModule({ declarations: [LoginComponent], imports: [CommonModule], }) export class LoginModule {}
We simple registered inside 1 component LoginComponent which is planned for our login page
Now we need to add login.component.
import {Component} from '@angular/core' @Component({ selector: 'app-login', templateUrl: './login.component.html', }) export class LoginComponent {}
and some markup.
<div>Login page</div>
The same we need to do for register page. It looks completely the same but we just replaced all names with Register.
Now we should register this two modules inside app.module.ts
imports: [ ... LoginModule, RegisterModule, ]
Our modules are completely ready. Now we just need to create routes for this 2 modules.
app-routing.module.ts
const routes: Routes = [ { path: 'login', component: LoginComponent, }, { path: 'register', component: RegisterComponent, }, ]
So routes is an array of objects with path and component. Now in browser we can just for example in login page without any error. But the problem is that we don't see the content of this component when we just to that page. This is because we didn't write in app.component.html special routing component which renders our components for specific pages.
<router-outlet></router-outlet>
Now in browser you can see that login page was rendered. If we just to register page than our other component will be rendered.
So this is how we normally create modules and render pages.
Let's add now 2 links inside our app.component.html so we can just without page reloading between pages.
<a routerLink="/login">Login</a> <a routerLink="/register">Register</a>
As you can see we can now jump between pages. You might ask what is this routerLink? It's a special property binding to create links between pages. But you might ask where are square brackets? Normally we write property bindings with square brackets that's true. But if we want to simple give a string inside we can omit them. Then it will just take a string from the value on the right.
It we put here square brackets we need to define our string as a real javascript string.
<a [routerLink]="'/login'">Login</a>
And this is less readable.
In this video you learned on the real example how routing is working in Angular and what is routerLink.
As it's a last video in Angular for beginners series I think you have enough knowledge to jump in my advanced Angular course. It won't easy of course but it's the knowledge that you need to fully understand how to create applications in Angular.
If angular for beginners is too easy for you or you want more advanced stuff check my 14 hours Angular course where we create a real project from beginning to the end. Link is also in the description. | https://monsterlessons-academy.com/posts/routing-in-angular | CC-MAIN-2022-40 | refinedweb | 768 | 59.09 |
Andy Wingo <address@hidden> schrieb: > Your patches look good, except for one. > > On Wed 21 Apr 2010 22:22, Volker Grabsch <address@hidden> writes: > > > --- a/libguile/bdw-gc.h > > +++ b/libguile/bdw-gc.h > > @@ -34,6 +34,8 @@ > > > > #endif > > > > +#define GC_NO_THREAD_REDIRECTS > > + > > #include <gc/gc.h> > > Why did you do this? The GC thread redirects causes some compiling errors, so I disabled them. I didn't digg further into that. Maybe there's a better solution. Since the patches are mostly independent from each other, I think it is okay to ignore that patch and commit just the other ones. Regarding the MinGW issues, there's more work to be done anyway. Greets, Volker -- Volker Grabsch ---<<(())>>--- Administrator NotJustHosting GbR | http://lists.gnu.org/archive/html/guile-devel/2010-05/msg00051.html | CC-MAIN-2015-22 | refinedweb | 118 | 69.79 |
RTC alarm with sleep mode does not work, WiPy never wakes
Hi, the issue is not completely new. In a previous firmware update it is listed as a known issue ("RTC periodic alarm with sleep mode is unstable, sometimes the WiPy never wakes"). However, the same problem occurs also in single mode (repeat=False). My wipy never wakes up from sleep mode when using the RTC alarm (I am using a wipy 1.0 with latest firmware and pycom extension board vs 1.0). Quite disappointing.
That's the code I used to implement the RTC alarm (without success)
import machine
from machine import RTC
import os
import time
rtc = RTC()
rtc.alarm(time=500, repeat=False)
rtc_irq = rtc.irq(trigger=RTC.ALARM0, handler=None, wake=machine.SLEEP)
machine.sleep()
I can get the wipy to wake up (using identical code) by connecting to an ftp client or when I use REPL. | https://forum.pycom.io/topic/51/rtc-alarm-with-sleep-mode-does-not-work-wipy-never-wakes | CC-MAIN-2018-51 | refinedweb | 152 | 64.61 |
An Introduction to Elm
Elm is a functional language that compiles to JavaScript. It helps you make websites and web apps. It has a strong emphasis on simplicity and quality tooling.
This guide will:
- Teach you the fundamentals of programming in Elm.
- Show you how to make interactive apps with The Elm Architecture.
- Emphasize principles and patterns that generalize to programming in any language.
By the end I hope you will not only be able to create great web apps in Elm, but also understand the core ideas and patterns that make Elm nice to use.
If you are on the fence, I can safely guarantee that if you give Elm a shot and actually make a project in it, you will end up writing better JavaScript code. The ideas transfer pretty easily!
A Quick Sample
Here is a little program that lets you increment and decrement a number:
import Browser import Html exposing (Html, button, div, text) import Html.Events exposing (onClick) main = Browser.sandbox { init = 0, update = update, view = view } type Msg = Increment | Decrement update msg model = case msg of Increment -> model + 1 Decrement -> model - 1 view model = div [] [ button [ onClick Decrement ] [ text "-" ] , div [] [ text (String.fromInt model) ] , button [ onClick Increment ] [ text "+" ] ]
Try it out in the online editor here.
The code can definitely look unfamiliar at first, so we will get into how this example works soon!
Why a functional language?
You can get some benefits from programming in a functional style, but there are some things you can only get from a functional language like Elm:
- No runtime errors in practice.
- Friendly error messages.
- Reliable refactoring.
- Automatically enforced semantic versioning for all Elm packages.
No combination of JS libraries can give you all of these guarantees. They come from the design of the language itself! And thanks to these guarantees, it is quite common for Elm programmers to say they never felt so confident while programming. Confident to add features quickly. Confident to refactor thousands of lines. But without the background anxiety that you missed something important!
I have put a huge emphasis on making Elm easy to learn and use, so all I ask is that you give Elm a shot and see what you think. I hope you will be pleasantly surprised! | https://guide.elm-lang.org/ | CC-MAIN-2021-43 | refinedweb | 378 | 65.32 |
We may want it dynamic, more animated, .... etc
Here is a custom message box library I created as an example of what you can do
you can then use this dll in all your projects as well
Let's Begin:
What I wanted to do with my message box is:
1- The message appears letter by letter in a nice animation
2- The picture in the box not to be one still picture, I wanted to select a path and view all the pictures in a sequence (just like GIF files)
3- I wanted to create custom buttons
I. First of all: (Creating the Form)
I created the form (msgfrm) and changed the opacity to 70%
included a picture box (pbPics)
and a label to include the message (lblMsg)
finally two timers to use in our animations one for text(Timer1) animation and the other for pictures animation (Timer2)
II. Creating a Global class of variables:
I created all.vb as a class containing all variables I need
Module all Public title As String ' Title of the message box Public list As New ArrayList ' List of pictures to view Public message As String ' The message contained in the message box Public temp As Char() ' array of characters for the message body Public count1 As Integer = 0 ' Counter for the text timer Public count2 As Integer = 0 ' counter for the picture timer Public result As String ' name of the button clicked by the user Public path As String ' path of the folder for pictures Public type As String ' type of the custom message Public names As New ArrayList ' array containing names of buttons to create Public xcenter, ycenter As Integer ' position of the form Public filename As String ' Public x, y As Integer ' variables to adjust buttons positions Public btns ' array of buttons Public clicked As Boolean = False ' to show a button is clicked End Module
I think the comments are self-explaining
III. Creating The Message box class
as we will use forms and file system so we will import three name spaces
Imports System.IO Imports System.Windows.Forms Imports System.Drawing
I declared some variables to use through the class methods
Public Class Msg Public messageBox As New msgfrm ' Creates a new instance (Object) from the form ' Enum to choose type of message buttons (you can create more if you wish) Enum CustomType OK = 1 OkCancel = 2 YesNo = 3 Custom = 4 End Enum
I created two overloaded functions to show the custom message
The first one is taking 4 parameters:
1- Title
2- Message
3- Path to pictures
4- Type
Public Function AniMsg(ByVal titlevar As String, ByVal MessageVar As String, ByVal PathVar As String, ByVal MsgType As CustomType) center of the screen xcenter = (Screen.PrimaryScreen.WorkingArea.Width - messageBox.Width) / 2 ycenter = (Screen.PrimaryScreen.WorkingArea.Height - messageBox.Height) / 2 messageBox.Left = xcenter messageBox.Top = ycenter ' Call the method responsible for showing body of the message ShowMsg() ' Call the method responsible for showing the pictures ShowPic() ' clears the buttons in the array names.Clear() ' set the button names depending on the type chosen Select Case type Case CustomType.OK names.Add("Ok") Case CustomType.OkCancel names.Add("Ok") names.Add("Cancel") Case CustomType.YesNo names.Add("Yes") names.Add("No") End Select ' Create the buttons ShowBtn() ' finally show the message box messageBox.ShowDialog() Return result ' returns the button name that was clicked by the user End Function
The second one taking 7 parameters:
1- Title
2- Message
3- Path to pictures
4- Type
5- Custom Button Names
6- Top position
7- Left position
Public Function AniMsg(ByVal titlevar As String, ByVal MessageVar As String, ByVal PathVar As String, ByVal MsgType As CustomType, ByVal CustomAnswers As String(), ByVal Top As Integer, ByVal Left As Integer) specified parameters xcenter = Left ycenter = Top MessageBox.Left = xcenter MessageBox.Top = ycenter ' Call the method responsible for showing body of the message ShowPic() ' Call the method responsible for showing the pictures ShowMsg() ' clears the buttons in the array names.Clear() ' set the button names depending on the type chosen Select Case MsgType Case CustomType.OK names.Add("Ok") Case CustomType.OkCancel names.Add("Ok") names.Add("Cancel") Case CustomType.YesNo names.Add("Yes") names.Add("No") Case CustomType.Custom ' if the user chose Custom type then he has to pass the answers array containing custom buttons For Each t In CustomAnswers names.Add(t) Next End Select ' Create the buttons ShowBtn() ' finally show the message box messageBox.ShowDialog() Return result ' returns the button name that was clicked by the user End Function
Then to the sub that creates the body of the message
Public Sub ShowMsg() ' make sure that the message height doesn't exceed the height of the form If message.Length > 656 Then ' if so then increase the height of the form ' we divide the remaining of the message by 82 (the message single line height by experience for the selected font) messageBox.Height += Math.Ceiling(((message.Length - 656) / 82)) End If ' make sure that the message doesn't exceed the label size If message.Length > 82 Then ' if so then increase label height ' we increase it per message line height messageBox.lblMsg.Height *= Math.Ceiling(message.Length / 82) End If messageBox.Text = "" ' convert the message to array of characters so we can show one letter in time temp = message.ToCharArray() ' set the counter to zero count1 = 0 ' start the timer to animate text messageBox.Timer1.Start() End Sub
and here is the timer function
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick Dim x As Char ' the character to be typed each timer tick ' if the counter exceeds the message length then stop If count1 > (message.Length - 1) Then Timer1.Stop() Return End If ' gets the character at the current position x = temp(count1) ' add the character to the label lblMsg.Text += x count1 += 1 ' increase the counter End Sub
Now the sub to show the pictures in the picture box
Public Sub ShowPic() ' make sure that the folder selected is valid If Directory.Exists(path) Then list.Clear() ' clears the picture list For Each fi In Directory.GetFiles(path) list.Add(fi) ' add files in this folder to the list Next ' set the counter to zero count2 = 0 ' start the timer messageBox.Timer2.Start() ' if this wasn't a directory then maybe a single file ElseIf File.Exists(path) Then ' gets the file name of the picture filename = path.Substring(path.LastIndexOf("\") + 1) ' then draw it to the picture box messageBox.pbPics.Image = System.Drawing.Bitmap.FromFile(path) End If End Sub
And here is the timer of the pictures
Private Sub Timer2_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer2.Tick ' if the counter reached the end of the list then restart it from the first If count2 = list.Count Then count2 = 0 End If ' assign each picture to the picture box for this tick Try pbPics.Image = System.Drawing.Bitmap.FromFile(list(count2)) Catch ex As OutOfMemoryException count2 += 1 End Try ' increase the counter count2 += 1 End Sub
till now we showed the pictures and the body in a beautiful way
the missing is the buttons of the message
Public Sub ShowBtn() ' get the x position of the first button created to be the same x as the message label ' and the y co-ordinate to be below the message by 10 pixels x = messageBox.lblMsg.Location.X y = messageBox.lblMsg.Location.Y + messageBox.lblMsg.Size.Height + 10 ' creates an array of buttons ' we are subtracting one as when you create the names array list, a null value is added to the last of the list Dim btns(names.Count - 1) As Button ' Loop to create buttons Dim i As Integer For i = 0 To btns.Count - 1 btns(i) = New Button() ' create a new instance of the button btns(i).Text = names(i) ' get the name of the button btns(i).Size = New Size(btns(i).Text.Length * 15, 25) ' assign the length of the button to its contents, but with a constant height AddHandler btns(i).Click, AddressOf BtnClick ' add an event handler to the button click ' after creating the first button If i > 0 Then ' check if the width of the form can create another button If (messageBox.Width - (btns(i - 1).Location.X + btns(i - 1).Size.Width + 10)) < btns(i).Size.Width Then ' if not, then set the x to the original x x = messageBox.lblMsg.Location.X ' and the y to a position under the last created button y = messageBox.lblMsg.Location.Y + messageBox.lblMsg.Size.Height + 38 End If End If ' set the button location btns(i).Location = New Point(x, y) messageBox.Controls.Add(btns(i)) ' add the x by 10 pixels to draw the next button x += 10 + btns(i).Size.Width Next End Sub
here is the button click event handler
Public Sub BtnClick(ByVal sender As Object, ByVal e As EventArgs) ' set the name of the button to the result result = CType(sender, Button).Text ' set clicked to be True clicked = True ' close the form messageBox.Close() End Sub
We are finished
now build the library and move on to the next step
IV. Try the library
take the dll file and import it into a new project by adding it as a reference
I created a form with a button and here is the button click
Imports CustomMessage Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim title, message, path As String Dim top, left As Integer Dim buttons(0 To 3) As String title = "Ahmedn1" message = "This is a test message for the Custom message class,\nYou can try any thing in this dll (namespace),\nTrust me it is very useful" path = "D:\Images\Anime" top = 100 left = 200 buttons(0) = "Ok" buttons(1) = "Cancel" buttons(2) = "Go away" buttons(3) = "Sure?!" Dim myMsg As New Msg MessageBox.Show(myMsg.AniMsg("Ahmedn1", message, path, Msg.CustomType.Custom, buttons, 100, 100)) End Sub End Class
try it and you can see the result as I can't attach it as a picture because the result is an animated message box
P.S.: you can change the timers intervals as you wish
I hope this was a useful tutorial for you as it is my first
| http://www.dreamincode.net/forums/topic/191206-custom-message-box/page__pid__1120315__st__0 | CC-MAIN-2013-20 | refinedweb | 1,731 | 60.14 |
23 October 2008 12:54 [Source: ICIS news]
LONDON (ICIS news)--Dow Chemical’s third-quarter earnings per share (EPS) slumped 29% year-on-year, excluding certain charges and gains, as profits from its hurricane-hit performance plastics and basic chemicals businesses tumbled, the company said on Thursday.
Third-quarter EPS was $0.60 against $0.84 in the third quarter of 2007, Dow said.
Net profits for the period were 6.2% higher at $428m (€334m), compared with $403m in the year-earlier period, with lower tax charges helping the most recent reporting period.
The chemical major said it was also hit by a 48%, or $2.6bn, surge in feedstock and energy costs, the largest increase in its history.
CEO Andrew Liveris warned of a global recession persisting through 2009 and said Dow would accelerate its focus on cost and capital control and on asset restructuring.
''Dow is well positioned, however, to weather this increasingly difficult economic downturn,” he said. “We have a strong balance sheet [and] we have a track record of strong financial discipline,” he added.
Sales were 13% higher at $15.4bn aided by a 22% increase in global prices, the largest year-on-year percentage increase, Dow said, since the first quarter of 2005.
Volumes were down 9% and hurt by the impact of Hurricanes Gustav and Ike. The volume decrease excluding the impact of those storms, however, was 5%.
Margin expansion was not achieved in both the basic and performance segments, as the hurricanes idled approximately 80% of the company’s North American capacity in September, when feedstock costs were declining, Dow said.
Earnings before interest and tax (EBIT) for Dow’s performance plastics business plunged to $146m in the quarter from $409m in the third quarter of 2007, while basic plastics' EBIT was down 13.4% at $481m against $556m in the third quarter of 2007.
Basic chemicals' EBIT dropped to $64m from $205m in the year-earlier quarter.
Profits from Dow’s agriculture businesses were higher and the company saw stronger income in the quarter from its joint ventures.
“Dow performed well in the third quarter despite a difficult economy and increased costs,” Liveris said.
“Our ability to take proactive measures, including the implementation of two broad-based price increases and aggressive cost controls, allowed us to post solid results against worsening market conditions, record high raw material costs and two hurricanes on the US Gulf,” he added.
'The global economy is now feeling the full effects of the same economic issues that have plagued the ?xml:namespace>
"These issues have now been exacerbated by the lack of credit, resulting in a drop in demand not only in the
"In our view, we will likely see a global recession through most of 2009," Liver | http://www.icis.com/Articles/2008/10/23/9165925/dows-q3-eps-drops-28-on-storms-and-slump.html | CC-MAIN-2014-15 | refinedweb | 463 | 61.36 |
XQuery/Installing eXgit
Contents
Background[edit]
Git has many features for managing data when many users are changing files around the world. Git has tools for seeing who has changed what data and how to view the differences. These features are not available in eXist (yet). However their is no standard REST interface for git.
Installing eXgit[edit]
Note: this is a work in progress. Not done! We hope to have a packinging tool and a simple to install .xar file in the future.
The software for eXgit is stored on github here:
This software depends on the Git Java library here:
You will need to build this project but the ONLY jar you need is:
org.eclipse.jgit.jar (Note, this is a 1.7MB file)
To build this I downloaded the zip file from github and did "mvn install". I did get errors so I had to do Mavin build with no tests:
mvn install -Dmaven.test.skip=true
Once you have both the jar files you can put them into $EXIST/lib/user
eXgit-0.3.0.jar org.eclipse.jgit.jar
You can now build the "xar file:
$ ant
This will put a build/eXgit-0.2.2.xar (about 1.6MB with the two jar files)
You can then load this into your eXist dashboard.
Note, for some reason the jar files are not working. We removed the reference to them in exist.xml and the build file and just manually copied them into the $EXIST_HOME/lib/user area.
Note that now the .xar file is about 2K!
Testing Installation[edit]
You must have a local git checkout.
Use this as your import statement:
import module namespace git="";
Sample XUnit Test[edit]
To test this you can clone any git repository. For example the following will make a copy of the eXide project in /db/exide.
xquery version "1.0"; import module namespace git=""; git:clone("", "/db/exide", "", "")
After this test runs you will notice that a .git file has been created in /db/exide/.git with all the git administrative files
Sample Unit Test[edit]
import module namespace {git:status($git-checkout-dir, '', false())} </testcase> | https://en.wikibooks.org/wiki/XQuery/Installing_eXgit | CC-MAIN-2016-40 | refinedweb | 361 | 76.32 |
3.9 I/O Efficiency
Using only the read and write functions, Program 3.3 copies a file. The following caveats apply to Program 3.3:
It reads from standard input and writes to standard output. This assumes that these have been set up by the shell before this program is executed. Indeed, all normal Unix shells provide a way to open a file for reading on standard input and to create (or rewrite) a file on standard output. This prevents the program from having to open the input and output files.
Many applications assume that standard input is file descriptor 0 and standard output is file descriptor 1. In this example we use the two defined names STDIN_FILENO and STDOUT_FILENO from <unistd.h>.
Program 3.3 Copy standard input to standard output.
#include "ourhdr.h" #define BUFFSIZE 8192 int main(void) { int n; char buf[BUFFSIZE]; while ( (n = read(STDIN_FILENO, buf, BUFFSIZE)) > 0) if (write(STDOUT_FILENO, buf, n) != n) err_sys("write error"); if (n < 0) err_sys("read error"); exit(0); }
The program doesn't close the input file or output file. Instead it uses the fact that whenever a process terminates, Unix closes all open file descriptors.
This example works for both text file and binary files, since there is no difference between the two to the Unix kernel.
One question we haven't answered, however, is how we chose the BUFFSIZE value. Before answering that, let's run the program using different values for BUFFSIZE. In Figure 3.1 we show the results for reading a 1,468,802 byte file, using 18 different buffer sizes.
Figure 3.1. Timing results for reading with different buffer sizes.
The file was read using Program 3.3 with standard output redirected to /dev/null. The filesystem used for this test was a Berkeley fast filesystem with 8192-byte blocks. (The st_blksize, which we describe in Section 4.12, is 8192.) This accounts for the minimum in the system time occurring at a BUFFSIZE of 8192. Increasing the buffer size beyond this has no effect.
We'll return to this timing example later in the text. In Section 3.13 we show the effect of synchronous writes, and in Section 5.8 we compare these unbuffered I/O times with the standard I/O library. | http://www.informit.com/articles/article.aspx?p=99706&seqNum=9 | CC-MAIN-2020-10 | refinedweb | 384 | 67.96 |
- 11 hours 297 Views | Created by Xiaoyun Li – MSFT - Wednesday, April 08, 2009 2:00 AM | Last reply by Ji.Zhou - Sunday, June 20, 2010 12:12 PM
- | 76 Views | Created by Vasilis Dimitriou - Tuesday, December 03, 2013 12:04 AM | Last reply by Vasilis Dimitriou - 53
C# and BlackberryIs it possible to write applications for Blackberry using only C#? TIA Worry is a misuse of imagination :)1 Replies | 31 Views | Created by incongruous - 2 hours 27 minutes ago | Last reply by Sheng Jiang 蒋晟 - 2 hours 3 3 minutes ago | Last reply by Christopher84 - 2 hours 25 | 52 Views | Created by abhijeeet - 6 hours 13 minutes ago | Last reply by Christopher84 - 2 hours 30 minutes ago
- Unanswered0Votes
listview selected index data rowusing vs 2012 c# I have a listview that contains a datatable, I added a binding source and bound some text boxes, how do I get the ...1 Replies | 35 Views | Created by CanAnn - 9 hours 8 minutes ago | Last reply by chriga - 2 hours 31 - 2 hours 32 minutes ago
- Unanswered0Votes
Getting used namespaces from other projectHello, I have a Class Library (Project_1) which uses a specific namespaces. After, I have other project (Project_2) which call the library and ...5 Replies | 52 Views | Created by Boltian - 5 hours 40 minutes ago | Last reply by PaulLinton - 2 hours 34 | 21 Views | Created by .Net Frenzy - 4 hours 30 minutes ago | Last reply by Sheng Jiang 蒋晟 - 2 hours 41 minutes ago
- Unanswered0Votes
c#- Monitoring an ExecutableI have to select any exe from my c# GUI app and monitor the file accesses for that ...4 Replies | 76 Views | Created by wbsat - 10 hours 57 minutes ago | Last reply by wbsat - 2 hours 44 | 31 Views | Created by SajiD designer - 4 hours 2 minutes ago | Last reply by Christopher84 - 2 hours 45 | 43 Views | Created by farooq.hnf - 13 hours 1 minutes ago | Last reply by PaulLinton - 2 hours 49 | 39 Views | Created by incongruous - 4 hours 42 minutes ago | Last reply by Mike Danes - 4 hours 29 | 27 Views | Created by A.B. Lambert - 5 hours 7 minutes ago
- Unanswered0Votes
visual studio c#hi, i downloaded a c# downloader from internet and then change the size and text of buttons but when I run the code it didn't change these things. plz tell whats the ...1 Replies | 38 Views | Created by MA Asim - 7 hours 1 minutes ago | Last reply by Wyck - 5 hours 43 | 108 Views | Created by nmedelec - Tuesday, December 03, 2013 9:07 PM | Last reply by Joel Engineer - 6 hours 26 minutes ago
- | http://social.msdn.microsoft.com/Forums/vstudio/en-us/home?forum=csharpgeneral | CC-MAIN-2013-48 | refinedweb | 429 | 52.87 |
The semantic Web has had some great claims made about it. With the recent advent of some C# class libraries for working with its various layers, it becomes easy to explore this 'greatness' practically and make up your own mind. One good application is to illustrate the effect the semantic Web can have on search results once data has become semantically structured. We are going to look at music genre as a good semantically rich information source that when related to music files has many advantages and creates a whole new Web of potential applications.
I'm sure you have all read background on what the semantic Web is and huge amounts of directed definitions. So I will try not add too much to your load. The semantic Web is a big mesh of information linked in a way that makes it machine processable, on a global scale. You can either think of it as being a new way of representing data on top of the World Wide Web or as a globally-linked database; your choice. With some recent class libraries developed in C# it is not only possible to implement, but ridiculously straight forward.
The first main difference between the Web and the semantic Web is the use of URIs, a more general form of URLs. This is the format in which Web addresses are written (). URIs, unlike URLs, do not necessarily retrieve information but are used to uniquely identify information on the semantic Web much like URLs are used to uniquely retrieve information on the current Web. The second major difference is that the semantic Web is built on RDF, instead of XHTML, which in turn is built on XML. This means we are only ever talking about data representation and not presentation. Sorry if you have confused the semantic Web with Web 2.0 but we will not cover those things here. RDF is used to create meta data about files and objects on the semantic or existing Web. Much like the meta data you include at the top of a current Web page or in a music file today except each item is uniquely identified with a URI instead of being just a string of text characters you type in. For example, to say an audiofile was performed by 'Chris' you break this meta-data statement into three parts; song1 URI, performer URI, Chris URI. All meta data statements, no matter how complex, can be broken down into these three parts; subject, predicate and value, respectively. However to be able to do anything useful with these statements, you must be able to define relationships. For example, if there was another meta data statement Chris URI (subject) CanOnlyPlay URI (predicate) Drums URI (Value). Then using these two statements, what Chris plays and the songs he plays on could be combined to attach the additional statement, Chris played drums on song1. This creation of new statements is done through a process known as inference by relating multiple meta-data statements often from multiple sources. These relationships are defined at the ontology or RDF-scheme level of the semantic Web in the diagram above.
To illustrate this, we are going to build a music system that uses the semantic Web to put a small amount of common sense inference into a semantic Web music search application. The idea is to give the semantic Web enough information to relate music files through their statements made about genres. I will keep this simple for the purpose of this article although you could add some really powerful functionality by defining complex relationships between statements. We will be using RDF scheme (RDFS) to define the relationships between statements. This is done by relating the URI strings in their subject predicate value parts using basic relationships such as SubClassOf. We will then use a C# class library to load in the statements from multiple RDF documents that describe several music files as well as load in the relationships defined in the RDF scheme document. The C# class library will then be used to create new statements (inference).
SubClassOf
RDFS's inference is not a complex task, but a simple set of 12 rules that are continuously applied to a list of statements already made. This continues to add new statements until no new statements can be added. These rules take the simple format of, if this subject, predicate and value then you can add this additional subject, predicate and value. All you need to do is keep looping through all the rules until you stop adding statements. A process known as entailment. At which point inference is complete. Very simple!
You can then query this newly created list of statements using various matches on different subject-predicate-value string combinations. For example if I want to find out what Chris played on song one I might ask something like Chris (subject) played(predicate) null(value), couldn't be easier, interpreted as what URI string value is connected to URI representing the subject Chris by the predicate played.
The wonderfully easy to use semantic Web library for C# semweb has all the capabilities needed to illustrate the huge range of potential music applications of the semantic Web.
The RDFS document supplied in the zip file contains genre and sub-genre relationships. The ontology is simplistic, not containing huge amounts of musical genre relationships, but could be easily expanded if needed.
The example code below is from the sample ASP.NET C# application. It was written in Visual Studio. NET 2005 using C# 2.0 but should work on previous versions. It requires the SemWeb class library produced by Joshua Tauberer which is easy to use. It simply does what it says on the tin. It first loads in two RDF documents music.xml and tracks.xml. Both RDF documents contain statements about music files which could be located anywhere on the Internet. It then sets-up strings to be used for the URIs, loads in the RDF scheme document (genre.xml) and creates an inference object passing in the scheme document and the two document assertions. This creates the new statements which are then queried to produce the results. Two queries are made, one against the store of statements before-any other statements have been added through inference, the other against the store of statements after the inference has taken place.
//A place memory store where the triples will be stored.
Store store = new MemoryStore();
Store store2 = new MemoryStore();
//Load first RDF document which is in XML format from a URL containing first lot
//of music statements
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
doc.Load("");
store.Import(new RdfXmlReader(doc)); // import assertions from document into the store
//load second RDF document which is in XML format from a URL containing second lot
//of music statements
System.Xml.XmlDocument doc3 = new System.Xml.XmlDocument();
doc3.Load("");
store.Import(new RdfXmlReader(doc3)); // import assertions from document into the store
//Define some representations (Entities) using URIs to identify some XML namespaces
const string RDF = "";
const string GEN = "";
Entity rdftype = RDF + "type"; //define the string for a class in the XML namespace
Entity GENjazz = GEN + "#jazz"; //define the string for a class in the XML namespace
Entity GENjazz = GEN + "#jazzfunk"; //define the string for a class in the XML namespace
//Load the RDFs scheme document that contains the relationships
System.Xml.XmlDocument doc2 = new System.Xml.XmlDocument();
doc2.Load("");
//Create additional statements based on looping round the twelve rules (inference)
//this takes the store and the RDFs document
SemWeb.Inference.RDFS rdfs = new SemWeb.Inference.RDFS(new RdfXmlReader(doc2), store);
// Query these newly created statements for all subjects that are related to
// GENjazz by predicate rdftype
// or in English get me all songs that are off type jazz
rdfs.Select(new Statement(null, rdftype, GENjazz), store2);
// loop round all results from queries
foreach (Statement s in store2.Select(new Statement(null, null, null)))
{
//Display output
output1.Text += s.Subject.Uri + s.Predicate.Uri + s.Object.Uri + "\n";
}
output1.Text += "\n";
foreach (Statement s in store.Select(new Statement(null, rdftype, GENjazzfunk)))
{
output2.Text += s.Subject.Uri + s.Predicate.Uri + s.Object.Uri + "\n";
}
output2.Text += "\n";
}
The two outputs should be the same. In the first query, a request is being made to return all music that is of type jazz, which because of the new assertions added by the inference steps now include all sub-genre relationships as well. However the only jazz pieces that are known to have the type jazzfunk which the inference steps have been additionally labelled as a type of jazz. So it just returns all jazz funk music as well. The second query queries the original statements and returns all jazzfunk tracks. This is obviously equal to the first query. Well done, you have just built a semantic Web music application.
<?xml version="1.0"?>
<rdf:RDF xmlns:rdf=""
xmlns:
<rdf:Description rdf:
<rdf:type rdf:
</rdf:Description>
<rdf:Description rdf:
<rdf:type rdf:
</rdf:Description>
<rdf:Description rdf:
<rdf:type rdf:
</rdf:Description>
<rdf:Description rdf:
<rdf:type rdf:
</rdf:Description>
</rdf:RDF>
This is an incredibly simple application of the semantic Web and one which requires little imagination to see its advantages. However let us discuss some more music applications for the semantic Web. With a little thought, you can see this is just a few stone's throws away from a recommender system and a large number of collaborative filtering systems that we see about now. However it is the connection of this type of information source that really makes it interesting. Music brainz is probably the largest and most useful example containing huge amounts of meta-data RDF statements about music that have many applications, including recommenders. Some of it is licensed under a creative commons public license meaning that it's free for commercial and non-commercial work. Whereas some of it is licensed under a creative commons license that restricts these parts to non-commercial work.
Music brainz gives you a collection of RDF classes that can be used as an impressive bootstrap onto and equally impressive repository of information. This together with Web service access to this information, makes it the first semantic Web service that has a musical application. Musicbrainz also has the ability to relate music information to the RDF assertions it has from the audio CD much like the services you have experienced on I-Tunes. Place a CD in your computer and you are presented with album-art, track-names etc. Music brainz however takes this to a whole new level due to the added information | http://www.codeproject.com/Articles/13376/Music-and-the-Semantic-Web?fid=278222&df=90&mpp=10&sort=Position&spc=None&tid=2813190&PageFlow=FixedWidth | CC-MAIN-2014-10 | refinedweb | 1,777 | 52.9 |
I didn't know about this until recently: You can take a delegate to an extension method as if it was an instance method: The delegate's target will be set to the instance. Nice!
Hi, Kirill.
This behavior is explcitly specified in the C# 3.0 Specification, 6.6 Method group conversions.
The interesting thing (which is not specified explicitly) is that you cannot use this trick with value types or type parameters:
using System;
static class A
{
static void Foo<T>(this T x)
{
Action a = 1.Foo; // error CS1113
Action b = x.Foo; // error CS1113
}
}
If you try to use a type parameter, known to be a reference type, the compiler will accept it, but PEVerify will complain:
static void Foo<T>(this T x)
where T : class
Action b = x.Foo;
Welcome to the forty-second issue of Community Convergence. The last few weeks have been a busy time | http://blogs.msdn.com/b/kirillosenkov/archive/2008/03/17/did-you-know-delegates-to-extension-methods.aspx | CC-MAIN-2015-48 | refinedweb | 153 | 64 |
ChainChain
DedicationDedication
all day long they work so hard / 'til the sun is going down / working on the highways and byways / and wearing, wearing a frown / you hear them moaning their lives away / then you hear somebody say: /
that's the sound of the men / working on the chain gang / that's the sound of the men / working on the chain gang /
--Sam Cooke, "Chain Gang" (1960)
OverviewOverview
Lots of small collections got you down? Tired of paying O(n) to concatenate lists, or generating a lot of garbage prepending to a vector? If so, Chain is for you!
Chain is a small library that supports efficient concatenation across many collection types, as well as efficient iteration across the results.
import chain.Chain val xs: Vector[Long] = ... val ys: Vector[Long] = ... // copies the entire contents of xs and ys // before performing the summation (xs ++ ys).foldLeft(0L)(_ + _) // does not copy anything, just iterates over // xs and ys in turn. (Chain(xs) ++ Chain(ys)).foldLeft(0L)(_ + _)
This example is somewhat contrived, but I bet you have lots of code that builds intermediate collections solely to iterate over them. Chain can help make that code more efficient.
Quick StartQuick Start
Chain supports Scala 2.10, 2.11, and 2.12.
To include Chain in your projects, you can use the following
build.sbt snippet:
libraryDependencies += "org.spire-math" %% "chain" % "0.3.0"
Chain also supports Scala.js. To use Chain in your Scala.js projects, include the following
build.sbt snippet:
libraryDependencies += "org.spire-math" %%% "chain" % "0.3.0"
DetailsDetails
Chain can wrap any
Iterable[A] values, and supports concatenation between mixed collection types. Here's an example that shows off a number of Chain's capabilities:
import chain.Chain val ws: Iterable[Int] = List(1,2,3) val xs: List[Int] = List(4,5,6) val ys: Vector[Int] = Vector(7,8,9,10,11) val zs: Option[Int] = Some(12) val a = Chain(ws) ++ Chain(xs) // no copying val b = Chain.all(ys, zs) // same as ys ++ zs, but no copying val c = a ++ b // still no copying val d = 9 +: c :+ 100 // supports prepend/append val ns: Iterable[Int] = c.toIterable // thin wrapper for scala compat c.toVector // Vector(1,2,3,4,5,6,7,8,9,10,11,12) c.iterator.toList // List(1,2,3,4,5,6,7,8,9,10,11,12) c.foreach(println) // prints 1-12 c.find(_ > 6) // Some(7) c.forall(_ >= 0) // true c.exists(_ > 100) // false c.map(_ * 2) // Chain(2,4,6,8,10,12,14,16,18,20,22,24) c.filter(_ % 3 == 0) // Chain(3,6,9,12)
(Note that
.toString evaluates the entire contents of the Chain, so displaying a chain value in the REPL will force iteration over the contents of the chain.)
Chain is sealed and consists of two concrete case classes:
Chain.Elemswraps a single collection.
Chain.Concatrepresents a single
++invocation.
Together these types create a tree. (Since we do not need to support arbitrary insertion into the tree, there is no need to balance it.) Iteration over the tree takes advantage of an in-memory stack to efficiently walk the contents in O(n) time.
Concatenating chains is always O(1), and iteration is always O(n).
Empty Chains can be obtained by
Chain.empty[A] and are represented as a singleton
Chain.Empty which is a
Chain(Nil). This value is immutable and can be shared safely. Chains with a single element are constructed by
Chain.single(x) which constructs
Chain(x :: Nil) instances. This is done transparently in the case of
+: and
:+. These encoding are relatively efficient although if you are working entirely with single elements a more efficient data structure is possible.
Some operations that transform the Chain will need to allocate a new collection (either directly, or wrapped in a new
Chain[A]). The comments explain the exact performance characteristics of each method, but here is a quick list of the methods which will allocate a new collection:
.map: always allocates a new collection.
.flatMap: always allocates a new collection.
.filter: always allocates a new collection.
.compress: when not already compressed, allocates a new collection.
.toVector: usually allocates a new
Vector[A].
(If your chain is a
Chain.Elems wrapping a
Vector[A], then
.toVector will just return that vector directly.)
CaveatsCaveats
To avoid inheriting inefficient methods (such as
.size),
Chain itself does not extend any Scala collection interfaces. However
.toIterable uses a very thin wrapper to support
Iterable[A], so if you need to interoperate with the Scala collections hierarchy you can use that method.
Currently Chain supports the most commonly-used collection methods. Most of the rest should be easy to implement using
.iterator,
.foldLeft, or .
find. Pull requests to add more of these methods will be gladly accepted.
The design of Chain assumes that the (relatively small) overhead of using
Iterator[A] internally is acceptable. In the case of a large number of very small (or empty) collections this could be less efficient than simply accumulating those values into a single collection. The
.compress method can be used in these situations.
Chain can be thought of as a limited kind of rope that is specialized to Scala collections (specifically
Iterable[A]). You can imagine a similar (but more principled) data structure that is based around a type class like
Foldable instead.
In general calling
.iterator should be relatively low cost. In cases where the chain is right-associated (e.g.
Chain(xs) ++ (...)), almost no work will take place. In cases where a chain is deeply left-associated, the call will need to descend until it finds the leftmost concrete collection that is not empty.
Future WorkFuture Work
Additional benchmarking and profiling would be great. Almost any chain method implemented with
.iterator could be specialized if it proved to be a hotspot.
It might be nice to have a few different types to support various expected work loads and collection shapes. The current approach leans towards supporting large collections.
As mentioned above, it would be great to have a story for using type classes instead of
Iterable[A] (either via an abstraction or a new type). It could also be nice to have a version which supported lazy filtering/mapping (although in many cases this can be emulated with things like
.iterator.filter).
All code is available to you under the MIT license, available at. | https://index.scala-lang.org/non/chain/archery/0.6.0?target=_2.10 | CC-MAIN-2020-10 | refinedweb | 1,079 | 60.01 |
setgid(3) [ultrix man page]
setuid(3) Library Functions Manual setuid(3) Name setuid, seteuid, setruid, setgid, setegid, setrgid - set user and group ID Syntax #include <sys/types.h> #include <unistd.h> setuid(uid) uid_t uid; seteuid(euid) uid_t euid; setruid(ruid) uid_t ruid; setgid(gid) gid_t gid; setegid(egid) gid_t egid; setrgid(rgid) gid_t rgid; Description The subroutine sets both the real and effective user ID of the current process to the ID specified. Likewise, the subroutine sets the real and effective group ID of the current process to the ID specified. The subroutine sets the effective user ID of the current process, while the subroutine sets the effective group ID of the current process. The subroutine sets the real user ID of the current process, while the subroutine sets the real group ID of the current process. These calls are only permitted to the super-user or if the argument is the real or effective ID. Environment POSIX SYSTEM_FIVE When your program is compiled in POSIX or System V mode the following semantics apply when using the or functions: If the process is the super-user the real, effective, and saved set (as described in user/group ID are set to uid. If the process is not the super-user, but uid is equal to the real or the saved set user/group ID, the effective user/group ID is set to uid. The real and saved set user/group ID remain unchanged. POSIX In POSIX mode, the function returns a value of type uid_t. The function returns a value of type gid_t. Return Values Zero is returned if the user ID or group ID is set; -1 is returned otherwise. See Also setreuid(2), setregid(2), getuid(2), getgid(2) setuid(3)
SETUID(2) BSD System Calls Manual SETUID(2) NAME
setuid, seteuid, setgid, setegid -- set user and group ID SYNOPSIS
#include <sys/types.h> effective user ID is that of the super user, user, or if the specified group ID is the same as the effective group ID. If not, but the specified group ID is the same as the real group ID, setgid() will set the effective group ID to the real group ID.-user-ID. RETURN VALUES
Upon success, these functions return 0; otherwise -1 is returned. If the user is not the super user, or the uid specified is not the real, effective ID, or saved ID, these functions return -1. SEE ALSO
getuid(2), getgid(2) STANDARDS
The setuid() and setgid() functions are compliant with the ISO/IEC 9945-1:1990 (``POSIX.1''). 4.2 Berkeley Distribution June 4, 1993 4.2 Berkeley Distribution | https://www.unix.com/man-page/ultrix/3/setgid/ | CC-MAIN-2021-43 | refinedweb | 442 | 60.45 |
.
To get exactly what you're looking for, the trick is to use
parse_known_args() instead of parse_args():
#!/bin/env python
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-a', action="store_true")
parser.add_argument('-b', action="store_true")
opts = parser.parse_known_args()
# Print info about flags
if opts[0].a: print('You set the option "-a"')
if opts[0].b: print('You set the option "-b"')
# Collect remainder (opts[1] is a list (possibly empty) of all remaining
args)
if opts[1]: print('You passed the strings %s' % opts[1])
EDIT:
The above code displays the following help information:
./clargs.py -h
usage: clargs_old.py [-h] [-a] [-b]
optional arguments:
-h, --help show this help message and exit
-a
-b
If you want to inform the user about the()
In general, the argument vector for any program starts with the program
itself, and then all of its arguments and options. Depending on the
language, the program may be sys.argv[0], argv[0], $0, or something else,
but it's basically always argument #0.
Each program whose job is to run another program—like nohup, and like the
Python interpreter itself—generally drops itself and all of its own
options, and gives the target program the rest of the command line.
So, nohup takes a COMMAND and zero or more ARGS. Inside that COMMAND,
argv[0] will be COMMAND itself (in this case, '/usr/bin/python'), and
argv[1] and later will be the additional arguments
('/home/path/to/script/script.py' and whatever $BUCKET resolves to).
Next, Python takes zero or more options, a script, and zero or more ar
Check this:
>>> from sys import argv
>>> from re import findall
>>> args = ' '.join(argv[1:])
>>> pattern = r'([^=]+)s*=s*[s*([^]]+)s*]'
>>> d = dict((t[0].strip(), map(lambda x: x.strip(',
'),t[1].split())) for t in findall(pattern,args))
>>> for k,v in d.items():
try: d[k] = map(int,v)
except: pass
>>> d
{'names': ['"J.J."', '"April"'], 'years': [25, 29]}.
print os.path.dirname(sys.executable)
is what you should use.
When you click it it is probably running through python.exe so you are
removing the extra char from the w.:
To access the underlying webdriver, you want to reference:
sst.actions._test.browser
Here is an example of an SST script that uses the webdriver.Firefox
instance directly:
import sst.actions
# a regular SST action
sst.actions.go_to('http:/testutils.org/sst')
# now using webdriver directly
sst.actions._test.browser.get('')
The example in your question could be written as:
from sst.actions import *
from selenium.webdriver.common import action_chains
go_to('http:/yadayada.net/')
## perform a bunch of actions
text = ## get text element with SST
driver = sst.actions._test.browser
action = action_chains.ActionChains(driver)
action.double_click(text)
action.perform().
In python the default return value of a function is None.
>>> def func():pass
>>> print func() #print or print() prints the return Value
None
>>> func() #remove print and the returned value is not
printed.
>>>
So, just use:
letter_grade(score) #remove the print
Another alternative is to replace all prints with return:
def letter_grade(score):
if 90 <= score <= 100:
return "A"
elif 80 <= score <= 89:
return "B"
elif 70 <= score <= 79:
return "C"
elif 60 <= score <= 69:
return "D"
elif score < 60:
return "F"
else:
#This is returned if all other conditions aren't satisfied
return "Invalid Marks"
Now use print():
>>>. | http://www.w3hello.com/questions/How-can-I-pass-String-value-from-EditText-In-Android-Activity-to-Python-Script-and-also-retrieve-the-result-from-a-function-in-the-python-script- | CC-MAIN-2018-17 | refinedweb | 559 | 58.79 |
_lwp_cond_reltimedwait(2)
- wait until a signal is posted
#include <signal.h> int sigwait(sigset_t *set);
cc [ flag ... ] file ... -D_POSIX_PTHREAD_SEMANTICS [ library...] #include <signal.h> int sigwait(const sigset_t *set, int *sig);
The sigwait() function selects a signal in set that is pending on the calling thread (see thr_create(3C) and pthread_create(3C).) If no signal in set is pending, sigwait() blocks until a signal in set becomes pending. The selected signal is cleared from the set of signals pending on the calling thread and the number of the signal is returned, or in the standard–conforming version (see standards(5)) placed in sig. The selection of a signal in set is independent of the signal mask of the calling thread. This means a thread can synchronously wait for signals that are being blocked by the signal mask of the calling thread . To ensure that only the caller receives the signals defined in set, all threads should have signals in set masked including the calling thread. If the set argument points to an invalid address, the behavior is undefined and errno may be set to EFAULT.
If sigwait() is called on an ignored signal, then the occurrence of the signal will be ignored, unless sigaction() changes the disposition. If more than one thread waits for the same signal, only one is unblocked when the signal arrives.
Upon successful completion, the default version of sigwait() returns a signal number; the standard–conforming version returns 0 and stores the received signal number at the location pointed to by sig. Otherwise, -1 is returned and errno is set to indicate an error.
The sigwait() function will fail if:
The wait was interrupted by an unblocked, caught signal.
The set argument contains an unsupported signal number.
The sigwait() function may fail if:
The set argument points to an invalid address.
Example 1 Creating a thread to handle receipt of a signal
The following sample C code creates a thread to handle the receipt of a signal. More specifically, it catches the asynchronously generated signal, SIGINT.
/******************************************************************** * * compile with -D_POSIX_PTHREAD_SEMANTICS switch; * required by sigwait() * * sigint thread handles delivery of signal. uses sigwait( ) to wait * for SIGINT signal. * ********************************************************************/ #include <pthread.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <signal.h> #include <synch.h> static void *threadTwo(void *); static void *threadThree(void *); static void *sigint(void *); sigset_t signalSet; void * main(void) { pthread_t t; pthread_t t2; pthread_t t3; sigfillset ( &signalSet ); /* * Block signals in initial thread. New threads will * inherit this signal mask. */ pthread_sigmask ( SIG_BLOCK, &signalSet, NULL ); printf("Creating threads\n"); pthread_create(&t, NULL, sigint, NULL); pthread_create(&t2, NULL, threadTwo, NULL); pthread_create(&t3, NULL, threadThree, NULL); printf("##################\n"); printf("press CTRL-C to deliver SIGINT to sigint thread\n"); printf("##################\n"); pthread_exit((void *)0); } static void * threadTwo(void *arg) { printf("hello world, from threadTwo [tid: %d]\n", pthread_self()); printf("threadTwo [tid: %d] is now complete and exiting\n", pthread_self()); pthread_exit((void *)0); } static void * threadThree(void *arg) { printf("hello world, from threadThree [tid: %d]\n", pthread_self()); printf("threadThree [tid: %d] is now complete and exiting\n", pthread_self()); pthread_exit((void *)0); } void * sigint(void *arg) { int sig; int err; printf("thread sigint [tid: %d] awaiting SIGINT\n", pthread_self()); /* /* use standard-conforming sigwait() -- 2 args: signal set, signum */ err = sigwait ( &signalSet, &sig ); /* test for SIGINT; could catch other signals */ if (err || sig != SIGINT) abort(); printf("\nSIGINT signal %d caught by sigint thread [tid: %d]\n", sig, pthread_self()); pthread_exit((void *)0); }
See attributes(5) for descriptions of the following attributes:
sigaction(2), signal.h(3HEAD), sigpending(2), sigprocmask(2), sigsuspend(2), pthread_create(3C), pthread_sigmask(3C), thr_create(3C), thr_sigsetmask(3C), attributes(5), standards(5)
The sigwait() function cannot be used to wait for signals that cannot be caught (see sigaction(2)). This restriction is silently imposed by the system.
Solaris 2.4 and earlier releases provided a sigwait() facility. | https://docs.oracle.com/cd/E23823_01/html/816-5167/sigwait-2.html | CC-MAIN-2018-47 | refinedweb | 639 | 53.81 |
LINQ where Clause
You can filter the results of the query by using the where clause in a query expression. Following the where keyword is the condition (or conditions) that must be met by an item to be included in the results. The great factor with LINQ is that you can use the obtainable ways in .NET Framework to supplement your condition. This lesson can show you some examples on victimisation the where clause to filter queried information.
You can use relational operators to compare a value or property of an item into another value. For example, suppose we want to retrieve numbers which are greater than 5 from an array of numbers, we can do so using the following LINQ query.
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; var greaterThanFive = from number in numbers where number > 5 select number;
The where clause states that the value of a number must be greater than 5 for it to be selected and included. We can even use logical operators for more complex conditions such as the following:
var sixToTen = from number in numbers where number > 5 && number <= 10 select number;
The query above only retrieves values greater than 5 and less than or equal 10, that is, values 6 to 10. If you have a collection of objects with several properties, you can also test those properties if they met the required condition.
List<Person> people = GetPersonList(); var smiths = from person in people where person.LastName == "Smith" select person;
The query retrieves every person whose LastName is Smith. We can use .NET methods in our condition. For instance, suppose we want to retrieve all the person whose last name starts with the letter ‘R’.
var startsWithR = from person in people where person.LastName.StartsWith("R") select person;
We used the StartsWith() method of the String class which returns true if a particular string starts with a specified string argument of the method.
Alternatively, we can use the Where() extension method from the System.Linq namespace. You can then pass a lambda expression that has one parameter representing every item from the data source and its body containing the boolean expression for the condition. The method returns the collection of objects that pass the required condition.
var greaterThanFive = numbers.Where ( number => number > 5 );
The lambda expression’s body is a single condition which tests the value of number if it is greater than 5. The following is another example which retrieves persons whose last name starts with ‘R’.
var startsWithR = people.Where( person => person.LastName.StartsWith("R") );
You can use another overloaded version of the method which accepts a lambda expression having two parameters. The first parameter represents every object from the collection, and the second parameter represents the index of that item in the collection. The following call to Where() method returns numbers whose index in its collection is even.
var evenIndices = numbers.Where( (number, index) => index % 2 == 0 );
You can use the Where() method when you simply want to filter a collection using a specified condition. | https://compitionpoint.com/linq-where/ | CC-MAIN-2021-25 | refinedweb | 511 | 63.09 |
This is a small project by Gareth Latty (Lattyware).
Other projects.
A generator for word-like strings that follow the 'feel' of a given input language.
It's useful for, for example, naming procedurally generated content in a way that avoids real words, but remains easy to pronounce.
Here is some example output with the default british-english output:
./wordgenerator.py british-english -n 20 --min 5 --max 15
Using a dictionary of italian words, for example, produces italian-sounding words:
./wordgenerator.py italian -n 10 --min 5 --max 15
Warning: This library does no checking on the produced words. They may be real words, and there is the possibility of it generating profanity. If this is unacceptable, then filter the output of this script, or pre-generate a set of words to use which you check. You have been warned.
Download:
Source: wordgenerator-1.2.tar.gz md5sum: 7fd90f5bb41f2112793a7676390273e2, or get it from the github project.
This program functions both as a library and a command line application.
You will need a dictionary to use this program - a newline delimited list of words to use as a source. Surprisingly good results can be obtained from very small input dictionaries, but best results will be gained from a good, varied selection from the language you wish to emulate. Linux users will often find good samples in /usr/share/dict. british-english - distributed with this, is taken from Arch Linux's words package, and the associated wbritish.copyright is taken from the same package and provides information on copyright with regards to that file.
Saving as JSON means that you don't need to do the expensive parsing of the dictionary again, and with large dictionaries will produce smaller files. If you intend to use the generator with the same input dictionary multiple times, doing this is highly reccomended.
For usage as a command line application, see the below explanation of arguments:
usage: wordgenerator.py [-h] [-w BOOL] [-n N] [--min N] [-m N] [-s FILE] [-o] [-l FILE] [--version] [FILE] positional arguments: FILE The path to a dictionary file for a language - a list of newline separated words. (default: read from standard input) optional arguments: -h, --help show this help message and exit -w BOOL, --weighted BOOL If true, a common segment in the language ismore likely to show up in an output word. (default: True) -n N, --number N The number of words to generate. (default: 1) --min N The minimum length of words to generate. (default: 0) -m N, --max N The rough maximum length of words to generate. (default: 14) -s FILE, --save FILE Save the library to disc as JSON data. When saving, other operations will be ignored. -o, --output Save the library, sending output to the standard output. -l FILE, --load FILE Load the library from JSON data on disc. --version show program's version number and exit
Example usage:
from wordgenerator import WordGenerator generator = WordGenerator("british-english") for word in generator.generate((10, 15), 10): #Generate 10 words of length 10-15. print(word) with open("british-english.json", 'w') as file: generator.save(file) #Save the dictionary to a JSON file for quick usage later.
from wordgenerator import WordGenerator from itertools import islice generator = WordGenerator() with open("british-english.json", 'r') as file: generator.load(file) #Load from JSON. for word in islice(generator, 25): #Get 25 words. print(word)
This script is provided under the GPLv3 licence, see LICENCE or for more. | http://www.lattyware.co.uk/projects/wordgenerator | CC-MAIN-2014-42 | refinedweb | 580 | 57.37 |
NAMEioperm - set port input/output permissions
SYNOPSIS#include <unistd.h> /* for libc5 */
#include <sys/io.h> /* for glibc */
int ioperm(unsigned long from, unsigned long num, int turn_on);
DESCRIPTIONIoperm sets the port access permission bits for the process for num bytes starting from port address from to the value turn_on. The use of ioperm requires root privileges.On success, zero is returned. On error, -1 is returned, and errno is set appropriately.
CONFORMING TOioperm is Linux specific and should not be used in programs intended to be portable.
SEE ALSOiopl(2)
Important: Use the man command (% man) to see how a command is used on your particular computer.
>> Linux/Unix Command Library | http://linux.about.com/library/cmd/blcmdl2_ioperm.htm | crawl-002 | refinedweb | 112 | 51.44 |
How can an applet or application pass data to and read output from a CGI script or Servlet?
Created May 4, 2012
To pass data to a CGI program or Servlet, you need to use the GET or POST method in HTTP. The data is sent as key=value pairs separated by ampersands. To do this in Java, we use the URLConnection class, which takes care of the details of the HTTP protocol for us. The only thing we have to specify is the URL of the server and the data to be sent.
As an example, here is an application that looks up a word in the Merriam-Webster online dictionary:
import java.net.*; import java.io.*; public class Post { public static void main(String[] args) { try { URL url = new URL(""); URLConnection connection = url.openConnection(); connection.setDoOutput(true); OutputStreamWriter ostream = new OutputStreamWriter(connection.getOutputStream()); BufferedWriter out = new BufferedWriter(ostream); out.write("book=Dictionary&va=doggerel "); out.flush(); out.close(); InputStream stream = connection.getInputStream(); BufferedInputStream in = new BufferedInputStream(stream); int i = 0; while ((i = in.read()) != -1) { System.out.write(i); } in.close(); } catch (MalformedURLException e) { } catch (IOException ee) { } } }Note that the data is sent using the write() method of the URLConnection's output stream. This data must be URL-encoded (use the URLEncoder class to do this). In the example above, the data is unchanged after URL-encoding.
Note that is works not just for CGI scripts and Servlets, but for any server-side mechanism you use to handle GET and POST requests, for instance a JSP page.
| http://www.jguru.com/faq/view.jsp?EID=31753 | CC-MAIN-2019-04 | refinedweb | 259 | 55.95 |
I have been reading C++ Primer Plus, and I'm stuck on this programming question:
This is what I have:This is what I have:Begin with the following structure declaration:
struct chaff
{
char dross[20];
int slag;
};
Write a program that uses placement new to place an array of two such structures in a
buffer. Then assign values to the structure members (remembering to use strcpy() for
the char array) and use a loop to display the contents. Option 1 is to use a static array,
like that in Listing 9.9, for the buffer. Option 2 is to use regular new to allocate the
buffer.
It compiles, but when I run it I get thisIt compiles, but when I run it I get thisCode:#include <iostream> #include <new> using namespace std; struct chaff { char dross[20]; int slag; }; int main() { char * buf = new char(sizeof(chaff) * 2); chaff * c1 = new (buf) chaff; chaff * c2 = new (buf + sizeof(chaff)) chaff; strcpy(c1->dross, "Chaff 1"); c1->slag = 5; strcpy(c2->dross, "Chaff 2"); c2->slag = 2; chaff * c; for (int i = 0; i < 2; i++) { c = (chaff *) &buf[sizeof(chaff) * i]; cout << c->dross << endl; cout << c->slag << endl; } delete [] buf; }
First-chance exception at 0x7c91916a in book samples.exe: 0xC0000005: Access violation reading location 0x0037a8ed.
First-chance exception at 0x7c812afb in book samples.exe: Microsoft C++ exception: std::bad_alloc at memory location 0x0012fc44..
Unhandled exception at 0x7c812afb in book samples.exe: Microsoft C++ exception: std::bad_alloc at memory location 0x0012fc44..
The program '[3552] book samples.exe: Native' has exited with code 0 (0x0). | http://cboard.cprogramming.com/cplusplus-programming/123526-what-am-i-doing-worng.html | CC-MAIN-2015-40 | refinedweb | 265 | 61.46 |
I've been trying to get a .Net COM component working in a Classic ASP site and was consistently getting an error the first time it was accessed:
Active Server Pages error 'ASP 0115'
Unexpected error
/engine/default.asp
A trappable error (E0434352) occurred in an external object. The script cannot continue running.
Active Server Pages error 'ASP 0240'
Script Engine Exception
/engine/default.asp
A ScriptEngine threw exception 'C0000005' in 'IActiveScript::Close()' from 'CActiveScriptEngine::FinalRelease()'.
Pretty vague. But at least it's consistently happening..
Since it's not long since I've had to try to use WinDbg to investigate an issue on a live server (see The WinDbg Blues), I thought maybe I could apply it to this problem. So I wanted to go through the motions of attaching to the w3wp.exe process where the exception occured so that I could look into it.
The first problem was that IIS is running in 32 bit mode for this site so I needed to use the 32 bit version of WinDbg. These can be obtained as part of the Windows Software Development Kit (SDK) for Windows 8. It doesn't matter if you're not running Windows 8, it doesn't matter if you don't want anything else in that download, it doesn't matter if you don't have .Net 4.5 installed and it warns you about it when you run the setup executable - select "Debugging Tools for Windows" when you're offered features to install and leave everything else unselected. This will install both the 64 and 32 bit versions of the tool.
The next problem was that ".loadby sos mscorwks" returned the error
Unable to find module 'mscorwks'
The answer to this was found at this MSDN blog post Error loading sos.dll; to use ".loadby sos clr"
So now some progress is being made! The next step is to view all of the managed threads in the process with the command "!threads":
Of these, one reports an exception. It's a bit vague-sounding, a "System.Reflection.TargetInvocationException" but more information can be gleaned with the PrintException command ("!pe"), specifying the address of the exception:
Not that helpful-looking yet, but there's a hint to dig deeper and look at the InnerException:
Well now we're getting somewhere! When the component tries to access the System.Web.HttpRuntime.Cache an exception is being raised. This message is a little cryptic and I have no idea why it would only be happening on first access but at least I have something to search for and it's not directly my code that's causing it!
Google brings me to this Stack Overflow question as the most promising lead: Attempted to read or write protected memory at System.Web.Hosting.UnsafeIISMethods.MgdGetSiteNameFromId. While there are no actual explanations, someone suggests that having encountered this they changed the build parameters to target "x86" specifically and the problem went away. Unfortunately, this was not the case for me. Instead, the HttpRuntime.Cache was only being used if the site didn't provide the COM component with a cache reference that it could stash things in - it was being used as a default cache mechanism. I changed the integration to remove this default and require a cache reference and now the problem has gone. Granted, I didn't strictly-speaking solve the underlying problem.. but I identified it and removed it with a solution I'm happier with overall, so I'm considering this a success! :)
While I was investigating this, I came across this post from WinDbg guru Tess Ferrandez First look at debugging .NET 4.0 dumps in Visual Studio 2010. Essentially saying that you can debug .Net 4 dumps direct in Visual Studio! Amazing!
There are a couple of caveats:
Side note: Because I'm curious, I wanted to know what specifically about a release build it was that prevented it from working. From playing around with the settings, there are two things that appear to make the difference - in the project properties, under the Build tab, "Optimize code" must be unchecked and "Debug Info" must be set to "full" (rather than the default "pdb-only" in the "Advanced Build Settings" (accessed by cliking the "Advanced" button). Obviously, disabling optimisations means you're disabling the benefits of generating a release build..
To try this out, I created the simplest program I could think of investigating:
using System; namespace WinDbgDumpTest { class Program { static void Main(string[] args) { var a = 123; Console.WriteLine(a); Console.ReadLine(); } } }
I built this and ran the executable direct from the build location in explorer (if I ran it from within Visual Studio then "WinDbgDumpTest.vshost.exe" appears in the process list, not "WinDbgDumpTest.exe", and this will be VS running the code rather than the code running on its own).
I then attached WinDbg to the process and ran the command
.dump /ma c:\WinDbgDump.dmp
which will "dump complete memory image" (according to the very useful WinDbg / SOS Cheat Sheet). If you don't specify "/ma" then only a "small memory image" will be dumped which will mean that Visual Studio tells you "The value of the local or argument {whatever} is unobtainable at this time" when you try to inspect variables. This caught me out for quite a while and started driving me mad until I realised what I'd done!
As described in that post (First look at debugging .NET 4.0 dumps in Visual Studio 2010), the default symbol server can be enabled by going to Tools / Options / Debgging / Symbols and enabling the microsoft symbol server location.
Then open the dump file in Visual Studio (nothing more complicated than going to File / Open and selecting the file).
This should display some summary information but what we want to do from here is click on the "Debug with Mixed" link which will load the state into Visual Studio as if we'd run the code and it had stopped at the point at which the dump was taken. You'll like get a warning at this point such as "Windows has triggered a breakpoint in WinDbgDump.dmp", just click "Break".
If you're examining a dump generated from code such as the example above, you'll want to select the Main Thread from the Threads window and then can jump to the current frame by clicking on the top entry in the Call Stack window.
At this point, you can examine values or jump around the call stack or do pretty much anything (not including clicking continuing execution - you'll get an error "The debugger cannot continue running the process. This operation is not supported when debugging dump files.") you could do if you were in the middle of pausing execution of code executed by Visual Studio - much easier than trying to poke around values in WinDbg! In the example here, I could hover over "a" and see that its value was 123 (similarly, this information is visible in the "Locals" window).
Posted at 16:26
For something I've been working on it looked like I was going to have to interact with COM objects from a legacy system without type libraries and where the internals were written in VBScript. Ouch. It seemed like a restriction of the environment meant that .Net 4 wouldn't be available and so the dynamic keyword wouldn't be available.
It would seem that the COMInteraction code that I wrote in the past would be ideal for this since it should wrap access to generic COM objects but I encountered a problem with that (which I'll touch briefly on later in this post).
So the next step was to find out about the mysterious IDispatch interface that I've heard whispered about in relation to dealings with generic COM objects! Unfortunately, I think in the end I found a way to get .Net 4 into play for my original problem so this might all have been a bit of a waste of time.. but not only was it really interesting but I also found nowhere else on the internet that was doing this with C#. And I read up a lot. (There's articles that touch on most of it, but not all - read on to find out more! :)
From IDispatch on Wikipedia:
IDispatch is the interface that exposes the OLE Automation protocol. It is one of the standard interfaces that can be exposed by COM objects .. IDispatch derives from IUnknown and extends its set of three methods (AddRef, Release and QueryInterface) with four more methods - GetTypeInfoCount, GetTypeInfo, GetIDsOfNames and Invoke.
Each property and method implemented by an object that supports the IDispatch interface has what is called a Dispatch ID, which is often abbreviated DISPID. The DISPID is the primary means of identifying a property or method and must be supplied to the Invoke function for a property or method to be invoked, along with an array of Variants containing the parameters. The GetIDsOfNames function can be used to get the appropriate DISPID from a property or method name that is in string format.
It's basically a way to determine what methods can be called on an object and how to call them.
I got most of the useful information first from these links:
The first thing to do is to cast the object reference to the IDispatch interface (this will only work if the object implements IDispatch, for the COM components I was targetting this was the case). The interface isn't available in the framework but can be hooked up with
[ComImport()] [Guid("00020400-0000-0000-C000-000000000046")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] interface IDispatch { [PreserveSig] int GetTypeInfoCount(out int Count); [PreserveSig] int GetTypeInfo ( [MarshalAs(UnmanagedType.U4)] int iTInfo, [MarshalAs(UnmanagedType.U4)] int lcid, out System.Runtime.InteropServices.ComTypes.ITypeInfo typeInfo ); [PreserveSig] int GetIDsOfNames ( ref Guid riid, [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr)] string[] rgsNames, int cNames, int lcid, [MarshalAs(UnmanagedType.LPArray)] int[] rgDispId ); [PreserveSig] int Invoke ( int dispIdMember, ref Guid riid, uint lcid, ushort wFlags, ref System.Runtime.InteropServices.ComTypes.DISPPARAMS pDispParams, out object pVarResult, ref System.Runtime.InteropServices.ComTypes.EXCEPINFO pExcepInfo, out UInt32 pArgErr ); }
Then the GetIDsofNames is called to determine whether a given method is present:
private const int LOCALE_SYSTEM_DEFAULT = 2048; // rgDispId will be populated with the DispId of the named member (if available) var rgDispId = new int[1] { 0 }; // IID_NULL must always be specified for the "riid" argument // ) throw new Exception("Uh-oh!"); return rgDispId[0];
Then the Invoke method is called with the Disp Id, the type of call (eg. execute method, set property, etc..), a "local context" ("applications that do not support multiple national languages can ignore this parameter" - IDispatch::Invoke method (Automation) at MSDN) and the parameters.
private const int LOCALE_SYSTEM_DEFAULT = 2048; private const ushort DISPATCH_METHOD = 1; var dispId = 19; // Or whatever the above code reported // This DISPPARAMS structure describes zero arguments var dispParams = new System.Runtime.InteropServices.ComTypes.DISPPARAMS() { cArgs = 0, cNamedArgs = 0, rgdispidNamedArgs = IntPtr.Zero, rgvarg = IntPtr.Zero };;
The DISPPARAMS structure (which is part of the framework) enables the specification of both "named" and "unnamed" arguments. When calling a method, unnamed arguments may be passed in but when setting a property, the value that the property is to be set to must be passed as a named argument with the special constant DISPID_PROPERTYPUT (-3).
The above code could also be used to retrieve a property value (a non-indexed property) by replacing the DISPATCH_METHOD value with DISPATCH_PROPERTYGET (2).
[DllImport(@"oleaut32.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall)] static extern Int32 VariantClear(IntPtr pvarg); private const int LOCALE_SYSTEM_DEFAULT = 2048; private const ushort DISPATCH_METHOD = 1; private const int SizeOfNativeVariant = 16; var dispId = 19; // Or whatever the above code reported var arg = "Value"; // This DISPPARAMS describes a single (unnamed) argument = 0, rgdispidNamedArgs = IntPtr.Zero,; } finally { VariantClear(pVariant); Marshal.FreeCoTaskMem(pVariant); }
As mentioned above, when calling methods there is no need to named arguments so cNamedArgs is still 0 and rgdispidNamedArgs is still IntPtr.Zero (a managed version of a null pointer).
From what I understand (and I'd never used Marshal.AllocCoTaskMem or Marshal.GetNativeVariantForObject before a couple of days ago!), the AllocCoTaskMem call allocates a chunk of unmanaged memory and then GetNativeVariantForObject copies a managed reference into that memory. A variant is always 16 bytes. This is the same variant type used for all VBScript calls, for example, and used for method arguments for IDispatch. More about the VARIANT structure can be found at this MSDN article.
The framework does some sort of clever manipulation to copy the contents of the managed reference into unmanaged memory, the internals of which I'm not going to worry too much about. But there's a couple of things to note; this is a copy operation so if I was getting involved with unmanaged memory for performance reasons then I'd probably want to avoid this. But it does mean that this copied memory is "safe" from the garbage collector doing anything with it. When you peel it back a layer, managed memory can't be expected to work as predictably as unmanaged memory as the garbage collector is free to be doing all manner of clever things to stay on top of memory usage and references and, er.. stuff. Which is a good thing because (for the large part) I don't have to worry about it! But it would be no good if the garbage collector moved memory around that the COM component was in the middle of accessing. Bad things would happen. Bad intermittent things (the worst kind). But this does have one important consequence; since the GC is not in control of this memory, I need to explicitly release it myself when I'm done with it.
Another side note on this: The system also needs to be sure that the GC doesn't do anything interesting with memory contents while it's performing to copy to the variant. The framework uses something called "automatic pinning" to ensure that the reference being considered by the Marshal.GetNativeVariantForObject doesn't move during this operation (ie. it is "pinned" in place in memory). There is also a way to manually pin data where a particular reference can be marked such that its memory not be touched by the GC until it's freed (using GCHandle.Alloc and the GCHandleType.Pinned option, and later calling .Free on the handle returned by Alloc) which may be used in the passing-by-reference approach I alluded to above, but I won't need it here.
[DllImport(@"oleaut32.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall)] static extern Int32 VariantClear(IntPtr pvarg); private const int LOCALE_SYSTEM_DEFAULT = 2048; private const ushort DISPATCH_PROPERTYPUT = 4; private const int DISPID_PROPERTYPUT = -3; private const int SizeOfNativeVariant = 16; var dispId = 19; // Or whatever the above code reported var arg = "Value"; // This DISPPARAMS describes a single named (DISPID_PROPERTYPUT) argument var pNamedArg = Marshal.AllocCoTaskMem(sizeof(Int64)); Marshal.WriteInt64(pNamedArg, DISPID_PROPERTYPUT); = 1, rgdispidNamedArgs = pNamedArg,_PROPERTYPUT, ref dispParams, out varResult, ref excepInfo, out pArgErr ); if (hrRet != 0) throw new Exception("FAIL!"); } finally { VariantClear(pVariant); Marshal.FreeCoTaskMem(pVariant); VariantClear(pNamedArg); Marshal.FreeCoTaskMem(pNamedArg); }
The example code in section 3.4 of the Setting a Property by IDispatch Invoke post I linked to earlier uses a manual pinning approach to specifying the named arguments data but as I understand it we can copy the DISPID_PROPERTYPUT value into unmanaged memory instead, in the same way as the property value is passed over the COM boundary.
The final step is to support multiple arguments, whether this be for calling methods or for dealing with indexed properties. This is the step that I've been unable to find any examples for in C#.
The problem is that there need to be multiple variant arguments passed to the Invoke call but no built-in way to allocate an array of variants to unmanaged memory. This Stack Overflow question on IntPtr arithmetics looked promising but didn't quite cover it. And it revealed that I didn't know very much about the unsafe and fixed keywords :(
The final code I've ended up with doesn't seem that complicated in and of itself, but I feel like I've gone through the wringer a bit trying to confirm that it's actually correct! The biggest question was how to go allocating a single variant
var rgvarg = Marshal.AllocCoTaskMem(SizeOfNativeVariant); Marshal.GetNativeVariantForObject(arg, rgvarg); // Do stuff.. VariantClear(rgvarg); Marshal.FreeCoTaskMem(rgvarg);
to allocating multiple. I understood that the array of variants should be laid out sequentially in memory but the leap took me some time to get to
var rgvarg = Marshal.AllocCoTaskMem(SizeOfNativeVariant * args.Length); var variantsToClear = new List<IntPtr>(); for (var index = 0; index < args.Length; index++) { var arg = args[(args.Length - 1) - index]; // Explanation below.. var pVariant = new IntPtr( rgvarg.ToInt64() + (SizeOfNativeVariant * index) ); Marshal.GetNativeVariantForObject(arg, pVariant); variantsToClear.Add(pVariant); } // Do stuff.. foreach (var variantToClear in variantsToClear) VariantClear(variantToClear); Marshal.FreeCoTaskMem(rgvarg);
Particularly the concerns about the pointer arithmetic which I wasn't sure C# would like, especially after trying to digest all of the Stack Overflow question. But another Add offset to IntPtr did give me some hope thought it led me get thrown by this MSDN page for the .Net 4 IntPtr.Add method, with its usage of unsafe and fixed!
public static void Main() { int[] arr = { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 }; unsafe { fixed(int* parr = arr) { IntPtr ptr = new IntPtr(parr); for (int ctr = 0; ctr < arr.Length; ctr++) { IntPtr newPtr = IntPtr.Add(ptr, ctr * sizeof(Int32)); Console.Write("{0} ", Marshal.ReadInt32(newPtr)); } } } }
So the good news; pointer arithmetic would, dealt with properly, not end the world. Ok, good. And apparently it's safe to always manipulate them using the ToInt64 method
IntPtr ptr = new IntPtr(oldptr.ToInt64() + 2);
whether on a 32 or 64 bit machine. With overhead on 32 bit systems, but I'm not looking for ultimate performance here, I'm looking for functionality! (This last part is one of the answers on Stack Overflow: Add offset to IntPtr.
From what I've learnt about pinning and its effects on the garbage collector, the "fixed" call in the MSDN example is to lock the array in place while it's being iterated over. Since at each insertion into the unmanaged memory I've allocated I'm using Marshal.GetNativeVariantForObject then I don't need to worry about this as that method is copying the data and automatic pinning is holding the data in place while it does so. So I'm all good - I just need to keep track of the variants I've copied so they can be cleared when I'm done and keep tracking of the one area of unmanaged memory I allocated which will need freeing.
One more thing! And this took me a while to track down - I wasn't getting errors but I wasn't getting the results I was expecting. According to the MSDN IDispatch::Invoke method (Automation) page, arguments are stored in the DISPPARAMS structure in reverse order. Reverse order!! Why??! Ah, who cares, I'm over it.
So, without further ado, here's an Invoke method that wraps up all of the above code so that any variety of call - method, indexed-or-not property get, indexed-or-not property set - can be made with all of the complications hidden away. If you don't want it to try to cast the return value then specify "object" as the type param. Anything that has a void return type will return null. This throws the named-argument requirement for property-setting into the mix but should be easy enough to follow if you're fine with everything up til now. (Where an indexed property is set, the last value in the args array should be the value to set it to and the preceeding args elements be the property indices).
public static T Invoke<T>(object source, InvokeFlags invokeFlags, int dispId, params object[] args) { if (source == null) throw new ArgumentNullException("source"); if (!Enum.IsDefined(typeof(InvokeFlags), invokeFlags)) throw new ArgumentOutOfRangeException("invokeFlags"); if (args == null) throw new ArgumentNullException("args"); var memoryAllocationsToFree = new List<IntPtr>(); IntPtr rgdispidNamedArgs; int cNamedArgs; if (invokeFlags == InvokeFlags.DISPATCH_PROPERTYPUT) { // There must be at least one argument specified; only one if it is a non-indexed property and // multiple if there are index values as well as the value to set to if (args.Length < 1) throw new ArgumentException("At least one argument must be specified for DISPATCH_PROPERTYPUT"); var pdPutID = Marshal.AllocCoTaskMem(sizeof(Int64)); Marshal.WriteInt64(pdPutID, DISPID_PROPERTYPUT); memoryAllocationsToFree.Add(pdPutID); rgdispidNamedArgs = pdPutID; cNamedArgs = 1; } else { rgdispidNamedArgs = IntPtr.Zero; cNamedArgs = 0; } var variantsToClear = new List<IntPtr>(); IntPtr rgvarg; if (args.Length == 0) rgvarg = IntPtr.Zero; else { // We need to allocate enough memory to store a variant for each argument (and then populate this // memory) rgvarg = Marshal.AllocCoTaskMem(SizeOfNativeVariant * args.Length); memoryAllocationsToFree.Add(rgvarg); for (var index = 0; index < args.Length; index++) { // Note: The "IDispatch::Invoke method (Automation)" page // () states that // "Arguments are stored in pDispParams->rgvarg in reverse order" so we'll reverse them here var arg = args[(args.Length - 1) - index]; // According to it seems like using ToInt64 here will be valid // for both 32 and 64 bit machines. While this may apparently not be the most performant approach, // it should do the job. // Don't think we have to worry about pinning any references when we do this manipulation here // since we are allocating the array in unmanaged memory and so the garbage collector won't be // moving anything around (and GetNativeVariantForObject copies the reference and automatic // pinning will prevent the GC from interfering while this is happening). var pVariant = new IntPtr( rgvarg.ToInt64() + (SizeOfNativeVariant * index) ); Marshal.GetNativeVariantForObject(arg, pVariant); variantsToClear.Add(pVariant); } } var dispParams = new ComTypes.DISPPARAMS() { cArgs = args.Length, rgvarg = rgvarg, cNamedArgs = cNamedArgs, rgdispidNamedArgs = rgdispidNamedArgs }; try { var IID_NULL = new Guid("00000000-0000-0000-0000-000000000000"); UInt32 pArgErr = 0; object varResult; var excepInfo = new ComTypes.EXCEPINFO(); var hrRet = ((IDispatch)source).Invoke ( dispId, ref IID_NULL, LOCALE_SYSTEM_DEFAULT, (ushort)invokeFlags, ref dispParams, out varResult, ref excepInfo, out pArgErr ); if (hrRet != 0) { var message = "Failing attempting to invoke method with DispId " + dispId + ": "; if ((excepInfo.bstrDescription ?? "").Trim() == "") message += "Unspecified error"; else message += excepInfo.bstrDescription; var errorType = GetErrorMessageForHResult(hrRet); if (errorType != CommonErrors.Unknown) message += " [" + errorType.ToString() + "]"; throw new ArgumentException(message); } return (T)varResult; } finally { foreach (var variantToClear in variantsToClear) VariantClear(variantToClear); foreach (var memoryAllocationToFree in memoryAllocationsToFree) Marshal.FreeCoTaskMem(memoryAllocationToFree); } } public static int GetDispId(object source, string name) { if (source == null) throw new ArgumentNullException("source"); if (string.IsNullOrEmpty(name)) throw new ArgumentNullException("Null/blank name specified"); // This will be populated with a the DispId of the named member (if available) var rgDispId = new int[1] {) { var message = "Invalid member \"" + name + "\""; var errorType = GetErrorMessageForHResult(hrRet); if (errorType != CommonErrors.Unknown) message += " [" + errorType.ToString() + "]"; throw new ArgumentException(message); } return rgDispId[0]; } public enum InvokeFlags : ushort { DISPATCH_METHOD = 1, DISPATCH_PROPERTYGET = 2, DISPATCH_PROPERTYPUT = 4 } private static CommonErrors GetErrorMessageForHResult(int hrRet) { if (Enum.IsDefined(typeof(CommonErrors), hrRet)) return (CommonErrors)hrRet; return CommonErrors.Unknown; } public enum CommonErrors { Unknown = 0, // A load of values from }
Included is a GetDispId method and an "InvokeFlags" enum to wrap up those values. If an error is encountered, it will try to look up the hresult value in an enum that I've trimmed out here but you can find the values at.
It's looking like the environment restriction against using .Net 4 is going to go away (I think it was just me being a bit dense with configuration to be honest but I'm not quite convinced yet!) so I should be able to replace all of this code I was thinking of using with the "dynamic" keyword again.
But it's certainly been interesting getting to the bottom of this, and it's given me a greater appreciation of the "dynamic" implementation! Until now I was under the impression that it did much of what it does with fairly straight forward reflection and some sort of caching for performance. But after looking into this I've looked into it more and realised that it does a lot more, varying its integration method depending upon what it's talking to (like if it's a .Net object, a IDispatch-implementing reference, an Iron Python object and whatever else). I have a much greater respect for it now! :)
One thing it has got me thinking about, though, is the COMInteraction code I wrote. The current code uses reflection and IL generation to sort of force method and property calls onto COM objects, which worked great for the components I was targetting at the time (VBScript WSC components) but which failed when I tried to use it with a Classic ASP Server reference that got passed through the chain. It didn't like the possibly hacky approach I used at all. But it is happy with being called by the Invoke method above since it implements IDispatch. So I'm contemplating now whether I can extend the work to generate different IL depending upon the source type; leaving it using reflection where possible and alternately using IDispatch where reflection won't work but IDispatch may. Sort of like "dynamic" much on a more conservative scale :)
Now that I understand more about how IDispatch enables the implementing type to be queried it answers a question I've wondered about before: how can the debugger show properties and data for a dynamic reference that's pointing at a COM object? The GetTypeInfo and GetIDsOfNames of the IDispatch interface can expose this information.
There's some example code on this blog post (by the same guy who wrote some of the other posts I linked earlier): Obtain Type Information of IDispatch-Based COM Objects from Managed Code.. I've played with it a bit and it looks interesting, but I've not gone any further than his method querying code (he retrieves a list of methods but doesn't examine the arguments that the methods take, for example).
Posted at 20:54
Dan is a big geek who likes making stuff with computers! He can be quite outspoken so clearly needs a blog :)
In the last few minutes he seems to have taken to referring to himself in the third person. He's quite enjoying it. | http://www.productiverage.com/Archive/2/2013 | CC-MAIN-2017-13 | refinedweb | 4,384 | 53.71 |
:
What.
As a second example you'll learn how to integrate a new kind of map into the collection framework. The idea is to implement a mutable map with String as the type of keys by a "Patricia trie":
To find the node corresponding to the string "abc" in this trie, simply follow the subtree labeled "a", proceed from there to the subtree labelled "b", to finally reach its subtree labelled "c". If the Patricia trie is used as a map, the value that's associated with a key is stored in the nodes that can be reached by the key. If it is a set, you simply store a marker saying that the node is present in the set.
Patricia tries support very efficient lookups and updates. Another nice feature is that they support selecting a subcollection by giving a prefix. For instance, in Figure 1 you can obtain the sub-collection of all keys that start with an "a" simply by following the "a" link from the root of the tree.
Based on these ideas we will now walk you through the implementation of a map that's implemented as a Patricia trie. We call the map a PrefixMap, which means that it provides a method withPrefix that selects a submap of all keys starting with a given prefix. We'll first define a prefix map with the keys shown in the running example:
A prefix map node has two mutable fields: suffixes and value. The value field contains an optional value that's associated with the node. It is initialized to None. The suffixes field contains a map from characters to PrefixMap values. It is initialized to the empty map.
You might ask why did we pick an immutable map as the implementation type for suffixes? Would not a mutable map have been more standard, since PrefixMap as a whole is also mutable? The answer is that immutable maps that contain only a few elements are very efficient in both space and execution time. For instance, maps that contain fewer than 5 elements are represented as a single object. By contrast, the standard mutable map is a HashMap, which typically occupies around 80 bytes, even if it is empty. So if small collections are common, it's better to pick immutable over mutable. In the case of Patricia tries, we'd expect that most nodes except the ones at the very top of the tree would contain only a few successors. So storing these successors in an immutable map is likely to be more efficient.
Now have a look at the first method that needs to be implemented for a map: get. The algorithm is as follows: To get the value associated with the empty string in a prefix map, simply select the optional value stored in the root of the tree. Otherwise, if the key string is not empty, try to select the submap corresponding to the first character of the string. If that yields a map, follow up by looking up the remainder of the key string after its first character in that map. If the selection fails, the key is not stored in the map, so return with None. The combined selection over an option value is elegantly expressed using flatMap. When applied to an optional value, ov, and a closure, f, which in turn returns an optional value, ov flatMap f will succeed if both ov and f return a defined value. Otherwise ov flatMap f will return None.
The next two methods to implement for a mutable map are += and -=. In the implementation of PrefixMap, these are defined in terms of two other methods: update and remove.
The remove method is very similar to get, except that before returning any associated value, the field containing that value is set to None. The update method first calls withPrefix to navigate to the tree node that needs to be updated, then sets the value field of that node to the given value. The withPrefix method navigates through the tree, creating sub-maps as necessary if some prefix of characters is not yet contained as a path in the tree.
The last abstract method to implement for a mutable map is iterator. This method needs to produce an iterator that yields all key/value pairs stored in the map. For any given prefix map this iterator is composed of the following parts: First, if the map contains a defined value, Some(x), in the value field at its root, then ("", x) is the first element returned from the iterator. Furthermore, the iterator needs to traverse the iterators of all submaps stored in the suffixes field, but it needs to add a character in front of every key string returned by those iterators. More precisely, if m is the submap reached from the root through a character chr, and (s, v) is an element returned from m.iterator, then the root's iterator will return (chr +: s, v) instead. This logic is implemented quite concisely as a concatenation of two for expressions in the implementation of the iterator method in PrefixMap. The first for expression iterates over value.iterator. This makes use of the fact that Option values define an iterator method that returns either no element, if the option value is None, or exactly one element x, if the option value is Some(x).
Note that there is no newBuilder method defined in PrefixMap. There is no need to, because maps and sets come with default builders, which are instances of class MapBuilder. For a mutable map the default builder starts with an empty map and then adds successive elements using the map's += method..
We'll now turn to the companion object PrefixMap. In fact it is not strictly necessary to define this companion object, as class PrefixMap can stand well on its own. The main purpose of object PrefixMap is to define some convenience factory methods. It also defines a CanBuildFrom implicit to make typing work out better.
The two convenience methods are empty and apply. The same methods are present for all other collections in Scala's collection framework so it makes sense to define them here, too. With the two methods, you can write PrefixMap literals like you do for any other collection:
You have now seen how Scala's collections are built and how you can build new kinds of collections. Because of Scala's rich support for abstraction, each new collection type can have a large number of methods without having to reimplement them all over again.
Have a question or opinion about Scala's collections API? Discuss this article in the Articles Forum topic, What's New in Scala 2.8: The Architecture of Scala Collections.
The Scala programming language website is at:
The Scala 2.8 release notes are at:
How to use Scala collections is described at:
Martin Odersky is the creator of the Scala language. He is a
professor at EPFL in Lausanne, Switzerland, and a founder of Scala
Solutions Inc. He works on programming languages and systems, more
specifically on the topic of how to combine object-oriented and
functional programming. Since 2001 he has concentrated on designing,
implementing, and refining Scala. Previously, he has influenced the
development of Java as a co-designer of Java generics and as the
original author of the current
javac reference compiler. He is a
fellow of the ACM.
Lex Spoon is a software engineer at LogicBlox, to the logic language that powers LogicBlox. He and his wife currently live in Atlanta with two cats, a chihuahua, and a turtle. | http://www.artima.com/scalazine/articles/scala_collections_architectureP.html | CC-MAIN-2017-22 | refinedweb | 1,272 | 61.06 |
Coding For Multiple Cores on Xbox 360 and Microsoft Windows
For years the performance of processors has increased steadily, and games and other programs have reaped the benefits of this increasing power without having to do anything special.
The rules have changed. The performance of single processor cores is now increasing very slowly, if at all. However, the computing power available in a typical computer or console continues to grow. The difference is that most of this performance gain now comes from having multiple processor cores in a single machine, often in a single chip. The Xbox 360 CPU has three processor cores on one chip, and roughly 70 percent of PC processors sold in 2006 were multi-core.
The increases in available processing power are just as dramatic as in the past, but now developers have to write multithreaded code in order to use this power. Multi-threaded programming brings with it new design and programming challenges. This topic gives some advice on how to get started with multithreaded programming.
The Importance of Good Design
Good multithreaded program design is critical, but it can be very difficult. If you haphazardly move your major game systems onto different threads, you will likely find that each thread spends most of its time waiting on the other threads. This type of design leads to increased complexity and significant debugging effort, with virtually no performance gain.
Every time that threads have to synchronize or share data there is the potential for data corruption, synchronization overhead, deadlocks, and complexity. Therefore, your multithreaded design needs to clearly document every synchronization and communication point, and it should minimize such points as much as possible. Where threads need to communicate, coding effort will increase, which can lower productivity if it affects too much source code.
The simplest design goal for multithreading is to break up the code into large independent pieces. If you then restrict these pieces to communicating just a few times per frame, you will see significant speedup from multithreading, without undue complexity.
Typical Threaded Tasks
A few types of tasks have proven amenable to being put onto separate threads. The following list is not intended to be exhaustive, but should give some ideas.
Rendering
Rendering — which may include walking the scene graph or, possibly, only calling D3D functions — often accounts for 50 percent or more of CPU time. Therefore, moving rendering to another thread can have significant benefits. The update thread can fill in some sort of render description buffer, which the rendering thread can then process.
The game update thread is always one frame ahead of the render thread, which means that it takes two frames before user actions show up on the screen. Although this increased latency can be a problem, the increased frame rate from splitting up the workload generally keeps the total latency acceptable.
In most cases all rendering is still done on a single thread, but it is a different thread from the game update.
The D3DCREATE_MULTITHREADED flag is sometimes used to allow rendering on one thread and resource creation on other threads; this flag is ignored on Xbox 360, and you should avoid using it on Windows. On Windows, specifying this flag forces D3D to spend a significant amount of time on synchronization, thus slowing down the render thread.
File Decompression
Load times are always too long, and streaming data into memory without affecting the frame rate can be challenging. If all data is aggressively compressed on disc, then data transfer speed from the hard drive or optical disc is less likely to be a limiting factor. On a single-threaded processor, there is usually not enough processor time available for compression to help load times. On a multiprocessor system, however, file decompression uses CPU cycles that would otherwise be wasted; it improves load times and streaming; and it saves space on the disc.
Do not use file decompression as a replacement for processing that should be done during production. For instance, if you devote an extra thread to parsing XML data during level loading, you are not using multithreading to improve the player's experience.
When using a file decompression thread, you should still use asynchronous file I/O and large reads in order to maximize data-reading efficiency.
Graphics Fluff
There are many graphical niceties that improve the look of the game but aren't strictly necessary. These include things like procedurally generated cloud animations, cloth and hair simulations, procedural waves, procedural vegetation, more particles, or non-gameplay physics.
Because these effects don't affect gameplay, they don't cause tricky synchronization problems—they can synchronize with the other threads once per frame or less often. Additionally, on games for Windows these effects can add value for gamers with multicore CPUs, while silently being omitted on single-core computers, thus giving an easy way of scaling across a wide range of capabilities.
Physics
Physics often cannot be put onto a separate thread to run in parallel with the game update because the game update usually requires the results of the physics calculations immediately. The alternative for multithreading physics is to run it on multiple processors. Although this can be done, it is a complex task requiring frequent access to shared data structures. If you can keep your physics workload low enough to fit on the main thread, your job will be simpler.
Libraries that support running physics on multiple threads are available. However, this can lead to a problem: when your game is running physics, it uses many threads, but the rest of the time it uses few. Running physics on multiple threads will require addressing this so that the workload is distributed evenly over the frame. If you write a multithreaded physics engine, you must pay careful attention to all of your data structures, synchronization points, and load balancing.
Example Multithreaded Designs
Games for Windows need to run on computers with different numbers of CPU cores. Most game machines still have only one core, although the number of two-core machines is growing rapidly. A typical game for Windows might break its workload into one thread for update and rendering, with optional worker threads for adding extra functionality. In addition, some background threads for doing file I/O and networking would probably be used. Figure 1 shows the threads, together with the main data transfer points.
Figure 1. Threading design in a game for Windows
A typical Xbox 360 game can use additional CPU-intensive software threads, so it might break up its workload into an update thread, rendering thread, and three worker threads, as shown in Figure 2.
Figure 2. Threading design in a game for Xbox 360
With the exception of file I/O and networking, these tasks all have the potential to be CPU-intensive enough to benefit from being on their own hardware thread. These tasks also have the potential to be independent enough that they can run for an entire frame without communicating.
The game update thread manages controller input, AI, and physics, and prepares instructions for the other four threads. These instructions are placed into buffers owned by the game update thread, so no synchronization is required as the instructions are generated.
At the end of the frame, the game update thread hands off the instruction buffers to the four other threads, and then starts working on the next frame, filling in another set of instruction buffers.
Because the update and rendering threads work in lockstep with each other, their communication buffers are simply double buffered: at any given time, the update thread is filling one buffer while the render thread is reading from the other.
The other worker threads are not necessarily tied to the frame rate. Decompressing a piece of data may take much less than a frame, or it may take many frames. Even the cloth and hair simulation may not need to run exactly at the frame rate because less frequent updates may be quite acceptable. Therefore, these three threads need different data structures to communicate with the update thread and the render thread. They each need an input queue that can hold work requests, and the render thread needs a data queue that can hold the results produced by the threads. At the end of each frame the update thread will add a block of work requests to worker threads' queues. Adding to the list just once per frame ensures that the update thread minimizes the synchronization overhead. Each of the worker threads pulls assignments from the work queue as quickly as it can, using a loop that looks something like this:
Because the data goes from the update threads to the worker threads and then to the render thread, there can be a delay of three or more frames before some actions make it to the screen. However, if you assign latency-tolerant tasks to the worker threads, then this should not be a problem.
An alternate design would be to have several worker threads all drawing from the same work queue. This would give automatic load balancing and would make it more likely that all of the worker threads would stay busy.
The game update thread must take care to not give too much work to the worker threads, or else the work queues may continuously grow. How the update thread manages this depends on what sort of tasks the worker threads are doing.
Simultaneous Multithreading and Number of Threads
All threads are not created equal. Two hardware threads might be on separate chips, on the same chip, or even on the same core. The most important configuration for game programmers to be aware of is two hardware threads on one core—Simultaneous Multi-Threading (SMT) or Hyper-Threading Technology (HT Technology).
SMT or HT Technology threads share the resources of the CPU core. Because they share the execution units, the maximum speedup from running two threads instead of one is typically 10 to 20 percent, instead of the 100 percent that is possible from two independent hardware threads.
More significantly, SMT or HT Technology threads share the L1 instruction and data caches. If their memory access patterns are incompatible, they can end up fighting over the cache and causing many cache misses. In the worst case, the total performance for the CPU core can actually decrease when a second thread is run. On Xbox 360, this is a fairly simple problem. The configuration of the Xbox 360 is known—three CPU cores each with two hardware threads—and developers assign their software threads to specific CPU threads and can measure to see whether their threading design gives them extra performance.
On Windows, the situation is more complicated. The number of threads and their configuration will vary from computer to computer, and determining the configuration is complicated. The function GetLogicalProcessorInformation gives information about the relationship between different hardware threads, and this function is available on Windows Vista, Windows 7, and Windows XP SP3. Therefore, for now you have to use the CPUID instruction and the algorithms given by Intel and AMD in order to decide how many "real" threads you have available. See the references for more information.
The CoreDetection sample in the DirectX SDK contains sample code that uses the GetLogicalProcessorInformation function or the CPUID instruction to return the CPU core topology. The CPUID instruction is used if GetLogicalProcessorInformation is not supported on the current platform. CoreDetection can be found in the following locations:
- Source:
DirectX SDK root\Samples\C++\Misc\CoreDetection
- Executable:
DirectX SDK root\Samples\C++\Misc\Bin\CoreDetection.exe
The safest assumption is to have no more than one CPU-intensive thread per CPU core. Having more CPU-intensive threads than CPU cores gives little or no benefits, and brings the extra overhead and complexity of additional threads.
Creating Threads
Creating threads is a fairly simple operation, but there are many potential errors. The code below shows the proper way of creating a thread, waiting for it to terminate, and then cleaning up.
const int stackSize = 65536; HANDLE hThread = (HANDLE)_beginthreadex( 0, stackSize, ThreadFunction, 0, 0, 0 ); // Do work on main thread here. // Wait for child thread to complete WaitForSingleObject( hThread, INFINITE ); CloseHandle( hThread ); ... unsigned __stdcall ThreadFunction( void* data ) { #if _XBOX_VER >= 200 // On Xbox 360 you must explicitly assign // software threads to hardware threads. XSetThreadProcessor( GetCurrentThread(), 2 ); #endif // Do child thread work here. return 0; }
When you create a thread, you have the option to specify the stack size for the child thread, or specify zero, in which case the child thread will inherit the parent thread's stack size. On Xbox 360, where stacks are fully committed when the thread starts, specifying zero can waste significant memory, because many child threads will not need as much stack as the parent. On Xbox 360 it is also important that the stack size be a multiple of 64-KB.
If you use the CreateThread function to create threads, then the C/C++ runtime (CRT) will not get properly initialized on Windows. We recommend that you use the CRT _beginthreadex function instead.
The return value from CreateThread or _beginthreadex is a thread handle. This thread can be used to wait for the child thread to terminate, which is much simpler and much more efficient than spinning in a loop checking the thread status. To wait for the thread to terminate, simply call WaitForSingleObject with the thread handle.
The resources for the thread will not be freed until the thread has terminated and the thread handle has been closed. Therefore, it is important to close the thread handle with CloseHandle when you are finished with it. If you will be waiting for the thread to terminate with WaitForSingleObject, be sure to not close the handle until after the wait has completed.
On Xbox 360, you must explicitly assign software threads to a particular hardware thread by using XSetThreadProcessor. Otherwise, all child threads will stay on the same hardware thread as the parent. On Windows, you can use SetThreadAffinityMask to strongly suggest to the operating system which hardware threads your thread should run on. This technique should generally be avoided on Windows since you don't know what other processes might be running on the system. It is typically better to let the Windows scheduler assign your threads to idle hardware threads.
Creating threads is an expensive operation. Threads should be created and destroyed rarely. If you find yourself wanting to create and destroy threads frequently, use a pool of threads that wait around for work instead.
Synchronizing Threads
For multiple threads to work together, you must be able to synchronize threads, pass messages, and request exclusive access to resources. Windows and Xbox 360 come with a rich set of synchronization primitives. For full details on these synchronization primitives, see the platform documentation.
Exclusive Access
Gaining exclusive access to a resource, data structure, or code path is a common need. One option for gaining exclusive access is a mutex, whose typical usage is shown here.
// Initialize HANDLE mutex = CreateMutex( 0, FALSE, 0 ); // Use void ManipulateSharedData() { WaitForSingleObject( mutex, INFINITE ); // Manipulate stuff... ReleaseMutex( mutex ); } // Destroy CloseHandle( mutex ); The kernel guarantees that, for a particular mutex, only one thread at a time can acquire it. The main disadvantage to mutexes is that they are relatively expensive to acquire and release. A faster alternative is a critical section. // Initialize CRITICAL_SECTION cs; InitializeCriticalSection( &cs ); // Use void ManipulateSharedData() { EnterCriticalSection( &cs ); // Manipulate stuff... LeaveCriticalSection( &cs ); } // Destroy DeleteCriticalSection( &cs );
Critical sections have similar semantics to mutexes, but they can be used to synchronize only within a process, not between processes. Their main advantage is that they execute roughly twenty times faster than mutexes.
Events
If two threads—perhaps an update thread and a render thread—are taking turns using a pair of render description buffers, they need a way to indicate when they are done with their particular buffer. This can be done by associating an event (allocated with CreateEvent) with each buffer. When a thread is done with a buffer, it can use SetEvent to signal this, and can then call WaitForSingleObject on the other buffer's event. This technique extrapolates easily to triple buffering of resources.
Semaphores
A semaphore is used to control how many threads can be running and is commonly used to implement work queues. One thread adds work to a queue and uses ReleaseSemaphore whenever it adds a new item to the queue. This allows one worker thread to be released from the pool of waiting threads. The worker threads just call WaitForSingleObject, and when it returns they know there is a work item in the queue for them. In addition, a critical section or other synchronization technique must be used in order to guarantee safe access to the shared work queue.
Avoid SuspendThread
Sometimes when you want a thread to stop what it is doing, it is tempting to use SuspendThread instead of the correct synchronization primitives. This is always a bad idea and can easily lead to deadlocks and other problems. SuspendThread also interacts badly with the Visual Studio debugger. Avoid SuspendThread. Use WaitForSingleObject instead.
WaitForSingleObject and WaitForMultipleObjects
The function WaitForSingleObject is the most commonly used synchronization function. However, sometimes you want a thread to wait until several conditions are simultaneously satisfied, or until one of a set of conditions are satisfied. In this case, you should use WaitForMultipleObjects.
Interlocked Functions and Lockless Programming
There is a family of functions for performing simple thread-safe operations without using locks. These are the Interlocked family of functions, such as InterlockedIncrement. These functions, plus other techniques using careful setting of flags, are together known as lockless programming. Lockless programming can be extremely tricky to do correctly, and is substantially more difficult on Xbox 360 than on Windows.
For more information about programming without locks, see Lockless Programming Considerations for Xbox 360 and Microsoft Windows.
Minimizing Synchronization
Some synchronization methods are faster than others. However, rather than optimizing your code by choosing the fastest synchronization techniques possible, it is usually better to synchronize less often. This is faster than synchronizing too frequently, and it makes for simpler code that is easier to debug.
Some operations, such as memory allocation, may have to use synchronization primitives in order to work correctly. Therefore, doing frequent allocations from the default shared heap will result in frequent synchronization, which will waste some performance. Avoiding frequent allocations or using per-thread heaps (using HEAP_NO_SERIALIZE if you use HeapCreate) can avoid this hidden synchronization.
Another cause of hidden synchronization is D3DCREATE_MULTITHREADED, which causes D3D on Windows to use synchronization on many operations. (The flag is ignored on Xbox 360.)
Per-thread data, also known as thread local storage, can be an important way of avoiding synchronization. Visual C++ allows you to declare global variables as being per-thread with the __declspec(thread) syntax.
This gives each thread in the process its own copy of tls_i, which can be referenced safely and efficiently without requiring synchronization.
The __declspec(thread) technique does not work with dynamically loaded DLLs. If you use dynamically loaded DLLs, you will need to use the TLSAlloc family of functions to implement thread local storage.
Destroying Threads
The only safe way to destroy a thread is to have the thread itself exit, either by returning from the main thread function or by having the thread call ExitThread or _endthreadex. If a thread is created with _beginthreadex, then it should use _endthreadex or return from the main thread function, since using ExitThread won't properly free CRT resources. Never call the TerminateThread function, because the thread will not be properly cleaned up. Threads should always commit suicide—they should never be murdered.
OpenMP
OpenMP is a language extension for adding multithreading to your program by using pragmas to guide the compiler in parallelizing loops. OpenMP is supported by Visual C++ 2005 on Windows and Xbox 360 and can be used in conjunction with manual thread management. OpenMP can be a convenient way to multithread parts of your code, but is unlikely to be the ideal solution, especially for games. OpenMP may be more applicable to longer-running production tasks such as processing art and other resources. For more information, see the Visual C++ documentation or go to the OpenMP website.
Profiling
Multithreaded profiling is important. It is easy to end up with long stalls where threads are waiting on each other. These stalls can be difficult to find and diagnose. To help identify them, consider adding instrumentation to your synchronization calls. A sampling profiler can also help identify these problems because it can record timing information without substantially altering it.
Timing
The rdtsc instruction is one way to get accurate timing information on Windows. Unfortunately, rdtsc has multiple problems that make it a poor choice for your shipping title. The rdtsc counters are not necessarily synchronized between CPUs, so when your thread moves between hardware threads you may get large positive or negative differences. Depending on power management settings, the frequency at which the rdtsc counter increments may also change as your game runs. To avoid these difficulties, you should prefer QueryPerformanceCounter and QueryPerformanceFrequency for high-precision timing in your shipping game. For more information about timing, see Game Timing and Multicore Processors.
Debugging
Visual Studio fully supports multithreaded debugging for Windows and Xbox 360. The Visual Studio threads window lets you switch between threads in order to see the different call stacks and local variables. The threads window also lets you freeze and thaw particular threads.
On Xbox 360, you can use the @hwthread meta-variable in the watch window to show the hardware thread on which the currently selected software thread is running.
The threads window is easier to use if you name your threads meaningfully. Visual Studio and other Microsoft debuggers allow you to name your threads. Implement the following SetThreadName function and call it from each thread as it starts up.
typedef struct tagTHREADNAME_INFO { DWORD dwType; // must be 0x1000 LPCSTR szName; // pointer to name (in user address space) DWORD dwThreadID; // thread ID (-1 = caller thread) DWORD dwFlags; // reserved for future use, must ) { } } // Example usage: SetThreadName(-1, "Main thread");
The kernel debugger (KD) and WinDBG also support multithreaded debugging.
Testing
Multithreaded programming can be tricky, and some multithreaded bugs show up only rarely, making them difficult to find and fix. One of the best ways to flush them out is to test on a wide range of computers, particularly those with four or more processors. Multithreaded code that works perfectly on a single-threaded computer may fail instantly on a four-processor computer. The performance and timing characteristics of AMD and Intel CPUs can vary substantially, so be sure to test on multiprocessor computers based on CPUs from both vendors.
Windows Vista and Windows 7 Improvements
For games targeting the newer versions of Windows, there are a number of APIs that can simplify the creation of scalable multithreaded applications. This is particularly true with the new ThreadPool API and some additional syncrhonziation primitives (condition variables, the slim read/writer lock, and one-time initialization). You can find an overview of these technologies in the following MSDN Magazine articles:
Applications using Direct3D 11 Features on these operating systems can also take advantage of the new design for concurrent object creation and deferred context command lists for better scalability for multithreaded rendering.
Summary
With careful design that minimizes the interactions between threads, you can get substantial performance gains from multithreaded programming without adding excessive complexity to your code. This will let your game code ride the next wave of processor improvements and deliver ever more compelling gaming experiences.
References
- Jim Beveridge & Robert Weiner, Multithreading Applications in Win32, Addison-Wesley, 1997
- Chuck Walbourn, Game Timing and Multicore Processors, Microsoft Corporation, 2005
- Microsoft Corporation: Multiprocessor Considerations for Kernel-Mode Drivers, 2004
- Intel: Detecting Multi-Core Processor Topology in an IA-32 Platform, 2006
- AMD: CPUID Specification, 2006
- MSDN Library: GetLogicalProcessorInformation
- OpenMP
Build date: 11/16/2013 | http://msdn.microsoft.com/en-us/library/ee416321(v=vs.85).aspx | CC-MAIN-2014-42 | refinedweb | 3,994 | 51.58 |
In the previous blogs about Redis, we learned the basics of Redis, Commands, and Hash Data Structure in Redis. This Time we will learn How to use Redis With Python?
Prerequisite for Using Redis with Python
Make Sure that Redis is installed on your machine. If working on Windows read How to install Redis on Windows 10?
Installing Redis in Python
We have our Redis set up in our machine now we want a package that would help us to connect with the Redis Server on our machine with the help of the python program.
Redis can be installed in python using pip (package installer python).
$ pip install redis
Bash/Shell
This command will install the Redis Python Package which will help us to connect with the Redis Server on our machine and execute in-memory No-SQL database commands.
Use Redis in Python
Now, when we have installed the Redis Python Package. It’s time to use it.
Import Redis
As you would already know, installed packages in python are imported to make use of it. So Let’s import Redis in Python.
>>> import redis
Python
Package installed successfully if no error occurs.
Run Redis Server
The Redis Python package makes use of the Redis server on our machine, So before running a python program that includes Redis commands, run the server, else you will get an error.
$ redis-server
Bash/Shell
Redis Instance in python
Redis package has a Redis Class that needs to be instantiated to connect to the Redis Server operating on our machine.
import redis
REDIS_PORT = 6379
REDIS_HOST = '127.0.0.1'
r = redis.Redis(host=REDIS_HOST, port=REDIS_PORT)
Python
By Default, the Redis Server operates on the localhost and the port 6379. You can change it at the time of installation.
The Redis Class in the Redis package takes the Host and the Port name and sets up a connection with our Redis Server on our Localhost.
Redis Commands in Python
Now it’s time to execute some of the Redis commands in Python to test whether the connection with Redis Server is built or not.
print(r.ping())
print(r.keys())
r.set('key1', 'value1')
print(r.get('key1'))
r.set('key2', 'value2')
print(r.keys())
Python
True
[]
b'value1'
[b'key2', b'key1']
Python
The Ping Command in Redis Python gives boolean Value i.e True (If the Connection with the Redis Server is proper).
Learn more about how to work with Redis in Python form the official Redis-py Documentation. | https://hackthedeveloper.com/use-redis-with-python/ | CC-MAIN-2021-39 | refinedweb | 419 | 64.3 |
How to use CNI when a native method is statemented in a j2me midlet?
Please note these java.net forums are being decommissioned and use the new and improved forums at.
How to use CNI when a native method is statemented in a j2me midlet?December 20, 2011 - 22:52
j2me code:
package game.lib;
public class StbInfo
{
public static native void getstbinfo();
}
the question is:
how can I implement this native method in jvm code?
where should I insert the code?
thank you for your help
I assume you are getting some sort of link error for the missing getstbinfo() method. Native methods for MIDP and midlets are implemented as KNI methods. When running on CDC/CVM, KNI methods are implemented as CNI methods with special KNI macros, so when missing you probably see the method name as CNIgame_lib_StbInfo_getbsdinfo.
The way to get the KNI native method so it can be built for CLDC or CDC is to use the KNIDECL macro. You can find it in kni.h, but there is a different version of the header depending on whether you are building for CLDC or CDC. For CDC, make sure you are using the one in cdc/src/share/export/kni.h. You should be able to find plenty of examples of the use of KNIDECL in the midp source. | https://www.java.net/forum/topic/mobile-embedded/phoneme-advanced-software/how-use-cni-when-native-method-statemented-j2me-midlet | CC-MAIN-2015-27 | refinedweb | 223 | 74.08 |
Too good
this example is too good,even all materials also too good
Appreciation!
This is a great beauty. My utmost thanks.
Well Done
I am very impressed by the way you simplify your codes.
Keep it up
string manipulation
how to create a program that a name will change to a number?
for example a letter a=1,b=2,c=3,d=4. . .
input: ab
output: 3
c program
sir please give me
w.a.p in a c program count the number of lines words characters in the given input
and important programs list give me
iam studying in m.c.a in A.N.U
please give me please give me
.........
thankyou sir
bye
Merge Sort optimization
Hi
Can you please suggest some optimization for this merge sort code.
Thanks
Amna
one problem
when i tried your program in my computer, it works perfectly while reading .java files, but when i use the program to read .doc or .docx files, it gives me some random numbers for lines, words and characters. could you please help with that.
thank
Count instances of each word
Count instances of each word I am working on a Java Project that reads a text file from the command line and outputs an alphabetical listing of the words preceded by the occurrence count. My program compiles and runs
word program - Java Beginners
word program HELLO MAM AND SIR I ASK YOUR HELP HOPE YOU GONNA HELP ME THANK YOU!!Design a program to search a word for letters that the user....(REmember that the alphabet contains 52 characters if you count uppercase and lowercase
java word counting - Java Beginners
java word counting Hi I want a code in java that replaces a word...... but this will change all the occurrence even if its part of another word the run... = new java.util.Scanner(System.in);String s,s1,s2;String resultString;int count
word and character counting - Java Beginners
word and character counting here is the java code i made but i have... javax.swing.*;
import java.io.*;
public class count
{
public static void main... = null;
String word;
int numLines = 0;
int numWords = 0
export to word document - Java Beginners
export to word document hi sir,when i am click on a button under the jtable,for example (print button),then i want to print that jtable in word... actionPerformed(ActionEvent ae){
int count=table.getRowCount
Word Count
Word Count
This example counts the number of occurrences of
a specific word...\kodejava>java WordCountExample
3 occurrences of the word 'you' in 'How r you?R you
Word replacment - Java Beginners
Word replacment Java code for the Word Replacement.Thnaks in Advance! Hipublic class WordReplaced{ public static void main(String[] args... information,
Java Word Count - Word Count Example in Java
Java Word Count - Word Count Example in Java
...;}
}
}
Download Word count Example... to count the number of
lines, number of words and number of characters | http://roseindia.net/tutorialhelp/allcomments/212 | CC-MAIN-2014-10 | refinedweb | 492 | 65.52 |
There are several libraries allowing access to the SPIFFS file system stored on the flash memory of an ESP32 in FTP. The ESP8266FtpServer.h library developed by David Paiva (nailbuster on GitHub) very easy to use, allows you to add a small FTP server to the Arduino code of the ESP32 project. It also works on ESP8266. It can be used to retrieve data files or remotely update the HTML interface files, the data file of a data acquisition.
The SPIFFS file system for ESP32 is used to store files on the flash memory module. We can separate the code of the HTML interface (HTML file, CSS style sheet, javascript code) as well as data or parameter files. We will use the SPIFFS.h library to access, create or modify the files from the Arduino code of the project..
It is not available from the library manager of the Arduino IDE. It will therefore be necessary to manually recover the files and add them to the ESP32 project.
Go to the project’s GitHub page here then download the project code
Unzip the ZIP archive then move the ESP8266FtpServer.cpp and ESP8266FtpServer.h files at the root of the project at the same level as the ino file of the project.
Example of an FTP file server on ESP32
Create a new sketch on the Arduino IDE and paste the following code.
Modify the following parameters:
- WiFi username and password
- Username and password of the FTP server
#ifdef ESP8266 #include <ESP8266WiFi.h> #elif defined ESP32 #include <WiFi.h> #include "SPIFFS.h" #endif #include "ESP8266FtpServer.h" const char* ssid = "enter_your_ssid"; const char* password = "enter_your_password"; const char* ftp_user = "esp32"; const char* ftp_password = "esp32";...")); // FTP Setup, ensure SPIFFS is started before try to use ftp methods #ifdef ESP32 if (SPIFFS.begin(true)) { #elif defined ESP8266 if (SPIFFS.begin()) { #endif Serial.println("SPIFFS opened!"); ftpSrv.begin(ftp_user, ftp_password); //username, password for ftp } } void loop() {(ftp_user, ftp_password); //
- comment to enable sending debug messages on the serial monitor (convenient for debugging)comment on Connection. The connection is now saved by FileZilla, it will not be necessary to do it again.
As the connection is not secure, you must accept the warning before you can connect to the ESP32.
Once the connection is established, you have access to all the files in the Data directory of the Arduino project.
SPIFFS and LittleFS files can also be accessed by FTP on ESP8266.
Updates
09/04/2020 First publication of the tutorial
- | https://diyprojects.io/esp32-access-spiffs-files-in-ftp-with-esp8266ftpserver-library/ | CC-MAIN-2021-49 | refinedweb | 413 | 65.62 |
The System.Diagnostics.Conditional attribute has been on blog-todo list for a while, and I’m finally getting around to it. For the quiz-loving folks, here you go:
Quiz:
First, some lingo: I’ll say a Conditional Function is a function with a Conditional attribute on it. The conditional function is active (within the scope of a symbol) if the symbol is defined, else it is inactive.
- What happens if you place a conditional attribute on Main?
- Can the semantics of the conditional attribute change from language to language (is it enforced by the languages or by the runtime)?
- Are inactive conditional functions compiled?
- Can you invoke conditional functions via a delegate?
- Can you invoke conditional functions via Reflection / MethodInfo.Invoke?
- Can conditional functions have byref parameters?
- What does it mean to place a conditional attribute on an attribute?
- If module A references an inactive conditional function in module B, does A need to have access to B at runtime? At compile time?
If you aced that, you can skip the rest of this entry. About half of them could be categorized as trick questions…
Here’s some background that helps answer those questions.
Conditional attributes can be placed on methods (and attributes in whidbey) to instruct the compiler to conditionally remove calls to the function if a symbol is not defined. This can be useful for debug-only functionality, like Debug.Assert, which has a Conditional(“DEBUG”) on it.
Conditional takes a string argument. If that string is defined (as determined by the compiler’s preprocessor), then the compiler emits the method call. If the symbol is not defined, C# still compiles the method, but does not compile the calls.
A quick demo:
Consider the following file x.cs:
using System; using System.Diagnostics; class Program { [Conditional("Test")] static void Test() { Console.WriteLine("'Test' is defined"); } static void Main() { Console.WriteLine("Start"); Test(); Console.WriteLine("End"); } }
When compiled without defining ‘Test’, the method is not executed.
C:\temp>csc x.cs & x.exe
Microsoft (R) Visual C# 2005 Compiler version 8.00.50727.1378
for Microsoft (R) Windows (R) 2005 Framework version 2.0.50727
Start
End
But when defining ‘Test’, the method is executed.
C:\temp>csc x.cs /d:Test & x.exe
Microsoft (R) Visual C# 2005 Compiler version 8.00.50727.1378
for Microsoft (R) Windows (R) 2005 Framework version 2.0.50727
Start
‘Test’ is defined
End
About Conditional Functions:
1. Compiler vs. CLR:
The Conditional attribute is entirely handled by the compiler without any cooperation from the runtime. The method is still jitted normally, but the compiler just doesn’t emit the calls if the symbol is not defined. You can verify this by running ildasm on the output.
However, by including the Conditional attribute in the BCL, the CLR is essentially defining a cross-language protocol, and then leaving it up to the different languages to implement this protocol.
2. Compiler Enforcement:
Since it’s a compiler thing, the compiler has to do most of the enforcement to provide the model it wants.
In C#’s case:
- Symbol and preprocess are determined by compiler, not the jitter. Each compiler can use its own techniques here. Csc.exe allows this to be set on the command line (/define, /d), or in source files via #define. Other compilers could use other techniques (such as environment variables, config files)
- C# requires that #define is the first whitespace token (see CS1032). Kudos on the consistency. Unlike C++, C# lets you define members in any order. If #defines were allowed in the middle of a file, then the ordering between the #define and the functions calling a [Conditional] would matter.
- C# is case sensitive about symbol comparisons.
- The signature must be return void (see CS0578) and can’t have Out params (see CS0685). This makes sense because the code needs to compile when the function call is removed. It does allows ref params.
- C# won’t let you directly create a delegate to conditional attribute. (see CS1618).
- C# normally flags unused locals. However, if a local is only used as an argument to calling a conditional function, then it would be unused when that conditional function is not active. C# does not flag these as unused.
- C# still type checks arguments to the condtional function, even when the conditional function is not active.
C#’s decisions here enforce an intuitive behavior: if the conditional functions are side-effect free, then removing them will not change program behavior or compiler warnings. (Exercise to reader: how would that break if C# didn’t have the policy above).
But different compilers could have different policy decisions here. For example, a compiler could evaluate arbitrarily complex expressions in the condition. MC++ just ignores the attribute.
3. CLR things.
Since the method is still compiled in, it can be referenced and invoked by Reflection. For example:
MethodInfo m = typeof(Program).GetMethod("Test"); m.Invoke(null, new object[] { });
The Conditional attribute just affects the callsite and not the definition, so you can invoke conditional functions from across modules. This is critical for Debug.Assert(), which is defined in system.dll.
Also, other .NET languages could have their own policy about how to handle Conditional attributes. For example, a naive .Net language (such as ILasm) would not even check if a callsite has a conditional attribute, and emit the call regardless.
So what if you put a conditional attribute on Main()?
This is a strange case. A compiler could flag an error here since the user’s intent is not clear. Does the user want the whole program to be a nop? In the absence of a compiler error, the behavior here is settled according to the existing rules (and loopholes in the compile). If the CLR makes the call to Main(), then the conditional attribute is ignored. This is what happens in C#. (See ‘What runs before Main()‘ ) If you use ‘void Main()’, the the Conditional attribute is ignored in C#. If you use ‘int Main()’, then you get an error that the conditional must be on type void.
What about Conditional on Attributes?
Conditional attributes are basically the same philosophy of conditional functions, but applied to attributes. | https://blogs.msdn.microsoft.com/jmstall/2007/10/15/trivia-about-the-conditional-attribute/ | CC-MAIN-2016-30 | refinedweb | 1,036 | 58.79 |
What's the advantages of typing "std::" before a vector initialization, for example:
std::vector<type> instance;
or
vector<type> instance;
Both seem to work, right? So what's better?
Printable View
What's the advantages of typing "std::" before a vector initialization, for example:
std::vector<type> instance;
or
vector<type> instance;
Both seem to work, right? So what's better?
Better? Neither is better. The current standard just states that vector is within the std namespace. Thus std::vector is correct in the current standard. If both work, your compiler doesn't harp on your code matching the standard. If you want your code to be correct, keep typing std::vector or using std::vector or using namespace std in your code.
Analogy:
I went to the store.
I goed to the store.
Which is better?
So basicly you never "have" to use std::?
Two of the compilers I commonly use do not care. Reason: One is microsoft's... the other is an older compiler for making sure stuff compiles on older compilers. The other three compilers I commonly use care quite a bit and basically say they don't know what I am talking about unless I put standard (well actually the newer GCC's typically hint to you what you may have done wrong).
To be more concise. Your compiler has the ultimate say in whether you need to put std. In your case, its not an issue. But if you want others to be able to compile your code, you may want to simply add
Example:
Code:
#include <vector>
#include <string>
#include <iostream>
int main()
{
using namespace std;
/* Code goes here */
return 0;
}
Unless you are using an old, non-standard compiler, you have to specify the std namespace somehow, just like with cout, cin, etc. You can use std:: in front of the name (my preference) or you can use a using directive or declaration.
There are differences. Generally speaking std:: is safer, but in simple programs it probably doesn't matter. In larger programs it's considered bad practice not to use the std:: version in header files, which is why I use it everywhere for consistency.
The bottom line is that if you have already made this decision for cout, cin, string, etc then follow the same advice for vector.
Thanks.
Microsoft's latest compiler doesn't care in some cases (specifically names from C libraries). It does give an error for vector, though.Code:
#include <cstdio>
int main()
{
printf("Hello World.\n");
} | http://cboard.cprogramming.com/cplusplus-programming/103539-std-vector-vector-difference-printable-thread.html | CC-MAIN-2015-40 | refinedweb | 421 | 66.03 |
WIP: Speed up showing repository tree
What does this MR do?What does this MR do?
Speed up showing repository tree.
BenchmarkBenchmark
The following is a benchmark script.
require "benchmark/ips" Benchmark.ips do |x| x.config(time: 10, warmup: 2) project = Project.find_with_namespace("gitlab-org/gitlab-ce") repository = project.repository commit = repository.commit("master") tree = repository.tree(commit.id, nil) x.report("new") do logs = repository.logs_tree(commit.id) end x.report("old") do contents = [] contents.push(*tree.trees) contents.push(*tree.blobs) contents.push(*tree.submodules) logs = contents.to_a.map do |content| last_commit = repository.last_commit_for_path(commit.id, content.name) { file_name: content.name, commit: last_commit } end end x.compare! end
And loads the script in the rails console.
[1] pry(main)> load "tmp/tree_logs_benchmark.rb" Calculating ------------------------------------- new 103.000 i/100ms old 1.000 i/100ms ------------------------------------------------- new 999.825 (±13.7%) i/s - 9.785k old 0.393 (± 0.0%) i/s - 4.000 Comparison: new: 999.8 i/s old: 0.4 i/s - 2544.45x slower
It is about 2500x faster to get tree logs from the gitlab-ce repository if the tree logs are cached.
Are there points in the code the reviewer needs to double check?Are there points in the code the reviewer needs to double check?
Cache key includes
<commit sha>.
So it is not necessary to expire the cache manually.
- cache key:
logs_tree/<commit sha>/<path>
- cache value: compressed
<content name>/<commit sha of content>/<committed date (unix time)>/<commit subject>\n[...]
Why was this MR needed?Why was this MR needed?
It is very slow to show the repository tree view.
added 1 commit
Compare with previous versionToggle commit list
added 1 commit
Compare with previous versionToggle commit list
/cc @yorickpeterse Can you take a look?
- Master
@hiroponz I'm not a fan of this. The code is overly complex, relies on pattern matching output (instead of using libgit2), doesn't support offsets (something we probably use for pagination), and use ad-hoc OpenStruct instances instead of proper classes. As far as I can tell it's also possible to exploit this code: the command executed takes the
shaand
filevariables but makes no attempt to escape them.
I would rather see the existing code improved in smaller increments (preferably using separate merge requests), and by using libgit2 instead of the Git CLI.
closedToggle commit list
@yorickpeterse Thank you for reviewing.
mentioned in merge request gitlab-com/www-gitlab-com!4935 (merged)Toggle commit list | https://gitlab.com/gitlab-org/gitlab-ce/merge_requests/8044 | CC-MAIN-2018-17 | refinedweb | 413 | 55.61 |
#include "SPI.h"#include <UTFT.h>#include <UTouch.h>#define FLASH_CS_PIN 52 #define SPI_RATE 2//Font selection //BVS= Bitstream vera sans, suffix = font size in pixel (height)#define BVS_13 10#define BVS_15 12#define BVS_19 14#define BVS_22 18#define BVS_28 22#define BVS_34 28#define BVS_43 38#define BVS_52 53#define BVS_74 78#define BVS_112 122extern uint8_t SmallFont[];UTFT myGLCD(CTE35); // Remember to change the model parameter to suit your display module!UTouch myTouch(6,5,32,3,2);void setup(){ delay(1000); myGLCD.SPI_Flash_init(FLASH_CS_PIN,SPI_RATE); Serial1.begin(38400); myGLCD.InitLCD(); myTouch.InitTouch(); myGLCD.setFont(SmallFont); myGLCD.clrScr(); myGLCD.Swtich_LCD_TB_Bit(0); myGLCD.Load_image(0,0,664); myGLCD.setColor(0,0,0); myGLCD.setBackColor(130,192,229); myGLCD.Put_Text("Sonora Technical",320,5,BVS_22);}void loop(){ myGLCD.drawRect(10,10,50,50); long x, y; myTouch.read(); x = myTouch.getX(); y = myTouch.getY(); while (true) {};}
I am having the same problem on the 3.2". Daniel and I are teaming up to work on this issue together. We have the same shields, LCDs, DUEs...and unfortunately..the same exact issues...Very frustrating to purchase products, download their demos, their libraries... then run them and the images are flipped, mirrored, rotated 180 deg. text is mirrored...bitmaps are not... etc.. etc... touchscreen counts down backwards, etc...Is there anyone using these 3.2" and 3.5" ColdTears products where they just work?Trying to determine if Daniel and I have a bad batch (we ordered them together).
Is there anyone using these 3.2" and 3.5" ColdTears products where they just work?
Please enter a valid email to subscribe
We need to confirm your email address.
To complete the subscription, please click the link in the
Thank you for subscribing!
Arduino
via Egeo 16
Torino, 10131
Italy | http://forum.arduino.cc/index.php?topic=157068.msg1213806 | CC-MAIN-2017-09 | refinedweb | 298 | 62.44 |
*
A friendly place for programming greenhorns!
Big Moose Saloon
Search
|
Java FAQ
|
Recent Topics
|
Flagged Topics
|
Hot Topics
|
Zero Replies
Register / Login
JavaRanch
»
Java Forums
»
Java
»
JSF
Author
Need a fix for <a4j:commandLink> to both run an action and oncomplete event.
Dan Acuff
Ranch Hand
Joined: Jul 13, 2009
Posts: 62
posted
Oct 26, 2012 15:39:02
0
Hi everyone and thank you for your time.
Our website runs on Java SEAM/JSF 1.2/RichFaces3.x.x and Facelets is there on the front-end as well.
I mostly work on another platform and language but am transitioning to this platform, so pardon me if I lack clarity in any areas.
I want to create a one text input form with a submit button, using ajax4jsf or a4j, and then once the bean.method is fired and a record stored in the DB - I need to rename the wrapper div's id attribute and insert some new innerHTML.
I was wondering if you all had suggestions on how to do this with your own approach?
and/or also I can show my try at tackling this simple problem next:
--------------------------------------------------------------------------------------------------
I have some code that I have managed to get working in Chrome, IE8, but not FireFox. BTW: my a4j: namespace is a: so that is what a: is in the code.
In FireFox, the
<a:commandLink
correctly submits a record to the database and does not return any values.
Next the oncomplete attribute fires an event to a JavaScript function - it's job is to replace the wrapper div id and load the new content.
First a portion of what I have in the front page code:
<h:inputText <a:commandLink <span>#{messages.submit}</span> </a:commandLink>
And then the Javascript functions:
function stockWatchTextChange() { document.getElementById('fstockwatch').setAttribute('id', 'fstockwatch_thanks'); document.getElementById('fstockwatch_thanks').innerHTML = 'Thank you. We\'ll send you an email once this item is back in stock'; } function stockWatchEnterSubmit(keyCode) { if(keyCode == 13){ document.getElementById('stockwatchSubmit').click(); } }
Hopefully there is enough information for us to at least look at the reason it failed in FireFox, but let me know if more information is needed. The Method in the bean is confirmed to work. And not a good idea to share it anyway.
Thanks all very much!
A VERY IMPORTANT P.S >>
Ok so my
testing
involves making sure you can BOTH click the button to submit your email AND type your email and just hit the Enter key. The only thing of all the browsers tested that failed is FireFox 14 (ithink) and it failed when typing and pressing Enter Key. It actually works in all browsers if you click the Submit button.
Tim Holloway
Saloon Keeper
Joined: Jun 25, 2001
Posts: 16136
21
I like...
posted
Oct 29, 2012 05:52:11
0
There are major differences between IE and Firefox when it comes to handling the ENTER key on a form.
Beyond that, a couple of minor observations:
1. I don't think "return false();" has meaning in oncomplete. onsubmit would be different.
2. RichFaces comes with some JSF-friendly macros that make it easier to access
JSF
DOM objects.
3. RichFaces also comes with a built-in (if antique) copy of jQuery that can make it easier to rearrange DOM objects in a browser-portable manner (and less code than raw javascript).
4. I'd be cautious about actually changing the IDs on DOM object, regardless.
5. Usually when I make the View mutable - which I rarely do on account of it's not generally recommended - I prefer to bind the root object of of mutating part of the View to a backing bean, let the backing bean meddle with the UI elements, and, when using AJAX, let the RichFaces reRender kick off the UI update. That way I don't need any oncomplete= javascript.
Customer surveys are for companies who didn't pay proper attention to begin with.
I agree. Here's the link:
subject: Need a fix for <a4j:commandLink> to both run an action and oncomplete event.
Similar Threads
problem with sending # character through ajax
to pass the id into javascript
readonly field value change
problem in regular expression
Difference in behaviour between javascript click() and user click on a button using JSF
All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter
JForum
|
Paul Wheaton | http://www.coderanch.com/t/596274/JSF/java/fix-commandLink-run-action-oncomplete | CC-MAIN-2014-42 | refinedweb | 731 | 70.63 |
char * gets ( char * str );
<cstdio>
Get string from stdin
Reads characters from stdin and stores them as a string into str until a newline character ('\n') or the End-of-File is reached.The ending newline character ('\n') is not included in the string.A null character ('\0') is automatically appended after the last character copied to str to signal the end of the C string.Notice that gets does not behave exactly as fgets does with stdin as argument: First, the ending newline character is not included with gets while with fgets it is. And second, gets does not let you specify a limit on how many characters are to be read, so you must be careful with the size of the array pointed by str to avoid buffer overflows.
/* gets example */
#include <stdio.h>
int main()
{
char string [256];
printf ("Insert your full address: ");
gets (string);
printf ("Your address is: %s\n",string);
return 0;
} | http://www.cplusplus.com/reference/clibrary/cstdio/gets/ | crawl-002 | refinedweb | 157 | 66.78 |
Steve Shogren
- Total activity 19
- Last activity
- Member since
- Following 0 users
- Followed by 0 users
- Votes 0
- Subscriptions 7
Steve Shogren commented, Steve Shogren created a post,
Broken Intention Actions Dialogue when using non-standard (remapped) cursor moving keysI have my keys mapped in a fashion similar to emacs/vim for cursor movement. When I hit the keystroke to bring up the intention actions dialogue (Alt-Enter) the keystroke I use to execute Editor->A...
Steve Shogren created a post,
error_reporting not working when running testsWhen I run this test in PhpStorm 98.240 with Phpunit 3.5 it fails, but it passes on the command line. They both pass in PhpStorm 1.02 with Phpunit 3.4.<?phpclass ExampleTest extends PHPUnit_Framewo...
Steve Shogren created a post,
Go To->Class Oddness in 98.191When trying to Go To -> Class in 98.191 and in 98.145 on a project with roughly five hundred classes, I noticed that if there is only one result remaining, the whole dialogue closes, and no class i...
Steve Shogren created a post,
Namespace AutocompleteWhen I create two classes called the same thing in different namespaces, and try to inherit from one of them, the autocomplete does not return any options for either class. Is there some way to hin... | https://intellij-support.jetbrains.com/hc/en-us/profiles/2113150549-Steve-Shogren?filter_by=activities | CC-MAIN-2019-43 | refinedweb | 215 | 65.32 |
audio_engine_channels(9E)
audio_engine_playahead(9E)
- report driver property information
#include <sys/types.h> #include <sys/ddi.h> #include <sys/sunddi.h> int prefixprop_op(dev_t dev, dev_info_t *dip, ddi_prop_op_t prop_op, int flags, char *name, caddr_t valuep, int *lengthp);
Solaris DDI specific (Solaris DDI). This entry point is required, but it can be ddi_prop_op(9F).
Device number associated with this device.
A pointer to the device information structure for this device.
Property operator. Valid operators are:
Get property length only. (valuep unaffected).
Get length and value into caller's buffer. (valuep used as input).
Get length and value into allocated buffer. (valuep returned as pointer to pointer to allocated buffer).
The only possible flag value is:
Do not pass request to parent if property not found.
Pointer to name of property to be interrogated.
If prop_op is PROP_LEN_AND_VAL_BUF, this should be a pointer to the user's buffer. If prop_op is PROP_LEN_AND_VAL_ALLOC, this should be the address of a pointer.
On exit, *lengthp will contain the property length. If prop_op is PROP_LEN_AND_VAL_BUF then lengthp should point to an int that contains the length of caller's buffer, before calling prop_op().
prop_op() is an entry point which reports the values of certain properties of the driver or device to the system. Each driver must have a prefix prop_op entry point, but most drivers that do not need to create or manage their own properties can use ddi_prop_op() for this entry point. Then the driver can use ddi_prop_update(9F) to create properties for its device.
prop_op() should return:
Property found and returned.
Property not found.
Prop explicitly undefined.
Property found, but unable to allocate memory. lengthp has the correct property length.
Property found, but the supplied buffer is too small. lengthp has the correct property length.
Example 1 Using prop_op() to Report Property Information
In the following example, prop_op() intercepts requests for the temperature property. The driver tracks changes to temperature using a variable in the state structure in order to avoid frequent calls to ddi_prop_update(9F). The temperature property is only updated when a request is made for this property..
int temperature; /* current device temperature */ . . . static int xxprop_op(dev_t dev, dev_info_t *dip, ddi_prop_op_t prop_op, int flags, char *name, caddr_t valuep, int *lengthp) { int instance; struct xxstate *xsp; if (dev == DDI_DEV_T_ANY) goto skip; instance = getminor(dev); xsp = ddi_get_soft_state(statep, instance); if (xsp == NULL) return (DDI_PROP_NOT_FOUND); if (strcmp(name, "temperature") == 0) { ddi_prop_update_int(dev, dip,\ "temperature", temperature); } /* other cases... */ skip: return (ddi_prop_op(dev, dip, prop_op, flags,\ name, valuep, lengthp)); }
Intro(9E), ddi_prop_op(9F), ddi_prop_update(9F) | http://docs.oracle.com/cd/E23824_01/html/821-1476/prop-op-9e.html | CC-MAIN-2015-35 | refinedweb | 418 | 51.24 |
Phil Weighill Smith <phil.weighill-smith@volantis.com> wrote ..
> Jim,
>
> What you've said sounds wrong to me; <action/> and <http/> are in the
> "default namespace" (a declared namespace that has no prefix), whatever
> that has been defined to be.
which is why I said old chestnut...and responded in the way I did to make a point.
> This could be the same as n1 if the URI for n1 is also associated with
> the default namespace, but that seems unlikely.
the only way those unprefixed elements are in some other namespace is if it is declared at
some encapsulating parent element.
for example;
<project xmlns="">
<n1:mytask>
<action/>
<http/>
</n1:mytask>
</project>
otherwise, if an xmlns declaration does not exist those elements belong to n1: namespace.
hth, Jim Fuller | https://mail-archives.eu.apache.org/mod_mbox/ant-dev/200509.mbox/%3C200509121049.j8CAnfd01842@server1.ruminate.co.uk%3E | CC-MAIN-2021-31 | refinedweb | 130 | 64.41 |
Figure 1 shows not one, but actually three user interfaces. The interface at the top is the one the user interacts with, while the two below are hidden offscreen and used only for printing (the major movie clips are labeled with their instance names in [brackets] for easy reference). This means that the two printing interfaces are only ever visible to the user in printouts.
This is possible because Flash is not limited to printing what is on-screen; in Flash, you can create movie clips offscreen and then print those offscreen clips. The movie clip to the bottom left (printArea1) is a cover sheet for the movie clip to the bottom right (printArea2), where the user's actual drawing is printed. This example complicates things further by placing a smaller sized "preview" of the drawing on the cover sheet in the center (the box labeled printPreview).
All told, you have three interfaces in to draw circles: on the main interface and on each of the two print interfaces. The question is: how to do this in the most efficient and maintainable fashion?
Start by creating a place to store information about the shapes a user has drawn. To do that, create a class called Circle with three properties: x-position (x), y-position (y), and color (c):
class Circle {
var x:Number;
var y:Number;
var c:Number;
// constructor
function Circle(x:Number, y:Number, c:Number) {
this.x = x;
this.y = y;
this.c = c;
}
function getX():Number {
return this.x;
}
// etc.
import Circle;
var circles = Array();
Please enable Javascript in your browser, before you post the comment! Now Javascript is disabled.
Your name/nickname
Your email
WebSite
Subject
(Maximum characters: 1200). You have 1200 characters left. | http://www.devx.com/webdev/Article/27318/0/page/2 | CC-MAIN-2017-04 | refinedweb | 289 | 63.7 |
Opens a file for reading, writing, or both. Also used to create a file.
Syntax
#include <prio.h> PRFileDesc* PR_Open( const char *name, PRIntn flags, PRIntn mode);
Parameters
The function has the following parameters:
name
- The pathname of the file to be opened.
flags
- The file status flags define how the file is accessed. It is a bitwise
ORof the following bit flags. In most cases, only one of the first three flags may be used. If the
flagsparameter does not include any of the first three flags (
PR_RDONLY,
PR_WRONLY, or
PR_RDWR), the open file can't be read or written, which is not useful.
NOTE: The constants PR_RDWR and friends are not in any interface (bug 433295). Thus they cannot be used in JavaScript, you have to use the octal constants (see File I/O Snippets).
mode
- When
PR_CREATE_FILEflag is set and the file is created, these flags define the access permission bits of the newly created file. This feature is currently only applicable on Unix platforms. It is ignored by any other platform but it may apply to other platforms in the future. Possible values of the
modeparameter are listed in the table below.
Returns
The function returns one of the following values:
- If the file is successfully opened, a pointer to a dynamically allocated
PRFileDescfor the newly opened file. The
PRFileDescshould be freed by calling
PR_Close.
- If the file was not opened successfully, a
NULLpointer.
Description
PR_Open creates a file descriptor (
PRFileDesc) for the file with the pathname
name and sets the file status flags of the file descriptor according to the value of
flags. If a new file is created as a result of the
PR_Open call, its file mode bits are set according to the
mode parameter. | https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSPR/Reference/PR_Open | CC-MAIN-2020-05 | refinedweb | 292 | 72.97 |
Python libraries for the Ceph librados library with use cython instead of ctypes
Python libraries for the Ceph librados library with use cython instead of ctypes
This a standalone library initially comes from this Ceph PR
But can be built against older version of Ceph from 0.80.X (firefly) to 10.1.X (perhaps more not tested)
This is designed for application that want to use a recent python-rados API without upgrading the whole ceph cluster.
Rados C handles provided by this library can’t be used with the ceph rbd.py or librbdpy.
The API of this python lib will be keep in sync with the upstream Ceph rados.py API.
Pre-requires:
$ sudo apt-get install cython librados2 librados-dev
Then, at the command line:
$ pip install cradox
Or, if you have virtualenvwrapper installed:
$ mkvirtualenv cradox $ pip install cradox
import cradox as rados
Ceph packages must be installed, the suite create a temporary Ceph cluster run the tests and destroy it.
tox
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/cradox/ | CC-MAIN-2017-26 | refinedweb | 185 | 68.91 |
accessible
Skip over Site Identifier
Skip over Generic Navigation
Skip over Search
Skip over Site Explorer
Site ExplorerSite Explorer
Joined: 7/23/2017
Last visit: 9/25/2018
Posts: 20
Rating:
(0)
Hello,
today is the day I got my IOT2040. Im am happy and testing everything. And have the first problem.
Using python 3.5 I get an error when using:
import mraa
CompilerNo module named mraa
Okay... no problem, lets go to python 2.7 It works!
Now lets use sqlite3 in python 2.7 -> error.
import sqlite3
CompilerNo module named sqlite3
I need to use both. What can I do? My favourite would be to get mraa working in python 3.5.I searched here and googled a bit - but things like opkg mraa-python3 does not find an package.Maybe I have to update the source.list -> but I am not familar with opkg and google was not my friend with this search, either.
Hope you can help me!
Thanks in advance!
Joined: 4/28/2015
Last visit: 4/18/2019
Posts: 1094
(172)
Hi,
are you using the exmaple image V2.1.3?
I attached two python scripts, one with mraa and one with sqlite3. These two scripts are working calling them with
python USER_LED_Colors.pyand python3 USER_LED_Colors.py
python USER_LED_Colors.py
and
python3 USER_LED_Colors.py
Can you try these two scripts?
Best regards!
python_scripts.zip (71 Downloads)
1 thankful Users
I did... SQLITE error in python 2.X.
In python 3.X both scripts work. But only because i had the right script for the user LED in my folder (not in your download) and becaus it is run in python2 not in python3.
I load the image a second time and run it from scratch - will deliver the result.
Okay. New Download - same problem.
Any ideas? I will try another SD-Card... but I dont think think it will help.
Update...
The problem is still there, but I have a solution which is ok for me.
I have a programm which reads the IO-Pins via mraa and when something is deteced I call another python program with popen and give the value to store in the database as an argument.
Hope this workaround can help someone if he encouners the same problem.
Joined: 8/18/2015
Last visit: 3/22/2019
Posts: 7
(2)
Update: This problem still exist.
I can't use this workaround. I must use Python3.
Can somebody help?
which image version are you using and what exactly is your problem? Something with mraa?
I have downloaded the newest image: example-v2.2.0.wic
Problem: mraa is not useable with python 3: Error: mraa not found (or similar)
Joined: 7/9/2017
Last visit: 12/20/2018
Posts: 13
No module named mraa
@Matze001 were you able to find any other solution? I would ideally not want to go forward with popen.
Joined: 12/12/2016
Posts: 210
(17)
mraa is not functional in python3 with the example image V2.2.0. This issue is now fixed, so building a fresh image against master branch would solve your problem. Check out this issue on github for more information.
I wouldn't recommend using python2, but there is still the possibilty of installing pip2 if you don't want to build an image.
Kind regards! | https://support.industry.siemens.com/tf/ww/en/posts/python-3-5-mraa/175536?page=0&pageSize=10 | CC-MAIN-2019-18 | refinedweb | 556 | 86.1 |
MEAM.Design - MaEvArM - Graphical Data Logging
Goal
The goal of the graphical data logging section is to provide an easy way to visualize data on the M1. It is possible to see data using the USB communications framework, but viewing in the terminal does not always give a very intuitive idea of what is happening.
In this guide, we will set up a method for viewing ADC values on a graph. You can throw any data at the graph, such as filtered ADC values.
Configure M1
The first step is to get your M1 to spit out Hex values over the USB port to your computer. Follow the USB guide, but use the following code instead:
#include "maevarm-usb.h"
int main(void)
{
unsigned int value = 512;
usb_init();
while(!usb_configured()); // wait for a connection
while(1)
{
usb_tx_hex(value);
usb_tx_string("\n");
}
}
Now, your M1 will be spitting out an endless stream of 0x8000's to your computer. Check that it is working by running one of the various terminal options described in the USB section.
Configure Python
Mac
You need to install matplotlib from: Get this file if on Snow Leopard: matplotlib-0.99.3-Apple-py2.6-macosx10.6.dmg
You also need to install PySerial from - get the source version. Unzip it, and open a Terminal. Change directories into the unzipped folder, and run "python setup.py" - this will install the pyserial library.
Windows
You're going to want to download the Portable Python distribution:. Make sure to download the 2.5.4 distribution. Now, grab pyserial from:. Don't get the Windows installer - get the tar.gz source file. Unzip that with 7-zip - you may have to then unzip the resulting tar file, too.
In the resulting pyserial-2.5 folder, copy the serial folder. Paste it into the "\App\Lib" directory of the Portable Python distribution.
Linux
If you are running Linux, BSD, or your own operating system that you wrote in your free time, chances are that you know how to get Python running as described.
Running the Script
Updated some Python code
link: PyLogger (right-click, select download as log_m1.py)
If having trouble, try this Logger, which eliminates a redundant new line check - thanks Miki. link: PyLogger2 (right-click, select download as log_m1.py)
link: PyViewer (right-click, select download as view_m1.py)
When in Windows, the Logger file should be modified to read from COM7 instead of /dev/cu.usbmodem411
Place these files anywhere if on Mac, or in the "~\App" directory of your Windows Portable Python install.
If on Windows, change into the Directory of your Portable Python installation. Go to the "\App" directory. Run "python.exe log_m1.py" - you should see a graph pop up with a straight line on it.
If on Mac OS X, open a Terminal and go to the directory where you downloaded the Python script. Run "python log_m1.py" - you should see a graph pop up with a straight line on it. For mac:
Running the Logger Wirelessly
If you want to log data wirelessly, | https://alliance.seas.upenn.edu/~medesign/wiki/index.php/Guides/MaEvArM-log | CC-MAIN-2017-13 | refinedweb | 510 | 67.04 |
So far we have seen how lines and formulas can estimate outputs given an input. We can describe any straight line with two different variables:
So far we have been rather fast and loose with choosing a line to estimate our output - we simply drew a line between the first and last points of our data set. Well today, we go further. Here, we take our first step toward training our model to match our data.
The first step in training is to calculate our regression line's accuracy -- that is, how well our regression line matches our actual data. Calculating a regression line's accuracy is the topic of this lesson.
In future lessons, we will improve upon our regression line's accuracy, so that it better predicts an output.
The first step towards calculating a regression line to predict an output is to calculate how well any regression line matches our data. We need to calculate how accurate our regression line is.
Let's find out what this means. Below we have data that represents the budget and revenue of four shows, with
x being the budget and
y being the revenue.
first_show = {'x': 0, 'y': 100} second_show = {'x': 100, 'y': 150} third_show = {'x': 200, 'y': 600} fourth_show = {'x': 400, 'y': 700} shows = [first_show, second_show, third_show, fourth_show] shows
Run code above with shift + enter
As we did in the last lab, let's draw a not-so-great regression line simply by drawing a line between our first and last points. We can use our
build_regression_line function to do so. You can view the code directly here.
Eventually, we'll improve this regression line. But first we need to see how good or bad a regression line is.
from linear_equations import build_regression_line x_values = list(map(lambda show: show['x'],shows)) y_values = list(map(lambda show: show['y'],shows)) regression_line = build_regression_line(x_values, y_values) regression_line
We can plot our regression line as the following using the plotting functions that we wrote previously:
from graph import m_b_trace, plot, trace_values from plotly.offline import iplot, init_notebook_mode init_notebook_mode(connected=True) data_trace = trace_values(x_values, y_values) regression_trace = m_b_trace(regression_line['m'], regression_line['b'], x_values) plot([regression_trace, data_trace])
So that is what our regression line looks like. And this the line translated into a function.
def sample_regression_formula(x): return 1.5(x) + 100
Ok, so now that we see what our regression line looks like, let's highlight how well our regression line matches our data.
Let's interpret the chart above. That first red line shows that our regression formula does not perfectly predict that first show.
- Our actual data -- the first blue dot -- shows that when $x = 100$, $y = 150$.
- However, our regression line predicts that at $x = 100$, $y = 250$.
So our regression line is off by 100, indicated by the length of the red line.
Each point where our regression line's estimated differs from the actual data is called an error. And our red lines display the size of this error. The length of the red line equals the size of the error.
Now let's put this formula into practice. The error is the actual value minus the expected value. So at point $x = 100$, the actual $y$ is 150. And at point x = 100, the expected value of $y$ is $250$. So:
If we did not have a graph to display this, we could calculate this error by using our formula for the regression line.
actual-
expected$ = 150 -250 = -100$.
Now that we have explained how to calculate an error given a regression line and data, let's learn some mathematical notation that let's us better express these concepts.
So far we have defined our regression function as $y = mx + b$. Where for a given value of $x$, we can calculate the value of $y$. However, this is not totally accurate - as our regression line is not calculating the actual value of $y$ but the expected value of $y$. So let's indicate this, by changing our regression line formula to look like the following:
Those little dashes over the $y$, $m$ and $b$ are called hats. So our function reads as y-hat equals m-hat multiplied by $x$ plus b-hat. These hats indicate that this formula does not give us the actual value of $y$, but simply our estimated value of $y$. The hats also say that this estimated value of $y$ is based on our estimated values of $m$ and $b$.
Note that $x$ is not a predicted value. This is because we are providing a value of $x$, not predicting it. For example, we are providing an show's budget as an input, not predicting it. So we are providing a value of $x$ and asking it to predict a value of $y$.
Now remember that we were given some real data as well. This means that we do have actual points for $x$ and $y$, which look like the following.
first_show = {'x': 0, 'y': 100} second_show = {'x': 100, 'y': 150} third_show = {'x': 200, 'y': 600} fourth_show = {'x': 400, 'y': 700} shows = [first_show, second_show, third_show, fourth_show] shows
So how do we represent our actual values of $y$? Here's how: $y$. No extra ink is needed.
Ok, so now we know the following:
Finally, we use the Greek letter $\varepsilon$, epsilon, to indicate error. So we say that
We can be a little more precise by saying we are talking about error at any specific point, where $y$ and $\hat{y}$ are at that $x$ value. This is written as:
$\varepsilon {i}$ = $y{i}$ - $\hat{y}_{i}$
Those little $i$s represent an index value, as in our first, second or third movie. Now, applying this to a specific point of say when $ x = 100 $, we can say:
We now know how to calculate the error at a given value of $x$, $x_i$, by using the formula, $\varepsilon_i$ = $y_i - \hat{y_i}$. Again, this is helpful at describing how well our regression line predicts the value of $y$ at a specific point.
However, we want to see well our regression describes our dataset in general - not just at a single given point. Let's move beyond calculating the error at a given point to describing the total error of the regression line across all of our data.
As an initial approach, we simply calculate the total error by summing the errors, $y - \hat{y}$, for every point in our dataset.
Total Error = $\sum_{i=1}^{n} y_i - \hat{y_i}$
This isn't bad, but we'll need to modify this approach slightly. To understand why, let's take another look at our data.
The errors at $x = 100$ and $x = 200$ begin to cancel each other out.
We don't want the errors to cancel each other out! To resolve this issue, we square the errors to ensure that we are always summing positive numbers.
${\varepsilon_i^2}$ = $({y_i - \hat{y_i}})^2$
So given a list of points with coordinates (x, y), we can calculate the squared error of each of the points, and sum them up. This is called our ** residual sum of squares ** (RSS). Using our sigma notation, our formula RSS looks like:
$ RSS = \sum_{i = 1}^n ({y_i - \hat{y_i}})^2 = \sum_{i = 1}^n \varepsilon_i^2 $
Residual Sum of Squares is just what it sounds like. A residual is simply the error -- the difference between the actual data and what our model expects. We square each residual and add them together to get RSS.
Let's calculate the RSS for our regression line and associated data. In our example, we have actual $x$ and $y$ values at the following points:
And we can calculate the values of $\hat{y} $ as $\hat{y} = 1.5 *x + 100 $, for each of those four points. So this gives us:
$RSS = (100 - 100)^2 + (150 - 250)^2 + (600 - 400)^2 + (700 - 700)^2$
which reduces to
$RSS = 0^2 + (-100)^2 + 200^2 + 0^2 = 50,000$
Now we have one number, the RSS, that represents how well our regression line fits the data. We got there by calculating the errors at each of our provided points, and then squaring the errors so that our errors are always positive.
Root Mean Squared Error (RMSE), is just a variation on RSS. Essentially, it tries to answer the question of what is the "typical" error of our model versus each data point. To do this, it scales down the size of that large RSS number by taking the square root of the RSS divided by the number of data points:
$ RSS = \sum_{i = 1}^n ({y_i - \hat{y_i}})^2$
$RMSE = \sqrt{\frac{RSS}{n}} $
Where n equals the number of elements in the data set.
Now let's walk through the reasoning for each step.
The first thing that makes our RSS large is the fact that we square each error. Remember that we squared each error, because we didn't want positive errors and negative errors to cancel out. Remember, we said that each place where we had a negative error, as in :
$actual - expected = -100$
We would square the error, such that $(-100)^2 = 10,000$.
Remember that we square each of our errors and add them together, which led to:
We then take the mean to get the average squared error (also called "mean squared error" or "MSE" for short:
We do this because with each additional data point in our data set, our error will tend to increase. So with increasing dataset size, RSS also increases. To counteract the effect of RSS increasing with the dataset size and not just accuracy, we divide by the size of the dataset.
The last step in calculating the RMSE, is to take the square root of the MSE:
$RMSE = \sqrt{12,500} = 111.8$
In general, the RMSE is calculated as:
$ RMSE = \sqrt{\frac{\sum_{i = 1}^n ({y_i - \hat{y_i}})^2}{n}} $
So the RMSE gives a typical estimate of how far each measurement is from the expectation. So this is "typical error" as opposed to an overall error.
Before this lesson, we simply assumed that our regression line made good predictions of $y$ for given values of $x$. In this lesson, we learned a metric that tells us how well our regression line fits our actual data. To do this, we started looking at the error at a given point, and defined error as the actual value of $y$ minus the expected value of $y$ from our regression line. Then we were able to determine how well our regression line describes the entire dataset by squaring the errors at each point (to eliminate negative errors), and adding these squared errors. This is called the Residual Sum of Squares (RSS). This is our metric for describing how well our regression line fits our data. Lastly, we learned how the RMSE tells us the "typical error" by dividing the square root of the RSS by the number of elements in our dataset. | https://learn.co/lessons/evaluating-regression-lines | CC-MAIN-2019-43 | refinedweb | 1,836 | 69.82 |
0
The following is a recursive function designed to return the factorial of a number.
def factorial(number, target): if number == 1: return target else: target = target*number factorial((number-1), target) print factorial(7, 1)
As you'll see if you run it however it doesn't return my 'target' variable (the factorial of 'number') but instead returns 'None'. I can get it to produce the factorial by changing line 3 from 'return target' to 'print target', but this is an imperfect solution because it doesn't allow me to use the output of this function in subsequent code. So, how do I get the function to 'return' the target?
While I'm at it, I'd also appreciate some help on this next bit of code which is designed to count down from 12 to 3.
def reduce(n): while n != 3: print n reduce((n-1)) reduce(12)
When I run it, it gets down to the number 4 and then ends up in an infinite loop, endlessly repeating '4'. Can anyone explain why?
Thanks,
Paul. | https://www.daniweb.com/programming/software-development/threads/320470/recursive-function-questions | CC-MAIN-2018-43 | refinedweb | 179 | 59.03 |
Content
All Articles
Python News
Numerically Python
Python & XML
Community
Database
Distributed
Education
Getting Started
Graphics
Internet
OS
Programming
Scientific
Tools
Tutorials
User Interfaces
ONLamp Subjects
Linux
Apache
MySQL
Perl
PHP
Python
BSD.
# end
some html
else
user in administrators:
mod_python.psp
<Directory /some/path>
AddHandler mod_python .psp
PythonHandler mod_python.psp
PythonDebug On
</Directory>
Here is the PSP code. It must be in a file ending with .psp,
at least, according to the above configuration:
.psp
!".
?name=john.
compile()..
req
psp, an instance of PSPInstance, which provides
access to a small PSP-specific API. This object has the following methods:
psp
PSPInstance
set_error_page(filename)
This allows you to specify a PSP page to be invoked when a Python error
occurs. This is useful for customizing error output, similar to the
errorPage directive in JSP.
errorPage
apply_data(object)
This method will call the callable object object, passing form
data as arguments and return the result. If you are familiar with JSP, this
works much like setProperty. If, for example you have an object
defined as follows:
object
setProperty
class Car:
def __init__(self, color):
self.color = color
# etc.
Then a PSP page called as result of a form submission (the form contains a
field named color) can do this:
color
<%
car = psp.apply_data(Car)
%>
This will call the callable object Car (classes are callable),
passing it the value of form field named color, resulting in an
instance of Car which is assigned to car.
Car
redirect(location)
This can be used for redirection from within PSP pages. It's important to
call this function absolutely first in the PSP page, because redirection cannot
happen after there is any output sent to the browser..
form
FieldStorage.
session
mod_python.Session.
filename.
PythonDebug
On
If the original link were, then will show the PSP-generated Python
source code. For this to work, you must register the .psp_ extension (with the underscore) with AddHandler:
.psp_
AddHandler
AddHandler mod_python .psp .psp_.
Publisher.
hello()).
psp.PSP.
run()
vars
greet
A nice feature of the PSP templates is that one template can contain
references to another in an expression. Let's expand the above example. The
Apache configuration stays the same, but we'll add another template file called
time.tmpl:
time.tmpl
<h2>
And the time is <%= now %>
</h2>
We'll modify the hello.tmpl template:
hello.tmpl
.
time_tmpl
no.
Sponsored by:
© 2017, O’Reilly Media, Inc.
(707) 827-7019
(800) 889-8969
All trademarks and registered trademarks appearing on oreilly.com are the property of their respective owners. | http://www.onjava.com/pub/a/python/2004/02/26/python_server_pages.html | CC-MAIN-2017-47 | refinedweb | 422 | 58.08 |
i have a 2d array that's array[10][10] and a double number. I want to put that number into the 1st line of the array how will i do that?
array[0]=number; does not work, is there a simple way of converting it?
for instance
double number;
double list[10][10]
number=5.35
i want to make
list[0] = 5.35 basically filling the first line. Please help, thanks
Heres the code that i tried
#include <stdio.h> int main () { char word[10][10]; double num; double number[10][10]; FILE*myin; myin=fopen("first.dat","r"); fscanf(myin,"%s",&word[0]); fscanf(myin,"%lf",&num); printf("%s\n%lf",word[0],num); number[0]=num; fclose(myin); return(0); } | https://www.daniweb.com/programming/software-development/threads/383250/store-a-number-into-a-2d-array | CC-MAIN-2022-21 | refinedweb | 124 | 70.19 |
Method Overloading Example In Java
Method Overloading Example In Java
In this section we will read about overloading in Java.
Method overloading in Java is achieved due to the Java supports... with the same name.
The concept of method overloading allows the Java programmer
Overloading considered Harmful - Java Tutorials
Overloading considered Harmful
2003-06-01 The Java Specialists' Newsletter... (Sascha) Hoeher sent me a piece he had
written in German on method overloading...
concepts! Then your Java introduction goes on telling you
about unique
JavaScript Array
described that how this JavaScript array's push() method can be used
into our... you in
understanding 'JavaScript array method'. For this we are using...
In this section, you will study how to access the array in JavaScript. You
Constructor overloading in java
Constructor overloading in java
In this section we will discuss about constructor overloading in java.
Constructor overloading is not much different from method overloading, in
method overloading you have multiple method with same
Overloading
Overloading program in method overloading it compile successfully and gives error in run time?
Hi Friend,
Post your code.
For more information, you can visit the following link:
Method Overloading Example
Thanks
Polymorphism : Method Overloading
In this tutorial you will learn one of polymorphism concept that is method overloading with example in Java 7
What is use of method overloading and overriding?
but by overloading, you can add values of all data types.
Java Method Overloading
Java...What is use of method overloading and overriding? Method overriding...() method of Object class, we can use it with different classes.
Overloading
Method overloading in java program
Method overloading in java program How can we use method overloading in java program?
Method overloading:?In method overloading methods have same name but different type of parameters.
Here is an example of method
Java file last modified date
Java file last modified date
In this section, you will learn how to get... it. You can use the lastModified() method to get the
file?s last modified timestamps. This method will return the time in
milliseconds as long value, you may
array in javascript - Java Beginners
array in javascript how to initialize array in javascript and can we increase the size of array later on?
is Array class in javascript ?
also...://
Hope
Java Constructor Overloading Example
Java Constructor Overloading Example
In this section we will read about the constructor overloading in Java. We
will see how the constructor overloading... will compile and execute the above Java class you will get the
output as follows
Last modified time of a webpage
Last modified time of a webpage how can we get the last modified time of a webpage using java
Overloading
Overloading Overloading in JAVA
How to Print Array in JavaScript
How to Print Array in JavaScript
In this section you will learn about Array in JavaScript. Array are important part of all programming languages. Array in JavaScript is
a variable that can hold more than one value. Array is a collection
Method Overloading
Method Overloading In java can method be overloaded in different class
Explain how you overcame a major obstacle
Explain how you overcame a major obstacle
Qus. Explain how you overcame a major... or just doing a job to get paid. Explain why you like it. Besides your personal
Java Get Method
Java Get Method
In this example you will learn how to use the get method in Java.
Java... to use get method in Java.
The example is going to show the date details
method overloading - Java Beginners
is referred to as Method Overloading. In the given example, we have defined...method overloading Write a program to demonstrate the method overloading for sum ( ) function. class overloadingDemo
{
public void
JavaScript array push() method
JavaScript array push() method
In this example code of JavaScript array push() method
we have described that how this JavaScript array's push() method can be used
Java file modified date
Java file modified date
In this section, you will learn how to find... the specified file exists. It it exists then we have used
lastModified() method...()- This method File class checks whether the file or directory
denoted by the pathname
JavaScript Array Contains Method
to show how an array
contains method(). As you already know we required the property...
JavaScript Array Contains Method
... it..
JavaScript code to use contain method in an array
<html>
<head>
Constructor Overloading in Java
In this section we have discussed about Constructor Overloading in Java....
Following example of Constructor Overloading will help you understand
the concept...;Roseindia",
10);
}
}
Resource:
Constructor Overloading in Java
Java Get Example
is method and how to use the get
method in Java, this example is going...;
Java Get Clipboard
In this section, you will study how to use... that how
one can calculate or get the execution time of a method or program in java
Java get byte array from file
Java get byte array from file what is the code example in Java for getting byte array from file in memory.
Thanks
This is very simple code in Java. Following tutorials will teach you how to achieve this.
Java
array example - Java Beginners
array example hi!!!!! can you help me with this question... get and set methods for an array property - it exposes too much of the inner... if numDependents is less than the length of the array
8. Add the method listed below
Preferences API - What do you Prefer? - Java Tutorials
Preferences API - What do you Prefer?
2001-09-17 The Java Specialists...;keyStr", 123l), etc. And you can
retrieve these values via the get("... /*defaultVal*/), etc. methods. Note that for every get method, a default
value must
Array
Array is it possible to define array like this..?
int[] intArray = new int[] {4,5,6,7,8}; Explain...?
Yes, you can.
Java Initialize Array
Constructor Overloading in Java
Constructor Overloading in Java
Here, you will learn more about Constructor and
how constructors are overloaded in Java. This section provides you a brief
introduction
Calling java class method from javascript
Calling java class method from javascript I want to call a java class method from javascript. The java class method is like "public String[] getWord()". I want to assign this string array value to a variable in javascript. I
Overloading in java
The overloading in seen with the constructor and the methods of the class
The following link have all the details
Constructor overloading in Java
Method overloading in Java
String Array - Java Beginners
, as to by which method can I separate the Integers from this Array of String... this question to you before, now the problem comes if my String Array consisted...,, what you told me in that..
Hoping you could resolve my this problem also
Java Method Overloading - Java Beginners
Java Method Overloading can method be overloaded in subclass or not? Hi Friend,
Yes A subclass can overload the methods.For Example...:
Thanks
JavaScript array join
to understand
JavaScript array join. For this we are using Java Script language...
JavaScript array join
....
!)array.join ( ) - This method return you an array1 object
that hold all
JavaScript Array get key
JavaScript Array get key
... in
understanding JavaScript Array get key. For this we implement JavaScript... for loop to iterate this
array..
JavaScript_Array_get_key.html
method - Java Beginners
in the Permissions class if you explain the underline sentence and give.... Suppose, for instance, that you want to write a method to return what... (deposit, withdraw, and so on), so you must return permission. You could create
What is JavaScript?
is Java script and other java related queries. How to define what is JavaScript... is JavaScript" and How it will help the developer in Java Program?
Let me.... By using the JavaScript you will get benefits like associative arrays, loosely typed
Java Script location.replace method
didnt understand the meaning of this?
Could you pls explain? awaiting for ur...Java Script location.replace method Hi,
What does `Print `{<SCRIPT LANGUAGE="JavaScript"> location.replace("} & urlpop & {","BOTTOM
Using get method in preferences
Using get method in preferences
In
this section you will learn how to use the get() method... of
the get() method. The above output shows that how a get() method takes the value
JavaScript Array Clear
JavaScript Array Clear
Clear() method is used to clear all the defined array. In this section, you will study how to clear the Array in JavaScript. You can
see
Use of array() method of FloatBuffer class in java.
Use of array() method of FloatBuffer class in java.
In this tutorial, we will see how to create a float array of float buffer.
FloatBuffer API...[]
array()
The array() method returns float array based on float
Method Overloading
Method Overloading
As we know that a method have its own signature which
is known by method's name and the parameter types. Java has a powerful feature
which is known as method
JavaScript Array get key
JavaScript Array get key
... in
understanding JavaScript Array get key. For this we implement JavaScript... for loop to iterate this
array..
JavaScript_Array_get
Java get available Font
Java get available Font
In this section, you will learn how to get the available... the available
GraphicsDevices and Font objects.
getAllFonts()- This is the method
JavaScript array object reference
that helps you in
understanding JavaScript array object reference. For this we are using... reverse method
returns you the reverse order of the element in the array. and store...
JavaScript array object reference
Java Merge Array
Java Merge Array
You all are aware of Arrays, their structure, declaration... into a single array. In this section, we are going to explain you this concept... to the method merge(int []...arr) indicates that you can merge number of arrays
Alphanumeric Validation in JavaScript
be a wrong input because name could not in digit that you
know.
Example...Alphanumeric Validation in JavaScript
In this tutorials we will discuss about alphanumeric validation in
JavaScript. Sometimes it may occur when user have
Explain about threads:how to start program in threads?
Explain about threads:how to start program in threads? import... to do multiple activities simultaneously in a process. For example:- If you want to type something and show date and time simultaneously you can use threads
String Array - Java Beginners
, as to by which method can I separate the Integers from this Array of String... important as I know the answer to the latter part ...........
Hoping you could...String Array From where can I get, all the functions that are needed
JavaScript Array Trim
JavaScript Array Trim
In the trim() method example, you will learn how to use the trim method
in JavaScript. The JavaScript method trim() removes all empty elements
JavaScript split string into array
JavaScript split string into array How to split the string...;
Description: The split() method is used to split a string into an array...(); here you declare new array of name stringArray.
stringArray
JavaScript array functions sort
JavaScript array functions sort
We try to explain you a example that makes easy to understand the concept of
JavaScript array function sort. The code create method overloading
Java method overloading
Example below demonstrates method overloading in
java. In java method overloading means creating more than a single method
with same name
Method Overloading in java
Method Overloading in java
... parameters to get the desired output.
-- Method Overloading, allows
the user to achieve...:
1. Method Overloading
2. Method Overriding
Here we will discuss only
JavaScript array merge
JavaScript array merge
In this Tutorial we want to describe you a code that help you in
understanding how to merge two different array into one array using Java Script.
We
JavaScript array remove an element
()
method. Here is the example code:
javascript_array_remove_element.html
<...
JavaScript array remove an element
As in the previous section of JavaScript array
tutorials
JavaScript Array Append
JavaScript Array Append
In this section, you will study how to append value to the array in
javascript.
To append values to an array using JavaScript, we have create
JavaScript Array
JavaScript Array:
Almost every language supports array, which is a collection of similar data type, but in JavaScript scripting language it could be or could not be of same. An array could be a collection of similar or dissimilar datatype
JavaScript Array of checkboxes
JavaScript Array of checkboxes
In this Tutorial we want to describe you a code that help you in
understanding JavaScript Array of checkboxes. For this we
How to Get Started with Java?
with. There is a multitude of options including JDK, NetBeans, etc.
How You Get to Work with Java...A Java Beginners Tutorial - How to Get Started with Java?
For a programmer... using any piece of software. Here we go as to show you how to get started
Get Length of Array
; -This method get you the calendar current time.
5)monthname.length ( )-This method return...
Get Length of Array
... of Array
in Java Script. In this code we import a package java.util and java
Real time examples - Java Beginners
/javascript-array/modified-java-method-overriding.shtml time examples what is method overloading,method overriding,constructor overloading concept in java and explain with real time examples?
JavaScript array method
JavaScript array method
...
in understanding JavaScript Method For this method we have JavaScript as script... element by calling array. length( ) method.
JavaScript Array Associative
JavaScript Array Associative
In this section, you will study how to use Associative Array in Javascript.
An associative array is like a regular array, but we insert
JavaScript array sort alphabetically
the
sort() method of Array class in JavaScript. Syntax of the sort method... an array of five
elements which all are strings. Here you can see that how the sort...
JavaScript array sort alphabetically
how can you say java is secure
how can you say java is secure we are using notepad editor for Java programming which is an Microsoft product, then how can you say Java is secure when you are using Microsoft product as an editor
how to get HTTP GET request value using javascript
how to get HTTP GET request value using javascript how to get HTTP GET request value using javascript
how is how you can get HTTP GET request value using javascript:
var parameter = window.location.search.replace
JavaScript Add Element to Array
through the example you will learn about how to add element
to an array using...
JavaScript Add Element to Array
In the given JavaScript example, we have created an array
PHP Get Array Length
PHP Get Array Length
To count the array length we use count method... is:
int count ($var [,int $mode=COUNT_NORMAL]);
Where
$var is an array...() will recursively count the array. This option is beneficial
Java Array Usage
Java Array Usage
We have already discussed that to refer an element within an
array, we use... the element at that
index. We also know that the array indices start with zero, so
JavaScript Array Clear
JavaScript Array Clear
In this tutorial you will learn how to use the clear... the defined array. In this section, you
will study how to clear the Array in JavaScript. You can see in the given
example, we have create an instance of array which
JavaScript Copy Array
useful in
complex applications. In this section, you will study how to copy an array. You can see in the
given example, we have created an array object 'arr1...
JavaScript Copy Array
How to get the capacity of ByteBuffer in java.
How to get the capacity of ByteBuffer in java.
..., we will discuss how to get the capacity of buffer. The ByteBuffer class...; In this example, we will
compute the
capacity of buffer. The capacity() method returns
method overloading in c program
method overloading in c program how is method overloading in C program is different from C++ program
JavaScript array for loop
JavaScript array for loop
In this Tutorial we want to understand you how an array...; This method return you default
time zone and current locale.
We declare
overloading - Java Server Faces Questions
overloading define overloading
Hi Friend,
Overloading is the ability to define more than one method with the same name in a class.
Example:
class Overloading {
void test() {
System.out.println("Hello
you get a password field in struts
you get a password field in struts How do you get a password field in struts
FTPClient : Get System Type
This section explain how to get system type by using method of FTPClient class in java
How will you load a specific locale? - Java Beginners
How will you load a specific locale? HI,
Please tell me how to load a specific locale in Java program.
Thanks
Hi Friend,
You can use ResourceBundle.getBundle("Locale.UK");
For more information, visit
Java get Folder Size
Java get Folder Size
In this section, you will learn how to get the size....
folder.listFiles()- This method returns an array of files presented
JavaScript Array Count
JavaScript Array Count
In the given JavaScript example we are going to show you, how to count the
length of array. For that we have to use the count() method in our code
String Array In Java
String Array In Java
In this section, you will learn how to use string array
in Java. Here, you will see how to declare a string array and the syntax for
using in the program
How will you add panel to a frame? - Java Interview Questions
How will you add panel to a frame? How will you add panel to a frame? you can simply use add method to add panel to a frame
i.e panelA.add(frameA) Hi Friend,
Using add() method of JFrame.
import
Overloading constructor in flex
Overloading constructor in flex Hi......
What is overloading a constructor? How do you overload constructors in flex?
please tell me about it...........
Thanks
Hi.....
Action script does not support overloading
calculate volume of cube, cylinder and rectangular box using method overloading in java
method overloading in java
calculate volume of cube, cylinder and rectangular box using method overloading in java...calculate volume of cube, cylinder and rectangular box using method overloading
What is the first argument of the String array in main() method?
What is the first argument of the String array in main() method? Hi,
What is the first argument of the String array in main() method?
Thanks... learn how to declare a string array and the syntax for using in the program
Java file get name
Java file get name
In this section, you will learn how to get the name of the file.
Description of code:
You can see in the given example, we have created... name is: " + st);
}
}
Through the method getName() of File class, you can
Java Reverse integer array
Java Reverse integer array
In this tutorial, you will learn how to reverse integer array. Here, we have
created a method to reverse an array which has been passed as a parameter and
returns a new array with all the elements in reverse
JavaScript array union
JavaScript array union
In this Tutorial we want to show you an example from array....
arr1.concat(arr2) - This method return you the combine element
Java file get size
Java file get size
In this section, you will learn how to get the size of a file.
Description of code:
You can see in the given example, we have created... is: " + filesizeInKB + " KB");
}
}
Through the method length(), you can get
java array
java array write a java method that takes an array of float values...)){
System.out.println("There are duplicate elements.");
Float array...++){
array[i]=new Float(arr[i]);
}
Set<Float>
Please write code for this program in java and Explain it ? pl'sssssssss
Please write code for this program in java and Explain it ? pl'sssssssss Question: We are given an array of 2n integers wherein each pair in this array of integers represents the year of birth and the year of death
How To Remove Array Element In Java
How To Remove Array Element In Java
In this section we will discuss about how... will demonstrate you about how to
delete an element from array. To remove the array... but you will have to care
about the size of the array because the array can
Java get User Home
Java get User Home
In this section, you will study how to get the user home. We...
In this section we want to describe a code that helps you to get the home
directory | http://www.roseindia.net/tutorialhelp/comment/82840 | CC-MAIN-2014-10 | refinedweb | 3,405 | 64.2 |
While hacking some code generator app in c# I ran into some issues. Being a compiled language, extending some parts of the generator would require recompiling the app, so if I want to use it in my project that mean I’d have to drag the source code all around… I don’t like the idea. I strongly think that all dev tools should be quickly extendable. I think that’s the main reason more and more devs are turning on to python, ruby and other scripting language.
The problems is, I’m using c#, and I don’t want to mix languages like that for the simple purpose of using a code generator… That’s when something popped up in my head. I remember something, somewhere deep in the .NET System.CodeDom namespace that could dynamically compile c# code and run it in the actual assembly. Yeah! If I can do that I can run c# code as script!!!
Too bad Oleg Shilo thought about it before I did, here’s the result.
I think this is opening a new world of possibility to the .net framework and .net dev tools. Imagine creating build script in c#, the only thing missing maybe is a couple of helper classes and methods…
Speaking of my code generator. You may ask why? Why another code generator, please! No! Not again! Let me explain…
All generator tools are based on the template to file pattern, or are optimized for this. Open a template, then parse it to a file, then use this file. I want to push this a step further, and I wont hide the fact that I’m porting some ruby’s generator concepts. So the patterns should be, send the generator some arguments and the the files are generated and parsed directly in your app directory structured. Simple, clean and mostly FAST. But not very portable since you app directory structure is not mine… That why all the generator logic is one class that inherits Generator and overrides a run methods. In the methods you do what you have to do:
[Generator("test")] public class TestGenerator : Generator { public override void Run(string[] args) { AddParameter("test", args[0]); CreateDirectory("Temp"); ProcessTemplate("Test.vm", @"Temp\SomeTest.txt"); } }
For now I’m using NVelocity template engine. I think this could get any more simple. You can pass parameters to the template and then create the structure and parse your templates or any other dependencies to the folder you want.
The generator is launch with this :
generate test Hello.
And what if I could create a dynamic scripting language with the System.CodeDom stuff! humm.. | https://macournoyer.wordpress.com/2006/01/22/sharp-and-dynamic/ | CC-MAIN-2018-09 | refinedweb | 441 | 64.1 |
Nomad’s Container Storage Interface (CSI) integration can manage external storage volumes for stateful workloads running inside your cluster. CSI providers are third-party plugins that run as Nomad jobs and can mount volumes created by your cloud provider. Nomad is aware of CSI-managed volumes during the scheduling process, enabling it to schedule your workloads based on the availability of volumes on a specific client.
Each storage provider builds its own CSI plugin, and you can leverage all of them in Nomad. You can launch jobs that claim storage volumes from AWS Elastic Block Storage (EBS) or Elastic File System (EFS) volumes, GCP persistent disks, Digital Ocean droplet storage volumes, or vendor-agnostic third-party providers like Portworx. This also means that the same plugins written by storage providers to support Kubernetes support Nomad as well. You can find a list of plugins in the Kubernetes CSI Developer Documentation.
Unlike Nomad’s
host_volume feature, CSI-managed volumes can be added
and removed from a Nomad cluster without changing the Nomad client
configuration.
Using Nomad’s CSI integration consists of three core workflows: running CSI plugins, registering volumes for those plugins, and running jobs that claim those volumes. In this guide, you'll run the AWS Elastic Block Storage (EBS) plugin, register an EBS volume for that plugin, and deploy a MySQL workload that claims that volume for persistent storage.
»Prerequisites
To perform the tasks described in this guide, you need:
a Nomad environment on AWS with Consul installed. You can use this Terraform environment to provision a sandbox environment. This tutorial will assume a cluster with one server node and two client nodes.
Nomad v0.11.0 or greater
Note: This tutorial is for demo purposes and only assumes a single server node.
»Deploy an AWS EBS volume
Next, create an AWS EBS volume for the CSI plugin to mount where needed for your jobs using the same Terraform stack you used to create the Nomad cluster.
Add the following new resources to your Terraform stack.
resource "aws_iam_role_policy" "mount_ebs_volumes" { name = "mount-ebs-volumes" role = aws_iam_role.instance_role.id policy = data.aws_iam_policy_document.mount_ebs_volumes.json } data "aws_iam_policy_document" "mount_ebs_volumes" { statement { effect = "Allow" actions = [ "ec2:DescribeInstances", "ec2:DescribeTags", "ec2:DescribeVolumes", "ec2:AttachVolume", "ec2:DetachVolume", ] resources = ["*"] } } resource "aws_ebs_volume" "mysql" { availability_zone = aws_instance.client[0].availability_zone size = 40 } output "ebs_volume" { value = <<EOM # volume registration type = "csi" id = "mysql" name = "mysql" external_id = "${aws_ebs_volume.mysql.id}" access_mode = "single-node-writer" attachment_mode = "file-system" plugin_id = "aws-ebs0" EOM }
Run
terraform plan and
terraform apply to create the new IAM
policy and EBS volume. Then run
terraform output ebs_volume > volume.hcl. You'll use this file later to register the volume with
Nomad.
»Notes about the above Terraform configuration
The IAM policy document and role policy are being added to the existing instance role for your EC2 instances. This policy will give the EC2 instances the ability to mount the volume you've created in Terraform, but will not give them the ability to create new volumes.
The EBS volume resource is the data volume you will attach via CSI later. The output will be used to register the volume with Nomad.
»Enable privileged Docker jobs
CSI Node plugins must run as privileged Docker jobs because they use bidirectional mount propagation in order to mount disks to the underlying host.
CSI Plugins running as
node or
monolith type require root privileges (or
CAP_SYS_ADMIN on Linux) to mount volumes on the host. With the Docker task
driver, you can use the
privileged = true configuration, but no other default
task drivers currently have this option.
Nomad’s default configuration does not allow privileged Docker jobs, and must be edited to allow them.
Bidirectional mount propagation can be dangerous and can damage the host operating system. For this reason, it is only allowed in privileged containers.
To enable, edit the configuration for all of your Nomad clients, and set
allow_privileged to true inside of the Docker plugin’s configuration.
Restart the Nomad client process to load this new configuration.
If your Nomad client configuration does not already specify a Docker plugin configuration, this minimal one will allow privileged containers. Add it to your Nomad client configuration and restart Nomad.
plugin "docker" { config { allow_privileged = true } }
There are certain Docker configurations that can prevent privileged containers from performing mounts on the host. The error message will likely contain the phrase "linux mounts: path ... is mounted on ... but it is not a shared mount". More information can be found in the Docker knowledge base
If you do not have privileged containers enabled in Nomad, you will receive the following error when you submit the plugin-aws-ebs-nodes job:
Failed to create container configuration for image "amazon/aws-ebs-csi-driver:latest": Docker privileged mode is disabled on this Nomad agent
»Deploy the EBS plugin
Plugins for CSI are run as Nomad jobs with a
plugin stanza. The
official plugin for AWS EBS can be found on GitHub in the
aws-ebs-csi-driver repository. It’s packaged as a
Docker container that you can run with the Docker task driver.
Each CSI plugin supports one or more types: Controllers and
Nodes. Node instances of a plugin need to run on every Nomad client
node where you want to mount volumes. You'll probably want to run Node
plugins instances as Nomad
system jobs. Some plugins also require
coordinating Controller instances that can run on any Nomad client
node.
The AWS EBS plugin requires a controller plugin to coordinate access
to the EBS volume, and node plugins to mount the volume to the EC2
instance. You'll create a controller job as a nomad
service job and
the node job as a Nomad
system job.
Create a file for the controller job called
plugin-ebs-controller.nomad with the following content.
job "plugin-aws-ebs-controller" { datacenters = ["dc1"] group "controller" { task "plugin" { driver = "docker" config { image = "amazon/aws-ebs-csi-driver:latest" args = [ "controller", "--endpoint=unix://csi/csi.sock", "--logtostderr", "--v=5", ] } csi_plugin { id = "aws-ebs0" type = "controller" mount_dir = "/csi" } resources { cpu = 500 memory = 256 } } } }
Create a file for the node job named
plugin-ebs-nodes.nomad with the following content.
job "plugin-aws-ebs-nodes" { datacenters = ["dc1"] # you can run node plugins as service jobs as well, but this ensures # that all nodes in the DC have a copy. type = "system" group "nodes" { task "plugin" { driver = "docker" config { image = "amazon/aws-ebs-csi-driver:latest" args = [ "node", "--endpoint=unix://csi/csi.sock", "--logtostderr", "--v=5", ] # node plugins must run as privileged jobs because they # mount disks to the host privileged = true } csi_plugin { id = "aws-ebs0" type = "node" mount_dir = "/csi" } resources { cpu = 500 memory = 256 } } } }
»Deploy the plugin jobs
Deploy both jobs with
nomad job run plugin-ebs-controller.nomad and
nomad job run plugin-ebs-nodes.nomad. It will take a few moments
for the plugins to register themselves as healthy with Nomad after the
job itself is running. You can check the plugin status with the
nomad plugin status command.
Note that the plugin does not have a namespace, even though the jobs that launched it do. Plugins are treated as resources available to the whole cluster in the same way as Nomad clients.
$ nomad job status ID Type Priority Status Submit Date plugin-aws-ebs-controller service 50 running 2020-03-20T10:49:13-04:00 plugin-aws-ebs-nodes system 50 running 2020-03-20T10:49:17-04:00
$ nomad plugin status aws-ebs0 ID = aws-ebs0 Provider = ebs.csi.aws.com Version = v0.6.0-dirty Controllers Healthy = 1 Controllers Expected = 1 Nodes Healthy = 2 Nodes Expected = 2 Allocations ID Node ID Task Group Version Desired Status Created Modified de2929cc ac41c184 controller 0 run running 1m26s ago 1m8s ago d1d4831e ac41c184 nodes 0 run running 1m22s ago 1m18s ago 2b815e02 b896731a nodes 0 run running 1m22s ago 1m14s ago
»Register the volume
The CSI plugins need to be told about each volume they manage, so for
each volume you'll run
nomad volume register. Earlier you used
Terraform to output a
volume.hcl file with the volume definition.
$ nomad volume register volume.hcl
$ No allocations placed
The volume status output above indicates that the volume is ready to be scheduled, but has no allocations currently using it.
= "csi" read_only = false source = "mysql" } restart { attempts = 10 interval = "5m" delay = "25s" mode = "delay" } task "mysql-server" { driver = "docker" volume_mount { volume = "mysql" destination = "/srv" read_only = false } env = { "MYSQL_ROOT_PASSWORD" = "password" } config { image = "hashicorp/mysql-portworx-demo:latest" args = ["--datadir", "/srv/mysql"]. Consult the"
The allocation status will have a section for the CSI volume, and the volume status will show the allocation claiming the volume.
$ nomad alloc status 6c3b3703 CSI Volumes: ID Read Only mysql false
$ ID Node ID Task Group Version Desired Status Created Modified 6c3b3703 ac41c184 mysql-server 3 run running 1m40s ago 1m2s ago
. Consult mysql is no longer running in the cluster.
$ nomad job status mysql No job(s) with prefix or id "mysql" found
»Re-deploy and verify
Using the
mysql.nomad job file [from earlier][create_job], verify that the information you added prior to destroying the database is still present.
mysql> select * from items; +----+----------+ | id | name | +----+----------+ | 1 | bike | | 2 | baseball | | 3 | chair | | 4 | glove | | 5 | hat | | 6 | keyboard | +----+----------+ 6 rows in set (0.00 sec)
»Cleanup
Once you have completed this guide, you should perform the following cleanup steps.
Stop and purge the
mysql-serverjob.
Unregister the EBS volume from Nomad with
nomad volume deregister mysql.
Stop and purge the
plugin-aws-ebs-controllerand
plugin-aws-ebs-nodesjob.
Destroy the EBS volume with
terraform destroy.
»Summary
In this guide, you deployed a CSI plugin to Nomad, registered an AWS EBS volume for that plugin, and created a job that mounted this volume to a Docker MySQL container that wrote data that persisted beyond the job’s lifecycle. | https://learn.hashicorp.com/tutorials/nomad/stateful-workloads-csi-volumes?in=nomad/stateful-workloads | CC-MAIN-2020-45 | refinedweb | 1,637 | 53.21 |
- NAME
- DESCRIPTION
- SYNOPSIS
- METHODS
- TODO
- CAVEATS
- SOURCE CODE
- DEPENDENCIES
- SEE ALSO
- BUGS
- AUTHOR
NAME
Class::DBI::Plugin::Pager - paged queries for CDBI
DESCRIPTION
Adds a pager method to your class that can query using SQL::Abstract where clauses, and limit the number of rows returned to a specific subset.
SYNOPSIS
METHODS
- import
Loads the
pagermethod into the CDBI app.
- pager( [$where, [$abstract_attr]], [$order_by], [$per_page], [$page], [$syntax] )
Also accepts named arguments:
where => $where, abstract_attr => $attr, order_by => $order_by, per_page => $per_page, page => $page, syntax => $syntax
Returns a pager object. This subclasses Data::Page.
Note that for positional arguments,
$abstract_attrcan only be passed if preceded by a
$whereargument.
$abstract_attrcan contain the
$order_bysetting (just as in SQL::Abstract).
- configuration
The named arguments all exist as get/set methods.
- where
A hashref specifying the query. See SQL::Abstract.
- abstract_attr
A hashref specifying extra options to be passed through to the SQL::Abstract constructor.
- order_by
Single column name or arrayref of column names for the ORDER BY clause. Defaults to the primary key(s) if not set.
- per_page
Number of results per page.
- page
The pager will retrieve results just for this page. Defaults to 1.
- syntax
Change the way the 'limit' clause is constructed. See
set_syntax. Default is
LimitOffset.
- search_where
Retrieves results from the pager. Accepts the same arguments as the
pagermethod.
- retrieve_all
Convenience method, generates a WHERE clause that matches all rows from the table.
Accepts the same arguments as the
pageror
search_wheremethods, except that no WHERE clause should be specified.
Note that the argument parsing routine called by the
pagermethod cannot cope with positional arguments that lack a WHERE clause, so either use named arguments, or the 'bit by bit' approach, or pass the arguments directly to
retrieve_all.
- set_syntax( [ $name || $class || $coderef ] )
Changes the syntax used to generate the
limitor other phrase that restricts the results set to the required page.
The syntax is implemented as a method called on the pager, which can be queried to provide the
$rowsand
$offsetparameters (see the subclasses included in this distribution).
- $class
A class with a
make_limitmethod.
- $name
Name of a class in the
Class::DBI::Plugin::Pager::namespace, which has a
make_limitmethod.
- $coderef
Will be called as a method on the pager object, so receives the pager as its argument.
- (no args)
Called without args, will default to
LimitOffset, which causes Class::DBI::Plugin::Pager::LimitOffset to be used.
- auto_set_syntax
This is called automatically when you call
pager, and attempts to set the syntax automatically.
If you are using a subclass of the pager, this method will not be called.
Will
dieif using Oracle or DB2, since there is no simple syntax for limiting the results set. DB2 has a
FETCHkeyword,directly.
Any driver not in the supported or unsupported lists defaults to LimitOffset.
Any additions to the supported and unsupported lists gratefully received.
SUBCLASSING:
- Class::DBI::Plugin::Pager::LimitOffset
LIMIT $rows OFFSET $offset
This is the default if your driver is not in the list of known drivers.
This should work for PostgreSQL, more recent MySQL, SQLite, and maybe some others.
- Class::DBI::Plugin::LimitXY
LIMIT $offset, $rows
Older versions of MySQL.
- Class::DBI::Plugin::LimitYX
LIMIT $rows, $offset
SQLite.
- Class::DBI::Plugin::RowsTo
ROWS $offset TO $offset + $rows
InterBase, also FireBird, maybe others?
TODO
I've only used this on an older version of MySQL. Reports of this thing working (or not) elsewhere would be useful.
It should be possible to use
set_sql to build the complex queries required by some databases to emulate LIMIT (see notes in source).
CAVEATS.
SOURCE CODE
The source code for this module is hosted on GitHub. Feel free to fork the repository and submit pull requests!
DEPENDENCIES
SQL::Abstract, Data::Page, Class::DBI::Plugin::AbstractCount, Class::Accessor, Class::Data::Inheritable, Carp.
SEE ALSO
Class::DBI::Pager does a similar job, but retrieves the entire results set into memory before chopping out the page you want.
BUGS
Please report all bugs via the CPAN Request Tracker at.
majestic@cpan.org
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
AUTHOR
David Baird | https://metacpan.org/pod/release/MAJESTIC/Class-DBI-Plugin-Pager-0.566/lib/Class/DBI/Plugin/Pager.pm | CC-MAIN-2015-40 | refinedweb | 684 | 57.98 |
Towers of Hanoi is a mathematical game or a puzzle in which there are three pegs, and some disks (originally 8) of different radius placed on top of one another such that no larger disk is placed on a smaller disk. The task is to transfer such a column of disks from a source peg to another destination peg. The constraints are we can move only one disk at a time, and we may use the third peg as a temporary storage for the disks, and a larger disk cannot be placed on top of a smaller disk.
The puzzle was invented by the French mathematician Édouard Lucas in 1883..[2] It is not clear whether Lucas invented this legend or was inspired by it.
In this post I will describe the basic recursive solution to the Towers of Hanoi
Towers of Hanoi
There are three pegs Source, Temp, Destination. There are n concentric rings of different sizes on the Source peg in such a way that the bottom most ring is the largest and the topmost ring is the smallest and a larger ring is not placed on a smaller ring. The task is to move this column on rings from the Source peg to the Destination peg using the Temp peg as temporary storage of the rings. The constraints are that only one ring can be moved from one peg to the other in one move, and a larger ring cannot be placed on top of a smaller ring. The configuration is shown below:
Initial State Source Temp Destination + + + | | | | | | +-----+ | | +---------+ | | +-------------+ | | +-----------------+ | | [================================================================] Final State Source Temp Destination + + + | | | | | | | | +-----+ | | +---------+ | | +-------------+ | | +-----------------+ [================================================================]
Let us define (S,T,D,n) as a problem instance where we need to move the disks from Source to Destination through Temp. The first location in the tuple denotes the initial letter of the source peg name, the second location in the tuple denotes the initial letter of the temporary peg name, and the third location in the tuple denotes the initial letter of the destination peg name and the fourth location denotes the number of disks for the current problem being solved. That is, the first, second and third location of the tuple represents the source, temp and destination poles for the current problem, and the third element the number of rings.
Therefore (S,T,D,n) represents the problem to transfer n disks from the source to destination through temp, when source is peg 1, temp is peg 2 and destination is peg 3. (T,S,D,n) means the source is peg 2, destination is peg 3 and temp is peg 1. This representation will be used in the following sections.
Recursive Solution
Although the monks devoted their lives to solve this problem, we won’t. We will see how an algorithm can be used to do the same.
Initially we have the main problem (S,T,D,n), ie. we need to move the disks from peg 1 to peg 3 through temp peg 2, and we have n disks. This problem instance can be broken down in the following sub problems:
- Move the topmost (n-1) disks from Source (peg 1) to Temp (peg 2)
- Move the nth (largest) disk from Source (peg 1) to Destination (peg 3)
- Move the (n-1) disks from Temp (peg 2) to Destination (peg 3)
The step 2 moves a single disk, but in step 1 and 3 the “Move the (n-1) disks …” is what cannot be done in one step. The work in step 2 and 3 ie. to “Move the topmost (n-1) disks from source peg 1 to temp peg 2” and “Move the nth (largest) disk from source peg 1 to destination peg 3″ are itself two Towers of Hanoi problems with (n-1) disks, and with different source and destination combinations.
In the first subproblem in Step 1 we are moving the top (n-1) disks from Source to Temp. As the problem from which this subproblem was created was (S,T,D,n) the subproblem is (S,D,T,n-1), ie. it needs to move the (n-1) disks from the peg 1 to peg 2. So, for this subproblem the source peg is peg 1 and destination peg is peg 2, and we can use peg 3 as temporary. The number of disks in this subproblem is m = (n-1). So this can be solved like above:
- Move the topmost (m-1) disks from Source (peg 1) to Temp (peg 3)
- Move the mth (largest) disk from Source (peg 1) to Destination (peg 2)
- Move the (m-1) disks from Temp (peg 3) to Destination (peg 2)
Note how the source, destination and temp pegs change.
Similarly, the second subproblem in Step 3 of the actual main problem is (T,S,D,n-1), the source peg is peg 2 and destination peg is peg 3, and we can use peg 1 as temporary. The number of disks in this subproblem is m = (n-1). So this can also be solved like above:
- Move the topmost (m-1) disks from Source (peg 2) to Temp (peg 1)
- Move the mth (largest) disk from Source (peg 2) to Destination (peg 3)
- Move the (m-1) disks from Temp (peg 1) to Destination (peg 3)
From the above analysis we can clearly see that after breaking the main problem into two subproblems can again be divided into more sub-subproblems, which in order will be broken down to more subproblem. In each subproblem the number of disks is one less than its immediate parent problem. This recursive subproblem division will stop when we have a problem with one disk to be solved, in which case the solution is trivial, ie. simply move the only disk directly from source to destination. Therefore if we represent a problem with a node and the subproblems as its children nodes, then we form a tree which will have leaf nodes having trivial problems ie. to move only one disk.
For each subproblem we have the Source, Destination and Temp changes. This can be noted from the above example. If you make the problem division tree, then you can see how the Source, Temp and Destination pole numbers change between subproblem hierarchy.
At at each problem the (S,T,D,n) the two subproblems created are (S,D,T,n-1) at step 1 and (T,S,D,n-1) at step 3. That is, the first subproblem is generated by swapping the location 2 and location 3 of the tuple representing the original problem, and the second subproblem is generated by swapping the location 1 and location 2 of the tuple of the original problem. Each will have one less disk, as the bottom most disk is moved in one move. This mechanism is applied recursively to each of the generated subproblems. Therefore the subproblem tree will look like below:
A tree for the Towers of Hanoi subproblem division. Only the subproblem branches are shown, the single disk move lies in between each pair of children are not shown. (S,T,D,n) + | +------------------------------+------------------------------+ | | + + (S,D,T,n-1) (T,S,D,n-1) +-------------------+ +-------------------+ | | | | + + + + (S,T,D,n-2) (D,S,T,n-2) (T,D,S,n-2) (S,T,D,n-2) +-------+ +-------+ +-------+ +-------+ | | | | | | | | (S,D,T,n-3) | | (S,D,T,n-3) (T,S,D,n-3) | | (T,S,D,n-3) + + . . + + . (T,S,D,n-3) (D,T,S,n-3) . . (D,T,S,n-3) (S,D,T,n-3) . . . . . . . . . . . . . . . . . . .
The left child of each node represents the first subproblem in step 1 and the right child the second subproblem in step 3. Note how the labelling location 2 and 3 swap in each left child of each note (first subproblem of each problem), and the labelling of location 1 and 2 swap in each right child of each node (second subproblem of each problem). This will help writing the following algorithm.
function TowersOfHanoi (Pole S, Pole T, Pole D, Integer n) { IF [ n == 0 ] THEN RETURN ENDIF TowersOfHanoi (S,D,T,n-1); PRINT ("Move disk no 'n' from 'S' to 'D'"); TowersOfHanoi (T,S,D,n-1); }
The above recursion will stop whenever n is 0. This is the case when the trivial problem is attempted to be broken down into more subproblems. When n = 0 then no operations are done, and the call simply returns. Therefore for a call TowersOfHanoi (S,T,D,1) only the PRINT statement will be executed, which will simply print the trivial solution which will move the only disk from the current source to destination peg. Note that in each recursive call the actual value of n is preserved in each of the recursion levels.
All the moves are done by the Step 2 of each subproblem, the other two steps simply divides the problem into smaller problems. The step 2 for each subproblem of size m moves the mth bottom disk from source to destination thus placing one disk into position.
Intuitively the recursive algorithm could be seen like this. The “for this …” can be thought as the problem division.
To move 3 disks from peg 1 (source) to peg 3 (destination)
- first we need to transfer first the top 2 disks from peg 1 to peg 2, for this …
- … we need to transfer top 1 disk from peg 1 (source) to peg 3 (temp)
- then transfer the bottom most disk of this subproblem, the disk 2 from peg 1 (source) to peg 2 (destination)
- at last transfer the disk 1 from peg 3 (temp) to peg 2 (destination)
- next, we need to transfer the bottom most disk of this subproblem, disk 3, from peg 1 (source) to peg 3 (destination).
- After which we need to transfer the pile of disk 2 and 1 on the peg 2 (temp) to peg 3 (destination), for which …
- … we need to transfer top 1 disk from peg 2 (source) to peg 1 (temp)
- transfer the bottom most disk of this subproblem, the disk 2 from peg 2 (source) to peg 3 (destination)
- transfer the disk 1 from peg 1 (temp) to peg 3 (destination)
Here is a C Language implementation:
Sourcecode
#include <stdio.h> void towers_of_hanoi (char source, char temp, char destination, int n) { if (n == 0) { return; } // (S,D,T,n-1) towers_of_hanoi (source, destination, temp, n-1); // move the bottom most disk from `source' to `destination' of the current problem printf ("\n%d disk (%c -> %c)", n, source, destination); // (T,S,D,n-1) towers_of_hanoi (temp, source, destination, n-1); } int main (void) { int n; printf ("\nNumber of Disks \"n\": "); scanf ("%d", &n); towers_of_hanoi ('S', 'T', 'D', n); printf ("\n"); return 0; }
The code follows exactly the form presented in the algorithm. The function towers_of_hanoi ('S', 'T', 'D', n) is called. This provides the actual problem’s source, temp and destination peg name identifiers ‘S‘, ‘T‘, ‘D‘ characters respectively. Inside the recursive call, these parameters are in effect swapped when calling recursively in the next depth. When we print the Step 2, ie. the print statement at any depth, it gives the actual move which is needed to solve the actual problem.
Time and Space
Now we can have a look at the time taken by this algorithm to execute and show each move for a solution for n disks. The analysis is easy. Let there be total
number of steps required to solve a Towers of Hanoi problem for n disks. From the above recursive algorithm we can see that the problem is broken down to 2 subproblems of size (n-1), and one operation to print the movement of the bottom most disk, which requires constant time, and can be seen as one operation.
Therefore the growth of time with respect to the input problem size is
with
as the trivial case and base condition of the recurrence relation. This homogeneous recurrence relation can easily be solved to
. Therefore total number of moves required to solve a Towers of Hanoi problem instance of size n is
. Like for 2 disks we have 3 moves, 3 disks we have 7 moves, and 10 disks we have 1023 moves. Clearly the time growth of the problem is
. Therefore even for a computer is supplied with an enough large value its CPU time can be entirely devoted to solve the input problem instance.
It will be interesting to investigate about its space requirements. As it is using recursion and actually performing a DFS therefore the memory requirements are modest. Only the longest path down the recursion tree needs to be stored in the system stack. Each branch will do down until a node does not reach n = 0. Therefore the maximum length of stored nodes (actually function stack frames for each call) will be n. Therefore the memory growth is
Related Post
Here is another similar post from this blog: Towers of Hanoi Iterative process: simulating recursion
Links
Have a look at these links too:
5 thoughts on “Recursive Solution to Towers of Hanoi”
nice post! you will love Prolog :) recursion and logical resolution are at its core
nice post. You will love Prolog! Recursion and logical resolution are at its core
it was very helpful to me….
thank you for posting this. i have also made a c++ program with same concept but it’s somewhat different in the recursive definition
have a look at my code on my blog codingloverlavi.blogspot.com
:):)
The main focus of this post was to describe in detail how the process works, to help the beginners who often confuse the process of recursion.
I had a look at your code, although could not get how your recursive definition differed form the well known definition.
Thanks for stopping by my blog ! | https://phoxis.org/2012/03/22/towers_of_hanoi_r/ | CC-MAIN-2020-29 | refinedweb | 2,299 | 64.04 |
MobileLPR is an LPR client library built for the .NET Compact Framework 2.0 that gives a Windows Mobile application the ability to print to an LPR (a.k.a..
My career for the past couple decades largely revolved around making mobile devices work productively for small and large businesses. Every year or two brought a new herd of devices, some with new capabilities, faster hardware, or simply repackaged in novel and useless ways. I watched the industry take a big step forward every five years, bringing not just bigger memory and faster processors, but actually putting more capabilities into those palm-size computing wonders. In the late 1990s, Microsoft introduced a new Operating System, Windows CE, that commoditized the role of personal hand-held devices and opened up the formerly-proprietary world of portable computing to the general programming population. About a decade later, echoing the growth of the Internet, these devices evolved to include network connectivity and many of the functions of less portable platforms. Today, nearly everyone uses a wireless device of some type that can be programmed nearly identically to its industrial siblings.
Displacing multitudes of special-purpose devices used for fixed-station data collection, scanning, and printing, families of isolated and single-function components merged into the general-purpose platforms in use today. Many common features have greatly improved in quality and ease-of-use, but printing is something that time nearly has left behind when it comes to mobile computing platforms. This deficiency is what MobileLPR was written to address.
In my pursuit of rewriting a system for a long-time loyal customer, I was faced with the requirement of replacing a wireless printing station that had been cobbled together from an industrial label printer and a small "brick" outfitted with a wireless radio and an embedded program. This printing node took its directions from a custom written PC server to service special inventory labeling requests for a small team of users outfitted with mobile computers.
Affordable printers are now available that either contain their own internal print servers or can be equipped with external print servers that can communicate with several standard printing protocols. They can be dropped onto a network, wired or wireless, and require nearly no additional infrastructure or ongoing administration to operate. This is the kind of device that was selected to become the label station for the new system, and created my need: an interface that allowed me print to a networked printer via a standard protocol.
Before jumping into this project, I found only a few Windows Mobile printing client software packages that sounded like they might work for me. After reading through their information, familiarizing myself with the LPR protocol, and staring at an empty wallet, I couldn't justify paying several hundred dollars for a commercial package to solve such a relatively simple task. Thus was born the idea of writing the MobileLPR library for fun and (not for) profit.
I found several indispensable documents on the web regarding LPR. The primary documentation was RFC 1179 - Line printer daemon protocol, a guide to the existing LPR protocol, mainly as it applied to BSD Unix servers. It was not a specification and left much to the imagination, but provided a fundamental understanding of the command set and data flow to be followed.
The greatest asset in my effort was the excellent LPRng SourceForge Project, "an enhanced, extended, and portable implementation of the Berkely LPR protocol" authored by Patrick Powell. Though not documented exhaustively, there was ample practical information about how LPR worked, decisions about how LPRng was implemented, and how it dealt with critical instructions that were missing from RFC 1179. The availability of Mr. Powell's source code and his treatise on printing made an otherwise difficult job fairly simple. Thank you, Mr. Powell!
The end result summarizes the protocols supported by MobileLPR:
The MobileLPR library was written to be simply a DLL attached to an application program. Referencing the DLL from your Visual Studio SmartDevice project makes all the power of its classes available to your program. Though anticlimactic, there really is only one class you need to be concerned with: LprJob. It is this class that is responsible for accepting the printing parameters and data files, organizing them to create a print job that is prescribed by the protocol in use, and sending the data to the print server.
LprJob
The first place to start is with the print server, which nowadays is usually built into the printer, to identify what capabilities it supports. For simplicity, the remainder of this article will not distinguish between internal and external print servers, and will refer to them collectively as "print server". Some offer Socket API, some LPD/LPR, and some offer both. Even if your printer does not have network capability, there are commercially available print server appliances that are inexpensive and provide either a direct socket connection or LPR; even some wireless routers and NAS devices have them. No matter what physical device houses the print server, MobileLPR can talk to it.
Once you have identified the print protocol to use, you need the address of the server. If you are on a network that provides dynamic DHCP services, you can configure the print server with a name and allow it to be assigned any address. If your print server is obtaining an address without dynamic DNS being available, either tie the IP address to the MAC address, or assign your print server a static address. Whether accessed by name or by numeric IP address depends on what your mobile device is capable of. A numeric IP address should always work.
The printer queue name is the next piece. In practice, there are no common naming conventions. Some print servers, especially the external ones, are capable of servicing multiple printers from one unit. In these devices, selection of the output printer is made either by individual port number or by separate print queues for each printer or interface. Queue names like "P0", "P1", "S0", or "S1" are not uncommon for communicating with printers connected to parallel and serial interfaces, respectively. Some print servers allow you to configure whatever name you want and attach it to the required interface. How to configure a print server is beyond the scope of this article, so I will be using the nondescript queue name of "printer" in my examples.
The LprJob class separates job setup into three logical areas: destination, printable data, and monitoring. Each instance of an LprJob object contains all the information necessary to connect to a print server, transfer the data to be printed, and know when that transfer is complete. It also provides the barest queue control operations as defined by the LPR protocol. Printable data is supplied as a list of one or more local data files. The LprJob class provides several events that can be used to monitor the progress of the print job.
The destination information identifies the print server and port number to connect to, the name of the printer queue to use, if any, and the method of transferring the data.
The most straightforward means of specifying a print job's destination is through the SetPrinterURI method, identifying all the components with a single string. The general syntax of the string follows the generic Uniform Resource Identifier specification that can be found as RFC 3986 and Uniform Resource Identifier (URI): Generic Syntax. For MobileLPR, its syntax is: protocol://[userinfo@]servername[:serverport][/printername]. Note that the SetPrinterURI method may generate a UriFormatException if the string is formatted incorrectly.
SetPrinterURI
UriFormatException
MobileLPR uses the scheme, authority, and path components of the URI string. The scheme component identifies the job transfer protocol. Easily readable protocol names (and aliases) are used to select the job transfer method to employ:
Scheme
Protocol
direct
Use a direct Socket API (TCP) connection to the specified print server. Standard port is 9100.
lpd
Same as lpr.
lpr
Use standard LPR protocol. Standard port is 515. This is the default protocol used if none (or an invalid scheme) is specified.
lprng
Use LPRng parameters in the control file, use expanded reserved local port numbers, but perform a basic LPR transfer. Standard port is 515.
raw
Same as direct.
The authority component contains the name of the print server, a non-default port number to use to establish a connection, and user information in case the print server requires authorization to execute the print job. For example, some LPR servers on Linux platforms may restrict printing to certain users, and hold or discard jobs for all others; supplying the user name gives the print server the information it needs to set appropriate permissions for printing. The default user name used is "MobileLPR".
If your program is running on a device that has DNS resolution ability, the server name can be specified as an alphanumeric domain name. Otherwise, it may be safest to use a numeric IP address here. Your network administrator should be able to tell you what services are available.
Port number may be optional. If the print services use the standard ports, selecting the protocol through the URI also sets the standard port number. If your print services are using non-standard ports, or you assign the connection parameters individually, the correct port number must be supplied for a successful connection.
The path component sets the name of the print queue that will service the print job. Depending on your print server, this name may or may not be case-sensitive. The print server documentation should contain the information you need. If in doubt, use the printer queue name exactly as it is configured in your print server.
Alternatively, the Protocol, ServerName, ServerPort, UserName, and PrinterName properties can be set individually. If you anticipate sending multiple jobs to the same destination, the DefaultProtocol, DefaultServerName, DefaultServerPort, and DefaultPrinterName properties can be set up first, so any new LprJob class instance will be created with those values already assigned.
ServerName
ServerPort
UserName
PrinterName
DefaultProtocol
DefaultServerName
DefaultServerPort
DefaultPrinterName
Example: to send the print job using LPR protocol to a print server named "lprserver", serviced by print queue "P1" on port 715, allowing printing by user "printuser", you can use:
LprJob job = new LprJob();
job.SetPrinterURI("lpr://printuser@lprserver:715/P1");
A simpler example is printing over a direct socket connection to a printer with an internal print server using all default information. The print server address is 1.2.3.4:
LprJob job = new LprJob();
job.SetPrinterURI("direct://1.2.3.4");
Now that the print server has been specified, it is time to attach the data files to the job. The AddDataFile method taking a single argument attaches a named data file to the job as a literal (raw, untranslated) file. That means the data that will be sent to the printer must be exactly as the printer expects it. An overload of the AddDataFile method allows specifying the format used for printing the file, selectable from the standard data formats for which LPR was designed. In most LPR installations, the format controls the filters that data will be passed through to get the desired printer output.
AddDataFile
Briefly, the formats may be broken down into two groups: literal (binary, raw, or untranslated) data sent with the Literal and Raster formats; and text data sent with all other formats. MobileLPR passes literal data unchanged. Text formats assume the data is of a textual nature, and data is translated from the native text format of the mobile device into ASCII text that LPR servers expect to receive. The data content represented by the text is not changed in any way. With either literal or text data, the application is responsible for generating the appropriate content.
Literal
Raster
Format
Content
Literal (untranslated, binary) file.*
CIF
Caltech Interchange Format plot file.
Ditroff
ditroff output file.
DVI
DVI (TeX output) file.
Formatted
Plain text file to be formatted.
Fortran
Plain text with FORTRAN carriage control.
Paginate
Text to process through the Unix 'pr' (paginate) command.
Plot
Berkeley Unix plot file.
Postscript
Standard Postscript file.
Sun raster image file.*
Troff
Graphic Systems C/A/T phototypesetter file.
*Data is sent without any translation.
The LPRng protocol limits the number of data files to 52, which corresponds to the number of index letters available for remote file names. The LPR protocol does not specify a limit, but many servers cannot handle more than one data file per job. No such restriction is enforced for the Direct protocol.
One difference where MobileLPR may diverge from the standard protocol is allowing multiple copies of the files to be printed, because there is no clear documentation concerning it. Copies specifies the number of copies to print for all data files in the job, and is not for individual files. Copies processing is done by MobileLPR. In the case of the LPR protocol, the entire job is sent iteratively for as many copies as are specified. For LPRng, copies are handled by including each data file multiple times within the job. For Direct, each data file is sent multiple times over the same socket connection. In practice, I don't think this design choice poses any problems with standard print servers, but that is an assumption on my part.
Copies
The TestMobileLPR sample program included as part of this article provides a typical example that shows the correct steps necessary in using the library.
A design consideration when putting together this library was maintaining a responsive user interface. Keeping this in mind, the SubmitJob method that is responsible for organizing and sending the print job to the print server executes the whole transfer process on a background thread. Several mechanisms are provided for determining when the job transfer is complete.
SubmitJob
The simplest mechanism is the IsComplete property. This is a flag that is set to false while an operation is in progress, and set to true when the operation is complete. This property can be used periodically for polling to see when the job is done.
IsComplete
Another mechanism provided is the WaitForCompletion method. An internal synchronization object reflects the state of the IsComplete property. This method waits until the synchronization object is signaled, so no polling has to be done. Calling this from your UI code will suspend user input/output until the print job completes.
WaitForCompletion
The final monitoring mechanism is a related group of events named LprJobStarted, LprJobProgressChanged, and LprJobCompleted. Two parameters are passed to any specified event handler. The first parameter is the LprJob object that raised the event; the second is an instance of LprJobProgressEventArgs, populated with the total number of bytes to be sent for the jobs (counting bytes in the local data) and the cumulative number of bytes sent at the time the event was raised. The LprJobProgressChanged event also passes the local and remote pathnames (in the case of LPR and LPRng protocols) of the data file being transferred.
LprJobStarted
LprJobProgressChanged
LprJobCompleted
LprJobProgressEventArgs
The LprJobStarted event is raised once when the job transfer begins. The Total event argument property will contain the total number of bytes to be transferred, which your application can use to set up a progress indicator.
Total
The LprJobProgressChanged event is raised every time a new block of data is sent to the server. The LprJobProgressEventArgs event argument properties are populated to reflect the current status of the print job.
Property
Total number of bytes to be sent for the entire print job.
Used
Number of bytes sent so far.
Pathname
Local pathname of the current file being transferred.
ServerFilename
Remote filename of the current file being transferred.
Command
LPR command number being executed.
The LprJobComplete event is guaranteed to be raised once at the end of the job, whether it succeeded or failed. The Used event argument property is the number of bytes that had been sent when the job ended. The LprJob object should not be disposed of while any operation is pending; in other words, wait until IsCompleted is true.
LprJobComplete
IsCompleted
The LastException property records any errors encountered. When the job is completed, it will contain the terminating exception, if any. No exceptions are raised after a job has been started, and this is the only mechanism available to determine if the job failed. How a job failure is handled is up to your application.
LastException
The LPR protocol specifies additional commands used for supporting print jobs. For the Direct protocol, only the SubmitJob method performs any real function.
Method
Function Performed
Transfers the data files to the print server. For LPR and LPRng, this takes care of creating and removing the control file and sequencing the commands and data stream according to the protocol. Launches a background thread to perform the work.
PrintWaitingJobs
Simply tells the print server to start servicing the queue, if not already running. Usually unnecessary.
GetQueueStatus
Requests a list of queued jobs from the print server. A short and a long format are available. The structure of responses is undefined, and will vary by print server. Specific job numbers may be listed to restrict the output to those jobs only. Job numbers must be those generated by the server.
RemoveJobs
Removes jobs from the print queue. Specific job numbers may be listed to restrict removal to those jobs only, otherwise the currently printing job is removed, if permitted. Job numbers must be those generated by the server.
When the connection has been defined, the data files attached, and the monitoring set up, you can launch the print job. This is simply done by calling the SubmitJob method. Always call command methods within a try-catch block. Any errors, whether originating from MobileLPR or the Operating System, will generate exceptions. After a job is launched, exceptions will be captured in the LastException property to be examined by your application after the job transfer is completed.
try-catch
When the printer's marketing material states that it supports LPD/LPR protocol, be suspicious. Unless the document clearly defines how to go about using it, don't believe it. In my case, the slick advertising sheet said in plain language that LPD/LPR was supported by the printer; however, in real life, there wasn't a single scrap of information about it in the printer's manual. Trial and error showed the printer's network interface responded on port 515. It would accept a print job and return status messages, but regardless of every print queue name I tried (including queue names taken from related manuals), it wouldn't print, and the status messages never changed. After all the work I put into my pretty little project, the printer was deaf to LPR.
A maximum of 52 data files (including copies) may be sent in one LPRng print job. Though RFC 1179 is silent on this point, some LPR servers can handle only a single data file per job. The LPRng limit is enforced for LPR and LPRng protocols, and will ignore additional files.
Some print servers take RFC 1179 very literally and treat its suggestions as gospel. With these print servers, specifying remote control files or data file names that do not strictly adhere to the guidelines result in a failure to output. The job may be accepted, but nothing will print. My advice is to stick to the LPR protocol when you don't know if LPRng extensions are supported.
I implemented only a few of the many LPRng enhancements: expanded reserved ports for the client side of the connection; the "A" unique job identifier and "Q" original printer queue name parameters in the control file; one of the multiple-copies mechanisms by sending a data file more than once distinguished by a ".Cn" suffix on additional copies for remote filenames; LPRng error messages for rejected jobs. Other features I considered unnecessary, like manipulations of queues on the server, I decided to omit.
The following snippet of code illustrates how basic you can get with this library. This is a Windows Forms application for a Smart Device. It has one form with a button on it to print a two-line text file created by the program.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using MobileLPR;
using System.IO;
namespace LprSample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Exception lastex = null;
LprJob job = null;
try
{
// Create a text file to print.
String tempname = Path.GetTempFileName();
StreamWriter file = new StreamWriter(tempname);
file.WriteLine("Hello, LPR server!");
file.WriteLine("How are you?");
file.Close();
// Create a print job for our file.
job = new LprJob();
// Connect to LPR server "lprserver",
// port 515, queue "printer".
job.SetPrinterURI("lpr://lprserver");
// Send one text data file.
job.AddDataFile(tempname, LprDataFormats.Formatted);
// Transfer the print job to the print server.
job.SubmitJob();
}
catch (Exception ex)
{
lastex = ex;
}
finally
{
if (job != null)
{
// Wait here until job transfer is finished.
job.WaitForCompletion();
lastex = job.LastException;
}
// Handle any errors in lastex here....
MessageBox.Show(lastex.Message.ToString());
}
}
}
}
There is a lot of room for improvements in this project. After starting with the LPR protocol, then tacking on some of the LPRng features, then Socket API, I realized I could have structured the basic job transfer execution in a more flexible manner. The transfer protocols could be encapsulated in a set of related classes, each providing a common interface to connect, create any additional files (e.g., control files) or connections, transfer data, and monitor status. These objects would be used by the SendJobFiles method of the LprJob class in a more cleanly written transfer loop. For its normal intended purpose, I considered this over-engineering.
SendJobFiles
IPP is rapidly gaining ground as a standardized network printing protocol. It defines a rich, complex set of interactions among printers, servers, and clients. It would be a good candidate to include as a protocol class, as mentioned, but I have not investigated its use of resources or difficulty of implementation to determine if it would be an effective addition to this mobile printing library.
Documentation can always stand lots of improvements. If this article and the internal comments in the code are not clear enough, I will make efforts to edit one or the other to add missing information or clarify ambiguous points. It's my desire to present a quality product, and your feedback is welcome.
Programming alone and with an inadequate toolkit is a frustrating and thankless task. I hope what I have provided here helps save you from burning a lot of wasted hours in the dark like the many that I have had to. Good coding to all, and to all a good. | http://www.codeproject.com/Articles/136875/MobileLPR-An-LPR-Client-for-NET-Compact-Framework?fid=1601105&df=90&mpp=10&sort=Position&spc=None&tid=4325668 | CC-MAIN-2015-32 | refinedweb | 3,798 | 54.73 |
I was suppose to create a simple Java program for calculating the area of a rectangle (height * width). Then check the
user’s input, and make sure that they enter in a positive integer, and letting them try again if
they enter in a negative number.(I'm not sure how to get them to try again.
I am suppose to use an "if" statements and indeterminate loops to achieve the solution.
The program will have the following requirements:
1.Ask the user to enter in both a height and width (as an integer)
2. If the user enters in a negative number, display an error
3. If the user enters in a negative number, give them another chance to enter in the
correct value
4. Calculate the area and display to the screen once two positive integers have been
entered.
import java.util.Scanner; public class RectangleAreaCalc { public static void main(String[] args) { int length; int width; int area; Scanner input = new Scanner(System.in); System.out.println("Please enter the length of the rectangle:"); length = input.nextInt(); if (length < 0) { System.out.println("Incorrect Input, Please enter a positive number for length"); } else System.out.println("Please enter the width of the rectangle:"); width = input.nextInt(); if (width <= 0) { System.out.println("Incorrect Input, Please enter a positive number for width"); } else { area = length * width; System.out.println("The area of a rectangle is:" + area); } } } | http://www.javaprogrammingforums.com/whats-wrong-my-code/36513-why-my-code-not-working.html | CC-MAIN-2015-32 | refinedweb | 237 | 58.89 |
great, lets get started . let me begin by saying this is not schoolwork , this is a lazy Saturday on the couch experimenting with python and and trying to learn the basics.Mostly just trying to get a handle on for loops and if statements.So anyways i was just messing with a silly bit of code to demonstrate various concepts to myself and i came across an anomaly of sorts ( well to me anyway ) and an error that i cant seem to figure out .
ok lets look at the code:
def boom(): import time mylst= [1,2,3] y=str("boom!!!!!!!!!!!!!!!!!!!!!!!!!") print('hello this message self destructs in 3 seconds:') for anythngiwantcangohere in mylst: time.sleep(1) print(anythngiwantcangohere) for anything in y: print (y) boom() ans = input('would you like to boom again? y/n') if ans == 'y': boom() else: print('goodbye')
ok so the function works as expected but does contain the anomaly that 'boom!!!!!!!!!!!' is print on the screen ALOT of times. I'm pretty sure i dont understand what im doing here:
for anything in y: print (y)
ok thats the first bit , the error comes into play on line 17
i cant seem to get it to accept " y "as input
the error given is:
Traceback (most recent call last):
File "/home/mojo/test.py", line 17, in <module>
ans = input('would you like to boom again? y/n')
File "<string>", line 1, in <module>
NameError: name 'y' is not defined
so thats where im stuck at , any hints tips or tricks ??????? | http://www.dreamincode.net/forums/topic/346243-noob-input-yn-y-is-not-defined/page__p__2006340 | CC-MAIN-2016-22 | refinedweb | 257 | 76.76 |
Hi, I try to use rhomobile DatePicker:
def DatePick
DateTimePicker.choose( url_for( :action => :datepick ), "EnterDate", Time.now, 1)
end
on RhoSimulator it wase work so good, but on real device (Motorola MC 3100 WinModile) it is not.
Program shut down witout any log messages.
I checked datepicker sample which getting from "" on MC65 and its work fine.
Would be easy to help you if you can give any error/log message.
Visnupriya R
Kutir Mobility
Thenk you. I use this example but witout result. maby it win' error. Log file dose not have any records abaut error.
Alexey, Have you tried it other Win Mobile devices ?
Visnupriya R
Yes, I also try on Win CE. Result is equal. Maby it becose a have not license on rhomobile (I use 2.1. version). I deside my problem by using JQuery date picker widjet.
Note: Its not to do with license though | https://developer.zebra.com/thread/3757 | CC-MAIN-2018-05 | refinedweb | 150 | 79.16 |
Convert local time to calendar time
#include <time.h> time_t mktime( struct tm* timeptr );
libc
Use the -l c option to qcc to link against this library. This library is usually included automatically.
The mktime() function converts the local time information in the struct tm specified by timeptr into a calendar time (Coordinated Universal Time) with the same encoding used by the time() function.
The original values of the tm_sec, tm_min, tm_hour, tm_mday and tm_mon fields aren't restricted to the ranges described for struct tm. If these fields aren't in their proper ranges, they, or -1 if mktime() can't convert it.
#include <stdio.h> #include <stdlib.h> #include <time.h> static const char *week_day[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; int main( void ) { struct tm new_year; time_t t; new_year.tm_year = 2001 - 1900; new_year.tm_mon = 0; new_year.tm_mday = 1; new_year.tm_hour = 0; new_year.tm_min = 0; new_year.tm_sec = 0; new_year.tm_isdst = 0; t = mktime( &new_year ); if ( t == (time_t)-1) printf("No conversion possible.\n"); else printf( "The 21st century began on a %s.\n", week_day[ new_year.tm_wday ] ); return EXIT_SUCCESS; }
produces the output:
The 21st century began on a Monday. | https://www.qnx.com/developers/docs/7.1/com.qnx.doc.neutrino.lib_ref/topic/m/mktime.html | CC-MAIN-2022-05 | refinedweb | 191 | 62.24 |
Spring Security: Customizing the User Authorization Process
By Mark Spritzler
TheServerSide.com
Mark is a trainer and consultant for
companies like SpringSource, NTier Training and JBoss. Mark is an expert in Spring, Hibernate and
iPhone development.
Customizing your user and authorization in Spring Security
Spring Security was built to provide a full, robust, security module for all of your applications. It was also built with extensibility and flexibility in mind. If you were to look at all the classes working together to provide the whole solution, you would see lots of classes, each designed to handle one particular aspect of the whole security picture. This makes Spring Security a little difficult to grasp at first as you see all of these classes. However, the complete separation of concerns really opens up Spring Security so you can customize just the parts that you need.
For this article, we are going to change the definition of a User and how that User is loaded. For the loading of the User, we are going to use Hibernate. Spring Security comes with classes to load from a database where you simply configure the class with two queries and uses JDBC. There are also classes for LDAP, a flat file, or even in memory. In most cases, these built in classes will do the trick. But if you already have a Hibernate Repository created that loads the data, why not reuse it.
Our application is a mythical Order Process system where we have already created domain classes and Hibernate Repository classes. There are Customer, Order, Item and Role domain objects and corresponding repository classes. The full details of these classes aren't needed.
In Spring Securirty a User/Principal is an
instance of the UserDetails interface.
At this point I have an interesting option. I can use one of my domain classes like Customer to also act as my User object. Or I could just create another class to implement UserDetails interface. I say this is interesting because sometimes we have an application where when the user first logs in we load up their Customer data and need to store it for as long as needed in the “session”. The typical solution is to put this object into the HttpSession in say a web application. Now we can remove this solution and either use Customer as our User object, or have the new UserDetails class that we create to hold on to the Customer object.
In this article I am going to use the Customer object as our UserDetails object. The one downfall to this approach is that we will have to add some properties here that are security specific which might be considered polluting our domain model.
Here is our code the Customer object fully implementing the UserDetails interface.
Our implementation is very simple in terms of the overriding methods, we just return instance variable values, just like normal getters and setters. The interesting part is in the constructor that receives a list of Strings for the roles that the User/Customer has.
Now that we created our own UserDetails implementation, lets use it to customize the authorization piece of Spring Security. This consists of implementing another interface called UserDetailsService. This interface is actually even easier in that we only have to implement one method.
Since we are going to be telling Spring Security about our customization via a standard Spring Configuration, these classes will be able to have our Services injected into it. And we are going to have our UserDetailsService delegate the data loading to our CustomerService which calls our CustomerHibernateRepository.
Since Customer already implements UserDetails we can just return it. Now underneath the covers in our service's call to the Repository our query is something like this. This is using HQL, but I think you can easily see what basic SQL query will be derived from it.
One thing to note, for some reason, Spring Security wants all role names to begin with “ROLE_” otherwise it won't work. If you don't have ROLE_ in your database, then you want to make sure that any query you write also will prepend your roles with “ROLE_”. Nice little gotcha there.
Now that we have our two customized classes written, it is now time to tell Spring that we want to use them instead of the built in classes that Spring Security provides. This, of course, is a spring configuration xml file, which you should already have, if you are using Spring Security, regardless of customizing it. So for sake of brevity, I will not go into detail on every security tag.
First our configuration:
In our configuration we just create a bean for our CustomerUserDetailsService passing in a CustomerService dependency via a constructor-arg, then using the security namespace we just tell the AuthenticationManager that we want to use our UserDetailsService which will return our CustomerUserDetails object.
There we have, a fully customized UserDetails and UserDetailsService in Spring Security. Everything else from Spring Security is being used as normal. Because Spring Security allows us to change any little part, we can choose exactly what we want to customize without have to write the entire kitchen sink along with it. Good Luck and happy customizing!
*********************** column on Spring Formatters and Converters
***********************
Books by Spring's Founder, Rod Johnson
26 Apr. | http://www.theserverside.com/tip/-Spring-Security-Customizing-Your-User-and-Authorization-in | CC-MAIN-2014-52 | refinedweb | 889 | 53.21 |
The EnumField class provides definitions for enum values. Enum fields may have default values that are delayed until the associated enum type is resolved. This is necessary to support certain circular references. For example:
from protorpc import messages class Message1(messages.Message): class Color(messages.Enum): RED = 1 GREEN = 2 BLUE = 3 # Validate this field's default value when default is accessed. animal = messages.EnumField('Message2.Animal', 1, default='HORSE') class Message2(messages.Message): class Animal(messages.Enum): DOG = 1 CAT = 2 HORSE = 3 # This fields default value will be validated right away since Color is # already fully resolved. color = messages.EnumField(Message1.Color, 1, default='RED')
EnumField is provided by the
protorpc.messages module.
Constructor
The constructor of the EnumField class is defined as follows:
- class EnumField(enum_type, number, required, repeated, variant, default)
Provides a field definition for Enum values.
Arguments
- enum_type
- The Enum type for a field. Must be a subclass of Enum.
- number
- The number of the field. Must be unique per message class.
- required
- Whether or not this field is required. Mutually exclusive with the
repeatedargument; do not specify
repeatedif you use
required.
- repeated
- Whether or not this field is repeated. Mutually exclusive with the
requiredargument; do not specify
requiredif you use
repeated.
- variant
- Further specifies the type of field. Some field types are further restrained based on the underlying wire format. Best practice is to use the default value, but developers can use this field to declare an integer field as a 32-bit integer vs. the default 64 bit.
- default
- Default value to use for the field if it is not found in stream.
Raises a FieldDefinitionError when
enum_typeis invalid.
Class Properties
The EnumField class provides the following class properties:
- type()
- Enum type used for the field.
- default()
- Default for the enum field. If the default value is unresolved, uses Enum type as the default.
Instance Methods
EnumField instances have the following method:
- validate_default_element(value)
- Validates the default element of the Enum field. Enum fields allow for delayed resolution of default values when the type of the field has not been resolved. The default value of a field may be a string or an integer. If the Enum type of the field has been resolved, the default value is validated against that type. | https://cloud.google.com/appengine/docs/standard/python/tools/protorpc/messages/enumfieldclass | CC-MAIN-2019-09 | refinedweb | 379 | 60.11 |
Type: Posts; User: love2mao
Find a weblogic manual. I have a good suggestion.
You really need to spend some time getting yourself...
Why not post your solution for thanks to our viewing :)
Transfer:= Download from A, and then upload onto B
Delete:= I'm not sure how to delete something from a ftp server
without human interaction
Gurus,
I have this question about what component to choose to implment JMS
service. The scenario is like below:
1) This is component will use JMS to communicate with another component
in J2EE...
I want to change byte "0x0d" into "0x0d0a" in a txt
file. Can I implememnt this with "sed"?
Thank you!
Brilliiiiiiiiiiant!!
That's what I want. Thanks a million.
I used
<CODE
Private Sub ChatList_DblClick()
End Sub
</CODE>
But how can I find out which item is dbl-clicked? Is there any other form of
event handling that could transfer back dbk-clicked...
So happy to know this! Thank you a million!
I'm trying to find out how classpath in ANT works. In a simple build.xml,
I intentionally species the classpath as "." only. I thought this could let ANT
believe not to reference system classpath...
Thank you frog :D
BTW, I wonder if you installed 2 JRE, how do you determine which Java
Plug-ins you use for your browser? The lastest installed one?
Hmm... I don't know how many developers have run into this issue.
The reality is that I have to maintain an app developed under JDK1.1.8
while at the same time I'm using JDK1.5 to develop my own...
Hi Gurus,
I have this practical question. When I browsed job posts, I saw this
requirement often, "case tools". Just wonder what they want you to know
when they ask for skillset about "case...
I dont think it a good idea. You're breaking the rule of Tomcat, and introducing security issue by doing this.
Hi Gurus,
I'm using Eclipse to develop Java. Just wonder if there's a good manual/book for Eclipse beginners, especially UML design, GUI design? Thank you!
Are you kidding us? I bet most people on this board don't read Spanish!
I tried parsing a java file into diagram with ArgoUML. But it seems like that
it doesn't support has-A realtion. am I wrong?
Thank you.
That's waht I want. thank you anyway!
Thank you. But I'm looking for a concatenating character!
Hi Gurus,
import java.io.*;
class Link{
public static void main(String[] arg){
System.out.println("This is a
long line break test!");
}
}
Hi Gurus,
I'm looking for a UML java source file analysis tool. It should be able to import java source file, and export graphic uml diagram. Can ArogoUML do this? If not, is there a easy-to-use...
Just wonder what's the necessary set of files we need to compile?
Besides "javac.exe" and referenced .jar files, do we need more? Thank you.
ArrayList implements interface RandomAccess, while
LinkedList not. I've thought LinkedList doesn't support random
success. However, cgecking its methods, I found out that it DOES!
set(int...
I heard about that we could retrieve the handle of the browser, and apply some API with this handle. Is this plausible? Thank you.
I have this code snippet
Private Sub SearchButton_Click()
Set IEObj = New InternetExplorer
IEObj.Visible = True
IEObj.Navigate2 ""
End Sub
Hi Gurus,
I'm studying java 1.4 collection classes. Just notice some confusing interfaces and abstract classes.
java.util contains such interfaces as:
Collection
List
Map
Set
Also, it... | http://forums.codeguru.com/search.php?s=26f41549857f7510cca9a7b6107b9e9f&searchid=964073 | CC-MAIN-2013-20 | refinedweb | 600 | 78.75 |
exempi - command line tool to manipulate XMP metadata
exempi { -h | [ -R ] [ -x ] [ { -w | -o <file> } ] [ { -g <prop_name> | -s <prop_name> -v <value> } ] } <files>
-h: show this help
-R: don’t reconcile
-x: dump XML
-X: file(s) is XMP
-w: write in place. Only for -s. Not compatible with -o.
-o <file>: file to write the output to.
-n <ns> <prefix>: set the prefix for a namespace.
-g <prop_name>: retrieve the value with prop_name.
-s <prop_name> -v <value>: retrieve or get the value.
<files> the files to read from.
The source code hasn’t been audited for security. The command line tool doesn’t have a strong input sanity checking easier.
Be careful not to run the tool as super-user. Be careful if you decide to use it in an online (web) application.
Patches and suggestions welcome.
Exempi is written by Hubert Figuiere
It contains the XMP SDK written by Adobe Systems Inc.
Exempi is licensed under the BSD license. | http://man.sourcentral.org/f19/1+exempi | CC-MAIN-2019-22 | refinedweb | 160 | 69.48 |
README
calcite-ui-iconscalcite-ui-icons
A collection of UI SVG icons created by Esri for mapping applications.
InstallationInstallation
npm install @esri/calcite-ui-icons --save
DescriptionDescription
Icons use an outlined style. Some icons include an additional filled version.
Every concept has 3 sizes:
- 16x16
- 24x24
- 32x32
Why 3 Sizes?Why 3 Sizes?
More info on what happens when you scale vector based icons here
Outline icons are the standardOutline icons are the standard
Outline icons have the default name. For example,
trash-16.svg will render the default outline icon.
Some icons have alternative states for toggling or greater flexibility. For those icons, appending
-f (
information-16-f.svg) will render the filled version.
Web ComponentWeb Component
For web apps, the easiest way to use calcite-ui-icons is with calcite-components. The calcite-icon component will handle fetching and rendering any icon from this set with the following api:
<calcite-icon</calcite-icon>
Sprite packagesSprite packages
Furthermore, sprites are available in 3 packages and live outside the
icons/ directory:
- sprite-16.svg
- sprite-24.svg
- sprite-32.svg
Alternative filled versions of the outlined icons have
-f appended to their name, and are included in the sprites above.
Icons in the sprite have an
id of the individual SVG file name.
JavaScript ExportsJavaScript Exports
The icons are also made available as named ES6 exports. This way you can import just the icons you need into your app:
import { arrowLeft16 } from "@esri/calcite-ui-icons"; console.log(arrowLeft16); // => "M16 6v3H5.035l5 5H6.5L0 7.5 6.5 1h3.536l-5 5z"
The icon names will be lower camel case. If the icon name starts with a number (ex. 2d-explore, 3d-glasses) prefix the name with
i. This is due to the fact that JavaScript variables cannot begin with a number. If the icon is a filled alternate, it will have
F at the end of the variable name.
If your build system does not perform tree shaking and dead code removal, there is a chance that importing the icons using this syntax will make your bundle extremely large. If that is the case, you can also import icons directly:
import { lock16F } from "@esri/calcite-ui-icons/js/lock16F.js";
Some icons use multiple paths and opacity in their construction, for these the data structure will be as follows:
import { imageLayer16 } from "@esri/calcite-ui-icons/js/imageLayer16.js"; console.log(imageLayer16) // => [{ path: "M16 6v3H5.035l5 5H6.5L0 7.5 6.5 1h3.536l-5 5z", opacity: .4 }, ...]
Note: It is not recommended to import the entire library of icons. This will have negative performance implications. Use the technique above to select only the icons your users actually need to download.
TypeScriptTypeScript
Types are also available for projects leveraging TypeScript.
CalciteIconPath describes all exported icons (both single and multipath) while
CalciteMultiPathEntry describes an individual path from a multipath icon.
JSON FormatJSON Format
All icons are also provided as part of a JSON file. If you installed via npm, you can import the full icon data set using the following:
var calciteIcons = require('@esri/calcite-ui-icons/docs/icons.json');
This will give you an object containing all the icons in the library at all sizes:
{ version: '{current version number}', icons: { blog: { alias: ['social'], category: 'Social-Media', 16:['M15.541...'], 24:['M23.756...'], 32:['M31.618...'] }, "image-layer": { alias:[ "raster", ...], category:"GIS", multiPath: true, 16:[{ path: "M16...", opacity: .4 }, ...], 24:[{ path: "M127...", opacity: .4 }, ...], 32:[{ path: "M112...", opacity: .4 }, ...] }, ... } }
Note: path data omitted for brevity.
Most icons will have simple strings as path data, but some will be more complex as they need to store not only path, but opacity as well for multiple shapes. Icons of this structure will be anotated with the
multiPath flag.
Individual icons structureIndividual icons structure
All the individual SVG icons have a common file structure.
This is what the
close-16.svg looks like:
<svg xmlns="" viewBox="0 0 16 16"> <path d="M0 10V7h10.965l-5-5H9.5L16 8.5 9.5 15H5.964l5-5H0z"/> </svg>
None of the icons have
stroke attributes. The
fill attribute can be defined with css:
svg { fill: gray; }
All the other styling properties applicable to the whole svg element are applicable.
svg:hover { fill: blue; }
Build PNG icons for mobile and desktopBuild PNG icons for mobile and desktop
For convenient use in iOS & desktop application projects, you can convert all icons to PNG.
First, run
npm install:
npm install
Then:
To create Xcode image sets (for use with iOS, macOS, iPadOS) with a default size:
npm run convert-all-ios
To create Xcode image sets with a specified size (e.g. 44x44):
npm run convert-all-ios:size 44
To create versions for use on desktop in one size:
npm run convert-all-desktop:size 64
To create versions for use on desktop in sizes ranging from 16 to 64, run:
npm run convert-all-desktop-multi
LicensingLicensing
All rights reserved under the copyright laws of the United States and applicable international laws, treaties, and conventions.
This material is licensed for use under the Esri Master License Agreement (MLA), and is bound by the terms of that agreement. You may redistribute and use this code without modification, provided you adhere to the terms of the MLA and include this copyright notice.
See use restrictions at
For additional information, contact: Environmental Systems Research Institute, Inc. Attn: Contracts and Legal Services Department 380 New York Street Redlands, California, USA 92373 USA
ContributingContributing
Please read the contribute document. | https://www.skypack.dev/view/@esri/calcite-ui-icons | CC-MAIN-2022-27 | refinedweb | 918 | 56.35 |
Technical Articles
How to create advanced reports in Onboarding? How to schedule data extracts in Onboarding?
Introduction
SAP Successfactors Onboarding 1.0 is not a source system for HRIS data, hence there are not many documentation or great reporting capabilities within Onboarding 1.0, But It is very important for the integration to be able to run some critical extracts and advance reports for meeting legal and day to day business requirements.
Through this blog, I am trying to explain how a user can create an Onboarding report and schedule data extracts from Onboarding to downstream systems. I will also try to cover common issues that you can face and how to troubleshoot them.
There are couple of KBAs that provide details about Onboarding Reports, but the information is scattered and not connecting the dots from start to end of the process.
Following the below steps in sequence will help in building a successful report/extract
- Check Report Permission
- Download Data Dictionary
- Validate Keys in Data Dictionary
- Create Tag and assign keys
- Create Advance Report
- Create Data Extract
Procedure
Step #1 – Check the authorization to make sure you are able to access Report Center in Onboarding.
Standard security guideline is to have a permission group specially created for report permission. Onboarding does not support any security based on data elements or panel. Once the user gets access to the onboarding report center, he or she can access new hire onboarding, Crossboarding or Offboarding data. How to create permission group…
Create Permission Group
Path: Onboarding > Security > Groups
I will suggest creating the permission group with role type as User hence it does not get any other administrative permission.
2. Assign Users to Groups
Path: Onboarding > Security > Assign Users to Groups
- Select Group from the drop-down.
- Enter employee first or last name and click search.
- Select the employee and click the left arrow to move from Unassigned Users to Assigned Users.
If Onboarding is integrated with BizX, please use User Sync and Permission Sync report to manage the RBP via one central place.
Step #2 – Download the Data Dictionary of the Onboarding Application
The Data Dictionary contains all of the fields that are used in SuccessFactors Onboarding and for the Recruiting and Employee Central integrations.
Path to download the data dictionary
On/Offboarding > Settings > Data Dictionary > Export All
Please make sure you do not modify the standard delivered Tag and associated data fields.
For reporting create your custom tag as per customer requirements and assign the data fields to the custom tag. Tags function like folders to organize and categorize the fields. Data Fields can appear in multiple tags and can be copied to multiple tags by the Onboarding Administrator.
Step #3 – If Data Fields is missing in Data Dictionary
There are couple of incidents like federal panels, where you cannot find the associated data fields/keys. In such scenarios reach out to your implementation partner or SAP Successfactors and ask for the reference fields/Keys details.
How to find the keys of a data field?
Only certified consultant can access this following below steps in super admin
Path: Home > Accounts > Manage HRData
Search an employee record and should be able to find the Key with value.
Once you have the text of the data fields/Keys, create the field with the same naming convention in the data dictionary.
Example: Add data field ‘EmployeeLogin’. This field contains the personnel number of a new hire.
In Data Dictionary, click the new field, a popup window will come, enter the data field name, label and description.
Fields are case sensitive hence make sure you have the correct key information.
If the field is already in the data dictionary, the system will give an error message.
Step #4 – Create a Tag and assign keys
I will suggest creating a Tag in Data Dictionary with the report name and assign all data fields to the tag. This will help in the selection of right data fields and only needed keys will be listed while building the report. It will save a lot of energy and time in finding the fields and avoid the errors.
Path: Onboarding Dashboard > Settings > Data Dictionary > Export Categories > New Tag
You can create the tag in any namespaces, but I will suggest using Integration. Since this is the only one available for data extracts from onboarding.
- Click New Tag which will open a new window and provide a new Tag name.
- In below screen print, I have provided Tag name – NewHire_BiographicalData. You can provide the tag name per your project naming convention.
- Add fields to the Tag, click on the folder name ‘Fields’. A new popup window will show up.
- Make sure namespace and tag are correct on the new window.
- Enter field name, select the field and click the forward arrow to move to the right section. Below screen print for reference where the field ‘FirstName’ is being searched.
- Repeat this process for every field/key. Super admin access would be required for this process.
Step #5 – Create an advance report
Please make a list of all the data fields which you like to report out from Onboarding Application. Make sure you are able to find them in the Data Dictionary. If they are missing, please go back to step #3.
Import Note – As part of the system design, the Advanced Report uses the key names as a header of the generated report. The report does not display the Label or Description of the key in the report header.
Path: Onboarding Dashboard > Reports > Advance Report
- In the Reports tab, click on the Advance Reports and click on the icon ‘Create’
- Report parameters – field definitions
- Report Name – Enter Report Name per project naming convention
- Report Scope – Select the project scope. Keep in mind every user who got the access to Report Tab of the Onboarding application can access all data elements of every new hire.
- Public – This report will be visible for all user who can access Onboarding Report
- Private – Apart from you, only users who got Proxy access can run this report
- Based on Template – If you have a template with already selected keys, click this checkbox.
- Report Template – Select from the drop down the available Template.
Template is a collection of the data fields/keys. This saves time in selecting each key for the report. Once you have the template with all keys, you can use this for additional reports
- Select report fields – Click next and you will be asked to select the listed keys which will be part of the report output.
If you need to add any new data fields, click the three dotted line shown below and in the select HR data key section enter and find a new field.
You can also search the field/key using tag filter shown below.
Select the Filter by Tag.
If you have created the Tag in step 4.1, select from the drop down and select the key.
Note – There is no option to select multiple keys at once. User will have to select one field at a time and make sure to click the icon ‘Add Field’.
The report output will be based on the sequence of the fields as they are selected. The sequence can be changed with the help of icon ‘Move Up and Move down’.
- Set Report Filter – There are number of options to filter the report output as needed.
- Process – Select the process example- onboarding, offboarding etc.
- Date Type – Select the time period based on the date type (start date vs Activity creation date)
- Select Field – Select the key to filter the data and use the operator as per need
Example: Onboarding hire date should be more than 01/01/2019 or employee login (number range) is more than 10000000.
- Save Report as Template – You can now save the current report as a template. This helps to use the existing Template for future report building.
- Now you are able to execute the Report.
It will take a few seconds/minutes to finish the execution of the report based on the data fields selection and volume of the data.Once finished ‘double click the report name’ and download the report output in excel.
Step #6 – Schedule the extract from Onboarding
Advanced Reports cannot be scheduled and will not run automatically. This is a limitation of the advance reports of the Onboarding Tool.
There is an option to extract the data from Onboarding via schedule job. This option is used for integration with SAP ECC or any other HR system of record. The Custom New Hire Data Export Feature is a job at the back end of Onboarding (Super Admin) which enables the application to send a file with a master data record in a CSV or XML format.
This is a good option to send only the delta file at the place sending the data dump.
Only one file can be sent per hour from the Onboarding system. This is system limitation hence a total of 24 files in a day can be generated.
Onboarding system can send the file to SFTP or FTP location. Based on your requirements after the process step is completed, the hourly job collects all transaction data and send the CSV or XML format file to a directory defined in the system configuration. The receiving end can process the file through middleware or manually download from SFTP location.
Note: Please reach out to SAP SuccessFactors support team via ticket for SFTP credentials and to schedule a job in Super Admin of Onboarding Tool.
Prerequisites – Make sure you have the following information and system settings.
- You are able to access Data Dictionary of the Onboarding
Path: Onboarding Dashboard > Settings > Data Dictionary
- List of Custom Tag and Mapped Keys
- Implementation Partner should check to make sure ‘CustomNewHireExportFeature’ is enabled in Super Admin.
Here are the steps to schedule the job:
- Create a Tag in the integration of namespace in the data dictionary. Give the tag name per your project naming standards. As you see I have created one below in the screenshot as “Biographical_Data”
- Once the tag is created, assign keys to tag by moving the fields to the right section using a forward arrow. You can rearrange the fields by icon Up and Down if needed.
- Create custom status
Note: This step can only be processed by SAP Successfactors Support team or Implementation Partner.
- Login to Super Admin and select the account name.
- Select the process and step
- Select Assign Actions and click Add Action
- Define the action properties per below screen print.
- Parameters should be based on customer naming standards.
- Activate CustomNewHireExportFeature in Super AdminNote: This step can only be processed by SAP Successfactors Support team or Implementation Partner.
- Select Features and click CustomNewHireDataExportFeature under Integrations
- Create new custom export and schedule
Note: This step can only be processed by SAP Successfactors Support team or Implementation Partner.
- Select the hours in the schedule
- Enter the email address to receive notification in case job with any issue
- Enter the parameters (refer to the screen print)
- Provide Custom Status Name
- Provide Custom Status Value
- Select the Tag in the dropdown in the field set
- Method – Select SFTP or FTP
- In the case of SFTP – Provide SFTP login information and folder structure
- File Format – CSV or XML document
- If you want custom headers for each key, select the checkbox and provide the name for the custom header separated by a comma
- Provide the name of the file
- At the end click Save and Activate.
I hope this blog helps to understand the principal of Onboarding Tool and how to write the Onboarding, Crossboarding or Offboarding reports.
Please provide your feedback and I will try to improve and incorporate your suggestions.
I will be glad to help you in resolving any issues with Successfactors solution. I can be reached at skype id ‘talk2jain’.
Have a nice day.
Related Knowledge Base Articles for reference
- KBA #2698674 – How to delete an Onboarding Advanced Reports in Onboarding?
- KBA #2082711 – Want to know more information about available reports that administrators can generate?
- KBA #2423857 – Understand why exported report shows data keys as header and not their field name
- KBA #2161955 – How to create the advance report.
- KBA #2349970 – Custom New Hire Data Export Feature – Onboarding 1.0
- KBA #2278872 – The User Sync between Employee Central/BizX and Onboarding Application.
- KBA #2278836 – The User Permission Sync between Employee Central/BizX and Onboarding Application.
- KBA #2441649 – How to Run A Onboarding Reports That Captures The Time Spent In Each Step – Onboarding
- KBA #2442968 – How to enable the Onboarding domain in reporting | https://blogs.sap.com/2019/07/02/how-to-create-advance-reports-in-onboarding-how-to-schedule-data-extracts-in-onboarding/ | CC-MAIN-2021-39 | refinedweb | 2,102 | 61.26 |
Updating Existing iOS Apps
- PDF for offline use:
-
- Xamarin University:
-
- Related Articles:
-
Let us know how you feel about this.
0/250
last updated: 2016-04
Follow these steps to update an existing Xamarin.iOS app to use the Unified API.
Updating an existing app to use the Unified API requires changes to the project file itself as well as to the namespaces and APIs used in the application code.
The Road to 64 Bits
The new Unified APIs are required to support 64 bit device architectures from a Xamarin.iOS mobile application. As of February 1st, 2015 Apple requires that all new app submissions to the iTunes App Store support 64 bit architectures.
Xamarin provides tooling for both Xamarin Studio and Visual Studio to automate the migration process from the Classic API to the Unified API or you can convert the project files manually. While the using the automatic tooling is highly suggested, this article will cover both methods.
Before You Start...
Before you update your existing code to the Unified API, it is highly recommended that you eliminate all compilation warnings. Many warnings in the Classic API will become errors once you migrate to Unified. Fixing them before you start is easier because the compiler messages from the Classic API often provide hints on what to update.
Automated Updating
Once the warnings have been fixed, select an existing iOS project in Xamarin Studio or Visual Studio and choose Migrate to Xamarin.iOS Unified API from the Project menu. For example:
You'll need to agree to this warning before the automated migration will run (obviously you should ensure you have backups/source control before embarking on this adventure):
The tool basically automates all the steps outlined in the Update Manually section presented below and is the suggested method of converting an existing Xamarin.iOS project to the Unified API.
Steps to Update Manually
Again, once the warnings have been fixed, follow these steps to manually update Xamarin.iOS apps to use the new Unified API:
1. Update Project Type & Build Target
Change the project flavor in your csproj files from
6BC8ED88-2882-458C-8E55-DFD12B67127B to
FEACFBD2-3405-455C-9665-78FE426C6842. Edit the csproj file in a text editor, replacing the first item in the
<ProjectTypeGuids> element as shown:
Change the Import element that contains
Xamarin.MonoTouch.CSharp.targets to
Xamarin.iOS.CSharp.targets as shown:
2. Update Project References
Expand the iOS application project's References node. It will initially show a broken monotouch reference similar to this screenshot (because we just changed the project type):
Right-click on the iOS application project to Edit References, then click on the monotouch reference and delete it using the red "X" button.
Now scroll to the end of the references list and tick the Xamarin.iOS assembly.
Press OK to save the project references changes.
3. Remove MonoTouch from Namespaces
Remove the MonoTouch prefix from namespaces in
using statements or wherever a classname has been fully qualified (eg.
MonoTouch.UIKit becomes just
UIKit).
4. Remap Types
Native types have been introduced which replace some Types that were previously used, such as instances of
System.Drawing.RectangleF with
CoreGraphics.CGRect (for example). The full list of types can be found on the native types page.
5. Fix Method Overrides
Some
UIKit methods have had their signature changed to use the new native types (such as
nint). If custom subclasses override these methods the signatures will no longer match and will result in errors. Fix these method overrides by changing the subclass to match the new signature using native types.
Examples include changing
public override int NumberOfSections (UITableView tableView) to return
nint and changing both return type and parameter types in
public override int RowsInSection (UITableView tableView, int section) to
nint.
Considerations
The following considerations should be taken into account when converting an existing Xamarin.iOS project from the Classic API to the new Unified API if that app relies on one or more Component or NuGet Package.
Components
Any component that you have included in your application will also need to be updated to the Unified API or you will get a conflict when you try to compile. For any included component, replace the current version with a new version from the Xamarin Component Store that supports the Unified API and do a clean build. Any component that has not yet been converted by the author, will display a 32 bit only warning in the component store.
NuGet Support
While we contributed changes to NuGet to work with the Unified API support, there has not been a new release of NuGet, so we are evaluating how to get NuGet to recognize the new APIs.
Until that time, just like the components, you'll need to switch any NuGet Package you have included in your project to a version that supports the Unified APIs and do a clean build afterwards.
Note: If you have an error in the form "Error 3 Cannot include both 'monotouch.dll' and 'Xamarin.iOS.dll' in the same Xamarin.iOS project - 'Xamarin.iOS.dll' is referenced explicitly, while 'monotouch.dll' is referenced by 'xxx, Version=0.0.000, Culture=neutral, PublicKeyToken=null'" after converting your application to the Unified APIs, it is typically due to having either a component or NuGet Package in the project that has not been updated to the Unified API. You'll need to remove the existing component/NuGet, update to a version that supports the Unified APIs and do a clean build.
Enabling 64 Bit Builds of Xamarin.iOS Apps
For a Xamarin.iOS mobile application that has been converted to the Unified API, the developer still needs to enable the building of the application for 64 bit machines from the app's Options. Please see the Enabling 64 Bit Builds of Xamarin.iOS Apps of the 32/64 bit Platform Considerations document for detailed instructions on enabling 64 bit builds.
Finishing Up
Whether or not you choose to use the automatic or manual method to convert your Xamarin.iOS application from the Classic to the Unified APIs, there are several instances that will require further, manual intervention. Please see our Tips for Updating Code to the Unified API document for known issues and work around. | https://developer.xamarin.com/guides/cross-platform/macios/unified/updating-ios-apps/ | CC-MAIN-2017-09 | refinedweb | 1,045 | 54.63 |
A table, which contains similar-typed columns of data. More...
#include <vtkTable.h>
A table, which contains similar-typed columns of data.
vtkTable is a basic data structure for storing columns of data. Internally, columns are stored in a vtkDataSetAttributes structure called RowData. However, using the vtkTable API additionally ensures that every column has the same number of entries, and provides row access (using vtkVariantArray) and single entry access (using vtkVariant).
The field data inherited from vtkDataObject may be used to store metadata related to the table.
Definition at line 62 of file vtkTable.h.
Definition at line 67 of file vtkTable.h.
Return 1 if this class is the same type of (or a subclass of) the named class.
Returns 0 otherwise. This method works in combination with vtkTypeMacro found in vtkSetGet.h..
Dump table contents.
If rowLimit is -1 then the full table is printed out (Default). If rowLimit is 0 then only the header row will be displayed. Otherwise, if rowLimit > 0 then Dump will print the first rowLimit rows of data.
Return what type of dataset this is.
Reimplemented from vtkDataObject.
Definition at line 81 of file vtkTable.h.
Return the actual size of the data in kibibytes (1024 bytes).
This number is valid only after the pipeline has updated. The memory size returned is guaranteed to be greater than or equal to the memory required to represent the data (e.g., extra space in arrays, etc. are not included in the return value).
Reimplemented from vtkDataObject.
Get/Set the main data (columns) of the table.
Get the number of rows in the table.
Set the number of rows in the table.
Note that memory allocation might be performed as a result of this, but no memory will be released.
Get a row of the table as a vtkVariantArray which has one entry for each column.
NOTE: This version of the method is NOT thread safe.
Get a row of the table as a vtkVariantArray which has one entry for each column.
Set a row of the table with a vtkVariantArray which has one entry for each column.
Insert a blank row at the end of the table.
Insert a row specified by a vtkVariantArray.
The number of entries in the array should match the number of columns in the table.
Delete a row from the table.
Rows below the deleted row are shifted up.
Get the number of columns in the table.
Get a column of the table by its name.
Get a column of the table by its column index.
Add a column to the table.
Remove a column from the table by its name.
Remove a column from the table by its column index.
Retrieve a value in the table by row and column index as a variant.
Note that this calls GetValueByName internally so that each column array must have its name set (and that name should be unique within the table).
Retrieve a value in the table by row index and column name as a variant.
Set a value in the table by row and column index as a variant.
Set a value in the table by row index and column name as a variant.
Initialize to an empty table.
Reimplemented from vtkDataObject.
Retrieve the table from vtkInformation.
Shallow/deep copy the data from src into this object.
Reimplemented from vtkDataObject.
Returns the attributes of the data object as a vtkFieldData.
This returns non-null values in all the same cases as GetAttributes, in addition to the case of FIELD, which will return the field data for any vtkDataObject subclass.
Reimplemented from vtkDataObject.
Get the number of elements for a specific attribute type (ROW, etc.).
Reimplemented from vtkDataObject.
Holds the column data of the table.
Definition at line 252 of file vtkTable.h.
Holds row information returned by GetRow().
Definition at line 257 of file vtkTable.h. | https://vtk.org/doc/nightly/html/classvtkTable.html | CC-MAIN-2021-10 | refinedweb | 646 | 69.58 |
In the first ten minutes of the episode, I was worried that they were going to take everything that was problematic about Sarah's stated arc in School Reunion and turn it up to 11. Both center around the idea that the companion sits around waiting for the Doctor until she grows old.
But what we get is far more nuanced. Amy became bitter in the 36 years she was left alone, and focuses that bitterness on the Doctor (which seems a bit unfair since she got herself into that mess, but whatever. Who presses the red button instead of the green?). It wasn't like he actually left her behind. She put herself into the fast-stream.
You could make much about how Rory waited 2000 years for Amy while Amy could barely stomach 36, but Rory is not the type to see things that way, nor should we be. Amy has had to fight for her life, again and again, all alone. Rory made the choice to wait, but Amy was stuck in the quarantine facility, and she had to do the best that she could in those circumstances.
So who could blame her for turning into Rousseau from Lost, all badass and mighty eccentric as a result of being deprived of her daughter and her companions (well, the daughter parallel exists, despite Amy and Rory forgetting about Melody, again).
Thankfully, Amy is the one that ends up saving herself. She thinks she's waiting for the Doctor and Rory to save her, but in a lovely twist, it turns out she's waiting for herself.
RORY'S CHOICE
Tom Macrae sets up what seems like a clear choice: older Amy or younger Amy? Rory, bless his heart, is such a good guy that he actually makes it seem like a difficult choice, though of course it isn't. He has to choose between an Amy whose life has passed her by, who has succumbed to bitterness and anger, who is out only for herself, and the Amy he knows (who may yet become all of the things we see in Old-Amy).
You could read the choice as Rory explicitly rejecting an old-aged Amy for the younger model, but that isn't really the choice for him, is it? He loves them both equally. We know that whichever one got out, Rory would do whatever he can for her. He almost accepts that Old-Amy is the only Amy, until the Doctor peskily overheard the original Amy. But Rory still doesn't make that choice. He accepts the option of rescuing them both. He thinks he can do that, and the Doctor lies that of course he can. Sneaky Doctor, depriving both Rory and Amy of agency. The Doctor decides he wants young Amy on the TARDIS, and manipulates them all to that end.
Silly Rory, forgetting Rule #1: The Doctor Lies.
ON THE DOCTOR'S DECISION TO CLOSE THE DOOR
Macrae has reintroduced a dark, manipulative side of the Doctor that we haven't seen since the Sylvester McCoy era. Remember when he tricked Ace into saving the mother she despised? Oh yeah. Is what he did to Old Amy worse? Oh yes.
According to the laws of time, surely he must save Older Amy? I understand how he can make that choice, given that both time-streams exist simultaneously. But who is he to make that choice? Who is he to decide that one lifetime nearing its conclusion is worth less than a life that has yet to be lived? Because this was a real life. This isn't like Donna's fake life in Silence of the Library, it is not a fiction. This brings to mind the erasure of Donna's memory. Would she have been happier had she died, knowing she became a hero, or happier with life as the selfish boor she was before? The Doctor made that choice for Donna. He didn't have the right.
He doesn't have the right to make that choice about Amy either, erasing a world of experience in order to return something more...what...innocent? The only difference this time is that Amy gets to carry on with the Doctor.
What's then troubling is that Old-Amy seems to affirm that choice, deciding her life is worthless, that she no longer has anything to live for. Yes, she died so that Amy could live, but she could have carried on in The Garden, with pet robot Rory (I want a pet robot Rory!).
ON EVERYTHING BEING MAGICALLY BACK TO NORMAL AT THE END
At the end, Rory clearly is not comfortable with everything that's happened, but he seems magically to have forgiven the Doctor. How could he? He recognized that, effectively, the Doctor killed Amy. An older Amy, sure, but isn't the whole point of the episode that she is still Amy? Rory should have stated, right then and there, that he wants to find his daughter and go home. Period.
And what about young Amy? She sees the Doctor and Rory explicitly choose to replace her older self with a younger model. Isn't that every woman's fear? It seems like a bit of a narrative cop-out that Amy is unconscious in that scene. What is Rory going to tell her happened? He can't tell her the honest truth, but I can't picture Rory lying to her either.
And they say relationships are complicated.
ON FORGOTTEN BABY SYNDROME
While young Amy is still a bit of a blank slate at the moment, at least older Amy has some clear drivers: she wants to live. She wants to survive, and she wants to be with Rory. But still, the writers wasted an opportunity with her. When she is asked what she's going to do after they're rescued, she says she's going to go traveling. If the line had simply been that she would go looking for Melody, it would have made so much sense, and it would have been poignant.
36 years is a long time to ponder one's regrets. And would older Amy have any greater regret than never having the chance to see her daughter again, that, in fact, she never even bothered to look for her before she was locked in the quarantine facility?
Anyway, I look forward to next week's episode, though I fully expect the writers to ignore any character growth from this episode.
OTHER
This episode reminds me of when I'd play video games simply so I could bathe in the beauty of the worlds they created, games like Myst, Riven and Obsidian, which had the same sense of beautiful oddness as The Garden does here.
-Am I the only one who wished that the Mona Lisa had "THIS IS NOT A FAKE" scrawled on the back? That would have been a neat bit of continuity.
-Did anyone else noticed how he "action music" specifically called back the action music from Utopia? Are we going to learn that the Master has the Ponds' forgotten baby and has in fact fob-watched the baby from their memories?
-If anyone actually followed the rules of my Pond-centric drinking game, they would be unconscious on the sidewalk in an alcohol-induced coma
It wasn't like he actually left her behind. She put herself into the fast-stream.
They did leave her behind, though. Remember, in the version of history she remembers, 36 years ago she actually saw Rory and the Doctor get in the TARDIS with her older self and leave her.
A lot of these have awesome subtle answers.
What's then troubling is that Old-Amy seems to affirm that choice, deciding her life is worthless, that she no longer has anything to live for. Yes, she died so that Amy could live, but she could have carried on in The Garden, with pet robot Rory
For almost 2000 years, Rory has experienced something of what Older Amy has gone through. When he started to open the door, he wasn't going to try to let her in... he was going to go out and join her. "There can't be two Amy's ON THE TARDIS" and "Which wife do you want?" leads naturally to Rory leaving younger Amy safe with the Doctor and older Amy happy with him. But the fact is, by now older Amy is physically much more tough than he and will force her way onto the TARDIS and die fast rather than fade away, and the only thing stopping her is knowing that it would destroy Rory himself because he would lose both Amys that way. She is not counting her life worthless, she's counting his as worth everything.
On Forgotten Baby Syndrome
Amy has to be thinking about how similar she looks to River, and she definitely will see the parallel between saving young Melody (thus destroying the River she came to know) and saving young Amy (thus destroying herself). In the end, she can do it to herself, but never to her daughter.
Did anyone else noticed how he "action music" specifically called back the action music from Utopia?
What I really noticed was that the same music played as the Doctor shut the TARDIS door between Rory and an Amy who would die and soon would not exist as played in Cold Blood after he had shut the TARDIS door between Amy and a Rory who had died and soon would not exist.
More great thoughts, hope! Really enjoyed your take. For me, the episode has a few too many cheap theatrics for it to be anything more than a pretty good episode. I agree with you that I like how the episode forces the characters to make decisions, and also that I hate how it then tries to absolve them of their choice.
For me the most interesting part of the episode that we get to see (because the actual most interesting part we don't get to see - Amy learning how to survive on her own) is Amy's manipulation of her older self (proving she's learned a trick or two from the Doctor) but then the episode robs us of her having to face the consequence of that act by having her be knocked out.
I thought Karen Gillan did an excellent job this week, but I would have preferred to see Older Amy stick around, Younger Amy trapped in the facility with Rory the Robot where she could grow into the woman she becomes.(Maybe Older Amy could have returned the favor on her younger self and manipulated things so the Doctor and Rory didn't know Younger Amy was still around.)
A good episode and a definite step in the right direction but this episode really only works if these strands of the TARDIS crew's decisions are carried forward.
Which, as you rightly mention, isn't likely to happen, except for maybe in a big wrap-up at the end of the season.
Just have to note: I also thought of the Myst/Riven type game with that garden. The whole facility felt a lot like one of those games, down to the gateways to the entertainment areas.
I was thinking, at the start of the episode, how many times Amy's been left to wait for the Doctor, from the time she was a child, to being held hostage when pregnant, to this episode.
Way too much great stuff in your post to comment on!
Maybe there is still a little bit of that pull for Amy regarding her loyalties, she points out to herself she called her robot Rory, not the Doctor. We've seen, recently, how deeply Amy cares for Rory, once she allowed herself to see it. I think Rory might force her to choose to either have a future together or continue traveling; I think there is a more forceful Rory to come.
Forgotten Melody, though, is perhaps the most intriguing loose end.
Really enjoyed your review - the continued lack of emotional reaction to the loss of Melody is really troubling me, spoiling my enjoyment of otherwise enjoyable and engaging episodes as it makes it so hard to connect to the characters.
"This episode reminds me of when I'd play video games simply so I could bathe in the beauty of the worlds they created, games like Myst, Riven and Obsidian, which had the same sense of beautiful oddness as The Garden does here."
The garden scenes were filmed at Dyffryn Gardens, just outside Cardiff - I recognised it instantly, as I go there often:
I also think something we both forgot in our respective articles is that A.Rory waited 2000 years let alone 36, and B. Rory had no choice when he was wiped out of existence, I think Old Amy had it easier.
if the tardis can't handle the paradox of the same person from 2 time periods, how does it let more than one doctor inside at a time?
Great analysis...I really do share the same concern you do: that all of this is really just being done in the moment for the episode, and all these things that should have greater resonance (like the Ponds losing their daughter) may end up being ignored going forward. I also make this point in my recap, but I would like to see Old Amy back as an antagonist for the Doctor (I agreed with Rory, this was all his fault).
And I'm not sure that I would have just been passed out on the sidewalk if I tried Drain the Pond. I think I would have more pickled and preserved for future generations.
@Sam once she was aware she was in a different time stream, she had to have assumed they'd jump into the TARDIS. She would know they didn't waste time gallivanting.
@mayamaia that is an absolutely fantastic theory about Rory wanting to get out! I never even thought about it that way.
@Mark it would have been great to see Older Amy leave, I agree. What a parallel it would be to seeing their daughter fully grown, if River gets to see her mother suddenly be old.
@I.L. Wolf While I wouldn't want to see an explicit ultimatum, maybe Amy will find out what the Doctor did, leaving her older self behind, and they'll both realize together that it's time to go. That the Doctor fetishizes youth above all else.
@llywela it's spoiling it a bit for me too. At this point I don't even need emotional realism, just a single line to acknowledge this is still going on. Thanks for the link to the pictures!
@Anonymous I don't think it's the TARDIS that has a problem with the paradox, I think it's the universe. The two timelines can exist in the quarantine zone, but not in the real world, at least not without ripping apart the fabric of time.
@Jon I would LOVE to see Old Amy back as an antagonist. I have always thought that at least some companions must grow to hate the Doctor (I always thought Tegan would have founded her own organization to destroy the Doctor, tbh). Maybe it's Old Amy in the astronaut suit...
And lol to being pickled and preserved...
i'm pretty certain the doctor said the tardis couln't deal with the paradox...
OCH - I don't think the issue is that she thinks they wasted their time. The issue is that they consciously chose not to save her. In the version of events she lived through, Rory showed up to save her 36 years late, she saw him in her future in the time glass thingy - and then he and the Doctor left with her future self, and abandoned her.
Regarding the forgotten Melody, I am beginning to suspect that Moffat's mind it has already been dealt with. Amy and Rory grew up with Melody. It's not the same as raising her but I think that's what, in his mind, has resolved it. They saw their baby grow up, they just didn't realize at the time that was what they were seeing.
You bring up a lot of good points. The fact is, that Dr Who, supposedly a children's show, has been dancing around some very adult themes. There was Amy & Rory having their baby stolen. And now last nights episode. I genuinely hope that we start to see this catch up to the characters emotionally. Where are the grieving parents? So far, we've seen very little of that theme. I get the feeling though that Amy and Rory's story with the Doctor is starting to wind down, and hopefully we'll get the emotional payoff that does seem to be lacking.
I don't think older Amy would have continued to exist once the TARDIS left, so she didn't have the option of living on in the garden with robot!Rory.
Rory should have stated, right then and there, that he wants to find his daughter and go home. Period.
But aren't those two things mutually exclusive? Amy and Rory are trapped - the Doctor is by far the best, possibly the only - ticket to them ever seeing Melody/River again.
Excellent, thoughtful review, though. What struck me was that somehow it was easier to forgive the Doctor when he looked gorgeous, yet Ten did all the things Eleven does. He lied, he privileged youth and prettiness over age and experience, he made significant decisions for other people on their behalf and, of course, (as Nine) he callously left a companion behind in an even worse situation.
Great post.
The only moral thing to do here was rescue the old Amy. Rescuing young Amy kills old Amy, rescuing old Amy merely traps young Amy. But that had been done, and those years had passed already. Young Amy could only be talked to because they broke into a time stream with that magnifying glass. Otherwise the story was simple: they were late. But that glass was looking back in time. Amy was having a conversation she had before.
She had lived the life that the young amy was about to, that was done. So the older amy should have been rescued.
( Obviously for the TV show it doesn't make sense unless you want Karen Gillan in prosthetics all the time).
I had some reservations about "The Girl Who Waited" but it was a clear improvement on "Night Terrors" and it was good to see Karen Gillan being allowed to do some proper acting for once and proving she can do more than just blundering around shouting out "Doctor!" a lot.
Because more than one doctor at a time have never tried to rewrite the past so that one of them wouldn't exist.
Actually, the TARDIS *can* hold a paradox like this in place--we've seen it before with the Toclafane. The problem is we're not quite clear if the TARDIS can do anything else while it is a paradox machine.
And in response to the review in general--I don't see it as resolved, I don't see the Doctor as suddenly forgiven by Rory. At that moment the Doctor dismisses himself from the scene so Rory can be with Amy. Then it ends rather abruptly leaving you feeling confused and without closure--probably the same exact way Amy and Rory are feeling!
This is why I love Doctor Who: that a television show can prompt such conversation....
First off, great analysis. You make an excellent point about Rory waiting for 2000 years and Amy only 36- hadn't thought of that. Also love your Mona Lisa graphic at the end- that made literally lol.
I think the Doctor closing the door on Amy was a shock; his almost going into denial about how she wasn't the real one exposed a character flaw that I think is worthy of being explored; that basically, the Doctor can and does screw up, and that when he does, he can't seem to confront it.
But you're right, he dodges Rory's question about him knowing that having both Amy's wouldn't work. It is very 7th Doctor-ish for him to do that.
Here is my (not as good as yours lol) review of the episode from my site.
@Sam that's an interesting thought! I didn't think about that, that that's what might make young Amy turn into bitter old Amy.
@Anonymous, it's true, I think the lack of closure is more of a problem. There are a lot of "serious conversations" that we are not privy to.
@Julia that's interesting, if in his head he doesn't even recognize older Amy as real.
Alright folks, I'm trying out a new comments system! I'm working to
import in all the old comments, so don't worry, the comments all still
exist, but it may take some time to get them back up!
I had a conversation the other day about Melody being conveniently forgotten about in this episode. I'm not entirely sure where I stand on that, though. After Let's Kill Hitler, the Ponds realize that they essentially grew up with her; so, are they still trying to find and raise baby Melody? It seems to me that that ship has sailed - the laws of Time and Narrative tell us that we already know how Melody grew up.
Of course, that depends on how many regenerations Melody has had. You suggest 5 in a previous post, while I suggest 3 in one of mine (), and, well, I think my evidence is pretty strong, although Moffat does love to screw with us.
And we know that Alex Kingston is River's last regeneration. Having her get rescued from the The Library would both cheapen the sacrifice and emotional weight of that story and muck up the Merlin / Nimué parallel that Moffat seems to be making.
All of that is to say: I'm not sure there's a Melody for Amy and Rory to be reunited with, at this point.
I think you're absolutely right that Alex Kingston is River's last generation (even though I'm sure there's a technical out, it would ruin a moment that was heartbreaking long before we even know her. By the way, have you watched that since? I cried through the entire episode.)
Which is why I like to think there is a regeneration in between, that she did get to go off and be badass, otherwise Melody/Mels is quite boringly teen degenerate, and there's nothing to suggest River being quite the badass we're led to believe she is.
I was thinking the same thing about the Mona Lisa! LOL
As far as the forgotten baby, I think now that Amy and Rory know who their daughter turns out to be and knows that she'll be okay, they're not as adamant on finding her. Plus they spent years with her as Mels (although I still thought that felt a little forced), so maybe that makes a difference? However, it's still hard to get over that their daughter was not mentioned once during this episode, when she was the most important thing in previous episodes.
I find it incredibly forced, and not at all plausible. They're parents, for godssakes! Unless they really really don't want to be parents, and no one has hinted that.
"It wasn't like he actually left her behind. She put herself into the fast-stream."
Amy did the EXACT SAME THING that Rory and the Doctor did (and actually, yeah, the reason she pressed the wrong button was because they wandered off and left her behind). There was no reason to believe that pressing the red button would have any negative consequences any more than there was reason to believe that pressing the green button -- equally arbitrary and ~irresponsible~ -- would. I actually can't deal with the idea that it was Amy's fault she got stuck in a parallel timeline for pressing the wrong button any more than I could deal with the idea that if someone chose to go outside it would be their fault if they got struck by lightning. And I really can't deal with the idea that it's unreasonable of her to be angry that they didn't come and get her sooner, that she was left alone in a hostile environment for 36 years by a Doctor who promised to come for her -- just like he promised to be back in "five minutes", just like he promised he'd rescue her daughter -- and failed to follow through.
Great thoughts on the episode. I, too, wish the episode hadn't ended with Amy's question upon awakening, "Where is she?" going unanswered. You may be right, this one may be a "done in one" adventure, never mentioned again; but someone else suggested that Rory's "I don't want to travel with you!" comment may be the beginning of him trying to convince Amy that their TARDIS days should be wrapping up.
I am glad they gave us such a thought-provoking episode -- more like these, please!
A bit late, but I love your thoughts on the episode.
I have to say, Moffat painted himself into a corner with the storylines he picked for Series 6. Kidnapping a baby, choosing between a life lived and a life of potential? These are dark plots that are very smart, very heavy--and have no place in a children's show.
At the end of the day, that is what Doctor Who is. And however hard we wish that the Doctor could live with the consequences of his actions (which we sometimes get to witness), it's inevitable that things would always go back to the way it used to be--because there's the idea that children must be protected from harsh realities such as these.
Now, had Doctor Who been an adult show like Torchwood, I think Moffat would have explored the darkness in the Doctor more.
Oh, and also, this is one of the problems of episodic stories being made to look serialized. It fails. Modern Doctor Who isn't a serial. No matter how hard they try, they always go back to what Doctor Who essentially is: an episodic series with a beginning, a middle, (sometimes a to-be-continued), and an end. And while some thoughts/ideas do crossover to following episodes, they're usually let go after that to enable viewers to jump in whenever they want.
Um. I'm trying to catch up with this AWESOME blog and the many thoughtful comments, but I'm hopelessly overwhelmed.
So, forgive me please if this question has already been thoroughly aired --- but in a series all about lost daughters, where is the Doctor's daughter?
Apparently she married David Tennant. Dirty old man :p
To be honest, I'm not unhappy to see the back of her. Perhaps if she's played by a different actress she might be more interesting.
And thanks for the kind words!
That's a really good point. Though I'm not sure Doctor Who has ever tried so explicitly to be a children's show vs an adult show. The classic series was very good at brining out serious moral issues, and no one would think it was done in a manner inappropriate for children.
In the Peter Davison and Sylvester McCoy episodes particularly, he definitely lives in the consequences of his actions.
I really liked this episode as it shows the doctor's calculating side, the doctor as a chess player. Normally, he's so clever that he finds the perfect solution and everybody is happy; well the 'good' guys at least. For the bad guys, you do all realise that he regularly lurches between genocide and pascism depending on who's writing the episode? The morals in this show are all over the place.
I'm also surprised how many people would save the older Amy. I don't suppose that anybody was upset in the christmas carol episode when he went back in time and completely rewrote Kazran's past. This is a similar calculation. Here he had to choose between leaving Amy for 36 years bitterly fighting for her life and completely on her own, or giving her a better life with Rory and him. It's not really that hard is it.
Of course, it's the execution of this decision that was dirty. He first lied to older Amy and then literally had to close the Tardis door on her. I guess that the real question is what he would have done if older Amy had arrived first.
A lot of people bemoan, Rory and Amy's lack of concern for Melody but in fact, we've not really been allowed to know how they really feel about her. Given the absolutely minimal contact they had with their baby, the extremely confused timelines and a dark suspicion that they can do nothing about the silence keeping their baby inside the spacesuit until she escapes; maybe they're not really sure what to feel. (I've not seen the rest of this series yet). | http://theoncominghope.blogspot.com/2011/09/doctor-who-on-forgotten-wives-and.html | CC-MAIN-2016-44 | refinedweb | 4,946 | 77.57 |
score:-1
When importing the audio file using Typescript, make sure you don't have brackets around the filename.
import audioFile from "./audio_test_sound.mp3"
score:4
Using
require() worked for me
<img id="spriteSheet" src={require("../assets/spritesheet.gif")} hidden={true} />
score:24
If you use create-react-app to setup your React project. You can try to add the follow lines in your
react-app-env.d.ts:
declare module '*.mp3' { const src: string; export default src; }
When you try to import a
mp3 file in
*.tsx, typescript compiler will try to find out its declaration, the same way as you import another class file. But when you try to require a
mp3 file, like this:
<audio src={require('./assets/xxx.mp3')}>
ts will not try to find its declaration, but handle it to webpack loader. This why in this way there is no compile error.
Source: stackoverflow.com
Related Query
- How to fix 'module not found' for audio files using file-loader? Images, CSS, and JSON are working just fine
- How to fix "Failed to load resource: net::ERR_FILE_NOT_FOUND" for static images on cordova app using Reactjs and create-react-app
- How to fix this error : " Module not found :can't resolve popper.js "
- How to fix Next.js Vercel deployment module not found error
- How to require css file using NPM and Meteor?
- CSS and Images files not coming after transpiling package with babel in new CRA
- Next.js pages using Link module not loading files with CSS import
- How to create React App including Web3 using create-react-app? I am getting Module not found Error. BREAKING CHANGE: webpack < 5 used
- How to fix the type error Type '(string | Element) [] is not assignable to type 'string | Element | undefined' using react and typescript?
- how to solve the error that fs module is not found when used react and next.js
- How to preload third-party's css and js files using webpack in ReactJS project?
- How to import custom css files using Chakra UI for React?
- How to get rid of 'Text components are not supported for now in ReactKonva. You text is: "Loading..."' using react-konva and react-google-maps/api?
- how to align two images using DIV which has row and column spanning image and texts in CSS
- Webpack loader configuration to load css and sass files for React JS
- How to fix error type void is not assignable to type using react and typescript?
- How can i restrict user from not selecting other file types using input type file with react and typescript?
- Cloudinary-React Could not find a declaration file for module 'cloudinary-react' - Not using TypeScript
- How do you access images in the public folder from a css file while using react-router-dom?
- RollupJS ES6 module can't get imported because of default not found for redux and redux-form
- How to fix the error type Item[] | undefined is not assignable to Item[] type using react and typescript?
- how to use backdropFilter in js file and not css without error
- import css does not work for class name with dashes for Webpack 5 and css loader 5
- Module not found using npm start for the APP.JS
- How to fix the error argument of type string or undefined is not assignable to parameter of type string using typescript and react?
- How to test the style inside the CSS class for React component using Jest and Enzyme?
- How to fix error "argument of type false is not assignable to (currentValue: boolean) => boolean" using react and typescript?
- How to fix error "argument of type (open: any) => boolean is not assignable to parameter of type boolean" using react and typescript?
- how can I modify react-flip-page width and height using css for media queries?
- How To Fix Invalid argument in `put` at index 0: Expected Blob or File when using React, Firebase and Filepond
More Query from same tag
- yarn install error:Failed to download Chromium
- Unable to pass props to child component in react
- Converting exact animations from desktop to phone (FRAMER API)
- React-select value not resetting to placeholder text on setState
- TypeError: getClientById is not a function when using useEffect in one component
- how can i get useState value inside useCallback (react hook)
- How to do multiple optional params with react-router?
- pre-rendering nextjs getStaticProps() giving an Error: Image is missing required "src" with next/image
- Style cell in react-datasheet-grid
- Cannot find module ReactToPrint
- Redux state - maximum recommended size
- Why is the data from my API not displaying on my chart.js chart in React?
- Does returning null in a component prevents child components from rendering?
- useState, setting icon active and inactive
- How to conditionally render a prop in TSX
- Trying to make a for loop to draw an SVG in React
- npm is showing errors while installing pacakages
- How can I trigger a function when one of my state changes?
- How to filter the props for to render with ReactJS?
- How to add space in a code area using HTML CSS
- Reactjs - Replacing array value from another
- Disable specific days in material ui calendar in React
- React.js: Is there a way to apply a separate style to a component to be rendered in array.map?
- express.js UnhandledPromiseRejectionWarning: error: insert into "table"
- Next.js custom hook for client side and prevent "did not match server/client" error
- Error while using React-table.js in Vue.js
- Why does passing event handler to child component not work
- problems with react-material-ui-carousel - can not display three cards in one row
- Button doesn't load the component
- react organizing links in render method | https://www.appsloveworld.com/reactjs/100/30/how-to-fix-module-not-found-for-audio-files-using-file-loader-images-css-and | CC-MAIN-2022-40 | refinedweb | 947 | 52.49 |
tl;dr; You can download files from S3 with
requests.get() (whole or in stream) or use the
boto3 library. Although slight differences in speed, the network I/O dictates more than the relative implementation of how you do it.
I'm working on an application that needs to download relatively large objects from S3. Some files are gzipped and size hovers around 1MB to 20MB (compressed).
So what's the fastest way to download them? In chunks, all in one go or with the boto3 library? I should warn, if the object we're downloading is not publically exposed I actually don't even know how to download other than using the
boto3 library. In this experiment I'm only concerned with publicly available objects.
f1()
The simplest first. Note that in a real application you would do something more with the
r.content and not just return its size. And in fact you might want to get the
text out instead since that's encoded.
def f1(url): r = requests.get(url) return len(r.content)
f2()
If you stream it you can minimize memory bloat in your application since you can re-use the chunks of memory if you're able to do something with the buffered content. In this case, the buffer is just piled on in memory, 512 bytes at a time.
def f2(url): r = requests.get(url, stream=True) buffer = io.BytesIO() for chunk in r.iter_content(chunk_size=512): if chunk: buffer.write(chunk) return len(buffer.getvalue())
I did put a counter into that for-loop to see how many times it writes and if you multiple that with 512 or 1024 respectively it does add up.
f3()
Same as
f2() but with twice as large chunks/
def f3(url): # same as f2 but bigger chunk size r = requests.get(url, stream=True) buffer = io.BytesIO() for chunk in r.iter_content(chunk_size=1024): if chunk: buffer.write(chunk) return len(buffer.getvalue())
f4()
I'm actually quite new to
boto3 (the cool thing was to use
boto before) and from some StackOverflow-surfing I found this solution to support downloading of gzipped or non-gzipped objects into a buffer:
def f4(url): _, bucket_name, key = urlparse(url).path.split('/', 2) obj = s3.Object( bucket_name=bucket_name, key=key ) buffer = io.BytesIO(obj.get()["Body"].read()) try: got_text = GzipFile(None, 'rb', fileobj=buffer).read() except OSError: buffer.seek(0) got_text = buffer.read() return len(got_text)
Note how it doesn't try to find out if the buffer is gzipped but instead relying on assuming it is plus a raised exception.
This feels clunky, around the "gunzipping", but it's probably quite representative of a final solution.
Complete experiment code here
At first I ran this on my laptop here on my decent home broadband whilst having lunch. The results were very similar to what I later found on EC2 but 7-10 times slower here. So let's focus on the results from within an EC2 node in us-west-1c.
The raw numbers are as follows (showing median values):
I ran each function 20 times. It's interesting, but not totally surprising that the function that was fastest for the large file wasn't necessarily the fastest for the smaller file.
The winners are
f1() and
f4() both with one gold and one silver each. Makes sense because it's often faster to do big things, over the network, all at once.
With a tiny margin,
f1() and
f4() are slightly faster but they are not as convenient because they're not streams. In
f2() and
f3() you have the ability to do something constructive with the stream. As a matter of fact, in my application I want to download the S3 object and parse it line by line so I can use
response.iter_lines() which makes this super convenient.
But most importantly, I think we can conclude that it doesn't matter much how you do it. Network I/O is still king.
Lastly, that
boto3 solution has the advantage that with credentials set right it can download objects from a private S3 bucket.
This experiment was conducted on a
m3.xlarge in us-west-1c. That 18MB file is a compressed file that, when unpacked, is 81MB. This little Python code basically managed to download 81MB in about 1 second. Yay!! The future is here and it's awesome.
Follow @peterbe on Twitter
Sure looks like you should have picked f1 and f4 as your winners.
Yes. Grrr. Typo. Will fix when I'm on a computer.
Nice, I am exactly looking for this kind of analysis
With that size I wouldn't not even bother about performance. Large files to me start with hundreds of megabytes. In other words, something that do not fit into lambdas memory being read in one chunk.
buffer = io.BytesIO(obj.get()["Body"].read())
This line reads the file into memory.
Put a print statement before and after and try on a large file and you will see. | https://api.minimalcss.app/plog/fastest-way-to-download-a-file-from-s3 | CC-MAIN-2020-45 | refinedweb | 843 | 76.01 |
Implementing Microservices Using KumuluzEE
Here's a great guide to getting started with microservices on Kumuluz EE.
Join the DZone community and get the full member experience.Join For Free
A lot of people in the Java ecosphere know about writing embedded microservices (without a separate container) using either Spring Boot or Dropwizard. Both have their merits but neither is completely Java EE oriented. Both reuse some Java EE component, for example Dropwizard uses JAX-RS for REST APIs and both support JPA for persistence. But if you want to use pure Java EE this becomes quite hard (although Spring Boot can be used completely in a Java EE-style).
Recently some new tools have popped up to support Java EE microservices with embedded containers, such as JBoss Swarm, Payara Micro and KumuluzEE. Today, I’ll show how to set up a simple KumuluzEE project. Bear in mind that KumuluzEE is not final and does not support all the Java EE specifications, but for most microservices it does the job.
We’re going to start off adding the necessary dependencies to our build file (Gradle).
compile 'com.kumuluz.ee:kumuluzee-core:1.0.0' compile 'com.kumuluz.ee:kumuluzee-servlet-jetty:1.0.0' compile 'com.kumuluz.ee:kumuluzee-cdi:1.0.0' compile 'com.kumuluz.ee:kumuluzee-jax-rs:1.0.0' compile 'com.kumuluz.ee:kumuluzee-bean-validation:1.0.0'
This adds the necessary dependencies to build a basic REST based microservice.
Next, we’re adding the basic Application class needed for JAX-RS deployments.
@ApplicationPath("/rest/") public class TestApplication extends Application { }
This will set the root path for all the REST endpoints you’ll add. Next, we’re going to add a basic REST endpoint.
@Path("/test") public class TestResource { @GET public int getInt() { return 42; } }
To run the application, you can start it in your IDE using the EeApplication class from KumuluzEE. This class has a main method and will start up the embedded Jetty container and deploy all the EE classes. Nothing more is needed. Alternatively, you can create an uberjar or use Capsule to create a self-running JAR, using the EeApplication as the main class.
That’s all there is to it. KumuluzEE supports the CDI standard, so you can easily add any of the Deltaspike integrations. It also supports JPA out of the box. It does not support JSF or WebSockets yet, but this is to be included in the next version. However, nothing prohibit you to include for example Atmosphere to add support for WebSockets already.
While not as feature-complete as the other players out there (Dropwizard and Spring Boot), KumuluzEE is a welcome addition to the microservices platforms. Check it out here
Opinions expressed by DZone contributors are their own. | https://dzone.com/articles/implementing-microservices-using-kumuluzee | CC-MAIN-2021-31 | refinedweb | 462 | 57.16 |
Windows Communication Foundation From the Inside
XElement has a slightly different way of talking about XML than what WCF uses. This can lead to subtle bugs if you're not careful.
Everywhere you see XML used in WCF, it is processed using an XmlReader and XmlWriter. These classes allow you to work with XML with extremely high performance but the classes themselves are not particularly easy to use. For someone who hasn't used this particular model before, it is surprisingly difficult to create and build up XML documents. XElement is the center of a newer and much easier library of classes for working with XML although it doesn't get quite the same performance as XmlReader and XmlWriter, particularly when doing stream processing.
When working with WCF you'll frequently see a Name and Namespace pair of parameters. These parameters are both string types. The name is the common name and the namespace qualifies the common name so that many people can choose names without having to worry about conflicts. Since the namespace is primarily for avoiding conflicts, some people like to cheat a bit and just use the name in comparisons when conflicts are unlikely.
XElement also has a Name. However, rather than being a string, this name is actually the XName type, which contains both the common name and the namespace. Some people who are used to using the Name in WCF translate that to the Name in XElement, which represents a change in behavior. The correct parallel would be element.Name.LocalName instead of element.Name.
This difference can be hard to spot because it frequently just happens to work if you change both sides of the comparison in the same way at the same time. Additionally, your choice of serializer and contract definition may affect the default namespace. A lot of the older mechanisms and tools used an empty default namespace so again many things will happen to work. Other serializer and contract mechanisms, such as with data contracts, generate temporary namespace, which is much more likely to mysteriously stop working due to failed matches when you change the comparison behavior.
Next time: Examining Header Values
I don't think I ever wrote about the changes made to WCF generated typed proxies in Orcas, although Wenlong | http://blogs.msdn.com/drnick/archive/2008/10/17/working-with-xelement-names.aspx | crawl-002 | refinedweb | 381 | 52.49 |
On Tue, Jan 06, 2009 at 12:48:00PM +0000, Daniel P. Berrange wrote: > There are a number of problems breaking the windows / mingw > build currently. > > - Use of 'close' without importing unistd.h > - Use of non-existant localtime_r oops :-) > - ERROR macro from logging.h clashes with a symbol imported > from windows.h oh, crap, okay we need a namespaced one > So this patch does > > - Adds the missing unistd.h include > - Uses localtime() if localtime_r() is missing (as checked from > configure) > - Adds a VIR_ prefix onto all logging macros, keeping > DEBUG() around because its just used in sooooo many > places > > The use of localtime() on Windows is OK, because the MicroSoft > implementation of this uses thread-local storage: > > > > And all other OS we care about have localtime_r > > Finally I fix a few compile warnings, so that Mingw can now be > built with --enable-compile-warnings=error to detect these > problems more quickly in future. Patch looks fine. But I spotted we still use strerror, I though this had to be discarded because it wasn't thread-safe ? +1 Daniel -- Daniel Veillard | libxml Gnome XML XSLT toolkit daniel veillard com | Rpmfind RPM search engine | virtualization library | https://www.redhat.com/archives/libvir-list/2009-January/msg00053.html | CC-MAIN-2015-14 | refinedweb | 194 | 61.56 |
Bubble Sort method is one of the most basic sorting methods, and the mechanism of bubble sorting is a simple sort method which is implemented by iterating through elements and adjusting the order of neighboring elements. The essence of the bubbling sort is the comparison of the adjacent two elements, and then the position is swapped in ascending or descending order.
Below is the code for descending bubble sort:
public class Training {public static void main (string[] args) { int [] array = {3,2,5,1,4};for (int time = 1; looptime < Array.Length; looptime++) {for (int i = 0,temp = 0; i < array.length-looptime; i++) {if (Array[i+1]>array[i]) {temp = Array[i+1];a RRAY[I+1] = array[i];array[i] = temp;}}} for (int i = 0; i < Array.Length; i++) {System.out.println (array[i]);}}}
the for The loop will place large data in the appropriate position once per cycle, such as Looptime =1 to put the maximum data in the last ; Looptime =2 ; Place the second largest data in the second-to-last element position; Array.length-looptime : from the aspect of improving the performance of the code, the number of cycles of "redundant" loops is reduced.
The following is the result of the operation:
Of course, there is an ascending sort of bubble, in fact, only the "if (Array[i+1]>array[i])" In the Boolean condition is changed to array[i+1]<array[i] can.
for (int i = 0; i < array.length-time; i++) {if (Array[i+1]<array[i]) {temp = a RRAY[I+1];ARRAY[I+1] = array[i];array[i] = temp;}} | http://topic.alibabacloud.com/a/java-sorting-algorithm-the-algorithm-implementation-of-bubble-sort-code_4_89_30002734.html | CC-MAIN-2019-18 | refinedweb | 267 | 51.58 |
Programming in C# with ADO.Net is much easier than it sounds. Microsoft has made it simpler for anyone to connect. ADO.NET has the ADOData class and if you are using a SQL Server Database you can use SQLDataSet classed for betrer speed and performance.
The first thing you need to do is add the following code to the top of the code form.
using System.Data;
The next thing you need to do is to add a ADO connection resource and an ADO Command resource. You can do this two ways. The first way is from the form.cs(design) open up the toolbox click on the Data components and drag and drop an adoConnection and adoDataSetCommand objects into the form.
The following code will be added to your code form.
private System.Data.ADO.ADODataSetCommand adoDataSetCommand1;private System.Data.ADO.ADOConnection adoConnection1;
Next you need to make a connection to the database using the adoConnection and th adoDataSetCommand objects. The connection and command string will look like this:
string sConn = "server=localhost;uid=sa;pwd=;database=northwind";string sCommand ="Select FirstName, LastName FROM Employees";
You then need to connect to the database. This is is done by calling a new ADODataSetCommand object using the command and connection string as the parameters.
ADODataSetCommand DSCmd = new ADODataSetCommand(sCommand, sConn);
So far the ADO.NET has look a lot like the ADO we have come to love and adore. Once we have made the database connection and have queried the Database we are ready for something new. The DataSet Object. The DataSet object. The DataSet Object is more than just an expanded RecordSet. With the DataSet Object you connect to a copy of a database table(s) or even an entire database. Also you are able to read and write to a XML files.
By calling FillDataSet() of the ADODataSetCommand you are able to load a DataSet with data from a database.
DataSet ds = new DataSet();DSCmd.FillDataSet(ds);
Next you need to create a new DataTable and connecting it to your DataSet, by using the method Tables of the DataSet class. DataTable class has several other methods two of which are Columns and Constraints, which returns a collection of columns and constraints respectively.
DataTable dt = ds.Tables["EMPLOYEES"];
You are now ready to get the data from the database. You can use the foreach function along with a DataRow object to access the data quite easily.
foreach(DataRow dr in dt.Rows){listBox1.Items.Add(dr["FirstName"] + ":" +dr["LastName"]};}
To put the data into a grid all you need to do is to create a data grid in the design mode and then after the DSCmd.FillDataSet(ds, "Employees"); use the following code
Datagrid1.DataSource=ds.Tables["Employees"].DefaultView;
This will put the data from the DataSet directly into the Datagrid.
The Complete Code:.
namespace WindowsApplication4{using System;using System.Drawing;using System.Collections;using System.ComponentModel;using System.WinForms;using System.Data; /// <summary>/// Summary description for Form1./// </summary>public class Form1 : System.WinForms.Form{/// <summary>/// Required designer variable./// </summary>private System.ComponentModel.Container components;private System.Data.ADO.ADODataSetCommand adoDataSetCommand1;private System.Data.ADO.ADOConnection adoConnection1;private System.WinForms.ListBox listBox1; public Form1(){//// Required for Windows Form Designer support// InitializeComponent();DataSet ds = new DataSet();adoDataSetCommand1.FillDataSet(ds);DataTable dt = ds.Tables["TREASURY"];foreach(DataRow dr in dt.Rows){listBox1.Items.Add(dr["BASE_LAST_UPDATED"] + ":" +dr["BASE_YIELD"] + " " +dr["COUPON"]); }}
View Relational Data in a DataGrid
ADO Vs ADO.NET Web Service | http://www.c-sharpcorner.com/UploadFile/ho3axp/ado.net.andrew11292005042215AM/ado.net.andrew.aspx | CC-MAIN-2014-10 | refinedweb | 581 | 52.15 |
Automotive Forums .com Car Chat
>
Nissan
>
240SX/Silvia/200SX(RWD)/Gazelle/180SX
> Silvia S15 |
Silvia S15
Silvia S15
Web
AF
LaZy4zNbOi
04-10-2003, 07:27 PM
Hey, I've seen tons of people post up wanting to do conversions to S15s and stuff and people who want to import S15s. I was wondering how many of you would be willing to buy a Nissan Silvia S15 that has no title or anything. But it is the whole car complete from front to back and it does run perfectly well (location in the states). How many of you would want to buy it and how much would you be willing to pay? (reasonable prices)
EDIT: This is just for curiousity reasons. :sun:
Suislide
04-12-2003, 12:17 PM
MORE DETAILS PLEASE!!!! :eek:
LaZy4zNbOi
04-12-2003, 08:10 PM
This is still sorta a long shot S13_Iketani but my friends and I want to build a car for senior project. It wouldn't be exactly building from scratch since i'm getting all the parts for a S15. The problem is we probably won't be able to get a title or anything. I have to do more research into kit car stuff. The thing is right now after adding up the cost of everything we were looking at around 15k. (importing the chasis from asia and all the other parts) We were shooting to make it just about 100% the same as any S15 in asia. But after we finish this project we will all be going off to college. So this baby that we build would have to find a new home. It probably won't be street legal... so its not like we could take it anywhere. I really believe that we can sell the car though for how much we put in. He on the other hand doesn't believe me. So he asked me to put up a poll. How much do you think we could get for this car? Then again it probably won't matter too much later on, cuz he's backin out of this project and planning to put his money into his own car. If we build this it'll be starting this winter.... finish by next summer... would be up for sale sometime in summer 2004 probably. Why you interested?
Suislide
04-12-2003, 10:27 PM
oooh you're putting one together...i dunno about that then. not that i'm dissing your craftsman skills or anything, but i wouldn't buy a kit car that someone else built. i guess i'd rather import a complete, factory built one...depends, i guess.
LaZy4zNbOi
04-12-2003, 10:51 PM
lol major components will be already there... I'm planning to get a S15 chassis with the S15 engine in it already i think i might go all brand new body pieces since there would probably be some dents and stuff in the ones in the junk yards. well it all depends. its not gonna be completely from scratch. Hey if i'm willing to do a few races in the car i'm pretty sure i'm gonna make sure its just as good as outta the factory. If we do build one and sell it, I'll make sure I get a mechanic to do a complete check up and everything. I mean this would be great for like a garage kind of use for off road and racing and stuff... yer going to check the car all the time making sure everything is okay. Well i'm hoping to hit lucky and try to find a car thats intact. I don't want to pay 15k just for the car though. Plus I don't want to do that whole importing through a Independent Commercial Importer and crap. they are just going to rip me off. i don't want any middle man. I don't kno. this is still planning phase. But I would really like to give this a go. I mean you can even visit the car and want to give it a small run near my house that's fine with me. i'm willing to take any picture of the car. i'll even allow you to see the whole car being put together the whole documentation and all. I have nothing to hide. I take pride in my work. its not like i'm a con artist. Yea i guess i understand the whole craftsmanship and everything. Does anyone know if there is a CD Manual out there for the Silvia? I have this Bently CD for my VW and it has everything on it, the amount to torque everything to and etc. i need to get one of these before i start doing stuff to the Silvia. keep posting me opinions and stuff... keeping in mind that the school requires us to spend at least 60 hours on this project. since i don't think i'm doing any major engine stuff... mostly just bolting stuff and little weilding, bolting on doors and body panels and boltin in some seats. that should take up 60 hours.
SR20DETpower
04-15-2003, 02:48 PM
in order for it to be a kit car u cant use the Sr20det as its not a legal engine in the united States. Drop in a KA-T
LMFAO
you can import anythng with no tests and run it as a kit car as long as u put in a different engine that is certified in US.
example while back in SCC I believe they had a US legal Lotus Elise run against a Cobra R.......the only catch....the Elise used an Integra engine.
SR20DETpower
04-15-2003, 02:50 PM
you could make that an awesome F"N project......
import a cheap S15 chassis from japan with a blown motor or something....
find a cheap KA24DE and turbo it and put it in there..... it would be road legal as a Kit car...... like any other old 1920's+ hot rod is........
LaZy4zNbOi
04-15-2003, 11:23 PM
Ugh I just found out I can't import the chassis?!?!?! what the hell!?!?! It has to be imported through an importer? because a chassis is still considered a motor vehicle? well actually doing that KA idea would nice... if i could get the FREAKIN CHASSIS! grrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr rrrrrrrrrr guess i gotta call up some places. anyone really kno the legalities about chassis and bodywork for kit cars?
SR20DETpower
04-16-2003, 07:04 AM
if you had one imported that didn't have an engine in it I don't see much of a problem. check out companies that import cars from Japan.
it would still have to have plates, nessecary lights(which it already has) mirrors all the normal functoining stuff.
LaZy4zNbOi
04-16-2003, 06:11 PM
Yea well thats what I thought too.. but after reading the stupid EPA Kit Car Laws... it doesn't work that way here i'll quote it:
motor or no motor its still considered as a car... :mad:
"Motor vehicles" must comply with the Clean Air Act and may not be disassembled nor purchased in a disassembled form for the purposes of evading the Clean Air Act or the Imports regulations. " :D My actual original plan :D
Oh and this is what PISSES ME OFF!
"the vehicle imported by an eligible ICI who must ensure that the kit car body/chassis complies with all applicable emission requirements. At the present time, there are no ICIs eligible to import kit cars."
GRRRRR CAN WE SAY (Hmmm am i allowed to swear?) FUCKERS! (admin plz edit that out if i'm not suppose to swear).
NSX-R-SSJ20K
05-05-2003, 09:20 AM
17.5 - 22.5 its about what they go for in the UK and what i'm saving for
SR20DETpower
07-29-2003, 03:17 PM
its a hell of a car for the price......weren't they about 20k new..?
too-cool-2
08-13-2003, 07:50 PM
actually the SR20 is legal becasue they used it in a FWD car. Even though they didn't use it in the 240, its still legal. The only thing to worry about is emissions, they wont certify you because of the visual examination.
Shiftlock
09-08-2003, 12:26 PM
Very,Very soon you'll be able to get away with it in Canada.I know it is legal to import S13 Silvias now,but the 88 model came with the CA18DET,which I believe cars 15 years and older have a lot less to comply with.I don't know if their was SR20DET's before 88,but I know they didn't put them into Silvias for another year or two,but the SR20DET(S13) should be able to pass emissions.
aumnsoccer
01-17-2004, 02:37 PM
actually the SR20 is legal becasue they used it in a FWD car. Even though they didn't use it in the 240, its still legal. The only thing to worry about is emissions, they wont certify you because of the visual examination.
logik23
12-12-2004, 12:22 AM
Damn, dude, check the date!!
AWDSR20
12-12-2004, 01:58 PM
why not use the S14 chassie and build on it?
theenlightement
12-14-2004, 06:02 PM
sites for silvia priceing and some for sale
R.W.240
12-14-2004, 06:48 PM
I really hope you didnt register on AF just to lay down some mad knowledge in a year old thread.
Hit_N_Run-player
12-14-2004, 07:22 PM
he is JdM tyte yo!! werd! let this thread die and stop bringing out the shovels!!
Web
AF
vBulletin®, Copyright ©2009, Jelsoft Enterprises Ltd.
Automotive Network, Inc., Copyright ©2009 | http://www.automotiveforums.com/t97463.html | crawl-002 | refinedweb | 1,652 | 82.95 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.