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
harmonizr bring tomorrow's Harmony to today's JavaScript Want to see pretty graphs? Log in now!Want to see pretty graphs? Log in now! npm install harmonizr Harmonizr A "transpiler" that brings tomorrow's Harmony to today's JavaScript. Features: - Harmony modules to AMD, Node.js, or Revealing Module Pattern - Maintains line numbers Demo Look in the demo directory or try it here. Installation $ npm install harmonizr Usage $ ./node_modules/.bin/harmonizr [options] path/to/input If you install Harmonizr globally or have ./node_modules/.bin in your PATH, you can omit the path to the harmonizr script. Specify --amd, --node, or --revealing to transform Harmony-style modules into AMD, Node.js, or JavaScript Revealing Module Pattern- style modules. This transpiles src/foo.js into a Node.js-compatible version at lib/foo.js: $ harmonizr --node --output lib/foo.js src/foo.js Use --module to implicitly wrap the entire file in a module declaration. The name of the module is required, but only appears in the output when using --revealing. Use --relatives with --node to indicate what modules should be loaded from the local directory and not the node_modules directory. For example, if a foo module needs to load bar and baz modules from the same directory as it (not from node_modules), you could do this: $ harmonizr --node --relatives bar,baz --output lib/foo.js src/foo.js Limitations - No nested modules. - No import * from module;. exportis only allowed when in front of a simple function or variable declaration. - Probably bugged. Code The actual source code is in the src directory. The Makefile transpiles that into a Node.js-style module in lib, AMD-style in demo, and Revealing Module Pattern-style in test. Harmonizr transpiles itself. Since Node.js doesn't support the newer syntax harmonizr.js uses in the src directory, it loads the harmonizr module out of the lib directory. Be careful when building. Tests are the test directory. Run them with npm test or by opening test.html. If you'd like to contribute, please try to include tests, ensure the code coverage stays at 100%, and that JSHint doesn't complain. Execute make to build, run JSHint, and run the tests (with code coverage).
https://www.npmjs.org/package/harmonizr
CC-MAIN-2014-15
refinedweb
369
53.17
Can someone please advise what I'm doing wrong with the following method. As an introduction, I've got a class containing currency of various denominations, which need to be added up and a total obtained. The method which I am confused on is supposed to convert each denomination of currency to the lowest value of the currency i.e. 'lambs' in my example. The problem is that when I start timesing (*) an attribute in my class, I get a huge number, much longer then the correct result. The code I am confused about is as follows: def getTotal (self): self.total = self.lamb * 10 + (self.bleat * 10) + (self.frolic * 50) + (self.ram * 100) return self.total In running a test, I commented out everything after self.bleat*10)... and then ran the program typing the values 1 for lamb and 1 for bleat. When the total is printed I expected a result of 11, but instead the result came out as: 11111111111111111111 Any ideas!
http://forums.devshed.com/python-programming/57240-re-method-class-last-post.html
CC-MAIN-2015-27
refinedweb
165
67.96
Microsoft provide an article of the same name (previously published as Q319401) and it shows a nice class 'ListViewColumnSorter ' for sorting a standard ListView when the user clicks the column header. This is very useful for String values, however for Numeric or DateTime data it gives odd results. E.g. 100 would come before 99 in an ascending sort as the string compare sees 1 < 9. So my challenge was to allow other types to be sorted. This turned out to be fairly simple as I just needed to create an inner class in ListViewColumnSorter which extends the .Net CaseInsensitiveComparer class, and then use this as the ObjectCompare member's type. Note: Ideally we would be able to use IComparer as the member's type, but the Compare method is not virtual in CaseInsensitiveComparer , so we have to create an exact type: public class ListViewColumnSorter : IComparer { private CaseInsensitiveComparer ObjectCompare; private MyComparer ObjectCompare; ... rest of Microsofts class implementation... } Here is my private inner comparer class, note the 'new int Compare' as Compare is not virtual, and also note we pass the values to the base compare as the correct type (e.g. Decimal, DateTime) so they compare correctly: You could extend this for other types, even custom classes as long as they support ICompare. Microsoft also have another article How to: Sort a GridView Column When a Header Is Clicked that shows this for WPF, which looks conceptually very similar. I need to test it out to see if it handles non-string types. #
http://geekswithblogs.net/bconlon/archive/2011/02/28/how-to-sort-a-listview-control-by-a-column-in.aspx
CC-MAIN-2017-47
refinedweb
253
50.46
. Urxvt is a clone of rxvt, to which xft fonts and unicode characters support were added. This is an alternative to Xterm, the X default terminal emulator. Installation First step to get Urxvt work is to merge it, so let's do it. # emerge -av rxvt-unicode Most likely, you will want to enable xft use flag so that you can use extra fonts (such as Inconsolata, a pretty good font for terminals). You might also want to enable 256-color use flag to get a larger color range. Configuration It is very likely that when you will launch Urxvt for the first time, you will want to make some customizations so that your terminal doesn't look ugly and fit your tastes. So we will go into it. If it does not exist, create a file ~/.Xresources. You may be used to handle your terminal configuration in ~/.Xdefaults which is generally autoloaded when you start X. However, this method is deprecated. So you should use ~/.Xresources now. If you use a display manager, ~/.Xresources is probably automatically loaded. If this is not the case, you will have to load it manually in your ~/.xinitrc with the command xrdb ~/.Xresources. If you want to split your configuration into multiple files, you can also use the -merge option of xrdb so that the last called file doesn't override the others. Color scheme First thing you might want to do is to change the color scheme. For instance, you may prefer working with white on black: ~/.Xresources- Switch foreground and background URxvt*background: black URxvt*foreground: white The prefix URxvt is optional. It is actually the namespace of the property you define. For instance, if we just wrote *background: black, the background color would have been global to any terminal emulator (Xterm, gnome-terminal, ...). You can also redefine other colors. For instance, I redefined color0 so that it is close to the background color (to display invisible characters in Vim) and color12 to a more readable color than dark blue on black: ~/.Xresources- Change some colors URxvt*color0: #353535 URxvt*color12: #6495ed When editing your colorscheme, it is often useful to reload your ~/.Xresources with xrdb ~/.Xresources and restart your terminal emulator so that you can note changes. Scrolling Maybe the scrollbar on the left annoys you. You can move it to the right or even remove it: ~/.Xresources- Move/Remove the scrollbar ! No scrollbar URxvt*scrollBar: false ! Or scrollbar on the right side URxvt*scrollBar_right: true Font When you spend a lot of time on your terminal, it is important to have a lean and readable font. A good font designed for console is 'Inconsolata. If you want to use it, you have to emerge it first. # emerge -q media-fonts/inconsolata Then, if you want to set your terminal font to Inconsolata with a size of 8px, write the following in your ~/.Xresources. ~/.Xresources- Changing font URxvt*font: xft:Inconsolata:size=8 If you think your the space between letters is too wide (or too nested), you can change it with the letterSpace: n property, which increases the size of the separation between letter by n (or decreases if negative). ~/.Xresources- Alter letters spacing URxvt*letterSpace: -1
http://www.funtoo.org/index.php?title=Toolchain_update&oldid=5866
CC-MAIN-2015-27
refinedweb
538
65.73
Multipage application structure with Sencha CMD Hello, Code:. - Join Date - Mar 2007 - Location - Gainesville, FL - 38,959 - Vote Rating - 1187 You would need to setup some custom ant tasks. I'd stick with singlepage applications tip, it is not perfect but I have already sticked with one page app. BT Hey all I really need to generate multi page app. Can any one help me how to configure it on ant or sencha CMD I think terminology is against us here, but to Cmd a page is an "application". A "workspace" is a container for apps (really pages), packages and frameworks. This collection is more often what developers view as their "application", but I will refrain from using that term here to avoid further confusing the matter. So, generating the workspace is step 1. Code: sencha generate workspace --ext ws Alternatively, you can use the "--sdk" switch if you already have the SDK you want downloaded (perhaps Sencha Touch or Ext JS pre-5): Code: sencha --sdk /path/to/ext51 generate workspace ws Code: cd ws sencha generate app --ext App1 apps/app1 sencha generate app --ext App2 apps/app2 Code: sencha generate package common Code: ws/ ext/ src/ ... packages/ common/ resources/ sass/ src/ package.json apps/ app1/ ... app.json app2/ ... app.json Code: "requires": [ "common" ] Code: cd apps/app1 sencha app build cd ../app2 sencha app build Code: sencha --cwd apps/app1 app build sencha --cwd apps/app2 app build Hope that helps. If you have more specific questions, feel free to ask.Don Griffin Director of Engineering - Frameworks (Ext JS / Sencha Touch) Check the docs. Learn how to (properly) report a framework issue and a Sencha Cmd issue "Use the source, Luke!" dongryphon, Thanks for your reply, I have one more doubt. inside packages/ common/src/ How I can write the code? Is it simply a Ext js Class or. is there any architecture to arrange the code. Can please suggest best way. Yes, the code inside the "src" folder of packages is the same as in the "app" folder of apps: just Ext.define calls to define your classes. I would recommend giving apps and packages their own top-level namespace or they could share a top-level namespace and have their own second level namespace. Option #1 (Top-level namespaces): Code: App1.view.Foo App2.view.Bar Common.view.Baz Code: Acme.app1.view.Foo Acme.app2.view.Bar Acme.common.view.Baz Code: apps/ app1/ app/ view/ Foo.js app2/ app/ view/ Bar.js packages/ common/ src/ view/ Baz.js apps/app1/app.json Code: "sass": { "namespace": "App1" // or "Acme.app1" if you go with Option #2 } Code: "sass": { "namespace": "App2" // or "Acme.app2" if you go with Option #2 } Code: "sass": { "namespace": "Common" // or "Acme.common" if you go with Option #2 }Don Griffin Director of Engineering - Frameworks (Ext JS / Sencha Touch) Check the docs. Learn how to (properly) report a framework issue and a Sencha Cmd issue "Use the source, Luke!" Second-level namespace for app So if I'd like to use second-level namespaces for my apps (e.g., MyCompany.myapp1, MyCompany.myapp2, etc.), what do I use for the Ext.application config name? The Sencha docs say: name : String The name of the Application. This should be a single word without spaces or periods because it is used as the Application's global namespace. All classes in your application should be namespaced under the Application's name - for example if your application name is 'MyApp', your classes should be named 'MyApp.model.User', 'MyApp.controller.Users', 'MyApp.view.Main' etc
https://www.sencha.com/forum/showthread.php?283461-Multipage-application-structure-with-Sencha-CMD&p=1036802
CC-MAIN-2016-18
refinedweb
600
66.13
On Wed, Jun 24, 2009 at 2:22 PM, Reimar D?ffinger <Reimar.Doeffinger at gmx.de>wrote: > On Wed, Jun 24, 2009 at 10:07:47PM +0200, Karl Blomster wrote: > > Frank Barchard wrote: > >> Thank! The types should be possible to deal with. Any suggestions for > a > >> portable 64 bit fseek? > > > > I think > > > > #ifdef _WIN32 > > # ifdef __MINGW32__ > > # define fseeko fseeko64 > > # define ftello ftello64 > > # else > > # define fseeko _fseeki64 > > # define ftello _ftelli64 > > # endif > > #endif > > > > is the closest you're going to get. > > See MinGW patches to add this feature. There is already a bug report with > an unfinished patch. That is the only proper place. Looking at file.c it uses posix /* XXX: use llseek */static int64_t file_seek(URLContext *h, int64_t pos, int whence){ int fd = (intptr_t) h->priv_data; return lseek(fd, pos, whence);} but os_support.h redirects lseek #ifdef __MINGW32__# include <fcntl.h># define lseek(f,p,w) _lseeki64((f), (p), (w))#endif That doesn't seem to handle 64 bit linux/bsd, but it would handle Visual C and Intel C, if the ifdef were removed or changed to #ifdef _WIN32# include <fcntl.h># define lseek(f,p,w) _lseeki64((f), (p), (w))#endif > _______________________________________________ > ffmpeg-devel mailing list > ffmpeg-devel at mplayerhq.hu > >
http://ffmpeg.org/pipermail/ffmpeg-devel/2009-June/071741.html
CC-MAIN-2016-36
refinedweb
204
67.35
valgrind false positives on gcc-generated string routines Bug Description #include <string.h> #include <stdio.h> #include <stdlib.h> main() { char *a = malloc(1); a[0] = '\0'; printf("%lu\n", (unsigned long)strlen(a)); } Compile with "gcc -O2" and run valgrind. ==5977== Invalid read of size 4 ==5977== at 0x400494: main (x.c:9) ==5977== Address 0x51ce040 is 0 bytes inside a block of size 1 alloc'd ==5977== at 0x4C28F9F: malloc (vg_replace_ ==5977== by 0x40048D: main (x.c:7) > http:// > > I think valgrind should simply special-case these kind of out of bounds > checks based on the instruction that was used. Great. Why don't you tell me then how I am supposed to differentiate between a vector load that is deliberately out of bounds vs one that is out of bounds by accident, so I can emit an error for the latter but not for the former? (In reply to comment #1) > Great. Why don't you tell me then how I am supposed to differentiate > between a vector load that is deliberately out of bounds vs one that is > out of bounds by accident, so I can emit an error for the latter but > not for the former? Hey.... I'm a user, you're the developer ;-) I'm really not the right person to ask. I guess there are some signatures... it is a vector load, with at least one element that is still part of an allocated array. Additionally, based on alignment the 'offending load(s)' can not cross a page boundary. Finally, the loaded byte(s) propagate as uninitialized data, but never trigger the 'used uninitialized error'. I suppose that you might get more details in the gcc bugzilla. Can you objdump -d the loop containing the complained-about load, and post the results? So the valgrind message I have is: ==12860== Invalid read of size 8 ==12860== at 0x400A38: integrate_gf_npbc_ (in /data03/ ==12860== by 0x40245B: main (in /data03/ ==12860== Address 0x58e9e40 is 0 bytes after a block of size 272 alloc'd ==12860== at 0x4C26C3A: malloc (in /usr/lib64/ ==12860== by 0x402209: main (in /data03/ The corresponding asm from objdump is: 0000000000400720 <integrate_ 400720: 41 57 push %r15 400722: 41 56 push %r14 400724: 41 55 push %r13 400726: 41 54 push %r12 400728: 49 89 fc mov %rdi,%r12 40072b: 31 ff xor %edi,%edi 40072d: 55 push %rbp 40072e: 53 push %rbx 40072f: 48 83 ec 50 sub $0x50,%rsp 400733: 49 63 18 movslq (%r8),%rbx 400736: 45 8b 09 mov (%r9),%r9d 400739: 48 89 54 24 20 mov %rdx,0x20(%rsp) 40073e: 49 63 50 04 movslq 0x4(%r8),%rdx 400742: 48 89 74 24 a0 mov %rsi,-0x60(%rsp) 400747: 49 63 70 08 movslq 0x8(%r8),%rsi 40074b: 48 8b 84 24 b0 00 00 mov 0xb0(%rsp),%rax 400752: 00 400753: 48 83 c2 01 add $0x1,%rdx 400757: 48 29 da sub %rbx,%rdx 40075a: 48 0f 48 d7 cmovs %rdi,%rdx 40075e: 48 89 54 24 f0 mov %rdx,-0x10(%rsp) 400763: 49 63 50 0c movslq 0xc(%r8),%rdx 400767: 48 8b 6c 24 f0 mov -0x10(%rsp),%rbp 40076c: 48 83 c2 01 add $0x1,%rdx 400770: 48 29 f2 sub %rsi,%rdx 400773: 48 0f af 54 24 f0 imul -0x10(%rsp),%rdx 400779: 48 85 d2 test %rdx,%rdx 40077c: 48 0f 49 fa cmovns %rdx,%rdi 400780: 48 89 da mov %rbx,%rdx 400783: 48 01 db add %rbx,%rbx 400786: 48 0f af ee imul %rsi,%rbp 40078a: 48 89 7c 24 c0 mov %rdi,-0x40(%rsp) 40078f: 48 f7 da neg %rdx 400792: 49 63 78 10 movslq 0x10(%r8),%rdi 400796: 48 01 f6 add %rsi,%rsi 400799: 48 f7 d3 not %rbx 40079c: 48 f7 d6 not %rsi 40079f: 48 89 5c 24 b0 mov %rbx,-0x50(%rsp) 4007a4: 44 89 4c 24 cc mov %r9d,-0x34(%rsp) 4007a9: 48 89 74 24 10 mov %rsi,0x10(%rsp) 4007ae: 48 8b b4 24 88 00 00 mov 0x88(%rsp),%rsi 4007b5: 00 4007b6: 48 29 ea sub %rbp,%rdx 4007b9: 48 8b 6c 24 c0 mov -0x40(%rsp),%rbp 4007be: 48 8d 1c 3f lea (%rdi,%rdi,1),%rbx 4007c2: 8b 36 mov (%rsi),%esi 4007c4: 48 0f af ef im... This seems to me like a bug in gcc. From the following analysis (start reading at 0x400a38), the value loaded from memory is never used -- xmm12 is completely overwritten by subsequent instructions, either in the post-loop block, or in the first instruction of the next iteration. ==12860== Invalid read of size 8 ==12860== at 0x400A38: integrate_gf_npbc_ # def xmm12 (low half loaded, high half zeroed) 4009d8: f2 44 0f 10 24 16 movsd (%rsi,% 4009de: 41 83 c6 01 add $0x1,%r14d 4009e2: f2 0f 10 31 movsd (%rcx),%xmm6 4009e6: 66 44 0f 16 64 16 08 movhpd 0x8(%rsi, 4009ed: f2 41 0f 10 04 17 movsd (%r15,%rdx,1),%xmm0 4009f3: 66 0f 16 71 08 movhpd 0x8(%rcx),%xmm6 4009f8: 66 41 0f 28 dc movapd %xmm12,%xmm3 4009fd: f2 44 0f 10 61 10 movsd 0x10(%rcx),%xmm12 400a03: 66 0f 28 ce movapd %xmm6,%xmm1 400a07: 66 41 0f 16 44 17 08 movhpd 0x8(%r15, 400a0e: 66 44 0f 16 61 18 movhpd 0x18(%rcx),%xmm12 400a14: f2 0f 10 33 movsd (%rbx),%xmm6 400a18: 66 0f 28 d0 movapd %xmm0,%xmm2 400a1c: 48 83 c2 10 add $0x10,%rdx 400a20: 66 41 0f 14 cc unpcklpd %xmm12,%xmm1 400a25: 66 0f 16 73 08 movhpd 0x8(%rbx),%xmm6 400a2a: f2 44 0f 10 63 10 movsd 0x10(%rbx),%xmm12 400a30: 48 83 c1 20 add $0x20,%rcx 400a34: 66 0f 28 c6 movapd %xmm6,%xmm0 # load high half xmm12 (error reported here). low half unchanged. 400a38: 66 44 0f 16 63 18 movhpd 0x18(%rbx),%xmm12 400a3e: 66 0f 28 f1 movapd %xmm1,%xmm6 400a42: 66 0f 59 ca mulpd %xmm2,%xmm1 400a46: 48 83 c3 20 add $0x20,%rbx 400a4a: 41 39 ee cmp %ebp,%r14d # reads low half xmm12 only 400a4d: 66 41 0f 14 c4 unpcklpd %xmm12,%xmm0 400a52: 66 0f 59 f3 mulpd %xmm3,%xmm6 400a56: 66 0f 59 d8 mulpd %xmm0,%xmm3 400a5a: 66 0f 58 f9 addpd %xmm1,%xmm7 400a5e: 66 0f 59 c2 mulpd %xmm2,%xmm0 400a62: 66 44 0f 58 de addpd %xmm6,%xmm11 400a67: 66 0f 58 eb addpd %xmm3,%xmm5 400a6b: 66 0f 58 e0 addpd %xmm0,%xmm4 400a6f: 0f 82 63 ff ff ff jb 4009d8 # (loop head) 400a75: 66 0f 28 c4 movapd %xmm4,%xmm0 400a79: 8b 54 24 a8 mov -0x58(%rsp),%edx # def xmm12 (overwrite both halves) 400a7d: 66 44 0f 28 e7 movapd %xmm7,%xmm12 Similar testcase is gcc's own libcpp/lex.c optimization, which also can access a few bytes after malloced area, as long as at least one byte in the value read is from within the malloced area. See search_line_* routines in lex.c, not just SSE4.2/SSE2, but also even the generic C version actually does this. I guess valgrind could mark somehow the extra bytes as undefined content and propagate it through following arithmetic instructions, complain only if some conditional jump was made solely on the undefined bits or if the undefined bits were stored somewhere (or similar heuristics). (In reply to comment #5) > This seems to me like a bug in gcc. Unfortunately, I'm an asm novice, so I can't tell. I see Jakub is on the CC as well, so maybe he can judge? Alternatively, I can reopen http:// and refer here? (In reply to comment #6) > Similar testcase is gcc's own libcpp/lex.c optimization, which also can access > a few bytes after malloced area, as long as at least one byte in the value read > is from within the malloced area. Those loops are (effectively) vectorised while loops, in which you use standard carry-chain propagation tricks to ensure that the stopping condition for the loop does not rely on the data from beyond the malloced area. It is not possible to vectorise them without such over-reading. By contrast, Joost's loop (and anything gcc can vectorise) are countable loops: the trip count is known (at run time) before the loop begins. It is always possible to vectorise such a loop without generating memory over reads, by having a vector loop to do (trip_count / vector_width) iterations, and a scalar fixup loop to do the final (trip_count % vector_width) iterations. > I guess valgrind could mark somehow the extra bytes as undefined content and > propagate it through following arithmetic instructions, complain only if some > conditional jump was made solely on the undefined bits or if the undefined bits > were stored somewhere (or similar heuristics). Well, maybe .. but Memcheck is too slow already. I don't want to junk it up with expensive and complicated heuristics that are irrelevant for 99.9% of the loads it will encounter. If you can show me some way to identify just the loads that need special treatment, then maybe. I don't see how to identify them, though. Another simple testcase: https:/ I don't think 99% above is the right figure, at least with recent gcc generated code these false positives are just way too common. We disable a bunch of them in glibc through a suppression file or overloading the strops implementations, but when gcc inlines those there is no way to get rid of the false positives. Can't valgrind just start tracking in more details whether the bytes are actually used or not when memcheck sees a suspect read (in most cases just an aligned read where at least the first byte is still in the allocated region and perhaps some further ones aren't)? Force then retranslation of the bb it was used in or something similar? (In reply to comment #9) > I don't think 99% above is the right figure, at least with recent > gcc generated What version of gcc? The #include <stdlib.h> #include <string.h> __attribute_ foo (void *p) { memcpy (p, "0123456789abcd", 15); } int main (void) { void *p = malloc (15); foo (p); return strlen (p) - 14; } testcase where strlen does this is expanded that way with GCC 4.6 (currently used e.g. in Fedora 15) with default options, but e.g. 4.5 or even earlier versions expand this the same way with -O2 -minline- I can see this problem isn't going to go away (alas); and we are seeing similar things on icc generated code. I'll look into it, but that won't happen for at least a couple of weeks. Isn't this exactly the problem that "--partial- http:// I can reproduce this with GCC 4.6, but not with GCC 4.7 or Clang. Hi all, I think I'm also seeing false positives because of vectorization, that unfortunately decreases the usefulness of valgrind. Below is a minimal working example that reproduces problems with std::string. The code is basically extracted from a library I was using (casacore 1.5) and in my software it generates a lot of incorrect "invalid read"s, although the library seems to be valid (although inherriting from string would not be my preferred solution). I hope this example is of use for evaluating the problem further. #include <string> #include <iostream> #include <cstring> #include <malloc.h> class StringAlt : public std::string { public: StringAlt(const char *c) : std::string(c) { } void operator=(const char *c) { std::string: }; typedef StringAlt StringImp; //typedef std::string StringImp; //<-- replacing prev with this also solves issue int main(int argc, char *argv[]) { const char *a1 = "blaaa"; char *a2 = strdup(a1); a2[2] = 0; StringImp s(a1); std::cout << "Assign A2\n"; s = a2; std::cout << s << '\n'; std::cout << "Assign A1\n"; s = a1; std::cout << s << '\n'; char *a3 = strdup(s.c_str()); std::cout << "Assign A3\n"; s = a3; std::cout << s << '\n'; free(a2); free(a3); } Compiled with g++ Debian 4.7.1-2, with "-O2" or "-O3" results in the error below. With "-O0", it works fine. Changing the order of statements can also cause the error to disappear, which makes it very hard to debug. Output: Assign A2 bl Assign A1 blaaa Assign A3 ==20872== Invalid read of size 4 ==20872== at 0x400C5C: main (in /home/anoko/ ==20872== Address 0x59550f4 is 4 bytes inside a block of size 6 alloc'd ==20872== at 0x4C28BED: malloc (vg_replace_ ==20872== by 0x564D911: strdup (strdup.c:43) ==20872== by 0x400C46: main (in /home/anoko/ ==20872== blaaa (In reply to comment #15) Try to rebuild the library with -fno-builtin- -fno-builtin-strdup does indeed get rid of the valgrind message. This bug report relates to two (closed invalid) bug reports in gcc bugzilla. http:// gcc.gnu. org/bugzilla/ show_bug. cgi?id= 47522 gcc.gnu. org/bugzilla/ show_bug. cgi?id= 44183 http:// PR47522 includes a runable example in the first comment. the issue appears to be that vectorization can result in code that loads elements beyond the last element of an allocated array. However, these loads will only happen for unaligned data, where access to the last+1 element can't trigger a page fault or other side effects (according to my interpretation of comments by gcc developers) and are never used. As such, this is considered valid. Since this kind of code will be produced increasingly by gcc, especially for numerical codes (whenever vectorization triggers, essentially) it would be great to have this somehow dealt with in valgrind.
https://bugs.launchpad.net/ubuntu/+source/valgrind/+bug/852760
CC-MAIN-2015-48
refinedweb
2,260
62.01
min¶ - paddle. min ( x, axis=None, keepdim=False, name=None ) [source] Computes the minimum of tensor elements over the given axis - Parameters x (Tensor) – A tensor, the data type is float32, float64, int32, int64. axis (int|list|tuple, optional) – The axis along which the minimum is computed. If None, compute the minimum over all elements of x and return a Tensor with a single element, otherwise must be in the range \([-x.ndim, x.ndim)\). minimum on the specified axis of input tensor, it’s data type is the same as input’s Tensor. Examples import paddle # x is a tensor with shape [2, 4] # the axis is a int element x = paddle.to_tensor([[0.2, 0.3, 0.5, 0.9], [0.1, 0.2, 0.6, 0.7]]) result1 = paddle.min(x) print(result1) #[0.1] result2 = paddle.min(x, axis=0) print(result2) #[0.1 0.2 0.5 0.7] result3 = paddle.min(x, axis=-1) print(result3) #[0.2 0.1] result4 = paddle.min(x, axis=1, keepdim=True) print(result4) #[[0.2] # [0.1]] # y is a Tensor with shape [2, 2, 2] # the axis is list y = paddle.to_tensor([[[1.0, 2.0], [3.0, 4.0]], [[5.0, 6.0], [7.0, 8.0]]]) result5 = paddle.min(y, axis=[1, 2]) print(result5) #[1. 5.] result6 = paddle.min(y, axis=[0, 1]) print(result6) #[1. 2.]
https://www.paddlepaddle.org.cn/documentation/docs/en/api/paddle/min_en.html
CC-MAIN-2021-25
refinedweb
234
61.22
Introduction: A Talking Color Sensor, Based on the AIY Voice Kit Having learned a bit about Braille recently, I was wondering if I could build something using the AIY voice kit for the Raspberry Pi, that may have a real-live benefit for the visually impaired. So described in the following you will find an prototype of a simple color detection device that reads its findings aloud. A more elaborate version of this system might be useful for persons with impaired sight or color blindness. The system is using an Raspberry Pi with an AIY voice HAT attached. A TCS34725 RGB sensor breakout is connected to the I2C port of the HAT. The breakout contains a bright warm white LED to illuminate the object to be analyzed. The breakout was placed in a housing to optimize and standardize measurement conditions. The three color sensor measures about the same three frequency ranges as the color sensors in your eyes. Then the red, green and blue (RGB) values are used to calculate the overall color impression. The nice thing about this special system is that it now tells you the color verbally, using the AIY voice kits' "say" command. Please have a look on the accompanying video. The device might also be useful as an example for an I2C sensor device connected to the AIY voice HAT. Step 1: Materials Used Raspberry Pi 3. ~ 35 US$ or EUR AIY voice kit, with headers soldered to the HAT. ~ 25US$ or EUR Adafruit TCS34725 breakout, with a header soldered. ~ 8 US$ or EUR Jumper cables. A breadboard (optional) For the sensor housing: - a used "Dolce Gusto" coffee capsule - a small round piece of 2mm Forex (PVC foam plate), about 37mm diameter - a non-reflecting black material to cover the inner walls of the housing. I used self-adhesive black rubber foam. Optional: a small switch to evoke the measurements A few drops of plastic glue and a cutter knife. Step 2: Assembly and Usage The Raspberry Pi with the AIY voice HAT was setup as described in the AIY manual. Before assembly, headers were soldered to the ports on the HAT. For the housing of the sensor, a "Dulce Gusto" coffee capsule was emptied, cleaned, and a part of the bottom carefully removed with a knife. You may use something else for this purpose, the coffee capsule just had the right size and shape. A round piece of 2mm Forex was cut from a plate, the breakout was then placed centrally on the Forex plate, the position marked with a felt pen, and a slot for the header on the breakout was cut at the appropriate position. Now the Forex piece was glued onto the housing and the sensor breakout attached to the Forex plate, using a Velcro strip. Then the inner walls were covered with a light absorbing black material, I used a self-adhesive rubber foam. Black cardboard should work as well. Now, using jumper cables, the I2C "3.3V" port of the HAT was connected to "V in" on the sensor, Ground to Gnd, sda to sda and scl to scl. I had used a breadboard to connect both parts, but that's not neccessary. Place the AIY_TCS34725 python script in the src folder and run the script from the dev terminal, entering "sec/AIY_TCS34752.py". You may have to make the python script executable first. When asked, place the sensor unit over the object to be measured, press the button in the AIY device and wait a second or two. Then, based upon the measured RGB and white values, the device first calculates the corresponding hue value, then estimates the color based on this value and communicates them verbally via the AIY voice system, e. g. as "dark red", but also gives the hue value. RGB, hue and brightness (lightness, to be exact) values are also printed to screen. To simplify the color annotation process, the RGB values are transformed into HSV (hue, saturation, value) format. This allows to annotate a color to a certain range of angles (i.e. a pie slice), and pick the color based on the calculated hue value. You need to normalize your device against a white and a black reference. Just measure the whitest and blackest pieces of paper you have available, take a measurement each, and place these values as maximum and minimum values into the code. Only optimal reference values will give a good color recognition. One basic problem is reflection. If you have an object with a glossy or polished surface it will reflect lot of the light emitted by the LED, appearing much lighter than it really is. You may use a sheet of membrane to scatter the light, but you may need to implement a correction factor. In the case of translucent objects, it might be handy to place them on a white paper, otherwise the amount of reflected light will be to small and the object reported as "black". If you want to measure the color of objects that emit light, you should switch off the LED on the breakout by connecting the "LED" port on the breakout to "Ground". Now set the normalization values accordingly. Another general problem is the illumination of the object. The warm white LED on the breakout emits a non-continuous spectrum of light. Therefore certain colors might be over- or underrepresented in the RGB spectrum. For more information on this topic, please have a look on my previous instructables on a colorimeters/ photometers and spectrometers:...... Step 3: The Code The code is a combination of a modification of a code from the AIY voice manual, and the TCS34725 sensor code by Bradspi. I had also tried to use the TCS34725 python code from Adafruit, but had problems run this and some other codes that are using external libraries in combination with the AIY HAT. Any help welcome. As mentioned before, the color annotation is based on a transformation on the RGB to hue values. You must set normalization settings based on experimental measurements of white and black reverence materials. Fill in the absolute values for R, G and B min or max accordingly. The script uses a new version of the "say" command that allows to regulate volume and pitch. In case, you may have to either update the audio.py and tty driver files or delete the "volume and pitch parts" from the script. #!/usr/bin/env python3 # This script is an adaption of the servo_demo.py script for the AIY voice HAT, # optimized for the color recognition uing the Afafruit TCS34725 breakout import aiy.audio import aiy.cloudspeech import aiy.voicehat #from gpiozero import LED # could be helpful for an external LED on servo-port #from gpiozero import Button # could be helpful for an external button on servo-port import time import smbus bus = smbus.SMBus(1) import colorsys def hue2color(hue): # color interpretation based on the calculated hue values if ((hue> 12) and (hue< 26)): # i.e. between 12° and 40°. All settings may require optimization color="orange" return color elif ((hue> 25) and (hue< 70)): color="yellow" return color elif ((hue> 69) and (hue< 165)): color="green" return color elif ((hue> 164) and (hue< 195)): # 180 +/- 15 color="cyan" return color elif ((hue> 194) and (hue< 270)): color="blue" return color elif ((hue> 269) and (hue< 320)): color="magenta" return color elif ((hue> 319) or (hue< 20)): color="red" return color else: print ("something went wrong") def tcs34725(): # measurement and interpretation. # The measurement is performed by the Bradspi TCS34725 script: #... bus.write_byte(0x29,0x80|0x12) ver = bus.read_byte(0x29) # version # should be 0x44 if ver == 0x44: print ("Device found\n") bus.write_byte(0x29, 0x80|0x00) # 0x00 = ENABLE register bus.write_byte(0x29, 0x01|0x02) # 0x01 = Power on, 0x02 RGB sensors enabled bus.write_byte(0x29, 0x80|0x14) # Reading results start register 14, LSB then MSB data = bus.read_i2c_block_data(0x29, 0) clear = clear = data[1] << 8 | data[0] red = data[3] << 8 | data[2] green = data[5] << 8 | data[4] blue = data[7] << 8 | data[6] crgb = "Absolute counts: C: %s, R: %s, G: %s, B: %s\n" % (clear, red, green, blue) print (crgb) time.sleep(1) else: print ("Device not found\n") # normalization and transformation of the measured RGBW values col="" # Maximum values Normalization factors, must be defined experimentally # e.g. vs. a white sheet of paper. Check and correct from time to time. max_bright = 5750 max_red = 1930 max_green = 2095 max_blue = 1980 # Background/Minimum values normalization factors, must be defined experimentally # e.g. vs. black sheet of paper. Check and correct from time to time. min_bright = 750 min_red = 340 min_green = 245 min_blue = 225 # normalized values, between 0 and 1 rel_bright = ((clear - min_bright)/(max_bright - min_bright)) rel_red = ((red - min_red)/(max_red - min_red)) rel_green = ((green - min_green)/(max_green - min_green)) rel_blue = ((blue - min_blue)/(max_blue - min_blue)) hsv_col = colorsys.rgb_to_hsv(rel_red, rel_green, rel_blue) hue = hsv_col[0]*359 if rel_bright > 0.9: col = "white" # if very bright -> white elif rel_bright < 0.1: col = "black" # if very dark -> black else: col = hue2color(hue) # color selection by hue values # print("relative values bright, red, green, blue:") # print (rel_bright, rel_red, rel_green, rel_blue) # print("HSV values (hue, saturation, value):", hsv_col) # print ("hue in ° ",hue) return [col, rel_bright, rel_red, rel_green, rel_blue, hue] def main(): button = aiy.voicehat.get_button() # change Button status led = aiy.voicehat.get_led() # change Button-LED status aiy.audio.get_recorder().start() # buttoni= Button(5) # distance sensor or other external button, connected to servo3/GPIO 05 aiy.audio.say("Hello!", lang="en-GB", volume=50, pitch=100) # volume and pitch require November 2017 revision of audio.py and _tty.py driver! aiy.audio.say("To start, move the sensor above the object. Then press the blue button", lang="en-GB", volume=50, pitch = 100) print("To activate color measurement place sensor above object, then press the blue button") while True: led.set_state(aiy.voicehat.LED.ON) button.wait_for_press() # for external button, replace button by buttoni led.set_state(aiy.voicehat.LED.BLINK) aiy.audio.say("Measuring", lang="en-GB", volume=50, pitch = 100) result = tcs34725() # evokes measurement and interpretation col = result[0] # color, as text hue = str(int(result[5])) # hue in °, as text r_red = str(int(result[2]*255)) # R value, as text r_green = str(int(result[3]*255)) # G value, as text r_blue = str(int(result[4]*255)) # B value, as text r_bright = str(int(result[1]*100)) # W value, as text led.set_state(aiy.voicehat.LED.OFF) if col == "white" or col=="black": bright = "" elif (result[1] >0.69): #brightness/lightness of color bright ="light" elif (result[1] <0.25): bright ="dark" else : bright ="medium" # communiating the results color_text =("The color of the object is " + bright + " " + col) print (color_text) aiy.audio.say(color_text, lang="en-GB", volume=75, pitch=100) hue_text = ("The hue value is "+ hue+ " degrees") print (hue_text) aiy.audio.say(hue_text, lang="en-GB", volume=75, pitch = 100) if __name__ == '__main__': main() Step 4: Some Links and Remarks The TCS34725 sensor data sheet can be found here: The code to read the sensor I have used was described here:... You may find some additional information on color measurements with this and another sensor in my previous instructables:...... Recommendations We have a be nice policy. Please be positive and constructive. If you like this instructable, please vote for it. Thanks, H
http://www.instructables.com/id/A-Talking-Color-Sensor-Based-on-the-AIY-Voice-Kit/
CC-MAIN-2018-17
refinedweb
1,881
63.19
We are given a list of numbers in increasing order, but there is a missing number in the list. We will write a program to find that missing number. For example, when user enters the 5 numbers in that order: 1, 2, 3, 4, 6 then the missing number is 5. To understand this program, you should have the basic knowledge of for loop and functions. Program We are asking user to input the size of array which means the number of elements user wish to enter, after that user is asked to enter those elements in increasing order by missing any element. The program finds the missing element. The logic we are using is: Sum of n integer elements is: n(n+1)/2. Here we are missing one element which means we should replace n with n+1 so the total of elements in our case becomes: (n+1)(n+2)/2. Once we have the total, we are removing all the elements that user has entered from the total, this way the remaining value is our missing number. #include <iostream> using namespace std; int findMissingNo (int arr[], int len){ int temp; temp = ((len+1)*(len+2))/2; for (int i = 0; i<len; i++) temp -= arr[i]; return temp; } int main() { int n; cout<<"Enter the size of array: "; cin>>n; int arr[n-1]; cout<<"Enter array elements: "; for(int i=0; i<n; i++){ cin>>arr[i]; } int missingNo = findMissingNo(arr,5); cout<<"Missing Number is: "<<missingNo; return 0; } Output: Enter the size of array: 5 Enter array elements: 1 2 3 5 6 Missing Number is: 4
https://beginnersbook.com/2017/09/cpp-program-to-find-the-missing-number/
CC-MAIN-2018-05
refinedweb
273
54.97
This document is also available in these non-normative formats: XML, PS, PDF, and TXT. Copyright © 2002 W3C® (MIT, INRIA, Keio), All Rights Reserved. W3C liability, trademark, document use, and software licensing rules apply. This document describes the Web Services Description Working Group's requirements for the Web Services Description specification. This is a W3C Last Call Working Draft of the Web Services Description Requirements document. It is a chartered deliverable of the Web Services Description Working Group (WG), which is part of the Web Services Activity. This document represents the current consensus within the Working Group about Web Services Description requirements. The Working Group does not intend to take this document further than Last Call, except to update this document in response to comments and requests from other Working Groups and the public. The Last Call review period ends on 31 December 2002. Notations 2 Definitions 2.1 Non-normative definitions 2.2 Normative definitions 3 Relationship to WG Charter 4 Requirements 4.1 General 4.2 Simplicity 4.3 Interface Description 4.4 Description of Interactions with a Service 4.5 Messages and Types 4.6 Service Types 4.7 InterfaceBindings 4.8 Reusability 4.9 Extensibility 4.10 Versioning 4.11 Security 4.12 Mapping to the Semantic Web 5 Requirements from other W3C WGs 5.1 XML Protocol 5.2 XForms 5.3 RDF 5.4 P3P A References B Acknowledgments (Non-Normative) The following terminology and typographical conventions have been used in this document. The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted in a manner similar to that described in [IETF RFC 2119]. (Changes from [IETF RFC 2119] are indicated with emphasis.) The requirement is an absolute requirement. The specification produced by the WG must address this requirement. There may exist valid reasons for the WG to ignore this requirement, but the implications of doing so must be understood and weighed before doing so. The requirement is truly optional. The WG may choose to omit the requirement for the sake of scope or schedule. For the sake of process and clarity, each requirement is annotated with meta data. Each requirement has an identification number. The numbers are arbitrary and do not imply any ordering or significance. Draft requirements are annotated to indicate their review status within the WG: A candidate requirement the WG is actively considering but has not yet reached consensus on. To indicate their source, requirements may be annotated with the initials of the original submitter, 'Charter' (from [WSD Charter]), or 'WG' (from WG discussion). The definitions in this section are drawn primarily from [WSDL 1.1] and are intended to be used for purposes of discussion. They are not intended to constrain the results of the WG. . ] [Definition: A Client is a software that makes use of a Web Service, acting as its 'user' or 'customer'.] [Definition: A Message is the basic unit of communication between a Web Service and a Client; data to be communicated to or from a Web Service as a single logical transmission.] [Definition: A sequence of Messages related to a single Web Service action is called an Operation.] [Definition: A logical grouping of operations. An Interface represents an abstract Web Service type, independent of transmission protocol and data format.] [Definition: An association between an Interface, a concrete protocol and/or a data format. An InterfaceBinding specifies the protocol and/or data format to be used in transmitting Messages defined by the associated Interface.] .] [Definition: A collection of EndPoints is called Service.] The Web Services Description WG Charter [WSD Charter] has two sections describing what is in-scope and what is out-of-scope of the problem space defined for the WG. The WG considers all the requirements in Section 1 of [WSD Charter] to be in-scope per the Charter. Reviewers and readers should be familiar with the Web Services Description WG Charter [WSD Charter] because it provides the critical context for the requirements and any discussion of them. The description language MUST allow any programming model, transport, or protocol for communication between peers. (From the Charter. Last revised 23 Apr 2002.) The WG specification(s) MUST describe constructs using the [XML Information Set] model (similar to the SOAP 1.2 specifications [SOAP 1.2 Part 1]). (From JS. Last revised 21 Feb 2002.) Processors of the description language MUST support XML Schema (). See also [XML Schema Part 1]. (From WG discussion. Last discussed 21 Feb 2002.) The description language MUST allow other type systems besides XML Schema () via extensibility. (From WG discussion. Last discussed 21 Feb 2002.) The WG specification(s) schema and examples MUST be written in XML Schema and SHOULD be written in the latest public W3C XML Schema Recommendation. (From WG discussion. Last revised 28 Feb 2002.) The WG specification(s) MUST correct errors/inconsistencies in [WSDL 1.1]. (From KL. Last revised 10 Apr 2002.) The WG specification(s) MUST provide detailed examples, including on-the-wire messages. (From KL. Last revised 10 Apr 2002.) The WG specification(s) SHOULD use available XML technologies. (From JS. Last revised 10 Apr 2002.) The WG specification(s) SHOULD support Web Services that operate on resource constrained devices. (From YF. Last discussed 10 Apr 2002.) The WG specification(s) SHOULD use consistent terminology across all sections of the specification(s). (From KL. Last revised 10 Apr 2002.) The WG MUST register a MIME type for WSDL (perhaps application/wsdl+xml). (From WG discussion. Last revised 27 Jun 2002.) [Rejected, KL] Provide better specification for document name and linking. WSDL 1.1 Section 2.1.1 is over simple. More detailed specification should be provided to define how the import mechanism works, especially how it is related to the import and include mechanism defined in the XML Schema specification [XML Schema Part 1]. (Last revised 10 Apr 2002. Redundant with R005, don't need each individual issue listed in the requirements doc. The WG already has two issues in its issues document for clarifying import, and adding include.) [Rejected, KL] Enable easy Interaction with Upper layers in the Web Services stack. Additional technologies will be required in the future to complete the Web Services architecture. As one of the fundamental layers of the Web Services stack, though WSDL should not depend on any other layers, one of the design goals of WSDL should be easy interaction with upper layers, such as Services composition layers. (Last revised 10 Apr 2002. Success is not measurable.) [Rejected, YF] WSDL specifications should be clear and easy to understand. This clarity implies that considerable editorial effort will be required in the structuring of the narrative through both outline/overview and normative reference material. (Last revised 10 Apr 2002. A specification should be precise. Clear and easy to understand are both very subjective) [Rejected, KL] Support up-to-date XML Schema. In all [WSDL 1.1] examples, the October 2000 version of the XML schema is used:. We understand that the 10/2000 schema was the most up-to-dated schema available at the time WSDL1.1 was released. However, in future versions of WSDL specification, the W3C Recommendation version of the XML schema should be used. The recommendation was released in May 2001 [XML Schema Part 1]:. (Last discussed 21 Feb 2002. Replaced with R098, R099, and R100.) The WG specification(s) MUST be simple to understand and implement correctly. The description language MUST be simple to use. (From the Charter. Last discussed 7 Mar 2002.) The WG specification(s) SHOULD be compatible with existing Web infrastructure. (From the Charter. Last discussed 7 Mar 2002.) [Rejected, Charter] Focus must be put on simplicity, modularity and decentralization. (Last discussed 21 Feb 2002. Replaced with R013, R102, R027.) [Rejected, JS] Be simple to understand and implement correctly; comparable to other widespread Web solutions. (Last discussed 21 Feb 2002. Replaced with R013.) [Rejected, JS] Specification shall be as lightweight as possible, keeping parts that are mandatory to a minimum. (Last discussed 7 Mar 2002. Covered by R013.) [Rejected, JS] Optional parts of the specification should be orthogonal to each other allowing non-conflicting configurations to be implemented. (Last discussed 7 Mar 2002. Good goal, but unnecessary as a specific requirement.) [Rejected, YF] Facilitate the creation of simple applications (fast and easy writing for simple apps). (Last discussed 7 Mar 2002. Merged in R013.) [Rejected, YF] Be possible to compare easily two WSDL Web Services. (Last discussed 7 Mar 2002. May raise intractable semantic issues.) [Rejected, YF] Since WSDL. (Last discussed 7 Mar 2002. Adequately covered by 'simple' in R013.) [Rejected, YF] The WSDL specification must clearly identify conformance requirements in a way that enables the conformance of an implementation of the specification to be tested (see also the W3C Conformance requirements (W3C members only)). (Last discussed 7 Mar 2002. Adequately covered by 'correct' in R013.) The description language MUST describe the Messages accepted and generated by the Web Service. (From the Charter. Last revised 21 Feb 2002.) The description language MUST allow describing application-level error Messages (AKA faults) generated by the Web Service. (From the Charter. Last revised 28 Feb 2002.) The description language MUST describe Messages independent from their use in message exchange patterns and/or InterfaceBindings. (From YF. Last revised 17 Oct 2002.) The description language MUST allow describing sets of Operations that form a logical group. (From JS. Last revised 28 Feb 2002.) The description language MUST allow describing abstract policies required or offered by Services. (From GD. Last revised 11 Apr 2002.) The description language MUST separate design-time from run-time information. (From JS. Last discussed 11 Apr 2002.) The description language MUST provide human-readable comment capabilities. (From the Charter. Last discussed 28 Feb 2002.) The content model for human-readable comment capabilities MUST be open. (From RD. Last discussed 11 June 2002.) The description language SHOULD allow deriving one Interface from another by extension of the logical group of Messages. (From JS. Last discussed 11 June 2002.) The description language SHOULD allow specifying QoS-like policies and mechanisms of a Web Service. For instance, an indication of how long it is going to take a Web Service to process the request. (From WG discussion. Last discussed 12 April 2002.) [Rejected, JS] The language must describe Interfaces separate from their concrete protocol, transport, data format or wire format deployment. (See also R046.) (Last discussed 7 Mar 2002. Covered by R071. ?I think we wrote this to respond to the partition description across multiple files (R071) but then discarded the other requirement (described in the wording of this requirement) that underlies the definition of an Interface versus an InterfaceBinding?) [Rejected, WS], WSDL should be able to model service level attributes/properties. (Last discussed 11 April 2002. Covered by R117, R116, R075.) [Rejected, SK] A Web Service description should be able to define extensible mechanisms for capturing meta-information associated with a message.. Some of the examples of the meta-information are: Some messages of a WS may require authentication information. Some messages of a WS may deal with in a particular Business Domain. For instance, submitPO, may be an overloaded message where one such message primarily deals with RosettaNet. QoS parameters (Last discussed 11 April 2002. Covered by R117, R116, and others.) [Rejected, KL] Distinction between interface definition and implementation definition. A description of a Web Service can be logically divided into three parts: Data type definition, Service Interface definition and Service Implementation definition. The data type definition can be viewed as part of the Service Interface Definition. Analogous to defining an abstract interface in a programming language and having many concrete implementations, a service interface definition can be instantiated and referenced by multiple service implementers. [WSDL 1.1] specification implies such a division by providing the mechanism for dividing a service definition into multiple WSDL documents. WSDL1.1 Section 2.1.2, Authoring Style, shows an example of separating a complete service definition into three documents: data type definition, abstract definitions and specific service bindings. However, this distinction is not clear and reference to each unit is very difficult. To facilitate easier allocation of responsibilities among different organizations (such as standard bodies and service providers) or among different teams within an organization (such as teams related to the different stages of a service's life-cycle: design time/development time, configuration time and run time), a better distinction between Interface definition and Implementation definition should be made in the specification. Elements such as Message, PortType, Operation are abstract interface definitions, and are usually defined at design time. Elements such as InterfaceBinding and Services usually get their value at configuration/deployment/run time. Mixing all these elements together is at least confusing to many people. (Last discussed 11 April 2002. Covered by R083.) [Rejected, KB] Describe Web Services Operations in an abstract format using the XML type system. (Last discussed 11 April, 2002. Covered by R099.) [Rejected, KB] Group logically related Operations together into abstract Interface types. (Last discussed 11 April, 2002. Covered by R041.) [Rejected, Charter] WG should allow different mechanisms, and must define one based on XML Schema. (Last discussed 21 Feb 2002. Covered by R021, R090, R100.) [Rejected, YF] Support abstract interfaces. (Last discussed 28 Feb 2002. Replaced by R109.) [Rejected, YF] Support interfaces derived from abstract interfaces. (Last discussed 28 Feb 2002. Replaced by R109.) [Rejected, KL] The final WSDL specification should be divided into two parts: the first part only focuses on the core interface definition language, and the second part addresses the binding extensions. This requirement concurs with the Charter's requirement for two separate deliverables. (Last discussed 28 Feb 2002. Concern that this over constrains the specification process.) The description language MUST allow describing the functionality associated with one-way messages (to and from the service described), request-response, solicit-response, and faults. (From the Charter. Last revised 28 Feb 2002.) The description language SHOULD allow describing both application data and context data of a Service. (From PF. Last discussed 12 April 2002.) The description language SHOULD allow describing asynchronous message exchange patterns. (From IS. Last discussed 11 April 2002.) The description language SHOULD allow indicating how long a Web Service is going to take to process the request. This is just a hint to the Client, and the Web Service would not be obligated to respect what it advertised. (From WV. Special case of R117.) The description language MAY allow describing events and output-oriented Operations. The description language MAY be very specific about events, defining a special type of a Message or even a separate definition entity. (From IS. Last discussed 12 April 2002.) [Rejected, JS] Describe arbitrary Message exchanges. (Last discussed 11 April 2002. Out of scope.) [Rejected, PF] WSDL is typically used to capture the Web Server requirements on the Client. For example, the Web Server will expect to see certain SOAP headers. When WSDL is used in higher protocols, such as an orchestration language, each side of the exchange may wish to publish their requirements, and the Client may have a requirement on the Web Server. For example, the Client may require the Web Server to set a particular header on the response. In WSDL today, there is an option to try to map this into the 'out-in' or 'out' interactions, by treating them as the 'conjugates' of the corresponding 'in-out' or 'in-only' Operations. However, this is unsatisfactory, as these interactions are not well defined, and there is no way to specify that an out-in is actually the conjugate of an in-out, or simply another Operation that has the same messages in the opposite order. It would be more satisfactory if the concept of 'conjugates' was exposed directly so that the Client side of an interaction could publish their requirements. This could be used by proposal such as flow or orchestration languages. (Last discussed 12 April 2002. Out of scope as a feature - move to use cases.) [Rejected, JJM] Must describe SOAP 1.2 MEP (Message Exchange Pattern) (charter says: "must [...] describe [...] one-way Messages, [...] request-response") (Last discussed 28 Feb 2002. Covered by R036.) [Rejected, JS] Must be able to describe simple one-way Messages, i.e., either incoming or outgoing (event) Messages. (Last discussed 28 Feb 2002. Covered by R036.) [Rejected, JS] Must be able to describe simple request-response-fault Message exchange. (Last discussed 28 Feb 2002. Covered by R036.) The description language MAY allow restricting and/or describing the possible flow of Messages between the Web Service and a Client. The description language MAY in particular allow describing what applicative Fault refers to what incorrect call flow. (Last discussed 11 June 2002. Beyond WG scope.) The description language MUST describe Messages independent from transfer encodings. (From JS. Last discussed 17 Oct 2002.) The description language SHOULD allow describing Messages that include references (URIs) to typed referents, both values and Services. (From PP. Last discussed 11 April, 2002.) [Rejected, JS] Be able to describe Messages that include arrays and nested arrays. (Last discussed 11 April 2002. Subsumed by R100.) [Rejected, JS] Be able to describe the semantic content of messages. (Last revised 11 April 2002. Out of scope.) [Rejected, IS] Be able to describe references to other Web Services (remote) or other Interfaces (EndPoints, local to this WSDL doc) that can be used as parts in Message definitions. Currently (as of [WSDL 1.1]) Message parts refer to data types (described in one or the other schema). The part must also be able to refer to a remote Web Service (WSDL URL/Service/Port) or a local Web Service/EndPoint qualified names. This has to be made clear as part of the standard for WS Clients and Web Service providers. (Last discussed 11 April 2002, covered by R085.) [Rejected, YF] Support grouping functionalities (Operations) that share the same Message-exchange pattern and transport InterfaceBinding. (Last discussed 11 April, 2002. Unclear what problem this "solution" is targeted at.) [Rejected, JR] Be able to classify/categorize [individual] Operations. With the usage of XML schema in the ELEMENT attribute of the PART element (current WSDL spec), it is possible to use a type system as a kind of taxonomy for a semantically enriched description of parameters. To automatically search a suitable Web Service respectively Operation from a set of Web Service descriptions, it is not enough only to consider the parameters but also a kind of Operation "type" (something like a taxonomy on Operations). So I would suggest a kind of ELEMENT or TYPE attribute for Operations. (Last discussed 11 April 2002. Out of scope.) [Rejected, IS] Be able to accommodate namespace clusters with data types (schemas) and Interface definitions (Message / EndPoint / InterfaceBinding). I.e., Service may have several namespaces with types and several other namespaces with Message/EndPoint definitions. That is pretty important for expressing proper OO model of a Service. Very few framework implementations pay attention to this. (In many cases namespaces are flattened out which results in name conflicts.) I guess it is so because namespaces of various type definitions and Message / EndPoint / InterfaceBinding definitions have never been emphasized as a requirement really. (Last discussed 11 April, 2002. This requirement seems to be addressed to poor/incomplete implementations of namespaces.) [Rejected, JS] Must be able to describe Messages using XML Schema simple and complex types. (Last discussed 11 April 2002. Covered by R099.) [Rejected, JS] Be able to describe Messages using other info sets. (Last discussed 11 April, 2002. Covered by R100.) The description language SHOULD group Interfaces into a Service type. (From JS. Last discussed 12 April 2002.) The description language SHOULD allow deriving one Service type from another by extension of the logical group of InterfaceBindings. (From JS. Last discussed 12 April 2002.) [Rejected, PM] Ability to associate a network address with an InterfaceBinding at runtime. For example, it is possible to have a Interface that supports Operations like "Register" and "Notify" where a user will provide an email address that a Web Service can send notifications to when the user registers with the Service. So the network address for the "Notify" Operation needs to be dynamically populated at runtime. (Last discussed 12 April 2002, Covered by R083 and R085, move to use cases.) [Rejected, JS] Be able to name an instance of a EndPoint independent of its address. (Last discussed 12 April 2002. Needs clarification.) [Rejected, JS] Be able to describe a logical group of fully-specified InterfaceBindings without specifying a network address that may be used to communicate with the instance of the InterfaceBinding. That is, be able to describe a Service type. (Prescribes a specific means to fulfill R106.) (Last discussed 12 April 2002, probably covered by R118.) The description language MUST describe EndPoint location using URIs. (From JS.) The description language MUST allow unambiguously mapping any on-the-wire Message to an Operation. (From WG discussion. Last revised 4 Apr 2002.) The description language MUST allow specifying an association between an Interface and one or more concrete protocols and/or data formats. (From the Charter. Last revised 12 Apr 2002.) The description language MUST allow binding of transport characteristics independently of data marshalling characteristics. (From PF. Last discussed 12 April 2002.) The description language MUST allow describing InterfaceBindings to other protocols besides those described in the specification. (From JS. Last revised 11 April 2002.) The WG MUST provide a normative description of the InterfaceBinding for HTTP/1.1 [IETF RFC 2616] GET and POST. (From the Charter. Last revised 28 Mar 2002.) The description language MUST allow binding Interfaces to transports other than HTTP/1.1 [IETF RFC 2616]. (From JS. Last discussed 12 April 2002.) The description language MUST allow describing the structure of incoming and outgoing SOAP 1.2 messages [SOAP 1.2 Part 1], including the contents, encoding, target, and optionality of SOAP 1.2 Header and Body blocks, SOAP RPC blocks, and SOAP Faults. (From JJM. Last revised 12 Apr 2002.) The description language MUST allow describing which SOAP features are offered by or required by an Operation or a Service. (From GD. Last revised 4 Apr 2002.) The WG MUST provide a normative description of the InterfaceBinding for SOAP 1.2 over HTTP/1.1. (From JS. Last revised 28 Mar 2002.) The WG specification(s) MUST ensure that the SOAP 1.2 InterfaceBinding is capable of describing transports other than HTTP. (From the Charter. Last revised 28 Mar 2002.) The normative description of the InterfaceBinding for SOAP 1.2 MUST support the SOAP 1.2 MEP for HTTP GET in and HTTP SOAP out. (From TAG. Last discussed 26 Sep 2002.) The WG specification(s) SHOULD support SOAP 1.2 intermediaries. (From JJM. Last discussed 11 April 2002.) [Rejected, Charter] The WG will make sure that SOAP 1.2 extensibility mechanism can be expressed. (Last discussed 11 April 2002. Covered by R113.) [Rejected, JJ] Based on the XML Protocol Usage Scenario (2.14 S21 Incremental parsing/processing of SOAP messages) and other requirements (a SOAP processor returning a large amount of data as attachment or message) there is a need for a SOAP processor and the SOAP client proxies to be constructed with the notion of data streaming in mind so that applications can scale well. (Especially in the case of dynamic proxy and stub creation scenarios.) This requirement for the SOAP processors imposed a requirement on the WSDL to be descriptive enough (like MIME binding or some kind of extension) to describe so that the Service Provider will do incremental parsing and processing of data (input) and the client can process the return message or attachment the same way. Without this description most of the toolkits will find it difficult to use this SOAP processor advantages for scalability and/or fail in interoperability. (Last discussed 12 April 2002. Covered by R117.) [Rejected, JS] Be able to describe the address for specific EndPoint instances within a Service. (Last discussed 12 April. Covered by R081.) [Rejected, PP] Support all HTTP methods (verbs), including WebDAV and allow the use of non-standard HTTP methods. (Last discussed 12 April 2002. Out of Scope.) [Rejected, JJM] Describe SOAP 1.2 Header and Body's content type. (Charter says: "must define [a mechanism for describing data types and structures] based on XML Schema" and "take into account ending work going on in XML Protocol".) (Last discussed 28 Mar 2002. Covered adequately by R028.) [Rejected, JJM] Describe SOAP 1.2 RPC parameters types (ibid.). (Last discussed 28 Mar 2002. Duplicate of R028.) [Rejected, Charter] It is expected that in the near-term future, Web Services will be accessed largely through SOAP Version 1.2 [SOAP 1.2 Part 1] (the XML-based protocol produced by the XML Protocol Working Group) carried over HTTP/1.1 [IETF RFC 2616], or by means of simple HTTP/1.1 GET and POST requests. Therefore, (a) the WG will provide a normative InterfaceBinding for SOAP Version 1.2 over HTTP, and (b) the WG should provide a normative InterfaceBinding for HTTP/1.1 GET and POST requests. (Last discussed 28 Mar 2002. Covered by R065 and R111, respectively.) [Rejected, JJM] Ensure that SOAP 1.2 bindings to SMTP or BEEP (for example) can be described. (Charter says: "ensure that other SOAP bindings can be described".) (Last discussed 28 Mar 2002. Adequately covered by R062.) [Rejected, JS] Be able to describe the wire format of Messages, including, but not limited to, XML, ASCII, binary, or some combination. (Last discussed 28 Mar 2002. Out of scope; should unambiguously refer to wire format but not describe wire format per se.) [Rejected, KL] Better Specification for InterfaceBinding Extensions. In addition to the core service definition framework, [WSDL 1.1] introduces specific InterfaceBinding extensions for SOAP 1.1, HTTP GET/POST, and MIME, and nothing precludes the use of other InterfaceBinding extensions. To keep the core service definition framework simple, a separate and more detailed specification or technical report should be dedicated for various InterfaceBindings. (Last discussed 28 Mar 2002. Technical requirement merged into R066; editorial prescription over constrains the specification process.) [Rejected, JS] Be able to describe SOAP 1.2 Messages [SOAP 1.2 Part 1]. (Last discussed 28 Mar 2002. Covered by R028.) [Rejected, JS] The WG will provide a normative description of SOAP 1.2 Messages. (Last discussed 28 Mar 2002. Covered by R065.) [Rejected, JS] Be able to describe SOAP 1.2 Header elements and Body elements. (Last discussed 28 Mar 2002. Covered by R028.) [Rejected, JS] Be able to describe SOAP 1.2 Faults. (Last discussed 28 Mar 2002. Covered by R028.) [Rejected, FC] [WSDL 1.1] defines services and operations and their bindings to various protocols. However, the details of how an operation is identified (either generally or specifically in particular bindings) is, shall we say, rather vague. As a result, some implementations use the namespace & element of the first child of Body (in SOAP RPC), others use SOAPAction header (in SOAP over HTTP), others use only the namespace, others the element name, others attempt to match the message type, etc. As a result, interoperability suffers. It seems like a normative model (at least) for operation determination is necessary for interoperability between clients and servers from different vendors. This may be a requirement to define such a requirement for all defined bindings, as opposed to something that can be completely specified in the description. But I believe that such a requirement exists. (Last discussed 4 Apr 2002. Pulled out part that is not covered by R065 into R114.) [Rejected, KB] Apply specific wire-format serializations (InterfaceBindings) for Service types. (Last discussed 4 Apr 2002. Covered by R065, R111, and R067.) [Rejected, KB] Apply in an orthogonal manner specific transport(s) for an InterfaceBinding. (Last discussed 4 Apr 2002. Confusion about the intention of this requirement; perhaps a requirement for partial InterfaceBindings?) [Rejected, MW] Must be able to describe messages that include binary data, where the binary data is transmitted efficiently. (Last discussed 4 Apr 2002. Consider this requirement to be discussing attachments, and consider attachments as part of providing a quality InterfaceBinding to SOAP per R065, R062. If there are attachments for other InterfaceBindings, then it's up to those bindings to provide appropriate support.) The description language MUST allow partitioning a description across multiple files. (From JS.) The description language MUST allow using a description fragment in more than one description. (From JS. Last discussed 12 April 2002.) [Rejected, YF] Support reusability of WSDL documents or parts of documents. (Last discussed 12 April 2002. Covered by R072.).) The description language MUST allow for extension in description language components, including at least message, port type, binding, and service. (From WG discussion. Last discussed 17 Oct 2002.) The description language MUST allow indicating whether a given extension is required or optional. (From JS. Last discussed 12 April 2002.). Last discussed 11 June 2002. Beyond WG scope.) [Rejected, JJM] Must support an open content model. (Charter says: "must support distributed extensibility" and "will look into extending Interface descriptions in a decentralized fashion".) (Last discussed 12 April 2002. Prescribes a specific (but plausible) means to fulfill R012 and R067.) [Rejected, Charter] Developers are likely to want to extend the functionality of an existing Web Service. The WG will look into extending interface descriptions in a decentralized fashion, i.e., without priori agreement with the original interface designers. (Last discussed 12 April 2002. Covered by R058.) [Rejected, JS] Be able to extend Interfaces using mechanisms not explicitly identified in the spec. (Last discussed 12 April 2002. Merged into R067.) [Rejected, JS] Be able to extend Message descriptions using mechanisms not explicitly identified in the spec. (Merged into R067.) [Rejected, JS] Be able to extend Service descriptions using mechanisms not explicitly identified in the spec. (Merged into R067.) [Rejected, IS] Extensible meta definitions. Be able to include typed metadata attributes for any definition element: Message, Operation, Interface, InterfaceBinding, EndPoint, and Service. The attributes may also be hierarchical (i.e., defined in another namespace). (Last discussed 12 April 2002. Attributes is overly prescriptive; definition elements requirement merged in R067; use of namespaces covered by R012.) The description language MUST allow identifying versions of Services. (From PF. Last discussed 12 April 2002.) The description language MUST allow identifying versions of descriptions. (From PF. Last discussed 12 April 2002.) [Rejected, FC] It would be good to allow for versioning of something smaller than a WSDL document. I suspect that tools vendors will "compose" these documents, and they may sometimes contain information about a number of unrelated services (or, more correctly, services that are related in ways other than application semantics (tool vendor, server location, etc)). It would be good if Web Services themselves were versioned, the Web Services being the semantic "unit" being defined. (Last discussed 12 April 2002. Duplicate of R075.) The WG specification(s) SHOULD define an equivalence relation on Service descriptions. (From SW. Last discussed 17 Oct 2002.) [Rejected, JS] Compliance must not preclude building implementations that are resistant to attacks. (Last revised 10 Apr 2002. Vague.) [Rejected, DM] The specification MAY document how a WSDL document can be signed, using XMLDsig, so that a potential user of the WSDL document can establish trust in the information conveyed about the web service. (Last revised 10 Apr 2002.) The WG specification(s) MUST allow providing a mapping from the description language to [RDF]. (From the Charter. Last revised 11 April, 2002.) The description language MUST ensure that all conceptual elements in the description of Messages are addressable by a URI reference [IETF RFC 2396]. (From the Semantic Web. Last discussed 11 June 2002.) These are requirements submitted by other W3C Working Groups and Activities. [Rejected, Charter] The WG will also take into account the encoding work going on in the XML Protocol Working Group. (Last discussed 11 April 2002, This is not a requirement on the specifications we produce, it is a requirement on the behavior of the Working Group.) [Rejected, JS] Coordinate with W3C XML Activity and XML Coordination Group. (Last discussed 11 April 2002, This is not a requirement on the specifications we produce, it is a requirement on the behavior of the Working Group.) This document is the work of the W3C Web Services Description Working Group. The people who have contributed to discussions on www-ws-desc@w3.org are also gratefully acknowledged.
http://www.w3.org/TR/ws-desc-reqs/
crawl-002
refinedweb
5,402
52.26
Difference or Gap of days between two given dates using C# In this tutorial, you will be learning how to find the difference or gap between two dates in C#. The user will enter two dates in the form of DD\MM\YYYY. The total number(gap or difference) of days between two date is an output. Design: There are many approaches to solve this problem: - The first approach is to find the number of days from the date d1 to date d2. - The second approach is to find the number of days(nd1) before the date d1 i.e., from 00/00/0000 and number of days(nd2) before the date d2. The difference between the two days(nd2-nd1) obtained is the actual gap between the two dates. We will implement the second approach as it is straight forward and easy to understand. Example: Let the two dates be: d1 = 2/2/2018 d2=1/2/2019 Count number of days before d1. Let this count be nd1. The leap year contains an extra day that has to be added to nd1. nd1 = year*365+month[i]+dd+number of leap year. where 1<=i<mon and month[] is array of no of days in each month Therefore nd1=2018*365+(31)+2+number of leap years. To calculate the number of leap years: Count of leap year for a date ‘dd/mm/yyyy’ can be calculated using the following formula: - Number of leap years = y/4 – y/100 + y/400 if m > 2 - Number of leap years= (y-1)/4 – (y-1)/100 + (y-1)/400 if m <= 2 (All above divisions must be done using integer arithmetic so that the remainder is ignored) for date 2/2/2018, the number of leap year is: Number of leap years=2017/4-2017/100+2017/400=489 (using 2nd formula as m<=2) Therefore, nd1=2018*365+(31)+2+489=737092 Similarly, find the number of days before date2, i.e nd2=737456 Therefore, the number of days between date1 and date2 is (nd2-nd1) 364 days. Difference between two dates in C# Below shows the program to find the number of days between two dates in C# using the above approach. // C# program two find number of days between two given dates using System; class pgm { public class Date { public int day, mon, year; }; static void get_date(Date d) { Console.WriteLine("Enter day:"); d.day=int.Parse(Console.ReadLine()); Console.WriteLine("Enter month:"); d.mon=int.Parse(Console.ReadLine()); Console.WriteLine("Enter year:"); d.year=int.Parse(Console.ReadLine()); } static int []monthDays = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; // This function counts number of // leap years before the given date static int countLeapYears(Date d) { int years = d.year; // Check if the current year // needs to be considered // for the count of leap years or not if (d.mon <= 2) { years--; } return years / 4 - years / 100 + years / 400; } // This function returns number // of days between two given dates static int getDifference(Date dt1, Date dt2) { // COUNT TOTAL NUMBER OF DAYS // BEFORE FIRST DATE 'dt1' // initialize count using years and day int nday1 = dt1.year * 365 + dt1.day; // Add days for months in given date for (int i = 0; i < dt1.mon- 1; i++) { nday1 += monthDays[i]; } // Since every leap year is of 366 days, // Add a day for every leap year nday1 += countLeapYears(dt1); // SIMILARLY, COUNT TOTAL // NUMBER OF DAYS BEFORE 'dt2' int nday2 = dt2.year * 365 + dt2.day; for (int i = 0; i < dt2.mon - 1; i++) { nday2 += monthDays[i]; } nday2 += countLeapYears(dt2); // return difference between two counts return (nday2 - nday1); } public static void Main(String[] args) { Date dt1 = new Date(); Date dt2 = new Date(); Console.WriteLine("Enter the date in the pattern i.e dd/mm/yy"); Console.WriteLine(" First Date :"); get_date(dt1); Console.WriteLine(" Second Date :"); get_date(dt2); Console.WriteLine("******First Date******"); Console.WriteLine(dt1.day+"\\"+dt1.mon+"\\"+dt1.year) ; Console.WriteLine("******Second Date*****"); Console.WriteLine(dt2.day+"\\"+dt2.mon+"\\"+dt2.year) ; Console.WriteLine("******Result*****"); Console.WriteLine("Difference between two dates is " + Math.Abs( getDifference(dt1, dt2))+" days"); } } // This code is contributed by DEVIPRASAD D MAHALE Output: Enter the date in the pattern i.e dd/mm/yyyy First Date Enter the date:2 Enter the month:2 Enter the date:2018 Second Date: Enter the date:1 Enter the month:2 Enter the date:2019 ********** First Date ********** Date is 2/2/2018 ********** Second Date ********** Date is 1/2/2019 ********** Result ********** Difference between two dates is 364 days. Hope you have understood the above program to find the difference or gap between two given dates in C#.
https://www.codespeedy.com/difference-or-gap-of-days-between-two-given-dates-using-c-sharp/
CC-MAIN-2020-40
refinedweb
778
71.75
On Thursday 16 August 2007 8:40 pm, Richard Guenther wrote: <<snip>> > you are still able to access variables that have just run in a program > after the program is done running. For instance, if I run a program that > declares a="assigned in program", I can later print out that variable in > shell mode. Yes, this is true if your script manipulates global variables. It is equivalent to running the python interpreter on the script using the -i flag, which leaves you in interactive mode after executing the script. Again, you can get a "clean" slate by simply going to the shell menu and selecting restart. This happens automatically if you run another script, each time you hit <F5> you get a clean run, and then you can play around with the results afterwords. The important thing is that the next run is not "tainted" it happens in a clean namespace. As I mentioned before, you can also "protect" against this by simply writing your programs in functions to avoid global variables. I personally put my scripts in a function called main, and I execute that. If I want some data to hang around so that I can play with it, then I poke it into a global variable or two. > So I've worked several Python books and tutorials, written both functional > programs and some OOP, and yet I find myself not real clear on what exactly > IDLE is ... :-( It's not really too mysterious if you're used to read-eval-print loops. The main thing is you need a good understanding of things that produce side-effects. Globals variables are always tricky in that way. The fact that built-in functions are not reserved in Python is just a little extra twist (e.g. you can redefine things like raw_input). > Ah well, at least my ubuntu menu launches IDLE in "normal" mode now. :-) Yeah, now you run into the problem that you can only have 1 IDLE process running at a time. I don't understand why IDLE uses a fixed port. --John > > ----- Original Message ---- > From: John Zelle <john.zelle at wartburg.edu> > To: edu-sig at python.org > Cc: Richard Guenther <heistooheavy at yahoo.com> > Sent: Wednesday, August 15, 2007 9:13:32 AM > Subject: Re: [Edu-sig] Using IDLE with students > > On Wednesday 15 August 2007 9:04 am, Richard Guenther wrote: > > Sorry if this is a bit simplistic: > > > >. > > > > Or, as happened recently "raw_input" gets accidentally assigned to a > > string. Then, any programs that end with "raw_input("Press Enter to exit > > this program")" will cause an error, even though the program script > > itself is fine. > > > > > > Obviously quiting and reloading IDLE will take care of this, but I was > > wondering what else may trip up students using IDLE. Maybe it would be > > nice if IDLE had an option called "Run fresh" that would clear any > > variables first....just musing here. > > Provided you start IDLE in the "normal" mode, running scripts should > execute in a separate subprocess, so the kinds of interactions you describe > here are not really a problem. When running in this mode, you can also do a > "restart" under the shell menu, and this will get you a fresh interactive > environment. > > The problem is that the default IDLE setup in some environments starts up > IDLE with the -n switch that causes it to run without separate subprocesses > for scripts. For example, under Windows, if you right-click on a Python > program and then select "edit with IDLE" it will open in the no-subprocess > mode. I always have my students create a shortcut to IDLE in their working > directories and make sure it starts IDLE without the -n switch, and I > emphasize starting IDLE and then loading programs. > > By the way, another thing that will really help is getting students in the > habit of writing scripts as functions and then just calling the function. > That way variables are local to the function/script regardless of how IDLE > is running (still doesn't solve problems like reassigning built-in > functions though). > > --John -- John M. Zelle, Ph.D. Wartburg College Professor of Computer Science Waverly, IA john.zelle at wartburg.edu (319) 352-8360
https://mail.python.org/pipermail/edu-sig/2007-August/008188.html
CC-MAIN-2014-10
refinedweb
699
71.44
. #include <iostream.h> void myFunction(); // prototype int x = 5, y = 7; // global variables int main() { cout << "x from main: " << x << "\n"; cout << "y from main: " << y << "\n\n"; myFunction(); cout << "Back from myFunction!\n\n"; cout << "x from main: " << x << "\n"; cout << "y from main: " << y << "\n"; return 0; } void myFunction() { int y = 10; //local variable cout << "x from myFunction: " << x << "\n"; cout << "y from myFunction: " << y << "\n\n"; } Difference between pre-defined and user-defined function The user-defined functions are defined by a user as per its own requirement while library functions or pre-defined come with compiler. Example: In the above code, main() function is pre-defined and myFunction() function is user-defined. A function prototype is a declaration of a function that omits the function body but does specify the function's return type, name, arity and argument types. While a function definition specifies what a function does, a function prototype can be thought of as specifying its interface. #include <iostream> using namespace std; void printMessage(void); // this is the prototype! int main () { printMessage(); return 0; } void printMessage (void) { cout << "Hello world!"; } If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for. Ask your questions, our development team will try to give answers to your questions.
http://www.roseindia.net/answers/viewqa/Development-process/22567-C-.html
CC-MAIN-2013-20
refinedweb
222
56.39
I¹ve made a bit of progress here after reading up on Darwin¹s GCC a bit more: ghc --make -no-hs-main -fPIC -optl '-dynamiclib' -optl '-undefined' -optl 'suppress' -optl '-flat_namespace' -o Inv.dylib InverseNormal.hs This dies when it links against haskell¹s own libraries, my guess is because they are position dependant. So the only way I see forward would be to recompile haskell with ³fPIC². This seems like a lot of hassle, so I¹m shelving this for now if anyone has any other (less distruptive) ways to proceed give me a shout even if it means linking statically. Cheers, Phil. Linker error now is: ld: warning codegen with reference kind 13 in _stg_CAF_BLACKHOLE_info prevents image from loading in dyld shared cache ld: absolute addressing (perhaps -mdynamic-no-pic) used in ___stginit_haskell98_Array_ from /usr/local/ghc/6.10.1/lib/ghc-6.10.1/haskell98-1.0.1.0/libHShaskell98-1.0.1. 0.a(Array__1.o) not allowed in slidable image collect2: ld returned 1 exit status On 10/01/2009 02:26, "Phil" <pbeadling at mail2web.com> wrote: > Hi, > > I¹m hitting a problem trying create shared haskell libs to be linked into a C > program on Mac OS X. > > I¹m using the latest download for Leopard from the GHC page: >. >. > > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe at haskell.org > -------------- next part -------------- An HTML attachment was scrubbed... URL:
http://www.haskell.org/pipermail/haskell-cafe/2009-January/053164.html
CC-MAIN-2014-15
refinedweb
230
60.14
Objectives - Understand the I2C bus. - Connect a I2C LCD display. - Send messages to the display. Bill of materials The I2C bus As the integration capacity to place thousands or millions of transistors on a single chip increased, the number of commercial components available, increased exponentially. Each time it was, and it is, easier to manufacture electronic building blocks integrated on a single chip, and soon the thickness of the catalogs of the manufacturers, fattened dangerously. It was relatively easy to find those building blocks but when you design required to use a dozen of these blocks, to assemble them together and get them to communicate effectively became a problem. Therefore, in the early 80s, one of the largest electronics manufacturers (Phillips), proposed a digital communication standard between the different components of an electronic system. It was an open standard that specified the speed rate, voltage levels and the protocol to follow in order to establish that communication. That standard was called Inter Integrated Circuits bus, or IIC, and soon became a de facto standard in the industry. The specifications have been improving over the years, but the basic idea remains the same: - A two wire protocol, one to transmit data, SDA (Serial DAta), and one asynchronous clock, SCL (Serial CLock), to indicate when data is read. Apart from GND and 5V (when required). - Each device connected to the I2C bus has its own 7 bits unique address, so, in theory, we can connect up to 27 = 128 devices. - One of these devices must act as master, that is, it controls the clock. - The clock speed is not required, since it is the master who controls the clock. - The bus is multi master, that is, the master can change, but only one can be active at a time, and provides a arbitration and collision detection protocol. (If you have not understood this, do not worry, it’s still early). The I2C bus can be also called IIC, I2C, and TWI (Two Wire Interface, or 2-wire interface), but it is always the same. The idea is that all devices are connected in parallel to the two bus lines, SDA and SCL. At a time there can only be a master, in this case, our Duino and so the others are configured as slaves. - There may be more than one master device. The standard proposes an arbitration system to transfer control from one to another, but at a given time, only one can be the master. - Note that there are also some pull-up resistors connected to SDA and SCL. They are mandatory, since the bus is active at low level (that is, the active signal is a 0, not a 1. Don’t worry, it doesn’t matter). - When you connect something to the I2C bus, it is essential to read its data sheet before to find out whether the pull-up resistors are already attached to the device or you have to place them yourself. - In the case of the I2C display that we are going to use, it typically includes the pull-up resistors. And the good piece of news is that our Arduino supports a standard library, which uses two of the analog pins for SDA (data) and SCL (Clock) functions. - In the Arduino UNO, the I2C pins are the analog pins A4 (SDA) and A5 (SCL). - In the Arduino Mega and DUE they are the pins 20 (SDA) and 21 (SCL). The I2C library is called Wire library in Arduino and manages the complete communication protocol, which is a nice gesture, because it saves us the boring part of studying the protocol and write the sketch to handle it. - This is not laziness, but to build on the work of others. It is one of the very great virtues of the Arduino community because it has many libraries available to incorporate in our projects without getting our hands dirty. In this chapter we will connect a 16 × 2 I2C LCD display, so you can check why in the last chapter we recommended to use it, rather than connecting it directly using 16 wires. But first, we need to take care of another matter. I2C SCANNER Each component connected to the I2C bus has a unique address, and each message or order transmitted to the bus includes this address, indicating which of the many possible, is the recipient of the message. But, of course, this implies that we should know beforehand the address of each device. Typically, we should check the technical information of the device’s manufacturer, and that usually tell us which is the default address. But as we know, in life things don’t happen as in the fairy tales, some charitable soul (and with a lot of background on his shoulders) made a little sketch for Arduino, which informs us of what is in our bus and in what direction it is moving:I2C_scan.rar Naturally, this program has no idea of which is the device that answers the call or what it does, but it is good enough to know that there is some device in the address xx. If we do not know which is the address of a given device, we can simply place it alone on the bus and see which is the address reported by the I2C scanner. The result for the LCD I am dealing with is 0x27 Hexadecimal. So now we can move on to talk about how to program the display. CIRCUIT WIRING DIAGRAM The connection is again trivial: We simply connect the analog pin A4 of Arduino to SDA (Data) and the pin A5 to SCL (Clock), apart from GND and 5V. We keep on with the program. THE CONTROL PROGRAM First you have to download a new library to be able to use the I2C display, called LiquidCrystal_I2C. This is an upgrade of the standard library that is built in your Arduino IDE (keep calm, it does not hurt and should be automatic). I have not found any information about the author or authors, I have only seen one reference to the library name, Malpartida. Download the library:liquidcrystal_i2c Let’s install it first. So go to: \\Sketch\Include library\Add .ZIP library... Search the library LiquidCrystal_I2C.zip in your download directory and double click on it to install it in your IDE. Now let’s include the I2C library, called Wire in the Arduino IDE, and follow these steps. Go to: \\Sketch\Include library\Wire Now we must include the LiquidCrystal library and then the LiquidCrystal_I2C. We should see the following three lines in the sketch: #include <Wire.h> #include <LCD.h> #include <LiquidCrystal_I2C.h> We are going to define a variable that holds the address of our device. In our case the address is 0x27. byte dir = 0x27 // This 0x means that it is an hexadecimal number, not a decimal one And at last we create an instance on the LiquidCrystal_I2C object: LiquidCrystal_I2C lcd( dir, 2, 1, 0, 4, 5, 6, 7); When we create the lcd object we pass it the display address, dir, and several numbers that indicate which pins of the display should use the library (these are not Arduino pins). Ignore it and copy. The rest is as follows:Sketch 42.1 #include <Wire.h> #include <LCD.h> #include <LiquidCrystal_I2C.h> #define I2C_ADDR 0x27 LiquidCrystal_I2C lcd(I2C_ADDR,2, 1, 0, 4, 5, 6, 7); void setup() { lcd.begin (16,2); // Initialize the display with 16 columns and 2 rows lcd.setBacklightPin(3,POSITIVE); lcd.setBacklight(HIGH); lcd.home (); // go home lcd.print("Prometec.org"); lcd.setCursor ( 0, 1 ); // go to the 2nd line lcd.print("Malpartida lib"); } void loop() {} Here you have the result: SUMMARY - We have introduced the 16×2 I2C LCD displays. - They work the same as the normal ones, but they require far fewer wires to connect them and lots of problems are avoided. - They are very practical and cost a little more than a normal one. Give a Reply
http://prometec.org/displays/the-i2c-bus/
CC-MAIN-2021-49
refinedweb
1,335
70.23
Lock Command Locks or unlocks a file or folder to deny or restore the right of users to check out an item for edit into a different workspace or to check in pending changes to an item from a different workspace. Required Permissions To use the lock command, you must have the Lock permission set to Allow. Having the Unlock other user's changes permission set to Allow is required to remove a lock held by another user if you do not have Write permission for that user's workspace. For more information, see Team Foundation Server Permissions. You can use the lock command to temporarily freeze the Team Foundation version control server version of an item so that you can check in a pending change without having to resolve any merge conflicts. If you want to permanently prevent access to an item in the Team Foundation version control server, you should use the Permission Command instead. For more information on how to find the tf command-line utility, see Tf Command-Line Utility Commands. How to Lock an Item You can lock an item using the lock command or by specifying a lock option during the commission of several other commands of the tf command-line utility that includes: Rename Command (Team Foundation Version Control) Delete Command (Team Foundation Version Control) For add and branch, the lock is placed on the namespace where the new item will be created. Locks placed with rename apply both to the old and new namespaces. For more information, see Lock and Unlock Folders or Files. Lock Types Team Foundation provides two types of locks: checkin and checkout. A check-in lock is less restrictive than a check-out lock. When you apply a check-in lock, users can continue to make local changes to the item in other workspaces. The changes cannot be checked in until you explicitly remove the check-in lock from the workspace. A check-out lock is more restrictive than a check-in lock. When you apply a check-out lock to a version-controlled file or folder, users can neither check out the file for edit nor check in pre-existing pending changes. You cannot acquire a check-out lock if there are currently any pending changes to an item. For more information about when to apply a check-out lock and when to apply a check-in lock, see Understanding Lock Types. How Locking Works If you have a file checked out when you lock it, its status is modified to contain the new lock type. If the files are not checked out, a "lock" change is added to the set of pending workspace changes. Unlike the checkout command, lock does not automatically make a file editable. Locks on folders are implicitly recursive. If you lock a folder, you do not have to lock the files it contains unless you want to apply the more restrictive check-out lock to a file in a folder that has a check-in lock. Unlocking an Item You can unlock a locked item using the none option. Additionally, Team Foundation unlocks an item automatically when you check in pending changes in the workspace. You can determine which files are locked in the Team Foundation version control server and by whom the files were locked using the Status Command. The following example prevents other users from checking out 314.cs. The following example prevents other users from checking in changes to 1256.cs but enables them to check it out in their workspaces. The following example prevents other users from pending changes to any items in the src/ folder in the Team Foundation version control server. The following example unlocks and makes all files in the src/ Team Foundation version control server folder available for check-out and check-in by other users.
http://msdn.microsoft.com/en-us/library/47b0c7w9(v=vs.100).aspx
CC-MAIN-2013-20
refinedweb
642
68.1
Details Description UDF that could be used to check if a String is numeric (or an Integer). Several tools such as Splunk, AbInitio have this UDF built-in and companies making an effort to move to Hadoop/Pig could use this. Use Case: In raw logs there are certain filters/conditions applied based on whether a particular field/value is numeric or not. For eg, SPLIT A INTO CATEGORY1 IF IsInt($0), CATEGORY2 IF !IsInt($0); Activity - All - Work Log - History - Activity - Transitions What about floats and doubles? Are we assuming they are not numeric? Good point. We could have functions IsFloat/IsDouble/IsLong overriding IsInt. And IsNumeric can be a single UDF that handles all the cases, since we do not have a notion of range checks on this UDF? Yeah, that's what I'd do. I wouldn't obsess over speed yet, I'd just implement it and see how fast it is, and then if it's prohibitively slow go from there. The more annoying issue is that since we're essentially converting it over, there's going to be two casts when there only needs to be one. You'll have IsInt() in the split, and then in the resultant field, you'll have to cast the int one over to an int. It'd be nice if it could take advantage of what is going on and post split, the true values will have the proper schema :int, and the ones that aren't will still be :chararray. 1. IsNumeric is not necessarily implemented for speed, rather it's for a different requirement. That is, for cases when user does not care if value is an Int/Long/Float/Double and simply would like to check if it is numeric. (Though this inherently gives you better performance) 2. I had originally thought of isInt or IsNumeric to be a UDF to determine if data is int/numeric but not to actually make the cast. I am curious as to how the UDF could produce variable output schema. Oh, I totally know what you mean, I'm just saying it would be cool... and given that you're doing, say, Integer.parseInt() and then just throwing away the result, it seems silly that someone would do the split, and then recast the int fields in the relation created by the data for which IsInt is true. There is currently no way for UDF to produce variable output schema (nor should there, be, really). This would be something specific to this use of split. I agree with you on that, it would be nice to have the UDF return the integer value in case input is an Integer, and a default otherwise. May be we can visit that at a later time. As per your feedback, here is what I am going to do. Let me know your thoughts on this 1. IsNumeric works for floating points 2. Override IsInt for Long, Double, Float public class IsNumeric extends EvalFunc<Boolean> { @Override public Boolean exec(Tuple input) throws IOException { if (input == null || input.size() == 0) return false; try { String str = (String)input.get(0); if (str == null || str.length() == 0) return false; if (str.startsWith("-")) str = str.substring(1); return str.matches("\\d+(\\.\\d+)?"); } catch (ClassCastException e) { warn(e.getMessage(), PigWarning.UDF_WARNING_1); return false; } } } That sounds fine. In the case of numeric, I think we need to think about when you want it to return true. 1. Should it only return true for valid Int, Long, Double, or Float values? Your example would return true, though this is way too large to be any of the above! 2. A Java double can take the form 2.22e308, or whathave you. You said that a regex is faster than a Double, but how much faster. You can build in all the rules, but eventually you're just reimplementing the logic of parseDouble. 1. IsNumeric does not check for Long/Double range at all. Its simply a check to verify whether a String contains ONLY digits or not. The reason to implement this is to give users the ability to make a check for numeric"ness", and not necessarily to cast it back to a data type. Example: At my previous company we stored item listings as a Numeric value. These Item Listing IDs could go well beyond the range of Long/Double. If I try to check for numeric"ness" based on a certain data type (long, double) it would fail. The reason I implemented this is currently I use it to only SPLIT based on numeric"ness" in the log files. Once I have determined the SPLIT I do not cast it to a particular data type. And the field on which I call isNumeric can be arbitrary in length. 2. Good point again, I do not expect a huge gain but Regex match will in most cases be slightly faster than parseDouble. Just to reiterate, the primary goal of implementing IsNumeric is not performance. I think isNumeric is a nice to have UDF. But if it sounds like it would confuse users more than its worth, we could just stick to isInt/IsLong etc. I don't think it's too confusing, I would just explicitly state the purpose of the UDF. It is a fair one, and is something that I've done manually before, so I think it makes sense to ask. Just document the purpose, and more importantly, what it doesn't do. Added IsFloat, isDouble, IsLong. Also added test cases for the same. Added documentation for IsNumeric Hi, Prashant, Thanks for the patch. Please add Apache License Header to every new file you add. Also can you add javadoc to every UDF you add (you can provide a link if it is a repetition) Adding Apache License and Javadoc comments See two piggybank test failure: TestDBStorage and TestMultiStorageCompression. But these certainly not related to this patch. I will trace them in a separate ticket. test-patch: 501 warnings). Every new file contains proper header, ignore release audit warning. Patch committed to trunk. Thanks Prashant for contributing! Daniel, thanks for the commit! And Jonathan, thanks for your input. Proposal to implement 2 UDFs 1. IsInt 2. IsNumeric IsInt is used to check whether the String input is an Integer. Note this function checks for Integer range 2,147,483,648 to 2,147,483,647. Use IsNumeric instead if you would like to check if a String is numeric. Also IsNumeric performs better as its a regex match compared to IsInt which makes a call to Integer.parseInt(String input) IsInt checks whether making a call to Integer.parseInt results in a NumberFormatException and returns the boolean accordingly. IsNumeric makes a Regex match against the Input to check whether all characters are numeric digits. I have added Test cases for both UDFs as well.
https://issues.apache.org/jira/browse/PIG-2443?focusedCommentId=13174343&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel
CC-MAIN-2015-32
refinedweb
1,151
74.79
import "github.com/thinkoner/thinkgo/router" metch.go middleware.go parameter.go pipeline.go resource_controller.go route.go router.go rule.go static.go utils.go Method Convert multiple method strings to an slice NewStaticHandle A Handler responds to a Static HTTP request. PrepareResponse Create a response instance from the given value. RunRoute Return the response for the given rule. Closure Anonymous function, Used in Middleware Handler MiddlewareFunc Handle an incoming request. Pipeline returns a new Pipeline Passable set the request being sent through the pipeline. func (p *Pipeline) Pipe(m Middleware) *Pipeline Pipe Push a Middleware Handler to the pipeline func (p *Pipeline) Run(destination Middleware) interface{} Run run the pipeline func (p *Pipeline) Through(hls []Middleware) *Pipeline Pipe Batch push Middleware Handlers to the pipeline type Response interface { Send(w http.ResponseWriter) } Response an HTTP response interface New Create a new Route instance. Add Add a router AddRule Add a Rule to the Router.Rules Any Register a new rule responding to all verbs. Delete Register a new DELETE rule with the router. Dispatch Dispatch the request Get Register a new GET rule with the router. Group Create a route group Head Register a new Head rule with the router. Match Find the first rule matching a given request. func (r *Route) Middleware(middlewares ...Middleware) *Route Middleware Set the middleware attached to the route. Options Register a new OPTIONS rule with the router. Patch Register a new PATCH rule with the router. Post Register a new POST rule with the router. Prefix Add a prefix to the route URI. Put Register a new PUT rule with the router. Register Register route from the collect. Static Register a new Static rule. Statics Bulk register Static rule. Rule Route rule Bind Bind the router to a given request for execution. func (r *Rule) GatherRouteMiddleware() []Middleware GatherRouteMiddleware Get all middleware, including the ones from the controller. Matches Determine if the rule matches given request. func (r *Rule) Middleware(middlewares ...Middleware) *Rule Middleware Set the middleware attached to the rule. Run Run the route action and return the response. Package router imports 11 packages (graph) and is imported by 3 packages. Updated 2019-11-12. Refresh now. Tools for package owners.
https://godoc.org/github.com/thinkoner/thinkgo/router
CC-MAIN-2019-47
refinedweb
369
60.21
If you have recently downloaded the new Async CTP you will notice that WCF uses Async Pattern and Event based Async Pattern in order to expose asynchronous operations. In order to make your service compatible with the new Async/Await Pattern try using an extension method similar to the following: The previous code snippet adds an extension method to the GetDateTime method of the Service1Client WCF proxy. Then used it like this (remember to add the extension method’s namespace into scope in order to use it): Replace the proxy’s type and operation name for the one you want to await. Sometime ago I published a way to use WCF service with the new Async Pattern in C#. The problem is that Pingback from Async C# 5: Using Async Pattern with WCF and Silverlight
http://weblogs.asp.net/mjarguello/archive/2011/03/13/async-ctp-c-5-how-to-make-wcf-work-with-async-ctp.aspx
crawl-003
refinedweb
135
53.14
Convert DegMinSec to Decimal Degrees Hello, I once again found a little time to toy with C Programming. I have applied the helpful advice from this message board since my last post. I used the utility on to check my output. I was pleased that my program output matched that of the utility except on my final test input of 1.0101. Please see the comments at the end of my program for details. Any help would be greatly appreciated!Any help would be greatly appreciated!Code: /* Name: TODECDEG.C */ /* Purpose: Convert Degrees Minutes Seconds to Decimal Degrees */ /* Author: JacquesLeJock */ /* Date: November 19, 2007 */ /* Compiler: Pacific C for MS-DOS, v7.51 */ #include <stdio.h> main() { double deg_min_sec = 0, decimal_deg = 0; double mind = 0, secd = 0; int deg = 0, min = 0, sec = 0; printf("Enter Degrees Minutes Seconds: "); scanf("%lf", °_min_sec); deg = deg_min_sec; /* conversion during assignment */ min = (deg_min_sec - deg) * 100; sec = ((deg_min_sec - deg) * 100 - min) * 100; mind = (double) min / 60; /* */ secd = (double) sec / 3600; decimal_deg = deg + mind + secd; printf("Decimal Degrees: %f\n\n", decimal_deg); return 0; } /* Sample output: Enter Degrees Minutes Seconds: 1.0101 Decimal Degrees: 1.016667 Press any key to continue ... */ /* Note: This conversion does not agree with. Their utility yields 1.016944. Why? */ Regards, Jacques
http://cboard.cprogramming.com/c-programming/96043-convert-degminsec-decimal-degrees-printable-thread.html
CC-MAIN-2016-18
refinedweb
209
66.84
02 March 2012 02:54 [Source: ICIS news] Correction: In the ICIS news story headlined “Saudi’s APC plans three-week turnaround at PP units in Apr/May” dated 2 March 2012, please read in the first paragraph … Saudi Arabia’s Advanced Petrochemical Company (APC) plans to … instead of … Advanced Polypropylene Company plans to … A corrected story follows. ?xml:namespace> Each of the PP lines has a nameplate capacity of 225,000 tonnes/year, the source said. The exact dates of the planned shutdown have yet to be fixed, the source said. APC officials could not be immediately reached for comment. The PP facilities produce only homo PP grades, such as yarn (raffia), injection and BOPP film, according to the source close to the company. APC is 47%-owned by Saudi Industrial Development Fund, while the remaining 53% is held by private
http://www.icis.com/Articles/2012/03/02/9537578/corrected-saudis-apc-plans-turnaround-at-pp-units-in-aprmay.html
CC-MAIN-2015-14
refinedweb
142
57.4
23 May 2007 By clicking Submit, you accept the Adobe Terms of Use. Because ActionScript 3.0 is so new, any experience you have with Flex 2 will be helpful, but a good grounding in ActionScript 2.0 should be sufficient to understand the structures. Advanced. One design pattern in particular, the state design pattern (or SDP), focuses on the different states in an application, transitions between states, and the different behaviors within a state. A simple Flash video player application, for example, has two states: Stop and Play. In the Stop state, the video is not playing; in the Play state, a video is playing. Furthermore, the player transitions from the Stop state to the Play state using a method that changes the application's state. Likewise, it transitions from Play to Stop using a different transition and method to make it happen. An interface holds the transitions, and each state implements the transitions as methods that are unique to that state. Each method is implemented differently depending on the context of its use. For example, the startPlay() method would do one thing in the Stop state and something entirely different the Play state, even though startPlay() is part of both states. To understand and appreciate the value of the SDP, it helps to know something about state machines. This article begins with a simple two-state application that plays and stops playing an FLV file. It requires only Flash CS3 Professional and Flash Player 9, which you can download from the links below. The initial application introduces the basics of a state machine and the state design pattern. (With a few changes, the applications in this article will work with Adobe Flex 2 as well.) The application is then expanded into a more robust one using the same state structure and incorporating Flash Media Server 2. This illustrates both the expandability of an application using a design pattern and the process of incorporating Flash Media Server 2 into that design using ActionScript 3.0. A state machine is the conceptual model of states you would be using in an application with the SDP; the actual application is the state engine. So if my video player application is designed around key states, that design represents the state machine. However, one need not worry about which is which because they're used differently and interchangeably in the literature on state machines. The important point to keep in mind is the idea of states and their differing contextual behavior. Rather than beginning with the usual diagrams associated with design patterns, I'll start with a statechart. At its most basic level, a statechart is an illustration of an application's states and transitions. As such, it is a model for the state machine and engine. Taking a simple video player application, you can see the Play and Stop states. When the application is first run, the application enters the Stop state and can transition only to the Play state (see Figure 1). The line going from the black dot to the Stop state shows the Application Not Running state. For all intents and purposes, however, assume that the starting point is the Stop state. This could be illustrated in a hierarchical state with Application Running and Application Not Running states, or you could even place the whole hierarchy into Computer On and Computer Off states, but that's not too useful because you aren't coding to those states. Before I discuss getting from one state to another, consider what each state can actually do. In the Stop state, I can initiate only the Play state. That is, I cannot stop in the Stop state because I'm already stopped. By the same token, if I'm in the Play state, the only thing I can do is transition to the Stop state. The transitions in a state machine are the actions that change states. In the simple statechart, the line from Stop to Play would be a startPlay() method of some sort; and from Play to Stop, it would be a stopPlay() method. As more states are added, you might find that you cannot transition directly from one state to another. Rather, you have to go through a series of states to get where you want to go. As you will see further on, if you're in the Stop state, you cannot go directly to the Pause state. You have to go first to the Play state before going to the Pause state. Finally, to initiate a transition, you need some kind of trigger. A trigger is any event that initiates a transition from one state to another. Usually we think of some kind of user action as a trigger, such as a mouse movement or button click. However, in simulations certain states can be triggered by ongoing conditions, such as an FLV ending play, draining a simulated battery, or a collision with an object. Likewise, triggers are subject to contexts and should work only in the appropriate contexts to initiate a state. So while you might use a Play button to initiate the Play state from the Stop state, it should not trigger a Play state from the Play state. Often triggers are placed along with the transitions on the statecharts. This helps identify the trigger events and the transitions they trigger. Figure 2 shows the statechart updated to include both the triggers and transitions they initiate. If you're interested in more information about using state engines, statecharts, and the more general aspects of working with Flash and states, see Flash MX for Interactive Simulation by Jonathan Kaye and David Castillo (Thomson, 2003). Although it goes back a couple generations of Flash, the book is timeless in its concepts and shows some very smooth device simulations. Fortunately,: package { //Test states import flash.display.Sprite; public class TestState extends Sprite { public function TestState():void { var test:VideoWorks = new VideoWorks(); test.startPlay(); test.startPlay(); test.stopPlay(); test.stopPlay(); } } } TestStatein the Document Class text window.. Now that the structure can support a simple FLV playback system, the next step is to add two more states and see if the state machine can be adapted to a Flash Media Server 2 application. To keep the focus on the design pattern, only two new states will be added to the Play, Stop, and Pause states: Record and Append. Making the change from a Flash application to a Flash Media Server (FMS) application requires key changes in the FLA script to include a connection to the server, as well as adding Camera and Microphone objects. Other than that, adding the Record and Append states is relatively simple. The first task when working with state machine models is to update the model. Figure 7 shows the addition of Append and Record. The original three states are pretty much the same as before. Note that the Stop state is the central one for all transitions except for the Play-Pause toggle. To change from any state except Pause, the transition must go first to the Stop state. As noted at the outset, statecharts make it easy to see required program changes. By adding the new states—Pause, Append, and Record—all of the other states and context need to be changed as well. However, you don't need to change a huge number of conditional statements. The testing application in the Actions panel needs changes as well, but because that code is more like a user of the state machine rather than an actual part of the state machine, it will be handled separately. The single big script for the entire FMS 2 state machine will still be saved as VideoWorks.as, so that's the file you'll be changing. However, the number of states has grown. I provide each with a comment and number next to it to help you keep track. (If you're more comfortable with smaller scripts, you can break this one down into individual classes.) Note: Because the Stop state does more than just stop the play—it stops the recording and appending as well—I changed the name of the methods from stopPlay() to stopAll(). Save the following code as State.as: package { import flash.net.NetStream; interface State { function startPlay(ns:NetStream, flv:String):void; function startRecord(ns:NetStream, flv:String):void; function startAppend(ns:NetStream, flv:String):void; function stopAll(ns:NetStream):void; function doPause(ns:NetStream):void; } } Save the following code as PlayState.as: package { //Play State #3 import flash.net.NetStream; stopAll(ns:NetStream):void { ns.close(); trace("Stop playing."); videoWorks.setState(videoWorks.getStopState()); } public function startRecord(ns:NetStream,flv:String):void { trace("You have to stop first."); } public function startAppend(ns:NetStream,flv:String):void { trace("You have to stop first."); } public function doPause(ns:NetStream):void { ns.togglePause(); trace("Start pausing."); videoWorks.setState(videoWorks.getPauseState()); } } } Save the following code as StopState.as: package { //Stop State #2 import flash.net.NetStream; class StopState implements State { var videoWorks:VideoWorks; public function StopState(videoWorks:VideoWorks) { trace("--Stop State--"); this.videoWorks=videoWorks; } public function startPlay(ns:NetStream,flv:String):void { //Note: the second paramater - 0 - specifies an FLV file //the NetStream method is from Client Side //Communication ActionScript but works with AS 3.0 //because ObjectEncoding is imported. ns.play(flv,0); trace("Begin playing"); videoWorks.setState(videoWorks.getPlayState()); } public function startRecord(ns:NetStream,flv:String):void { ns.publish(flv,"record"); trace("Begin recording"); videoWorks.setState(videoWorks.getRecordState()); } public function startAppend(ns:NetStream,flv:String):void { ns.publish(flv,"append"); trace("Begin appending"); videoWorks.setState(videoWorks.getAppendState()); } public function stopAll(ns:NetStream):void { trace("You're already stopped"); } public function doPause(ns:NetStream):void { trace("Must be playing to pause."); } } } Save the following code as RecordState.as: package { //Record State #5 import flash.net.NetStream; class RecordState implements State { var videoWorks:VideoWorks; public function RecordState(videoWorks:VideoWorks) { trace("--Record State--"); this.videoWorks=videoWorks; } public function startPlay(ns:NetStream,flv:String):void { trace("You have to stop first."); } public function stopAll(ns:NetStream):void { ns.close(); trace("Stop recording."); videoWorks.setState(videoWorks.getStopState()); } public function startRecord(ns:NetStream,flv:String):void { trace("You're already recording"); } public function startAppend(ns:NetStream,flv:String):void { trace("You have to stop first."); } public function doPause(ns:NetStream):void { trace("Must be playing to pause."); } } } Save the following code as AppendState.as: package { //Append State #6 import flash.net.NetStream; class AppendState implements State { var videoWorks:VideoWorks; public function AppendState(videoWorks:VideoWorks) { trace("--Append State--"); this.videoWorks=videoWorks; } public function startPlay(ns:NetStream,flv:String):void { trace("You have to stop first."); } public function stopAll(ns:NetStream):void { ns.close(); trace("Stop appending."); videoWorks.setState(videoWorks.getStopState()); } public function startRecord(ns:NetStream,flv:String):void { trace("You have to stop first."); } public function startAppend(ns:NetStream,flv:String):void { trace("You're already appending"); } public function doPause(ns:NetStream):void { trace("Must be playing to pause."); } } } Save the following code as PauseState.as: package { //Pause State #4 import flash.net.NetStream; class PauseState implements State { var videoWorks:VideoWorks; public function PauseState(videoWorks:VideoWorks) { trace("--Pause State--"); this.videoWorks=videoWorks; } public function startPlay(ns:NetStream,flv:String):void { trace("You have to go to unpause"); } public function stopAll(ns:NetStream):void { trace("Don't go to Stop from Pause"); } public function startRecord(ns:NetStream,flv:String):void { trace("You have to stop first."); } public function startAppend(ns:NetStream,flv:String):void { trace("You have to stop first."); } public function doPause(ns:NetStream):void { ns.togglePause(); trace("Quit pausing."); videoWorks.setState(videoWorks.getPlayState()); } } } Save the following code as VideoWorks.as: package { //Context Class #7 import flash.net.NetStream; public class VideoWorks { var playState:State; var stopState:State; var recordState:State; var appendState:State; var pauseState:State; var state:State; public function VideoWorks () { trace ("Video Player is on"); playState = new PlayState(this); stopState = new StopState(this); recordState = new RecordState(this); appendState = new AppendState(this); pauseState=new PauseState(this); state=stopState; } public function startPlay (ns:NetStream,flv:String):void { state.startPlay (ns,flv); } public function startRecord (ns:NetStream,flv:String):void { state.startRecord (ns,flv); } public function startAppend (ns:NetStream,flv:String):void { state.startAppend (ns,flv); } public function stopAll (ns:NetStream):void { state.stopAll (ns); } public function doPause (ns:NetStream):void { state.doPause (ns); } public function setState (state:State):void { trace ("A new state is set"); this.state=state; } public function getState ():State { return state; } public function getPlayState ():State { return this.playState; } public function getRecordState ():State { return this.recordState; } public function getAppendState ():State { return this.appendState; } public function getPauseState ():State { return this.pauseState; } public function getStopState () :State { return this.stopState; } } } That's a lot of code to create something as simple as a video application with record, append, play, pause, and stop functionality. However, this design follows every principle of good OOP. You could expand it further by adding more states to the current system. To implement the FMS 2 state machine, you need to write an ActionScript file that will instantiate an instance of the VideoWorks class and then add the name of the class in the Document Class window of an FLA file . In the folder where you keep your FMS 2 server-side folders, add a folder named flvstate. After your first recording, FMS 2 automatically generates a folder named flv within the flvstate folder. That's where you need to place all of your FLV files that were not recorded with this application. Besides connecting to the server, the code must also deal with a cautionary user interface issue. When using a NetStream.togglePause(), you do not want the user to click the Stop button while paused. To fix that problem, the Stop button's visibility is set to false when the pause is toggled on. (The button conveniently disappears, along with the temptation to click it.) Before you add more code to the script for the Actions panel, you need to add more buttons to the Stage along with giving them instance names. Figure 8 shows the final configuration with the assigned instance names to the objects on the Stage. The first step is to create a class that will have all of the right packages you need. In an ActionScript file, write the following script and save it as TestVidFMS.as: package { //Test Module #8 import flash.display.Sprite; import flash.net.NetConnection; import flash.net.NetStream; import flash.net.ObjectEncoding; import flash.media.Video; import flash.media.Camera; import flash.media.Microphone; import flash.text.TextField; import flash.text.TextFieldType; import flash.events.MouseEvent; import flash.events.NetStatusEvent; public class TestVidFMS extends Sprite { private var nc:NetConnection; private var ns:NetStream; private var dummy:Object; private var flv_txt:TextField; private var cam:Camera; private var mic:Microphone; private var stateVid:VideoWorks; private var playCheck:Boolean; private var pauseCheck:Boolean; private var playBtn:NetBtn; private var stopBtn:NetBtn; private var pauseBtn:NetBtn; private var recordBtn:NetBtn; private var appendBtn:NetBtn; public function TestVidFMS () { //************ //Add the text field //************ flv_txt= new TextField(); flv_txt.border=true; flv_txt.background=true; flv_txt.backgroundColor=0xfab383; flv_txt.type=TextFieldType.INPUT; flv_txt.x=(550/2)-45; flv_txt.y=15; flv_txt.width=90; flv_txt.height=18; addChild (flv_txt); //FMS State Machine NetConnection.defaultObjectEncoding=flash.net.ObjectEncoding.AMF0; nc = new NetConnection(); nc.objectEncoding = flash.net.ObjectEncoding.AMF0; nc.addEventListener (NetStatusEvent.NET_STATUS,checkHookupStatus); //Use your own domain/IP address on RTMP nc.connect ("rtmp://192.168.0.11/flvstate/flv"); //OR set up a local connection //nc.connect("rtmp:/flvstate/flv"); //nc.connect(null); //Camera & Microphone Settings cam = Camera.getCamera(); cam.setMode (320,240,15); cam.setKeyFrameInterval (30); cam.setQuality (0,80); mic = Microphone.getMicrophone(); mic.rate=11; //Add video object vid=new Video(320,240); addChild (vid); vid.x=(550/2)-(320/2); vid.y=40; setLocal (); //Instantiate State Machine stateVid=new VideoWorks; //Play, Stop, Record, Append and Pause Buttons playBtn=new NetBtn("Play"); addChild (playBtn); playBtn.x=(550/2)-(320/2); playBtn.y=300; var playCheck:Boolean=false; recordBtn=new NetBtn("Record"); addChild (recordBtn); recordBtn.x=(550/2)+((320/2)-60); recordBtn.y=300; appendBtn=new NetBtn("Append"); addChild (appendBtn); appendBtn.x=(550/2)+((320/2)-60); appendBtn.y=330; stopBtn=new NetBtn("Stop"); addChild (stopBtn); stopBtn.x=(550/2)-25; stopBtn.y=300; pauseBtn=new NetBtn("Pause"); addChild (pauseBtn); pauseBtn.x=(550/2)-(320/2); pauseBtn.y=330; pauseCheck=true; //Add Event Listeners playBtn.addEventListener (MouseEvent.CLICK,doPlay); stopBtn.addEventListener (MouseEvent.CLICK,doStop); recordBtn.addEventListener (MouseEvent.CLICK,doRecord); appendBtn.addEventListener (MouseEvent.CLICK,doAppend); pauseBtn.addEventListener (MouseEvent.CLICK,doPause); } //Add Control Functions function setNet () { vid.attachNetStream (ns); } function setLocal () { vid.attachCamera (cam); } var flv:String; function doPlay (e:MouseEvent):void { if (flv_txt.text != "" && flv_txt.text != "Provide file name") { setNet (); flv_txt.textColor=0x000000; flv=flv_txt.text; stateVid.startPlay (ns,flv); if (! playCheck) { playCheck=true; } } else { flv_txt.textColor=0xcc0000; flv_txt.text="Provide file name"; } } function doRecord (e:MouseEvent):void { if (flv_txt.text != "" && flv_txt.text != "Provide file name") { ns.attachAudio (mic); ns.attachCamera (cam); flv_txt.textColor=0x000000; flv=flv_txt.text; stateVid.startRecord (ns,flv); if (! playCheck) { playCheck=true; } } else { flv_txt.textColor=0xcc0000; flv_txt.text="Provide file name"; } } function doAppend (e:MouseEvent):void { if (flv_txt.text != "" && flv_txt.text != "Provide file name") { ns.attachAudio (mic); ns.attachCamera (cam); flv_txt.textColor=0x000000; flv=flv_txt.text; stateVid.startAppend (ns,flv); if (! playCheck) { playCheck=true; } } else { flv_txt.textColor=0xcc0000; flv_txt.text="Provide file name"; } } function doPause (e:MouseEvent):void { if (pauseCheck) { pauseCheck=false; if (playCheck) { stopBtn.visible=false; } stateVid.doPause (ns); } else { pauseCheck=true; stopBtn.visible=true; stateVid.doPause (ns); } } function doStop (e:MouseEvent):void { playCheck=false; stateVid.stopAll (ns); vid.clear (); setLocal (); } //Check connection, instantiate stream, //and set up metadata event handler function checkHookupStatus (event:NetStatusEvent):void { if (event.info.code == "NetConnection.Connect.Success") { ns = new NetStream(nc); dummy=new Object(); ns.client=dummy; dummy.onMetaData=getMeta; ns.addEventListener (NetStatusEvent.NET_STATUS,flvCheck); } } //MetaData function getMeta (mdata:Object):void { trace (mdata.duration); } //Handle flv private function flvCheck (event:NetStatusEvent):void { switch (event.info.code) { case "NetStream.Play.Stop" : stateVid.stopAll(ns); setLocal(); break; case "NetStream.Play.StreamNotFound" : stateVid.stopAll(ns); flv_txt.text="File not found"; setLocal(); break; } } } } Once you save the TestVidFMS.as file, open a new FLA file and, in the Document Class window, type TestVidFMS. Give it a test ride and you're all set. As Brian Lesser and Stefan Richter helpfully pointed out to me, one of the critical new pieces of code when working with ActionScript 3.0 is the following line: NetConnection.defaultObjectEncoding=flash.net.ObjectEncoding.AMF0; Flash Media Server 2 uses Action Message Format 0, (AMF0) encoding. Flex 2 now uses AMF3. For more information on getting started with ActionScript 3.0 and Flash Media Server 2, see Brian Lesser's article, Building a Simple Flex 2/FMS 2 Test Application. The bulk of the code stored in the test file deals with setting up the button instances, attaching listeners to the buttons, and creating the button callbacks. The VideoWorks class is instantiated in the stateVid object and the button callbacks simply use the state engine's implementation of the different methods. Note that if you click Record or Append while playing a video, the Output window lets you know what's going on in the state engine. It tells you what has to be done before you can either record or append a file. The user doesn't end up making a mistake. The concept of a state machine is not only one to optimize your application, but it can include many helpful features that keep the user from having a bad experience. For more information about ActionScript 3.0 and design patterns, see ActionScript 3.0 Design Patterns (by Bill Sanders and Chandima Cumaranatunge: O'Reilly, 2007). For some good examples of design patterns used with Flash Communication Server, see Programming Flash Communication Server (by Brian Lesser, Giacomo Guilizzoni, Joey Lott, Robert Reinhardt, and Justin Watkins; O'Reilly). The ultimate work on Flash and state machines can be found in How to Construct and Use Device Simulations: Flash MX for Interactive Simulation (Jonathan Kaye and David Castillo; Delmar Learning). It provides an illuminating discussion of state machines and statecharts.
http://www.adobe.com/devnet/adobe-media-server/articles/video_state_machine_as3.html
CC-MAIN-2014-35
refinedweb
3,353
50.43
Description A motor that enforces the angular speed w(t) between two ChShaft shafts, using a rheonomic constraint. (ex very good and reactive controllers). By default it is initialized with constant angular speed: df/dt= 1 rad/s, use SetSpeedFunction() to change to other speed functions. #include <ChShaftsMotorSpeed.h> Member Function Documentation Method to allow deserialization of transient data from archives. Method to allow de serialization of transient data from archives. Reimplemented from chrono::ChShaftsMotorBase. number of scalar constraints, if any, in this item (only bilateral constr.) Children classes might override this. Reimplemented from chrono::ChPhysicsItem. Use this function after gear creation, to initialize it, given two shafts to join. The first shaft is the 'output' shaft of the motor, the second is the 'truss', often fixed and not rotating. The torque is applied to the output shaft, while the truss shafts gets the same torque but with opposite sign. Each shaft must belong to the same ChSystem. - Parameters - Reimplemented from chrono::ChShaftsCouple. Tell to a system descriptor that there are constraints of type ChConstraint in this object (for further passing it to a solver) Basically does nothing, but maybe that inherited classes may specialize this. Reimplemented from chrono::ChPhysicsItem. Tell to a system descriptor that there are variables of type ChVariables in this object (for further passing it to a solver) Basically does nothing, but maybe that inherited classes may specialize this. Reimplemented from chrono::ChPhysicsItem. From item's state to global state vectors y={x,v} pasting the states at the specified offsets. Reimplemented from chrono::ChPhysicsItem. From global state vectors y={x,v} to item's state (and update) fetching the states at the specified offsets. Reimplemented from chrono::ChPhysicsItem. Set if the constraint must avoid angular drift. If true, it means that the constraint is satisfied also at the rotation level, by integrating the velocity in a separate auxiliary state. Default, true. Sets the angular speed function w(t), in [rad/s]. It is a function of time. Best if C0 continuous, otherwise it gives peaks in accelerations.PhysicsItem.PhysicsItem.
http://api.projectchrono.org/classchrono_1_1_ch_shafts_motor_speed.html
CC-MAIN-2019-51
refinedweb
344
59.3
Introduction Sometimes managing forms in react can be a drag, And if you decide to use libraries like redux-form they carry significant performance overhead which you might not be able to afford in the application you are building. Formik is here to your rescue, it is a small library with bundle size of 12 kB compared to redux-form which has a bundle size of 22.5 kB minified gzipped, and the best part; Formik helps with the wearisome task of form handling, which are - Handling form state - Handling form validation and errors - Handling form submission You can check the docs for more information about the library on Formik Formik also seamlessly integrates with material-ui; it is a react library that implement Google material design, providing components like input, button, label and several others out of the box. You can also check out their docs for more information Material-Ui Finally, there is Yup. What is Yup? It is a JavaScript object schema validator and object parser. In this context Yup simply helps handle validation. This does not mean that you can’t write your own custom validator for Formik but I find my experience using Yup good and it improves the readability of my code. More on Yup here in the docs Yup. This article will explain how to build forms and handle form validation with Formik, Yup and Material-UI. Here is a quick overview of what we are going to do in this guide: - Create a react app using create-react-app. - Create a simple form with Material-UI and Formik. - Write validation rules/ validation schema with Yup. - Use Yup with Formik. This tutorial assumes you have knowledge of react. There is a code sandbox demo of the form we are going to build here: Formik Demo Application Installation: - Create react application using CRA Create React App Create-react-app formik-form-demo After running this our project structure should look like this: Now open the App.js file in the src folder and then delete the contents of the parent div that has a className of App. In your terminal run Yarn add or npm install formik yup @material-ui/core This command adds formik, Yup and material-UI to our dependencies. Now that our dependencies have been installed, create a new folder called InputForm in the src folder then create index.js and form.js files in the InputForm folder. This is what your src folder should look like now: The form.js file is going to contain the presentation while the index.js is going to contain most of the logic. Currently your application should be displaying a blank page, so right now let's just get our form displaying. In your form.js file add the following code import React from "react"; import Button from "@material-ui/core/Button"; import TextField from "@material-ui/core/TextField"; export const Form = (props) => { return ( <form onSubmit={() => {}}> <TextField id="name" name="name" label="Name" fullWidth /> <TextField id="email" name="email" label="Email" fullWidth /> <TextField id="password" name="password" label="Password" fullWidth <TextField id="confirmPassword" name="confirmPassword" label="Confirm Password" fullWidth <Button type="submit" fullWidth Submit </Button> </form> ); }; What we have done here is create a simple form with four fields (Name, Email, Password and Confirm password) and a Button with material-UI. In index.js file in the InputForm folder add the following code: import React, { Component } from "react"; import { Formik } from "formik"; import withStyles from "@material-ui/core/styles/withStyles"; import { Form } from "./form"; import Paper from "@material-ui/core/Paper"; const styles = theme => ({ paper: { marginTop: theme.spacing.unit * 8, display: "flex", flexDirection: "column", alignItems: "center", padding: `${theme.spacing.unit * 5}px ${theme.spacing.unit * 5}px ${theme .spacing.unit * 5}px` }, container: { maxWidth: "200px" } }); class InputForm extends Component { constructor(props) { super(props); this.state = {}; } render() { const classes = this.props; return ( <React.Fragment> <div className={classes.container}> <Paper elevation={1} className={classes.paper}> <h1>Form</h1> <Formik render={props => <Form {...props} />} /> </Paper> </div> </React.Fragment> ); } } export default withStyles(styles)(InputForm); Here we have created a class component called InputForm. At the top we imported the form component we just created. And then passed it as a render prop to the Formik component. There are three ways to render things with Formik <Formik component /> <Formik render /> <Formik children /> We used the render props in the above. All three render methods will be passed some props which include: - errors - handleChange - handle - isValid - touched - setFieldTouched There are a couple more props passed to your component, check the docs for all of them Formik Docs Next go to the App.js file in the src folder, import the InputForm component then add it as a child of the div. This our App.js now and the form should be rendered. import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; import InputForm from './InputForm' class App extends Component { render() { return ( <div className="App"> <InputForm/> </div> ); } } export default App; Now We have our form rendered, Let’s start with the form validation. This is where Yup is needed, Basically Yup provides functions that helps us write intuitive validation rules. First we import Yup into the Index.js file in the InputForm folder then we use its APIs to write our validation rules. Import statement import * as Yup from "yup" Note: importing all the functions/APIs of a library into your codebase is not a good practice. Now add this following code to the Index.js file in the InputForm folder, This is our validation rules or Validation scheme. const validationSchema = Yup.object({ name: Yup.string("Enter a name") .required("Name is required"), email: Yup.string("Enter your email") .email("Enter a valid email") .required("Email is required"), password: Yup.string("") .min(8, "Password must contain at least 8 characters") .required("Enter your password"), confirmPassword: Yup.string("Enter your password") .required("Confirm your password") .oneOf([Yup.ref("password")], "Password does not match") I don’t know about you but at first glance this looks very intuitive. Yup provides several APIs which makes Object validation easy. Some of them are listed below. APIs Yup.object() : Is used to define the keys of the object and the schema for those key. In this examples it is used to define the fields we are validating (name, email, password, confirmPassword) and also define validation rules for those fields. Yup.string(): Defines a string schema. This specifies that field should be a string, it also accepts an optional argument which is used to set the error message. All four fields we defined are strings. Also, we can chain functions or methods so that it is possible have more than one validation rule for each field. Yup.required(): This specifies that field is required and must not be empty. It also takes an optional argument to define the error message. Yup.email(): Defines a email schema and also takes an optional argument. Yup.min(): Sets the minimum length for the value. It accept two arguments, the length and the error message. Yup.ref(): It creates a reference to another sibling field or sibling descendant field. It accepts a compulsory argument which is the field we are referencing. Yup.oneOf(): Whitelist a set of values. It accepts an array of the whitelisted value/values and an optional argument that sets the error message. Check the Docs for a full list of the APIs. Now that we have defined our validation schema/rules, how do we integrate it into our application? Remember I earlier said that Yup seamlessly integrates with Formik, well Formik provides a special prop for Yup called validationSchema which will automatically transform Yup's validation errors into a pretty object. So we pass our validation rules to the validationSchema prop. Formik also allows you to set initial value for your fields using the initialValues prop. So the render function of our InputForm component should look like this when we add the validationSchema and initialValues prop to the Formik component. render() { const classes = this.props; const values = { name: "", email: "", confirmPassword: "", password: "" }; return ( <React.Fragment> <div className={classes.container}> <Paper elevation={1} className={classes.paper}> <h1>Form</h1> <Formik render={props => <Form {...props} />} initialValues={values} validationSchema={validationSchema} /> </Paper> </div> </React.Fragment> ); } We have defined the validation rules and initial values, Now let's use the props passed to the Form component to handle validate the inputs. In our Form component in the InputForm folder, we destructure the props and create a change function which handles our input changes const { values: { name, email, password, confirmPassword }, errors, touched, handleSubmit, handleChange, isValid, setFieldTouched } = props; const change = (name, e) => { e.persist(); handleChange(e); setFieldTouched(name, true, false); }; There are a couple of props passed to the Form component by Formik but I won’t be using all of them in this demo. Props used are: values : An object that contains the initial values of the form fields. errors : An object containing error messages of the field. touched : An object containing fields that have been touched/visited, fields that have been touched are set to true otherwise they are set to false. handleChange : General Input handler, This will update the values[key] where key is the event-emitting input's name attribute. If the name attribute is not present, handleChange will look for an input's id attribute. isValid: Returns true if there are no errors i.e (no errors in the errors object). setFieldTouched: is a function used to set the touched state of a field. The first argument is the name of the field, the second argument is the value you want to set the touched state to which is true and the last argument is a boolean used to prevent validation. Now let's make changes to Form component so that we can see the error messages when there’s an error. Material-UI TextField component provides two props which can help us display our error message in an elegant way, these props are helperText and error for displaying the error. The Form component should look like this when we add these props to our TextField component. export const Form = props => { const { values: { name, email, password, confirmPassword }, errors, touched, handleChange, isValid, setFieldTouched } = props; const change = (name, e) => { e.persist(); handleChange(e); setFieldTouched(name, true, false); }; return ( <form onSubmit={() => { alert("submitted"); }} > <TextField id="name" name="name" helperText={touched.name ? errors.name : ""} error={touched.name && Boolean(errors.name)} label="Name" value={name} onChange={change.bind(null, "name")} fullWidth /> <TextField id="email" name="email" helperText={touched.email ? errors.email : ""} error={touched.email && Boolean(errors.email)} label="Email" fullWidth value={email} onChange={change.bind(null, "email")} /> <TextField id="password" name="password" helperText={touched.password ? errors.password : ""} error={touched.password && Boolean(errors.password)} label="Password" fullWidth type="password" value={password} onChange={change.bind(null, "password")} /> <TextField id="confirmPassword" name="confirmPassword" helperText={touched.confirmPassword ? errors.confirmPassword : ""} error={touched.confirmPassword && Boolean(errors.confirmPassword)} label="Confirm Password" fullWidth type="password" value={confirmPassword} onChange={change.bind(null, "confirmPassword")} /> <Button type="submit" fullWidth variant="raised" color="primary" disabled={!isValid} > Submit </Button> </form> ); }; You should notice that I added three props to the Textfield component, helperText, error and onChange. onChange is set to the change function we wrote above for handling changes to the input field. The helperText prop is set to a ternary operator (If statement) that states if the field is touched, set the helperText prop to the error message of that field else set it to an empty string. The error prop is set to a boolean to indicate an error in validation. And finally the Button component has a prop called disabled which disables the button, we set it to not !isValid so if there is any error in the errors object the button remains disabled, I mean we don’t want to be submitting invalid values. Creating forms with Formik,Material-UI and Yup is awesome. This is my first technical article/post so I am open to any suggestion that can help improve my writing. If you have any question or suggestion comment below. Special thanks to my friend YJTheRuler for editing this article, He writes for @radronline about Afro-beat music and African culture. Top comments (34) I wrote a small helper to reduce the boilerplate: And then use the spread operator on your components: <TextField {...formikProps('fieldName')}/> The initial value is required to tell React it's a controlled component. The above function only works for TextFields (Checkboxes, etc, don't directly support helperText so it would need to be modified). Thanks!!!! I'd like to add a simple enhancement by adding error: touched[name] && Boolean(errors[name]), this will remove an error from the console A disadvantage of this approach is that you can't really use the Formik's <Field />component. And for each input field, you need to write a lot of unwanted and repeating code, which I have marked in red. You can easily use the useField hook and transfer the field object as props to the material-ui TextField. Take a look at this :) jaredpalmer.com/formik/docs/api/us... Hi! Giacomo, i don't get how to compose usefield hook with material-ui TextField. Can you write a quick example ? Hello, I have created an example of how to use an useField hook with material-ui TextField. Below is a simple FormikTextField component, that can be reused across the whole application. It is important that this component is nested under the <Formik>component so it can access the necessary properties inside the useField() hook. You can provide additional styling properties to the FormikTextFieldcomponent similarly as to the original TextFieldcomponent. Thanks for pointing this out, I haven't used <Field/>component before so I will check it out How can I get the values from the form to submit them? And how can I set the value to the state if it has been fetched from the database like I would do in a normal form: <TextField id={'name'} label={'Username'} name={'name'} type={'text'} style={width} autoComplete={'username'} value={this.state.name} onChange={this.handleChange} /> possible use state. create state values then in your componentdidmountor where ever you make your database calls you can setstate of that value. then pass it to the Formik's initialValuesprop Link to demo use state. then in your componentdidmountyou can do your database call then setstate and then pass the state values to Formik initialValuesprop. Link to Demo Thanks for your quick reply. But what if I load the email and username from the state. How can I disable the touched option on those input fields? Because they don't have to be changed everytime but my button keeps disabled. I tried some things like checking if the state is set and if its set then: this.props.setFieldTouched('email', true, false);but that doesn't seem to work. Could you please provide me more info about the function to check if the field is touched? So I can try to modify it myself? Sorry I have be busy recently, Right now I don't think formik has any apis to check if a field is touched. Hey, this is a great tutorial. Many thanks! With regard to the styling bit, I'm having trouble getting the styles func/object in InputForm/index.js to have any effect. It doesn't seem to have any effect in your code sandbox demo either. This is my first foray with CSS in JS outside of React Native. Your stylesfunc takes in a themeargument, which lead me to think I need to wrap everything at a higher level with a <MuiThemeProvider />, but I haven't worked out what to give it for it's mandatory 'theme' prop yet. Any advice on this would be great! Predictably, about 10 seconds after posting that comment I found out what the problem was. Looking at the withStyles()docs, I can see that this: const classes = this.props; should be... const {classes} = this.props; It did seem strange at the time that withStyles would replace all props to the component, rather than just add to them. withStyleswill not replace all the props to that component, it should just add to them. Good Article. If Yup.required() is configured for a textfield, meaning it is a required field. How would you pass that information to the TextField so that is renders the label with the * suffix, either ideally before even touching the field but if that's impossible then at the very least after touching? Look here to see what the required field is supposed to look like material-ui.com/demos/text-fields/ Thanks. I have not been able to figure out how to do this yet, I will keep looking for solutions. if you find a solution please share. As you know beforehand which fields will be required, you can just use the "required" prop on the according TextField. Thank you very much Nero, you saved my day. I didn't know how to manage form using formik and material-ui. I need a way to subscribe users to a mailchimp list using several fields and this is the only guide I found. Great tutorial! I'm trying to use a select, and I'm using the material-ui example But when I use the change()I don't get the value. Any suggestions? I ran into this problem some time ago. Material ui select don't use the same change handlers like the input and text fields. Formik provides us with a change handler called(handleChange) as props so you can use that. That is what i used in the example below so your onChange should be onChange={handleChange('building')}, buildingbeing the namefor that select So I guess my question now is how can I customize handleChange? For simplicity, what I need to be able to do is make an axios call, sending select's value onChange. Hi Nero, I tried using Formik,Yup and MaterialUi together. But it seems like there is a considerable lag when typing in the textfields (of the materialUI) present in the form. The form that I'm using contains many inputs, maybe why the lag is being caused. Any way to avoid this delay ?. Also is there a full rendering of the component, when each and every textfield component is being changed ? as I find the state is being formik state is being updated on every keystroke. If so how can i avoid this. I really don't want my entire component to get rendered on every keystroke :(. I appreciated the article and was able to successfully integrate Formik, Material-UI, and Yup into my project. I still have a lot more to do, but this was a great starting point to help me connect the dots, so to speak. Hi, I have made a version of your package with fully updated package.json. Latest formik, react etc. No errors, no warnings, everything works as in your somewhat outdated example. I also fixed some google usability issues. I have not added anything except fixing breaking changes etc. Will you be interested to have this code?. Then please email me, or send me a message. Great article. I based my implementation off this, only adding the Formik-Material-UI library to handle the rendering of components. Hi sir, I am building forms in react using Formik and Yup for validations. I am not getting how we restrict a user to enter limited characters for example, Mobile Number : user should enter only 10 digits not more that In my code i am passing max length to input tag Could you please help me ? HI this may be a silly question , I know this is something to do with object destructuring What is does values: { name, email, password, confirmPassword }, DO is it same is props.values.name const { values: { name, email, password, confirmPassword }, errors, touched, handleSubmit, handleChange, isValid, setFieldTouched } = props Thanks for this great article. I learned a lot! Hi, the former was really descriptive, but how can we use select option components as material UI - formic components? thanks sir what happen when we not using e.persist() ?
https://dev.to/finallynero/react-form-using-formik-material-ui-and-yup-2e8h
CC-MAIN-2022-40
refinedweb
3,369
65.32
Overview - Title - describe the lifecycle of an item - Duration - 144 - Difficulty - Medium - Types - Documentation - sphinx,rst - Mentors - thomaswaldmann,rb_proj,waldi,esyr,pkumar_7 - Count - 0 Too early. Rename and delete will likely get changes when namespaces branch is ready to get merged. Screenshots could be invalid then. Description Abstract describe the lifecyle of an item Details With moin2 we have items instead of pages and attachments. This change envolves also lots of new manipulation possibilities. You have describe the lifecyle of a new item for users. This includes: - create - modify - rename - meta - set a tag - revert - delete The new documentation has to be added to the section items, e.g. lifecyle of an item in rst Syntax. deliverables: patch or changeset Benefits This taks adds more user documentations. Skill Requirements see Tags Extra (optional) Links Note: unless otherwise noted, tasks usually refer to moin2 ()! or - repository of moin2 - repository of moin 1.9 - please join us on IRC #moin-dev
http://www.moinmo.in/EasyToDo/lifecycle%20of%20an%20item
crawl-003
refinedweb
159
58.69
How to Create a MakeCode Package for Micro:Bit Introduction Microsoft MakeCode is a block based coding language designed to introduce people to coding. MakeCode is nice because it allows the basic structures and thought processes used in algorithm design to take place without having to worry about syntax or data type. Under the hood, MakeCode is based on static typescript and javascript. In this tutorial, we'll develop a MakeCode extension for the Soil Moisture Sensor using an existing SparkFun extension. Thing's You'll Need First, let's set up our build environment, we'll start by downloading and installing Node.js. You'll also need a GitHub account. Now go ahead and open any old command prompt and navigate to to where you store your GitHub files (I create a GitHub folder on my C:\ drive so for me this is C:\GitHub). Then go ahead and run the following commands. This installs a few npm packages to use. language:bash npm install npm install jake npm install typings We'll then clone the PXT directory into our GitHub folder and run these npm packages we just installed. At the end, back out to the GitHub folder once more. This is accomplished with the following commands. language:bash git clone cd pxt git checkout v0 npm install typings install jake cd.. We'll then clone in the Micro:Bit target, and install pxt there. language:bash git clone cd pxt-microbit npm install -g pxt npm install cd.. This should be everything we need to build our project, now let's clone in an existing SparkFun MakeCode package and get started editing it. language:bash git clone What to Change Let's go ahead and create a new GitHub repository for our new MakeCode package, we'll call it pxt-gator-moisture. Clone this repo into your GitHub folder, then go ahead and copy over the contents of the pxt-gator-light repo. We'll mainly be looking at the two gatorlight files, the pxt.JSON file, the README.MD, and eventually the icon.png. First, we're going to go through and rename everything to gatormoisture, so go ahead and rename the two gatorlight files, once we've renamed them, go ahead and open up pxt.json and replace every instance of the word light with moisture. The *.json file tells MakeCode which files to include, and since we changed our filenames, we'll have to change them here as well. Don't neglect to roll the version number back to 0.0.1 as well as change the description to something that makes more sense. We're then going to open up both gatormoisture files and replace every instance of light with moisture once again. Let's now look at where the code behind our blocks actually lives, the blocks live in the *.ts file while the actual functions live in the *.cpp. Let's check out the *.cpp first. We make sure to include pxt.h with every package, as well as use the pxt namespace. We then create a namespace, " gatormoisture" and put the function that calculates lux from a given ADC value. It's a pretty simple function but we'll be able to call it from our *.ts file, which is what we really wanted. */ //% uint16_t getLux(int16_t ADCVal) { return ADCVal * .976; } } While we're here, let's change getLux to a getMoisture function that returns a float in between 0 and 1 instead of a value in lux. For this, we will simply divide the ADCVal passed in by the full-scale range of the ADC (1023). In the end, our gatormoisture.cpp looks like the following. */ //% float getMoisture(int16_t ADCVal) { return ADCVal / 1023.0; } } Now let's check out how our blocks are created in the *.ts file, which should look like the following after we've changed everything from light to moisture. language:c enum gatorMoistureType{ moisture=1, adcVal=2, } //% color=#f44242 icon="\uf185" namespace gatorMoisture { // Functions for reading moisture from the gatormoisture in moisture or straight adv value /** * Reads the number */ //% weight=30 blockId="gatorMoisture_moisture" block="Get moisture on pin %pin | in %gatorMoistureType" } } /** * Function used for simulator, actual implementation is in gatormoisture.cpp */ //% shim=gatorMoisture::getMoisture function getMoisture(ADCVal: number) { // Fake function for simulator return 0 } } If we want to have options in dropdowns for our blocks, we create them using an enum. We will be able to choose whether we want moisture, a value between 0 and 1, or the straight adcVal. So outside of the namespace, we create an enum (shown below) for our possible data types. language:c enum gatorMoistureType{ moisture=1, adcVal=2, } We then must pick a color and icon for our extension, which is done in the line before we declare our namespace. The color can be any 6-digit, hexadecimal value, while the icon will use it's identifier from the FontAwesome icon library. The color and icon declarations are shown below. language:c //% color=#f44242 icon="\uf185" We then need to define what our block looks like and where it sits relative to other blocks. This is done by setting weight, blockId, and block. A block with weight 100 will list itself above blocks with weights below 100 and and below blocks with weights above 100. This allows you to decide how you want all of your blocks to be listed. The blockId MUST be mynamespacetitle_functionTitle so for our moisture block, which is in the gatorMoisture namespace, our blockId will be gatorMoisture_moisture. Finally, we decide exactly what goes into the text for the block using the block string. Any variable that we want to become a dropdown will be prefaced with a %. The following code will create a block with a dropdown for pin selection and a dropdown that allows you to choose between moisture and adcVal. This block will call the function moisture using whatever arguments that have been selected from the dropdown. language:c //% weight=30 blockId="gatorMoisture_moisture" block="Get moisture on pin %pin | in %gatorMoistureType" Finally, we'll need to write the function that actually reads our pin. Any function that is declared as export will appear as a block in MakeCode. Arguments for this function will be whatever we declared as dropdown capable variables and we'll usually need to set up a switch statement based on the type to return the proper values for each type selected. Notice how we call getMoisture, the function contained in our *.cpp when our type is moisture. We also must declare what the function returns, in this case, a number. language:c } } Any functions in our *.cpp will need a dummy function for the simulator. We create the analog for our getMoisture function as follows. Notice how, since it isn't exported, we won't see it in MakeCode. language:c //% shim=gatorMoisture::getMoisture function getMoisture(ADCVal: number) { // Fake function for simulator return 0 } Finally, we'll need to change the final part of the README (line 49) to our namespace followed by the GitHub address, this looks like gatorMoisture=github:sparkfun/pxt-gator-soil and allows the package to be recognized as a MakeCode extension. Compiling your Code Now that we've written all of our code, it's time to compile and test it, go ahead and open up a command prompt window and navigate to the directory where your MakeCode package lives. Once there, run the following commands to link to install the necessary PXT tools to build your code language:bash npm install npm install typings npm install jake npm link ../pxt pxt target microbit pxt install We then want to build our code and commit and push our changes to GitHub. language:bash pxt build git add -A git commit -m "changing names to gator:moisture" pxt bump The pxt bump command will prompt you to enter a version number with which to tag your release, just make sure it's higher than or equal to the version that you are being prompted to enter. The command will then tag your commit and push it to GitHub as a release. Test, Rinse, Repeat! To test our code, let's go ahead and open up the MakeCode Website and navigate down to extensions. From there, we'll log into our GitHub using a token, to do this, simply follow the instructions when you click login to GitHub. After we log in, we can paste the URL for the GitHub repo into the extension search bar, click on the result to include it! If it doesn't pop up, ensure that your repository is public. Once you've included your extension, feel free to check out its various features, edit the code as necessary and re-upload it to GitHub until you're satisfied! Resources and Going Further In the end, we'll eventually want our extension to be approved by Microsoft. Make sure to check out the MakeCode extension approval checklist. Then fill out this form to get started getting your package approved.
https://learn.sparkfun.com/tutorials/how-to-create-a-makecode-package-for-microbit
CC-MAIN-2021-21
refinedweb
1,509
71.34
Brad, We have our version of snprintf, just in case the installed standard library doesn't support it. This function called opal_snprintf will be aliased to snprintf (./opal/include/opal_config_bottom.h:410). As you are supposed to always include opal_config.h as first header in your files, using snprintf will always be safe. george. On Oct 27, 2008, at 8:08 AM, Brad Penoff wrote: > Greetings, > > In the current ompi-trunk (r19808), my build was breaking. I have > created a small patch to fix this, but I wanted to ask the team about > something first. One of the problems was with snprintf. I read a > little bit more about this and I found this quote about snprintf: > > "snprintf does not form part of the widely implemented ANSI C > standard, as sprintf does. However, it came into the language for the > later C99 standard and often existed in C libraries before that." > > So I'm wondering, should the use of snprintf as in > ompi/contrib/vt/vt/tools/opari/tool/opari.cc depend on the value of > _GLIBCXX_USE_C99 ? > > For my system, one "fix" seemed to be to just delete this "using > std::snprintf;" line. Everything then compiled and worked, but I don't > know how general/desired this "solution" is. Any comments on snprintf > and this solution? > > Thanks, > brad > > $ svn diff > Index: ompi/contrib/vt/vt/tools/opari/tool/opari.cc > =================================================================== > --- ompi/contrib/vt/vt/tools/opari/tool/opari.cc (revision 19808) > +++ ompi/contrib/vt/vt/tools/opari/tool/opari.cc (working copy) > @@ -15,7 +15,6 @@ > using std::cout; > using std::cerr; > #include <cstdio> > - using std::snprintf; > using std::remove; > #include <cstring> > using std::strcmp; > Index: orte/tools/orte-iof/orte-iof.c > =================================================================== > --- orte/tools/orte-iof/orte-iof.c (revision 19808) > +++ orte/tools/orte-iof/orte-iof.c (working copy) > @@ -37,6 +37,9 @@ > #ifdef HAVE_STDLIB_H > #include <stdlib.h> > #endif /* HAVE_STDLIB_H */ > +#ifdef HAVE_SIGNAL_H > +#include <signal.h> > +#endif /* HAVE_SIGNAL_H */ > #ifdef HAVE_SYS_STAT_H > #include <sys/stat.h> > #endif /* HAVE_SYS_STAT_H */ > _______________________________________________ > devel mailing list > devel@open-mpi.org > _______________________________________________ devel mailing list devel@open-mpi.org
https://www.open-mpi.org/community/lists/devel/att-4820/attachment
CC-MAIN-2016-30
refinedweb
343
59.9
Hi all, New to Android and IOS device apps and Xamarin, but years of experience with C# and Windows Phone/desktop apps, but this has stumped me. I have an application (Android to start with, then the IOS and Win versions later) that will be used for safety testing equipment in the field. An XML gets downloaded to the tablet once a day with a Windows PC application (via USB/Wireless - there will be no webservices involved). This XML I need to then "import" into a SQLite database on the tablet. The App will update the data in the database throughout the day. At the end of the day, the updated data gets extracted from the database and placed into an "export" xml file that gets re-imported into the PC app With the apps I have written over the years, I just easily load the XML into a Dataset and use the Dataset. Obviously, cant do this under Android/IOS hence using a DB. I have looked at code for creating the SQLite DB and to de-serialize the XML (haven't put anything together yet) but most of it seems doable but with a lot of code to get the desired result. So, some questions. 1) Have others done this how did they accomplish it. 2) Is loading this into a SQLite database the best way (I hate json but if you suggest that and provide a sample then I will experiment). 3) I need to create the Database from scratch everyday as the Database will only contain data relevant for that days work. 4) Do I need to de-serialize the XML to get the fields/data from the XML file to update the DB, or can it be done a different way. The reason I ask is that I have looked at Xamarin's Working with Files document. In their example, they only seem to be using 1 field called Monkey in their LIST Type to de-serialise the XML into, BUT, my exported XMLs (there will be one per DB table) contain multiple fields and data and I am stumped at how can it be de-serialized if I don't know all the "fields" or have a "LIST Type" (well, I know them from the PC app side, but I was hoping I didn't have to hard code them). I'm not after a full coded solution, just some ideas on how you would go about this. Maybe I am trying to make this too complicated (or more likely confused from all the different samples I have seen). Thanks, Rob I don't know an awful lot of background here, and so; I'll just shoot this out there blindly.. I think what you're concerned about is perhaps a lack of ability to bind an SQLite source to ADO.NET DataSets etc. For example, load the DataSet with the contents of the XML file, and then use an adapter to push changes to the database, and the other way around... I'm sure there is a way, I just haven't worked with SQLite in that way. But you do have one thing going for you, it sounds as though the XML files used to ship data to the handheld is always generated originally from a desktop app, and that desktop app is already working. So it stands to reason that you could at least load a dataset on the device with that source XML file. Assuming that you have the XML file on the Android filesystem, shouldn't you just be able to create a dataset, and use the ReadXML method? I find that while working with SQLite, the schema is always very well known. So there's the manual step of defining what the SQLite database will be so your application can manage the data, sure, but that's not an extra step, youd be doing that anyways. What you're left with is moving data to and from the data sets (while reading or overwriting the xml files). So those datasets would only exist for the purposes of importing or exporting to or from the SQLite database. (That could easily be isolated with an activity from the rest of your app) I think you're doing yourself a disservice by not using a web service by the way, even if self-hosted within that desktop app, and only having them running during a sync process. I feel as though it would give you more control, have less code to maintain, and of course just perform better.. But that's a bold statement without any background to the app, sounds like you have a system the client's been happy with for a while.. Hope that helps! I'll try and remember to check back up if you need me to try anything... Hi Mike. Thanks for your email, very much appreciated. To fill in some blanks. I created the desktop app as it consumes an Access database. The PC App does all the grunt work of putting data into the access database (created by someone else) such as client information, job information and test results from the field. Luckily, there is only about 7 small tables, 5 tables will only be used for lookups. The "client" wants to on-sell this Application to his Franchisees as a stand-a-lone PC App with Smart Device App included to test the equipment out in the field. Yes, it is a disservice not using web services, but the "client" doesn't want this as mentioned above, each "franchisee" is meant to look after their own data and the main company doesn't need to know about it. What I did all day yesterday was to try some things out. What I came up with was this (yes, a bit of manual work/code) and it seems to work OK (only with one table tested at the moment). 1) I export the XML file (1 per table) to the Device 2) I created the DB on the device using Classes created for each table and with SQLite-net, send the commands: Note: dbConnection defined elsewhere as: public static SQLiteAsyncConnection dbConnection; dbPath defined as: public static string dbPath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "fsm.db"); dbConnection = new SQLiteAsyncConnection(dbPath); //Create tables dbConnection.CreateTableAsync<dbtblAlarm>(); dbConnection.CreateTableAsync<next table>(); (repeated for each "class/table") The class for one of the tables looks like this: public class dbtblAlarm { [PrimaryKey, AutoIncrement] public int Asset_Key { get; set; } public string Asset_ID { get; set; } public int Site { get; set; } public int Location { get; set; } public string Type { get; set; } public string Voltage { get; set; } public int Battery_10yr { get; set; } public string Make { get; set; } public string Model { get; set; } public string Serial_Number { get; set; } public string Manufacture_Date { get; set; } public int Test_Period { get; set; } public int In_Service { get; set; } public string Notes { get; set; } } 3) I open each XML document up as an XDocument XDocument infodocument = XDocument.Load(xmlFile); 4) I run a LINQ query on the XML to retrieve the data and load the class up. For example, using the class above, this is the code to read the XML and save to the class. var alarm = from r in infodocument.Descendants("Alarm") select new { _Asset_Key = r.Element("Asset_Key").Value, _Asset_ID = r.Element("Asset_ID").Value, _Site = r.Element("Site").Value, _Location = r.Element("Location").Value, _Type = r.Element("Type").Value, _Voltage = r.Element("Voltage").Value, _Battery_10yr = r.Element("Battery_10yr").Value, _Make = r.Element("Make").Value, _Model = r.Element("Model").Value, _Serial_Number = r.Element("Serial_Number").Value, _Manufacture_Date = r.Element("Manufacture_Date").Value, _Test_Period = r.Element("Test_Period").Value, _In_Service = r.Element("In_Service").Value, _Notes = r.Element("Notes").Value, }; 5) The last command I use is to Update the database and I found that using the following code, I can just send the data and it will determine whether or not the data exists and needs updating, or inserting. The only thing now is to see what the database and data look like, but I haven't got that far yet. Sure, the code isn't the prettiest (and if you see any glaring mistakes or better ways to do it, I would love to know). This code is run in a new thread (launched from the UI but not under the UI thread which is now causing other issues (like showing an alert on the UI if an update fails) but I will put in a different post later). Getting back to the Dataset thingy, I only thought there were datatables that were available to use, and from what I read, a lot highly recommend you DONT use them, hence why I thought the DB was the best way. So, that's as far as I got. Thanks for your input. Rob Awesome, look I'm not here to judge specific code, lol Your approach is sound enough, read the Xml Document into the table. I guess in terms of whether to insert or update.. well if you can always assume the incoming XML file is up to date and has all records, I would clear the table before importing again. I would make this more complicated if you need 2-way merging... But since you're working on a copy to device and import , and export and then copy out of device, I suspect it doesn't need to be more complicated than that. Also, sure, if you want to see what that SQLite database looks like, now that you're importing stuffs into it... you should check out SQLiteBrowser. (It's free and pretty useful) Also, when I responded this morning, I did so hastily, getting ready for a meeting. You asked if I saw anything that maybe you could do better, to let you know. I'm not sure if better is the right word for this suggestion, just something to keep in mind. Where you grab "Alarms" from the XML file, and you iterate through them to insert into the database. If you have any special rules in the table schema, such as required fields, or optional fields (In my experience it's the data that may or may not be there that would more likely cause an issue), consider guarding inputs. In .NET strings can be null of course, or in the case of pulling from an XML file, they can be empty as well. So when you have something like Convert.ToInt32, that's effectively a parse. And depending on how you have any supporting XSD's set up, you may be able to export that Xml file with some empty values (or potentially without even packing that element at all). It's very likely that you're not, but the Android app won't know anything about that. I consider it best practice (even if it doesn't always make sense, so use common sense I guess) to check before parsing. example: if (r == null) continue; //or log, or throw up (but don't bother trying to read fields off of it) ... dbtblalarm.Battery_10yr = string.IsNullOrWhitespace(r.Battery_10yr) ? null : Convert.ToInt32(r._Battery_10yr); ... Because if the table allows nulls, you'd rather insert a null value than the default parse result. Convert.To functions are really safe, so safe that a null value will insert a 0 instead of a null. Or on the other side of the fence, if the table doesn't allow nulls, or for some business reason has specific requirements on un-entered values, it allows you to gracefully handle that, instead of trying to make a catch all solve all your problems. And obviously, that could be modified to handle any other special case. Sometimes it also makes sense to make a table specifically for importing, that doesn't really have much in terms of expectations to the quality of the data at all. I like the term "staging" for those tables, the idea is that you get the data from the file, into the staging table, and then you implement the import using "transforms". It's a nice pattern for when you have really complicated business rules as to how you handle the data, especially if the data is going into environments that are heavily normalized. Anyways, my two cents. But honestly, those are pretty straight forward code snippets. Only so many ways to smash a rock! Thanks for all that. Much appreciated. I haven't got to the error checking part, just threw something together to see if the concept would work. Thanks for the error check ideas. I usually do something similar. Thanks for the reference to the SQLite DB browser. I have downloaded it and looked at my SQLite DB and everything is AOK, so I will keep going down the path I have started. Thanks again for your input. Hello Robert, I am in the exact situation here. I have a requirement to create tables and load data from XML into a SQLite DB in C#. Your approach of using LINQ to XML and SQLite was exactly what i was thinking of. Can you please let me know if you were successful in this. Could you please share the code you used. Much appreciated! Thanks!
https://forums.xamarin.com/discussion/65356/load-xml-to-sqlite-database-some-ideas-help
CC-MAIN-2019-22
refinedweb
2,215
69.31
If you go back and re-read PEP 359, a lot of the motivating examples -- creating namespaces, setting GUI properties, templating HTML -- are still compelling. If you add in the examples of ORM tables and interactive fiction processors, I think what unites all the examples is that the make statement is a way of creating a DSL from within Python. Can using a DSL within Python be pythonic ,though? That's a difficult question to answer. But, on the other hand, just because there's no clean, non-magical way of making a DSL within Python doesn't mean people won't try and indeed, we can see the results of their trying out there today. For example, see Biwako <> a recent project which abuses metaclasses to create a declarative syntax for processing file formats. Here's an excerpt from that page: > For example, here’s a very simple Biwako class that will can parse part of the > GIF file format, allowing you to easily get to the width and height of any GIF image. > > from biwako import bin > > class GIF(bin.Structure, endianness=bin.LittleEndian, encoding='ascii'): > tag = bin.FixedString('GIF') > version = bin.String(size=3) > width = bin.Integer(size=2) > height = bin.Integer(size=2) > > Now you have a class that can accept any GIF image as a file (or any file-like > object that’s readable) and parse it into the attributes shown on this class. > > >>> image = GIF(open('example.gif', 'rb')) > >>> image.width, image.height > (400, 300) So basically, the author of this project is calling GIF a "class" but it's not something that really operates the way a normal class does, because it's subclassing the magical bin.Structure class and inheriting its metaclass. With a little searching, you can find similar examples of abuse that are centered around the with statement rather than metaclasses. People have made the with statement into an XML generator <> or an anonymous block handler <>. Seeing examples like these make me think a re-examination of PEP 359 would be a good idea. Of course, I do think it needs a little more work (in particular, I think the make statement should have an equivalent of a __prepare__ method and should receive the BLOCK as a callback instead of automatically executing it), but the core idea is worth taking another look at. -- Carl
https://mail.python.org/pipermail/python-ideas/2011-March/009328.html
CC-MAIN-2016-30
refinedweb
394
61.67
The classes which are defined within another classes are known as Nested Classes. These are also known as Inner Class. The Class in which inner class resides are known as Outer Class. Inner Class has access to the private member of the outer class. But the Outer Class doesn't have access to the member of the inner class including public member also. Nested classes are of two types : Static nested classes are classes which is defined through static modifier. Static nested classes can access the member of the it's outer class through an object. Static inner classes can't access the member of the outer class direclty. The non static classes have access to all the members of the it's outer class. Given below example will give you clear idea about inner or outer classes : class Outer { int x = 100; void test() { Inner inner = new Inner(); inner.display(); } // Inner Class class Inner { void display() { System.out.println("display : x = " + x); } } } public class SimpleInnerClass { public static void main(String args[]) { Outer outer = new Outer(); outer link to the outer class,java tutorial,java tutorials Post your Comment
http://roseindia.net/javatutorials/outer_class.shtml
CC-MAIN-2016-30
refinedweb
189
56.45
Source code for sympy.core.sympify """sympify -- convert objects SymPy internal format""" from __future__ import print_function, division from inspect import getmro from .core import all_classes as sympy_classes from .compatibility import iterable, string_types, range from .evaluate import global_evaluate class SympifyError(ValueError): def __init__(self, expr, base_exc=None): self.expr = expr self.base_exc = base_exc def __str__(self): if self.base_exc is None: return "SympifyError: %r" % (self.expr,) return ("Sympify of expression '%s' failed, because of exception being " "raised:\n%s: %s" % (self.expr, self.base_exc.__class__.__name__, str(self.base_exc))) converter = {} # See sympify docstring. class CantSympify(object): """ Mix in this trait to a class to disallow sympification of its instances. Examples ======== >>>. It currently accepts as arguments: - any object defined in sympy - standard numeric python types: int, long, float, Decimal - strings (like "0.09" or "2e-19") - booleans, including ``None`` (will leave ``None`` unchanged) - lists, sets or tuples containing any of the above .. warning:: Note that this function uses ``eval``, and thus shouldn't be used on unsanitized input. If the argument is already a type that SymPy understands, it will do nothing but return that value. This can be used at the beginning of a function to ensure you are working with the correct type. >>> from sympy import sympify >>> sympify(2).is_integer True >>> sympify(2).is_real True >>> sympify(2.0).is_real True >>> sympify("2.0").is_real True >>> sympify("2e-45").is_real True If the expression could not be converted, a SympifyError is raised. >>> sympify("x***2") Traceback (most recent call last): ... SympifyError: SympifyError: "could not parse u'x***2'"('I & Q', _clash1) I & --------- To extend ``sympify`` to convert custom objects (not derived from ``Basic``), just define a ``_sympy_`` method to your class. You can do that even to classes that you do not own by subclassing or adding the method at runtime. >>> from sympy import Matrix >>> class MyList1(object): ... def __iter__(self): ... yield 1 ... yield 2 ... return ... def __getitem__(self, i): return list(self)[i] ... def _sympy_ SymPy object, e.g. ``converter[MyList] = lambda x: Matrix(x)``. >>> class MyList2(object): # XXX Do not do this if you control the class! ... def __iter__(self): # Use _sympy_! ... yield 1 ... yield 2 ... return ... def __getitem__(self, i): return list(self)[i] >>> from sympy.core.sympify import converter >>> converter[MyList2] = lambda x: Matrix(x) >>> sympify(MyList2()): if global_evaluate[0] is False: evaluate = global_evaluate[0] else: evaluate = True try: if a in sympy_classes: return a except TypeError: # Type of a is unhashable pass try: cls = a.__class__ except AttributeError: # a is probably an old-style class object cls = type(a) if cls in sympy_classes: return a if cls is type(None): if strict: raise SympifyError(a) else: return a #Support for basic numpy datatypes if type(a).__module__ == 'numpy': import numpy as np if np.isscalar(a): if not isinstance(a, np.floating): return sympify(np.asscalar(a)) else: try: from sympy.core.numbers import Float prec = np.finfo(a).nmant a = str(list(np.reshape(np.asarray(a), (1, np.size(a)))[0]))[1:-1] return Float(a, precision=prec) except NotImplementedError: raise SympifyError('Translation for numpy float : %s ' 'is not implemented' %): for coerce in (float, int): try: return sympify(coerce(a)) except (TypeError, ValueError, AttributeError, SympifyError): continue if strict: raise SympifyError(a) try: from ..tensor.array import Array return Array(a.flat, a.shape) # works with e.g. NumPy arrays except AttributeError: pass if iterable(a): try: return type(a)([sympify(x, locals=locals, convert_xor=convert_xor, rational=rational) for x in a]) except TypeError: # Not all iterables are rebuildable with their type. pass if isinstance(a, dict): try: return type(a)([sympify(x, locals=locals, convert_xor=convert_xor, rational=rational) for x in a.items()]) except TypeError: # Not all iterables are rebuildable with their type. pass # At this point we were given an arbitrary expression # which does not inherit from Basic and doesn't implement # _sympy_ (which is a canonical and robust way to convert # anything to SymPy expression). # # As a last chance, we try to take "a"'s normal form via unicode() # and try to parse it. If it fails, then we have no luck and # return an exception try:def _sympify(a): """ Short version of sympify for internal usage for __add__ and __eq__ methods where it is ok to allow some things (like Python integers and floats) in the expression. This excludes things (like strings) that are unwise to allow into such an expression. >>> from sympy import Integer >>> Integer(1) == 1 True >>> Integer(1) == '1' False >>> from sympy
http://docs.sympy.org/dev/_modules/sympy/core/sympify.html
CC-MAIN-2017-26
refinedweb
744
50.84
Lightning Components framework provides a great way to easily decompose applications into components. But building applications also depend on tons of other OSS libraries like JQuery, Twitter Bootstrap, Moment.js and more to implement various features. While loading 3rd party libraries is trivial, loading them into a trusted enterprise environment like Salesforce needs to meet our strict security needs. They also need to meet various application needs such as loading multiples files in a specific order. So with Spring ‘15 release we created a new component called ltng:require to load libraries while being secure. It has the following features: Asynchronously load multiple CSS and/or JS libraries Load libraries in any dependency order the app needs Let the app know when loading all JS libraries are complete Most importantly, load only verifiable libraries (for security purposes) Let’s take at the syntax to better understand it: <ltng:require styles – Allows us to specify multiple CSS files separated by comma. They will be loaded from left-to-right. scripts – Allows us to specify multiple JS files separated by comma. Again they will be loaded from left-to-right afterScriptsLoaded – Allows us to provide a JS function to notify when all JS files are loaded. Notes: Files paths must always start from /resource. i.e they must be a static resource to enforce security. CDNs are not allowed at this point because they are outside of Salesforce data centers and can’t be controlled. In the future, we may allow admins to whitelist CDNs for their orgs. If you upload a JS or CSS directly into Static resource, then you should reference them by resource name without .css or .js suffix. For example: /resource/myjsfile or /resource/mycssfile If your resource is inside a zip file, then you should use .css or .js suffix. For example: /resource/<resourcename>/path/to/myjsfile.js A Bootstrap Dropdown Component Example: This is a simple wrapper around Twitter Bootstrap’s dropdown menu. This dropdown menu needs 1. JQuery, 2. Bootsrap’s own JS(aka bootstrapjs) and 3. it’s own CSS to work properly. Also it need us to first load JQuery before loading bootstrapjs. Here is the code to load all three of them: <ltng:require The above code loads bootstrap CSS and JQuery in parallel. And once JQuery is downloaded, it loads bootstrapjs and finally calls “jsLoaded” controller JavaScript function. dropdown.cmp <aura:component> <ltng:require <div class='mynamespace'> <div> <div id="dLabel" type="button" class='btn btn-success' data- Some Menu <span></span> </div> <ul role="menu" aria- <li role="presentation"><a role="menuitem" href="">Action</a></li> <li role="presentation"><a role="menuitem" href="">Another action</a></li> </ul> </div> </div> </aura:component> dropdowncontroller.js ({ jsLoaded: function(component, event, helper) { alert('ready to go'); } }) Usage or myapp.app <aura:application> <c:dropdown /> </aura:application> CSS Namespacing: Many 3rd party CSS libraries like Twitter Bootstrap changes styles for the entire application. This can cause problems when running your component in S1 Mobile app or inside Lightning App Builder. We strongly recommend CSS-namespacing them before using them. This namespace is not the same as your org’s namespace but a simple CSS class name to avoid your CSS bleeding into other components. This could be any unique classname name for a container (div) that wraps your component. For example if your component’s markup is: <div class=’redColor’> my component </div> And CSS is: .redColor {color: red} Wrap the markup in another div with a unique class name (say ‘’cssns’) <div class=’cssns’> <div class=’redColor’> my component </div> </div> And update your CSS file to look like: .cssns .redColor { color: red } Now, since libraries like Twitter Bootstrap has 1000s of class names, you need to use some tool to namespace all those 1000s of classes like the CSS namespacer tool and use the custom Twitter Bootstrap. CSS Namespacer tool: is a simple tool (source) that adds any namespace you want to the entire CSS file. New to Lightning Components? There are many resources to get started: - Lightning Components Trailhead (Link): This provides a simple and fun way to learn Lightning Components. In addition, you’ll acquire badges and points to show off. - Lightning Component Developer Guide (Link) This provides detailed information of everything Lightning Components. - Aura Docs (Link) – This is a built-in lightning app that comes with every org that has Lightning. It provides documentation of every lightning component currently running in that specific org. To open it, simply open /auradocs () in your org.
https://developer.salesforce.com/blogs/2015/05/loading-external-js-css-libraries-lightning-components
CC-MAIN-2021-39
refinedweb
754
54.73
Scripting Hyper-V with WMI and PowerShell Part 1 – Introduction + Querying State Introduction When it comes to scripting Hyper-V there are really 2 methods: 1. Using the virtualization WMI provider that ships with Hyper-V. 2. Using the cmdlets provided by System Centre Virtual Machine Manager 2008 So which option should you use? Well if you want an easy life, the answer is absolutely Option 2. Use SCVMM 2008, and scripting Hyper-V is like a pleasurable dream. The cmdlets are task orientated, provide a rich set of features and really do work very well. So why is this a guide to Option 1 – Using the virtualization WMI provider? Well, sometimes Hyper-V will be used without an accompanying System Centre deployment, and if that’s the case, using WMI is your only scripting option. I`ll be honest, using the WMI provider to script Hyper-V is unintuitive, complicated and feels quite clunky. So the question has to be asked “Why is the Hyper-V WMI provider so difficult to use?” The answer is Industry Standards. The virtualization WMI provider fully complies with the standards outlined by the Distributed Management Task Force (DMTF). Whilst standards are great for creating consistency among different vendors, there are often comprises with the simplicity of individual solutions. Contrastingly the SCVMM cmdlets are a bespoke solution designed by Microsoft to be simple, intuitive and powerful, but do not adhere to any industry standards. So, with the expectation that the Hyper-V WMI journey will be a challenging one, let’s get on with it. WMI Basics As mentioned we will be using the virtualization WMI provider, and before going any further I would strongly recommend that you spend some time understanding WMI to a reasonable depth. If you can answer the following questions, you’re probably familiar enough with WMI to get the most out of this tutorial: 1. What is namespace? 2. What is a class? 3. How do you create a WMI Object in PowerShell? Basic WMI information is out of scope for this tutorial, so if you can’t answer the above questions, before continuing I would suggest the following pre-reading/viewing: 1. Brief WMI Intro on Technet Edge - 2. Windows, PowerShell and WMI – Tech Ed 2008 Session 3. Microsoft Windows PowerShell Step by Step Book- Hyper-V + WMI There are 2 key points you need to understand to start using the Hyper-V WMI provider. 1. All Hyper-V classes live in the “Virtualization” namespace. Therefore whenever you want to instantiate an object you need to specify this namespace. The following sample lists all the classes available in this namespace: Get-WMIObject –namespace “root\virtualization” -list 2. PowerShell must be elevated and running as an administrator. If you run PowerShell in a non-administrative context you will not be able to connect to any guests, and will only be able to affect the host. In Server 2008 you need to right-click the PowerShell icon, then click “Run As Administrator” to achieve this, even if logged on as an administrator. VMStateQuery Often, I find the best way to learn something is with a worked example. Attached to this post is VMStateQuery.ps1, which is an example PowerShell script which can be used to determine the state of guests deployed to a Hyper-V host. The script can be used to return the state of all guests on a host, or the state of 1 particular guest. Usage . This line connects using WMI and retrieves all instances of MSVM_ComputerSystem on the computer specified by $VHost. This line returns an array of all guests and the host, each one represented by an object. In order to find out what we can with this object type we can do two things. Firstly, use Get-Member to obtain all properties and methods, or use this MSDN link, which details each property and method. Having looked at the properties of this object we can see 2 properties that will be particularly useful when trying to query a guest’s state: elementname and enabledstate. ElementName is the name of the guest that you see in the Hyper-V MMC console, and enabledstate is a number that represents the state of the machine. This bit of code filters our array of guests, and returns any that match the following $vms = $vms | where-object {$_.elementname -eq $vguest} We simply use where-object to filter, such that only guests whose elementname equals $vguest are retained. We use the enabledstate property to identify the state of the machine. However, the state of the machine is a number which might not make too much sense. Therefore I’ve created a function called ConvertStateToFriendly which simply uses a switch statement to return a friendly word for the state. The call to this function is nested as an expression that can be used by the format-table cmdlet to display the information nicely. Here’s the code: "} When you get all instances of MSVM_ComputerSystem, one of the returned objects represents the host system. In this script I am not really interested in the state of the host, just the state of the guests. Therefore the above line simply looks at the caption property of the objects, and drops the object with the name “Hosting Computer System”. All the rest of the script is generic PowerShell code, used for parameters, error checking and other useful bits and pieces. Hyper-V WMI Resources The two best resources for Hyper-V WMI scripting that I have come across so far are the MSDN page, and James O’Neil’s Hyper-V management library on CodePlex. The MSDN page is the definitive source on the WMI provider and is here: The Code Plex project which James uploaded is a pretty comprehensive library on managing Hyper-V and WMI. It’s an excellent source, but be warned it is pretty hardcore and very code efficient in places, which can sometimes be quite tricky to understand (maybe that’s just me J) My colleague Richard Macdonald has written a very similar script, but using C# instead of PowerShell. Check out his blog here for the code. Well that’s it for part 1. Stay tuned for Part 2 –Hyper-V Data Gathering. Enjoy BenP You may have seen from a recent post that I received a new laptop that was capable of running Hyper-V. If you would like to receive an email when updates are made to this post, please register here RSS Trademarks | Privacy Statement
http://blogs.technet.com/benp/archive/2008/08/11/scripting-hyper-v-with-wmi-and-powershell-part-1-introduction-querying-state.aspx
crawl-002
refinedweb
1,091
61.56
Learn about Java variables, types of variables in Java, example of how to declare variables and best practices for variables naming convention. The Java programming language uses both “fields” and “variables” as part of its terminology. Fields refer to variables declared outside methods, and variables are referred to declarations inside methods, including method arguments. 1. What is variable As term suggest, a variable is whose value can vary during the runtime. In Java, a variable is a named reference to a memory area where value of the variable is stored. 1.1. Variable declaration syntax A variable declaration has following syntax: [data_type] [variable_name] = [variable_value]; - data_type – refer to type of information stored in memory area. - variable_name – refer to name of variable. - variable_value – refer to value to be stored in memory area. For example, below statements are valid variable declarations in Java. int i = 10; //Variable of int type String str = "howtodoinjava.com"; //Variable of string type Object obj = new Object(); //Variable of object type int[] scores = [1,2,3,4,5,6,7,8,9]; //Variable of int type 1.2. Java variable example int i = 10; int j = 10; int sum = i + j; System.out.println( sum ); Program output. 20 2. Widening and Narrowing 2.1. Widening When a small primitive type value is automatically accommodated in a bigger/wider primitive data type, this is called widening of the variable. In given example, int type variable is assigned to long type variable without any data loss or error. int i = 10; long j = i; System.out.println( i ); System.out.println( j ); Program output. 10 10 2.2. Narrowing When a larger primitive type value is assigned in a smaller size primitive data type, this is called narrowing of the variable. It can cause some data loss due to less number of bits available to store the data. It requires explicit type-casting to required data type. In given example, int type variable is assigned to byte type variable with data loss. int i=198; byte j=(byte)i; System.out.println( i ); System.out.println( j ); Program output. 198 -58 3. Types of Variables In Java, there are four types of variables. These variables can be either of primitive types, class types or array types. All variables are divided based on scope of variables where they can be accessed. Instance Variable Variables declared (in class) without statickeyword. Non-static fields are also known as instance variables because their values are unique to each instance of a class. They are also called state variables. public class VariableExample { int counter = 20; //1 - Instance variable } Static Variable Also know as class variables. It is any field declared with the staticmodifier. It means that there is exactly one copy of this variable in existence, regardless of how many times the class has been instantiated. public class VariableExample { static float PI = 3.14f; //2 - Class variable } A variable declared as “public static” can be treated as global variable in java. Local variable These are used inside methods as temporary variables exist during the method execution. The syntax for declaring a local variable is similar to declaring a field. Local variables are only visible to the methods in which they are declared; they are not accessible from the rest of the class. public class VariableExample { public static void main( String[] args ) { int age = 30; //3 - Local variable (inside method body) } } Method Argument An argument is a variable that is passed to a method when the method is called. Arguments are also only accessible inside the method that declares them, although a value is assigned to them when the method is called. public class VariableExample { public static void main( String[] args ) { print( 40 ); } public static void print ( int param ) { //4 - Method Argument System.out.println ( param ); } } 4. Instance variables vs Class Variables - Instance variables (non-static fields) are unique to each instance of a class. - Class variables (static fields) are fields declared with the staticmodifier; there is exactly one copy of a class variable, regardless of how many times the class has been instantiated. - To access instance variable, you MUST create a new instance of class. Class variables are accessible through class reference, and do not require to create object instance. Take an example. We have a class Datawhich have one instance variable as well as one class variable. public class Data { int counter = 20; static float PI = 3.14f; } We can access both variable in given way. public class Main { public static void main(String[] args) { Data dataInstance = new Data(); //Need new instance System.out.println( dataInstance.counter ); //20 //Can access using class reference System.out.println( Data.PI ); //3.14 } } 5. Java Variable Naming Conventions There are a few rules and conventions related to how to define variable names. - Java variable names are case sensitive. The variable name employeeis not the same as Employeeor EMPLOYEE. - Java variable names must start with a letter, or the $or _character. - After the first character in a Java variable name, the name can also contain numbers, $or _characters. - Variable names cannot be reserved keywords in Java. For instance, the words break or continueare reserved words in Java. Therefore you cannot name your variables to them. - Variable names should written in lowercase. For instance, variableor apple. - If variable names consist of multiple words, then follow camelcase notation. For instance, deptNameor - Static final fields (constants) should be named in all UPPERCASE, typically using an _to separate the words in the name. For example LOGGERor INTEREST_RATE. Happy Learning !!
https://howtodoinjava.com/java/basics/java-variables/
CC-MAIN-2020-10
refinedweb
917
58.58
Introduction: Calculator Coded With Python After learning a bit about the programming language Python, I though that it would be neat to try and replicate some of the math that they Python shell does with a GUI. While I clearly did not match the shell's performance my calculator adds a few helpful shortcuts such as the numbers "pi" and "e" as well as the trig functions sin() cos() and tan(). You will need to keep everything both files in the zip file in the same folder for this to work. The code has a number of comments, but if you have any questions as to how anything works please let me know and I will be happy to show you! Recommendations We have a be nice policy. Please be positive and constructive. 5 Comments I have edited the code to fix the print issue but I keep on getting this error: Traceback (most recent call last): File "/Downloads/Revised Calculator/Gui.py", line 67, in <module> import tkFont ModuleNotFoundError: No module named 'tkFont' Here are the edited files. Please edit your code. All of your print commands are missing parenthesis. amazing what did you make this for? school? I did, it was a short project.
http://www.instructables.com/id/Calculator-Coded-with-Python/
CC-MAIN-2018-26
refinedweb
206
79.8
Read from dbf's if codepage is unsupported by modules dbf and codecs (895 cz Kamenicky, ..). Project description Make possible to read from dbf’s with codepage unsupported by modules dbf and codecs (895 cz Kamenicky, ..) import dbf from dbf_read_iffy import fix_init, fix_895 fix_init(dbf) t = dbf.Table('autori.dbf') t.open('read-only') for record in t: print fix_895(record.autor) t.close() You can ignore Python 2.7 installation error in test_v3.py (from aenum which is requirement of dbf). For 620 pl Mazovia: You can define conversion map in fix_620(). If possible please: Fork me, clone your fork, commit/push, generate Pull request from your fork. Thx. Project details Release history Release notifications Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/dbf_read_iffy/
CC-MAIN-2018-39
refinedweb
137
68.77
I wanted to find out the overhead of getting the stack trace and finding a specific method in the array of stack frames. The profiled code looked like this: private static MethodBase GetCallerMethod(string caller) { StackTrace st = new StackTrace(2); return (from f in st.GetFrames() let m = f.GetMethod() where m.Name == caller select m).FirstOrDefault(); } I used QueryThreadCycleTime API or more precise measurements [DllImport("kernel32.dll")] [return: MarshalAs(UnmanagedType.Bool)] static extern bool QueryThreadCycleTime(IntPtr ThreadHandle, out ulong CycleTime); [DllImport("kernel32.dll")] static extern IntPtr GetCurrentThread(); and here is what I found out for my test case: - Average CPU cycles to get StackFrame[]: ~500,000 - Average CPU cycles for Linq query to find the calling method (which is usually near the top of the stack): ~70,000 - In comparison, a call to a local SQL server database to execute a stored procedure (getting a record based on primary key) on a very small database (narrow, well indexed tables with < 100 rows): ~910,000 In summary, based on my tests, the cost of finding a stack frame is in the same ballpark as making a stored procedure call on a very small (sample) well indexed database residing on the same machine.
https://blogs.msdn.microsoft.com/irenak/2014/09/27/sysk-394-cost-of-getting-stacktrace-and-finding-a-stackframe/
CC-MAIN-2017-30
refinedweb
202
58.92
android / platform / system / core / master / . / init / readme.txt blob: bf440c2b78a090c5d0caf81c867547f28f06e71f [ file ] [ log ] [ blame ] Android Init Language --------------------- The Android Init Language consists of five broad classes of statements, which are. Actions and Services implicitly declare a new section. All commands or options belong to the section most recently declared. Commands or options before the first section are ignored. Actions and Services have unique names. If a second Action is defined with the same name as an existing one, its commands are appended to the commands of the existing action. If a second Service is defined with the same name as an existing one, it is ignored and an error message is logged. Init .rc Files -------------- The init language is used in plaintext files that take the .rc file extension. These are typically multiple of these in multiple locations on the system, described below. /init.rc is the primary .rc file and is loaded by the init executable at the beginning of its execution. It is responsible for the initial set up of the system. It imports /init.${ro.hardware}.rc which is the primary vendor supplied .rc file. During the mount_all command, the init executable loads all of the files contained within the /{system,vendor,odm}/etc/init/ directories. These directories are intended for all Actions and Services used after file system mounting. The intention of these directories is as follows 1) /system/etc/init/ is for core system items such as SurfaceFlinger and MediaService. 2) /vendor/etc/init/ is for SoC vendor items such as actions or daemons needed for core SoC functionality. 3) /odm/etc/init/ is for device manufacturer items such as actions or daemons needed for motion sensor or other peripheral functionality.>> [ <seclabel> ] ] ] Create a unix domain socket named /dev/socket/<name> and pass its fd to the launched process. <type> must be "dgram", "stream" or "seqpacket". User and group default to 0. 'seclabel' is the SELinux security context for the socket. It defaults to the service security context, as specified by seclabel or computed based on the service executable file security context.) seclabel <seclabel> Change to .. writepid <file...> Write the child's pid to the given files when it forks. Meant for cgroup/cpuset usage. Triggers -------- Triggers are strings which can be used to match certain kinds of events and used to cause an action to occur. Triggers are subdivided into event triggers and property triggers. Event triggers are strings triggered by the 'trigger' command or by the QueueEventTrigger() function within the init executable. These take the form of a simple string such as 'boot' or 'late-init'. Property triggers are strings triggered when a named property changes value to a given new value or when a named property changes value to any new value. These take the form of 'property:<name>=<value>' and 'property:<name>=*' respectively. Property triggers are additionally evaluated and triggered accordingly during the initial boot phase of init. An Action can have multiple property triggers but may only have one event trigger. For example: 'on boot && property:a=b' defines an action that is only executed when the 'boot' event trigger happens and the property a equals b. 'on property:a=b && property:c=d' defines an action that is executed at three times, 1) During initial boot if property a=b and property c=d 2) Any time that property a transitions to value b, while property c already equals d. 3) Any time that property c transitions to value d, while property a already equals b. Commands -------- bootchart_init Start bootcharting if configured (see below). This is included in the default init.rc. chmod <octal-mode> <path> Change file access permissions. chown <owner> <group> <path> Change file owner and group. class_start <serviceclass> Start all services of the specified class if they are not already running. class_stop <serviceclass> Stop and disable all services of the specified class if they are currently running. class_reset <serviceclass> Stop all services of the specified class if they are currently running, without disabling them. They can be restarted later using class_start. copy <src> <dst> Copies a file. Similar to write, but useful for binary/large amounts of data.. export <name> <value> Set the environment variable <name> equal to <value> in the global environment (which will be inherited by all processes started after this command is executed) hostname <name> Set the host name. ifup <interface> Bring the network interface <interface> online. insmod <path> Install the module at <path>>.> Calls fs_mgr_mount_all on the given fs_mgr-format fstab. mount <type> <device> <dir> [ <flag> ]* [<options>] Attempt to mount the named device at the directory <dir> <device> may be of the form mtd@name to specify a mtd block device by name. <flag>s include "ro", "rw", "remount", "noatime", ... <options> include "barrier=1", "noauto_da_alloc", "discard", ... as a comma separated string, eg: barrier=1,noauto_da_alloc powerctl Internal implementation detail used to respond to changes to the "sys.powerctl" system property, used to implement rebooting. restart <service> Like stop, but doesn't disable. setprop <name> <value> Set system property <name> to <value>. Properties are expanded within <value>. setrlimit <resource> <cur> <max> Set the rlimit for a resource. start <service> Start a service running if it is not already running.. write <path> <content> Open the file at <path> and write a string to it with write(2). If the file does not exist, it will be created. If it does exist, it will be truncated. Properties are expanded within <content>. Imports ------- The import keyword is not a command, but rather its own section and is handled immediately after the .rc file that contains it has finished being parsed. It takes the below form: import <path> Parse an init config file, extending the current configuration. If <path> is a directory, each file in the directory is parsed as a config file. It is not recursive, nested directories will not be parsed. There are only two times where the init executable imports .rc files, 1) When it imports /init.rc during initial boot 2) When it imports /{system,vendor,odm}/etc/init/ during mount_all Properties ---------- Init provides information about the services that it is responsible for via the below properties. init.svc.<name> State of a named service ("stopped", "stopping", "running", "restarting") Bootcharting ------------ This version of init contains code to perform "bootcharting": generating log files that can be later processed by the tools provided by. On the emulator, use the -bootchart <timeout> option to boot with bootcharting activated for <timeout> seconds. On a device, create /data/bootchart/start with a command like the following: adb shell 'echo $TIMEOUT > /data/bootchart/start' Where the value of $TIMEOUT corresponds to the desired bootcharted period in seconds. Bootcharting will stop after that many seconds have elapsed. You can also stop the bootcharting at any moment by doing the following: adb shell 'echo 1 > /data/bootchart/stop' Note that /data/bootchart/stop is deleted automatically by init at the end of the bootcharting. This is not the case with /data/bootchart/start, so don't forget to delete it. Comparing two bootcharts ------------------------ -------- Systrace [1]. [1] Debugging init -------------- You might want to call klog_set_level(6) after the klog_init() call so you see the kernel logging in dmesg (or the emulator output).
https://android.googlesource.com/platform/system/core/+/master/init/readme.txt
CC-MAIN-2015-40
refinedweb
1,199
57.77
Misleading branch coverage of empty methods Branch coverage of an abc.abstractmethod with just a doc string in the method, shows the decorator line as uncovered branch that never reaches "exit". import abc class AExample(object): @abc.abstractmethod # exit def method(self): """doc """ class Example(AExample): def method(self): return True Example().method() When I replace the doc string with "pass", the decorator line is a covered branch. However the pass statement is not covered at all. class AExample(object): @abc.abstractmethod def method(self): pass # uncovered Turns out this isn't about abstract methods, it's about empty uncalled methods with only a docstring: It's unclear to me what the correct behavior is, it seems to me it's either a) no executed, or b) covered, but not a branch coverage thing. (b) is somewhat more convenient, but I'm not sure it's more correct. (a) would seem more appropriate for a bare function definition with only a docstring, while (b) seems right for an abstractmethod, so perhaps that should be special-cased as the OP suggested. Incidentally, it's easy enough to do per-project because the "blamed" lines are the ones with the decorators. In your project .coveragerc: This will be fixed when the ast-branch code is merged. This is fixed in 44719bd, which will be 4.1
https://bitbucket.org/ned/coveragepy/issues/129/misleading-branch-coverage-of-empty
CC-MAIN-2018-26
refinedweb
224
65.22
Opened 2 years ago Last modified 1 year ago Newforms-admin apply autoescape to a function output even when this function has the "allow_tags" attribute defined. There must be a way to output escape aware content from functions to the admin interface in order to output html content. You can probably achieve outputting html by just using mark_safe(). Perhaps the documentation needs to be updated to remove the allow_tags reference? No I can´t :) See above: from django.db import models from django.utils.safestring import mark_safe from django.contrib import admin class Example(models.Model): name = models.CharField() def test(self): return mark_safe('<b>%s</b>' % (self.name)) class ExampleOptions(admin.ModelAdmin): list_display = ('name', 'test') admin_site = admin.AdminSite() admin_site.register(Example, ExampleOptions) This should output the name in bold weight but this is not true for now. But I agree with you, allow_tags should not be available in favor of mark_safe or some SafeData? subclass ;) I found my mistake, I need to set the "allow_tags" attribute even if I return a safe string. See above: class Example(models.Model): name = models.CharField() def test(self): return mark_safe('<b>%s</b>' % (self.name)) test.allow_tags = True Maybe we should remove the allow_tags attribute? patch Created a patch so that mark_safe doesn't have to be used explicitly. This is conform the current documentation. This bug is already fixed in the trunk, but wasn't in the newforms-admin branch. I was messing around with merging branches and noticed that trunk does this, but newforms-admin does not. Ugh, the post commit hook is not closing tickets. This was fixed in [7394]. By Edgewall Software.
http://code.djangoproject.com/ticket/6226
crawl-002
refinedweb
274
62.04
Introduction Working with variables in data analysis always drives the question: How are the variables dependent, linked, and varying against each other? Covariance and Correlation measures aid in establishing this. Covariance brings about the variation across variables. We use covariance to measure how much two variables change with each other. Correlation reveals the relation between the variables. We use correlation to determine how strongly linked two variables are to each other. In this article, we'll learn how to calculate the covariance and correlation in Python. Covariance and Correlation - In Simple Terms Both covariance and correlation are about the relationship between the variables. Covariance defines the directional association between the variables. Covariance values range from -inf to +inf where a positive value denotes that both the variables move in the same direction and a negative value denotes that both the variables move in opposite directions. Correlation is a standardized statistical measure that expresses the extent to which two variables are linearly related (meaning how much they change together at a constant rate). The strength and directional association of the relationship between two variables are defined by correlation and it ranges from -1 to +1. Similar to covariance, a positive value denotes that both variables move in the same direction whereas a negative value tells us that they move in opposite directions. Both covariance and correlation are vital tools used in data exploration for feature selection and multivariate analyses. For example, an investor looking to spread the risk of a portfolio might look for stocks with a high covariance, as it suggests that their prices move up at the same time. However, a similar movement is not enough on its own. The investor would then use the correlation metric to determine how strongly linked those stock prices are to each other. Setup for Python Code - Retrieving Sample Data With the basics learned from the previous section, let's move ahead to calculate covariance in python. For this example, we will be working on the well-known Iris dataset. We're only working with the setosa species to be specific, hence this will be just a sample of the dataset about some lovely purple flowers! Let's have a look at the dataset, on which we will be performing the analysis: We are about to pick two columns, for our analysis - sepal_length and sepal_width. In a new Python file (you can name it covariance_correlation.py), let's begin by creating two lists with values for the sepal_length and sepal_width properties of the flower: with open('iris_setosa.csv','r') as f: g=f.readlines() # Each line is split based on commas, and the list of floats are formed sep_length = [float(x.split(',')[0]) for x in g[1:]] sep_width = [float(x.split(',')[1]) for x in g[1:]] In data science, it always helps to visualize the data you're working on. Here's a Seaborn regression plot (Scatter Plot + linear regression fit) of these setosa properties on different axes: Visually the data points seem to be having a high correlation close to the regression line. Let's see if our observations match up to their covariance and correlation values. Calculating Covariance in Python The following formula computes the covariance: In the above formula, - xi, yi - are individual elements of the x and y series - x̄, y̅ - are the mathematical means of the x and y series - N - is the number of elements in the series The denominator is N for a whole dataset and N - 1 in the case of a sample. As our dataset is a small sample of the entire Iris dataset, we use N - 1. With the math formula mentioned above as our reference, let's create this function in pure Python: def covariance] numerator = sum([sub_x[i]*sub_y[i] for i in range(len(sub_x))]) denominator = len(x)-1 cov = numerator/denominator return cov with open('iris_setosa.csv', 'r') as f: ... cov_func = covariance(sep_length, sep_width) print("Covariance from the custom function:", cov_func) We first find the mean values of our datasets. We then use a list comprehension to iterate over every element in our two series' of data and subtract their values from the mean. A for loop could have been used a well if that's your preference. We then use those intermediate values of the two series' and multiply them with each other in another list comprehension. We sum the result of that list and store it as the numerator. The denominator is a lot easier to calculate, be sure to decraese it by 1 when you're finding the covariance for sample data! We then return the value when the numerator is divided by its denominator, which results in the covariance. Running our script would give us this output: Covariance from the custom function: 0.09921632653061219 The positive value denotes that both the variables move in the same direction. Calculating Correlation in Python The most widely used formula to compute correlation coefficient is Pearson's 'r': In the above formula, - xi, yi - are individual elements of the x and y series - The numerator corresponds to the covariance - The denominators correspond to the individual standard deviations of x and y Seems like we've discussed everything we need to get the correlation in this series of articles! Let's calculate the correlation now: def correlation] # covariance for x and y numerator = sum([sub_x[i]*sub_y[i] for i in range(len(sub_x))]) # Standard Deviation of x and y std_deviation_x = sum([sub_x[i]**2.0 for i in range(len(sub_x))]) std_deviation_y = sum([sub_y[i]**2.0 for i in range(len(sub_y))]) # squaring by 0.5 to find the square root denominator = (std_deviation_x*std_deviation_y)**0.5 # short but equivalent to (std_deviation_x**0.5) * (std_deviation_y**0.5) cor = numerator/denominator return cor with open('iris_setosa.csv', 'r') as f: ... cor_func = correlation(sep_length, sep_width) print("Correlation from the custom function:", cor_func) As this value needs the covariance of the two variables, our function pretty much works out that value once again. Once the covariance is computed, we then calculate the standard deviation for each variable. From there, the correlation is simply dividing the covariance with the multiplication of the squares of the standard deviation. Running this code we get the following output, confirming that these properties have a positive (sign of the value, either +, -, or none if 0) and strong (the value is close to 1) relationship: Correlation from the custom function: 0.7425466856651597 Conclusion In this article, we learned two statistical instruments: covariance and correlation in detail. We've learned what their values mean for our data, how they are represented in Mathematics and how to implement them in Python. Both of these measures can be very helpful in determining relationships between two variables.
https://stackabuse.com/covariance-and-correlation-in-python/
CC-MAIN-2021-21
refinedweb
1,127
52.8
10 September 2012 04:22 [Source: ICIS news] ?xml:namespace> Honam bought two cargoes for delivery to Daesan at a premium of $18.50/tonne (€14.43/tonne) to Honam previously purchased two cargoes totalling 50,000 tonnes for delivery in the second half of October. The naphtha cargoes fetched a premium of around $11/tonne to The company has so far bought 275,000 tonnes of spot naphtha for October delivery, compared with 250,000 tonnes of spot purchase made for September delivery because of a lower usage of alternative feedstock, liquefied petroleum gas (LPG), traders said. “They have a bigger spot requirement for October because of less LPG usage,” one trader said. Firm spot buying from South Korean crackers have helped drive up premiums amid a tightly supplied market, traders said. Honam runs a 1m tonne/year cracker in Yeosu and a separate 1.07m tonne/year cracker in Daesan, according to ICIS data. Honam is operating both crackers at 100% capacity, a company source had
http://www.icis.com/Articles/2012/09/10/9593948/s.koreas-honam-buys-75000-tonnes-naphtha-for-second-half-oct.html
CC-MAIN-2014-49
refinedweb
168
54.02
#include <rte_swx_table.h> Table entry. Definition at line 67 of file rte_swx_table.h. Used to facilitate the membership of this table entry to a linked list. Key value for the current entry. Array of key_size bytes or NULL if the key_size for the current table is 0. Definition at line 76 of file rte_swx_table.h. Key mask for the current entry. Array of key_size bytes that is logically and'ed with key_mask0 of the current table. A NULL value means that all the key bits already enabled by key_mask0 are part of the key of the current entry. Definition at line 83 of file rte_swx_table.h. Placeholder for a possible compressed version of the key and key_mask of the current entry. Typically a hash signature, its main purpose is to the linked list search operation. Should be ignored by the API functions below. Definition at line 90 of file rte_swx_table.h. Key priority for the current entry. Useful for wildcard match (as match rules are commonly overlapping with other rules), ignored for exact match (as match rules never overlap, hence all rules have the same match priority) and for LPM (match priority is driven by the prefix length, with non-overlapping prefixes essentially having the same match priority). Value 0 indicates the highest match priority. Definition at line 99 of file rte_swx_table.h. Action ID for the current entry. Definition at line 102 of file rte_swx_table.h. Action data for the current entry. Considering S as the action data size of the action_id action, which must be less than or equal to the table action_data_size, the action_data field must point to an array of S bytes when S is non-zero. The action_data field is ignored when S is zero. Definition at line 110 of file rte_swx_table.h.
http://doc.dpdk.org/api-21.08/structrte__swx__table__entry.html
CC-MAIN-2021-49
refinedweb
298
67.76
#include <FXGLCanvas.h> #include <FXGLCanvas.h> Inheritance diagram for FX::FXGLCanvas: NULL 0 Construct an OpenGL-capable canvas, with its own private display list. Construct an OpenGL-capable canvas, sharing display list with another GL canvas. This canvas becomes a member of a display list share group. All members of the display list share group have to have the same visual. [virtual] Destructor. Return TRUE if it is sharing display lists. Create all of the server-side resources for this window. Reimplemented from FX::FXWindow. Reimplemented in FX::FXGLViewer. Detach the server-side resources for this window. Destroy the server-side resources for this window. Reimplemented from FX::FXWindow. Make OpenGL context current prior to performing OpenGL commands. Make OpenGL context non current. Return TRUE if this window's context is current. [inline] Get GL context handle. Swap front and back buffer. Save object to stream. Load object from stream.
http://fox-toolkit.org/ref14/classFX_1_1FXGLCanvas.html
CC-MAIN-2021-17
refinedweb
150
64.07
Scout/Concepts/CodeType A CodeType is a structure to represent a tree key-code association. They are used in SmartField and SmartColumn. Contents Description CodeType are used in SmartField to let the user choose between a finish list of values. The value stored by the field correspond to the key of the selected code. A CodeType can be seen as a tree of Codes. Each code associate to the key (the Id) other properties: among others a Text and an IconId. In order to have the same resolving mechanism (getting the display text of a key) CodeType are also used in SmartColumn. To chose multiple value of the list, the fields ListBox (flat CodeType) and TreeBox (hierarchical CodeType) can be used. Organisation of the codes The codes are organized in a tree. Therefore a CodeType can have one or more child codes at the root level, and each code can have other child codes. In lot of cases a list of codes (meaning a tree containing only leafs at the first level) is sufficient to cover most of the need. Child codes are ordered in their parent code. This is realized with the order annotation. Type of the key The type of the key is defined by its generic parameter <T>. It is very common to use a type from the java.lang.* package (like Integer or String) but any Java Object is suitable. It must: - implements Serializable - have correctly implemented equals()and hashCode()functions -. Using a CodeType SmartField or SmartColumn CodeType in a SmartField (or SmartColumn). public class YesOrNoSmartField extends AbstractSmartField<Boolean> { // other configuration of properties. @Override protected Class<? extends ICodeType<?>> getConfiguredCodeType(){ return YesOrNoCodeType.class; } } If the SmartField (or SmartColumn) works with a CodeType, a specific LookupCall is instantiated to get the LookupRows based on the Codes contained in a CodeType. Accessing a code directly Scout-runtime will handle the instantiation and the caching of CodeTypes. This function returns the text corresponding to the key using a CodeType: public String getColorName(String key){ ICode c = CODES.getCodeType(ColorCodeType.class).getCode(key); if(c != null) { return c.getText(); } return null; } } Static CodeType Java Code and structure The common way to define a CodeType is to extend AbstractCodeType. Each code is an inner-class extending AbstractCode. Like usual the properties of Codes and CodeTypes can be set with getConfiguredXxxxxx() methods. See the Java Code of a simple YesOrNoCodeType having just two codes: YesOrNoCodeType.YesCode YesOrNoCodeType.NoCode With the SDK The SDK provides some help to generate CodeTypes and Codes. The CodeType appears in the Explorer View in the Enumerations folder under shared. It is possible to add a new CodeType using a wizard. Dynamic CodeType Code types are not necessary hardcoded. It is possible to implement other mechanisms to load that the CodeType Class is not aware of the language and the partition it is instantiate for. Only the CodeTypeStore that manage the CodeType instances knows for which language and which partition they have been instantiated.
http://wiki.eclipse.org/index.php?title=Scout/Concepts/CodeType&direction=prev&oldid=276089
CC-MAIN-2017-47
refinedweb
495
57.67
Optimization: Shift dropped list heads by coeffecient to prevent thunk generation Consider the following snippet(s) equivalent to ([a..b] !! n), the source of (!!) and the source of drop: normal_list :: Int -> Int normal_list n = head $ drop n [a..b] shifted_list :: Int -> Int shifted_list n = head $ drop (n-n) [(a+n)..b] xs !! n | n < 0 = undefined [] !! _ = undefined (x:_) !! 0 = x (_:xs) !! n = xs !! (n-1) drop n xs | n <= 0 = xs drop _ [] = [] drop n (_:xs) = drop (n-1) xs Notice the (_:xs) matching in these functions as a result of WHNF. In the first case, normal_list, thunks are generated for x in (x_:xs) of the target list and overhead is seen in the pattern matching/guard of n in drop. In the second case, shifted_list, this overhead can be completely removed by adding a coefficient such that the list starts at the programmatically defined lower bound, a, plus the known fact that the head is dropped n times. Hence, given the example above, consider: [x * x + 3 | x <- [1..]] !! n -- versus [x * x + 3 | x <- [(1+n)..]] !! (n-n) -- which is optimized into [x * x + 3 | x <- [(n+1)..]] !! 0 -- which is effectively head [x * x + 3 | x <- [(n+1)..]] The operation is turned from O(n) into O(1). Consider benchmark proving GHC 7.4.2 does not make this optimization under -O2: import Criterion.Main normal_list :: Int -> Int normal_list n = head $ drop n [1..] shifted_list :: Int -> Int shifted_list n = head $ drop (n-n) [(1+n)..] main = defaultMain [ bench "normal_list 1000" $ whnf normal_list 1000 , bench "shifted_list 1000" $ whnf shifted_list 1000 ] C:\Users\Kyle\Desktop>ghc -O2 listco.hs [1 of 1] Compiling Main ( listco.hs, listco.o ) Linking listco.exe ... C:\Users\Kyle\Desktop>listco.exe warming up estimating clock resolution... mean is 4.644044 us (160001 iterations) found 319255 outliers among 159999 samples (199.5%) 159256 (99.5%) low severe 159999 (100.0%) high severe estimating cost of a clock call... mean is 310.3118 ns (34 iterations) benchmarking normal_list 1000 Warning: Couldn't open /dev/urandom Warning: using system clock for seed instead (quality will be lower) mean: 7.352463 us, lb 7.058339 us, ub 7.646574 us, ci 0.950 std dev: 1.478087 us, lb 1.478066 us, ub 1.478200 us, ci 0.950 variance introduced by outliers: 94.651% variance is severely inflated by outliers benchmarking shifted_list 1000 mean: 46.42819 ns, lb 45.44244 ns, ub 47.21689 ns, ci 0.950 std dev: 4.495757 ns, lb 4.035428 ns, ub 4.832396 ns, ci 0.950 variance introduced by outliers: 77.960% variance is severely inflated by outliers
https://gitlab.haskell.org/ghc/ghc/-/issues/7977
CC-MAIN-2020-29
refinedweb
446
80.28
In this tutorial we are going to learn about Python File Operations such as python read file, python write file, open file, delete file and copy file. Our previous tutorial was on Python Dictionary. You can find that in this link. Table of Contents Python File In the previous tutorial we used console to take input. Now, we will be taking input using file. That means, we will read from and write into files. To do so, we need to maintain some steps. Those are - Open a file - Take input from that file / Write output to that file - Close the file We will also learn some useful operations such as copy file and delete file. Why Should We Use File Operation Suppose, you are trying to solve some problem. But you can’t solve it at once. Also, the input dataset of that problem is huge and you need to test the dataset over and over again. In that case you can use Python File Operation. You can write the dataset in a text file and take input from that text file according to your need over and over again. Again, if you have to reuse the output of your program, you can save that in a file. Then, after finishing your program, you can analysis the output of that program using another program. In these case you need Python File Operation. There may be some other cases where you may need Python File Operation. Python Open File According to the previous discussion, the first step we have to perform in Python File Operation is opening that file. You can open a file by using open() function. This function take two arguments. The first one is file address and the other one is opening mode. There are some mode to open a file. Most common of them are listed below: - ‘r’ : This mode indicate that file will be open for reading only - ‘w’ : This mode indicate that file will be open for writing only. If file containing containing that name does not exists, it will create a new one - ‘a’ : This mode indicate that the output of that program will be append to the previous output of that file - ‘r+’ : This mode indicate that file will be open for both reading and writing Additionally, for Windows operating system you can append ‘b’ for accessing the file in binary. As Windows makes difference between binary file and text file. Suppose, we place a text file name ‘file.txt’ in the same directory where our code is placed. Now we want to open that file. However, the open(filename, mode) function returns a file object. With that file object you can proceed your further operation. #directory: /home/imtiaz/code.py text_file = open('file.txt','r') #Another method using full location text_file2 = open('/home/imtiaz/file.txt','r') print('First Method') print(text_file) print('Second Method') print(text_file2) The output of the following code will be ================== RESTART: /home/imtiaz/code.py ================== First Method Second Method >>> Python Read File, Python Write File There are some methods to read from and write to file. The following list are the common function for read and write in python. Note that, to perform read operation you need to open that file in read mode and for writing into that file, you need to open that in write mode. If you open a file in write mode, the previous data stored into that fill will be erased. - read() : This function reads the entire file and returns a string - readline() : This function reads lines from that file and returns as a string. It fetch the line n, if it is been called nth time. - readlines() : This function returns a list where each element is single line of that file. - readlines() : This function returns a list where each element is single line of that file. - write() : This function writes a fixed sequence of characters to a file. - writelines() : This function writes a list of string. - append() : This function append string to the file instead of overwriting the file. The following code will guide you to read from file using Python File Operation. We take ‘file.txt’ as our input file. #open the file text_file = open('/Users/pankaj/abc.txt','r') #get the list of line line_list = text_file.readlines(); #for each line from the list, print the line for line in line_list: print(line) text_file.close() #don't forget to close the file Again, the sample code for writing into file is given below. #open the file text_file = open('/Users/pankaj/file.txt','w') #initialize an empty list word_list= [] #iterate 4 times for i in range (1, 5): print("Please enter data: ") line = input() #take input word_list.append(line) #append to the list text_file.writelines(word_list) #write 4 words to the file text_file.close() #don’t forget to close the file Python Copy File We can use shutil to copy file. Below is an example showing two different methods to copy file. import shutil shutil.copy2('/Users/pankaj/abc.txt', '/Users/pankaj/abc_copy2.txt') #another way to copy file shutil.copyfile('/Users/pankaj/abc.txt', '/Users/pankaj/abc_copyfile.txt') print("File Copy Done") Python Delete File We can use below code to delete a file in python. import shutil import os #two ways to delete file shutil.os.remove('/Users/pankaj/abc_copy2.txt') os.remove('/Users/pankaj/abc_copy2.txt') Python Close File As you see in the previous example, we used close() function to close the file. Closing the file is important. So that’s all for Python File Operation. If you have any query, please feel free to ask that in comment box. Python FileNotFoundError You will get this error if the file or directory is not present. A sample stack trace is given below. File "/Users/pankaj/Desktop/string1.py", line 2, in <module> text_file = open('/Users/pankaj/Desktop/abc.txt','r') FileNotFoundError: [Errno 2] No such file or directory: '/Users/pankaj/Desktop/abc.txt' Please check the file path and correct it to get rid of FileNotFoundError. References:
https://www.journaldev.com/14408/python-read-file-open-write-delete-copy
CC-MAIN-2019-39
refinedweb
1,010
75
Java code for the Geode project was originally developed using conventions based on The Elements of Java Style, by A. Vermeulen, S. Ambler, et. al. As an open-source project we are following the Google Java Style guide, emphasizing a few of the more important points in this page. General Principles When modifying existing software, your changes should follow the style of the original code. Do not introduce a new coding style in a modification, and do not attempt to rewrite the old software just to make it match the new style. The use of different styles within a single source file produces code that is more difficult to read and comprehend. Rewriting old code simply to change its style may result in the introduction of costly yet avoidable defects. Apply these rules to any code you write, not just code destined for production or only if it is visible to the user. This includes code documentation (javadocs). Formatting Conventions In order to create a source base that has a unified appearance and is easy to read and comprehend we include conventions for formatting Java code. Most of the formatting conventions for this project center around the use of white space and the placement of brackets. Formatter settings for Eclipse and IntelliJ are covered first, followed by more detailed descriptions. Always use braces, even around one-line `if`, `else` and other control statements. Locate the opening brace '{' of each block statement in the last character position of the line that introduced the block. Place the closing brace '}' of a block on a line of its own, aligned with the first character of the line that introduced the block. The following examples illustrate how this rule applies to each of the various Java definition and control constructs. // CORRECT: A public class definition public class MyClass { ... } // WRONG: public class MyClass { ... } // WRONG: public class MyClass { ... } // CORRECT: A method definition void method(int j) { ... } // CORRECT: A do/while do { ... } while (...) Eclipse and IntelliJ formatter settings Eclipse On MacOS "Preferences..." can be found under the "Eclipse" menu. Then import the "imports" settings file Window > Preferences > Java > Code Style > Organize Imports > Import etc/eclipseOrganizeImports.importorder IntelliJ format Import etc/intellijIdeaCodeStyle.xml.
https://cwiki.apache.org/confluence/display/GEODE/Code+Style+Guide
CC-MAIN-2018-51
refinedweb
365
56.35
A little while ago a Star Wars-themed Flash game made the blog and email rounds, letting players try to stump Darth Vader. It was even discussed here on CodeProject. The premise of the game is that Darth asks you to think of something, and attempts to guess what you were thinking of by asking questions to which you answer "Yes", "No", "Maybe", "Sometimes", etc. Part of the fun of the game is hearing Darth insult you, seeing the dancing Storm Trooper at the end, and other UI fluff, but part of the fun is also watching Darth home in on your word by asking what occasionally seems like really insightful questions. After playing the game for a short time, I realized that it was just walking a tree structure of questions and "things". I was struck by the similarity of the game to one I played back in the early 80's on my TRS-80 Color Computer (obviously, without the Flash interface). Back then, PC implementations of fake AI programs like Eliza were all the rage, and decision trees were seen as a possible way to implement limited AI. The program (unfortunately I can't remember the name) asked you Yes and No questions, and seemed to learn from the experience. We were young and easily impressed back then. It was all just string manipulation, of course, but it was *compelling* string manipulation. Evidently it's just as compelling now. After watching people in the office play the Sith game repeatedly, I became interested in re-implementing the original in C# and XML using everyone's other favourite fact-hungry villain, the Borg. In this article, I'll show you how to write a game that mimics the core functionality of the Sith game and talk about console applications, XML serialization and the good old days... I think it's beneficial to talk through a sample run before we dive into the code. I'll use the same data as is shown in Image 1. You can distinguish user input from program output because user input is always coloured bright green. When the application runs, it prompts the user to think of a noun. In this example, the user will be thinking of a rabbit. The application asks its only question and solicits a yes or no answer from the user. In the database provided in my source, the initial question is "Is it alive (y/n)". The answer to this question (thinking of a rabbit), is "Yes", so the user enters "y". The app traverses the tree on the "Yes" side and reads the noun on the Yes branch of the initial question (turtle). If the "Yes" node had been another Question object, the game would have just asked that question text and continued to traverse the "Yes" and "No" properties of the questions until a Noun object was found. In this example, though, it has arrived at the end of this branch of the decision tree and asks the user if "turtle" was the noun which they were thinking. Question Yes No Noun The answer will be "no", since we're thinking "rabbit". Now the app switches into knowledge acquisition logic. The application asks the user for the noun of which they were thinking. The user types "rabbit". The app then solicits a question that distinguishes the noun the user had (rabbit) from the noun the program was expecting (turtle). The user can type some question like "Is it a reptile". The app then saves the new knowledge back to the original data file, resets its internal pointer back to the root Question object, and asks the user if they want to play again. The XML data file is portable, and can be emailed around to people to play. Talk is cheap and occasionally confusing. You can see how the object model (and the persistent XML which describes the object model) evolves through this simple example in Image 2. There are two basic constructs in the object model, Question objects and Noun objects. Noun objects just have a Text property. Question objects have a Text property, and Yes or No properties that are followed based on the responses given by the user to the Text property of the Question. The Yes or No properties of the Question object can be other Question objects, or Noun objects. Since the nodes can be one of two different types, I created an interface both Question and Noun objects implement, called IBorgElement, and use that as the type of the Yes and No Question properties. I consolidated the common elements of Question and Noun types into the interface (a string Text property and a Serialize method) but I didn't have to. Text IBorgElement Serialize using System; using System.Xml; namespace Borg { public interface IBorgElement { string Text {get;} void Serialize(XmlDocument doc, XmlNode node); } } The Noun object is really straightforward. It can be instantiated with an XML node to aid in deserialization, and it can be instantiated with just the string for the Text property: public Noun(string text) { _text = text; } public Noun(XmlNode node) { XmlAttribute text = node.Attributes[Noun.TEXT_ATTRIBUTE_NAME]; if (text != null) _text = text.InnerText; } Noun.TEXT_ATTRIBUTE_NAME is just a private constant string describing the name of the Text attribute in the Noun node of the XML document. In this case, it's "Text". I didn't like having the literal "Text" scattered around the class for serialization and deserialization, so I made it a private constant. You'll see this in the Question class too. Noun.TEXT_ATTRIBUTE_NAME The only other interesting aspect of the Noun class is the serialization code. The Noun and Question objects have to be serialized into an XML document after each new fact is added to the object model. Serialized Noun objects are pretty trivial and look like this in the XML file: <Noun Text="turtle" /> It is their position in the document which confers the relationship to other nouns. The code to serialize the state of the object looks like this: void Borg.IBorgElement.Serialize(XmlDocument doc, XmlNode node) { XmlNode noun = doc.CreateNode(XmlNodeType.Element, Noun.NodeName, string.Empty); XmlAttribute text = doc.CreateAttribute(string.Empty, Noun.TEXT_ATTRIBUTE_NAME, string.Empty); text.InnerText = _text; // Add the attribute to the new Noun node. noun.Attributes.Append(text); // Add the Noun node to it's place in the master document. node.AppendChild(noun); } This code would get called by a Question object when it is serialized, if either the Yes or No properties are Noun objects. I'll show you that in the section below. The method needs a reference to the main XmlDocument object in order to create new nodes and attributes, and uses the XmlNode parameter to know where in the document to add itself. Noun.NodeName is a public, static property of the class and returns the name of the XML node for the Noun. It's public so other classes can know what the name of Noun nodes are too. XmlDocument XmlNode Noun.NodeName Since they implement the same interface as Noun objects, they share some similarities. They have a string Text property and can serialize themselves using the same parameters as passed to Noun objects. They can be constructed with either an XML node or with values for the properties. Question objects are different from Noun objects, though, in that they have Yes and No properties of type IBorgElement. public IBorgElement Yes { get {return _yes;} set {_yes = value;} } public IBorgElement No { get {return _no;} set {_no = value;} } These properties are used by the App class to move through the decision tree to either the next question or a noun, depending on the user input. App The Question and Noun objects are just smart buckets for data, with limited active functionality. The App class does the work of playing the game. It first validates input, and makes some assumptions about the database ("collective" in Borg terminology) you want to use. It loads the file and passes the first question (the first XmlNode below the root) to the constructor of the root Question. That constructor parses the Question node and passes the Yes and No XmlNodes to Question or Noun constructors, depending on the name of the node. Questions are recursively constructed until Noun XML nodes end the new object creation. Once the hierarchy is fully constructed, the App class asks the first question. It solicits an answer by passing control to a function that waits until the user has entered a "Y" or a "N": private static YesNoAnswer SolicitAnswer(string question, ConsoleEx.Colour colour) { string answer = string.Empty; // Keep prompting until the user presses "y" or "n" do { ConsoleEx.Write(question + " (y/n) ", colour); answer = ConsoleEx.ReadLine(ConsoleEx.Colour.Green); // User input in green. } while (answer.ToLower() != "n" && answer.ToLower() != "y"); return (answer == "y" ? YesNoAnswer.Yes : YesNoAnswer.No); } Once the question is answered, App checks the type of the Yes or No IBorgElement object. If it's a Question object, it sets the current pointer to the new Question object and starts the process again. If the IBorgElement object is a Noun object, it launches into a new set of logic. The App class asks the user if the noun they were thinking of was the Noun in the final object. If it was, the game pats itself on the back and checks to see if the user wants to play again. If the noun was not guessed correctly, the application asks for the noun the user picked. It then solicits a question that answers Yes to the old noun, and No to the new noun. This question is solicited in a deliberate way, because the application is going to put the old noun on the No side of the new question and the new noun on the Yes side of the new question. If the new question is phrased incorrectly, the answers will be switched the next time the question is hit. Once the App class knows the old and new noun and the question that distinguishes them, it creates a new Question object with the Yes and No IBorgElement nodes set to the new and old nouns, respectively. It puts the new Question object back where the old noun was in the object hierarchy, and persists the data. Refer back to Image 2 for a graphical representation of this if you want. The data is persisted by creating a new XmlDocument object with a dummy root ("Database" node), and passing it to the root Question object serialization routine. private static void SaveDatabase(IBorgElement data, string fileName) { XmlDocument doc = new XmlDocument(); // Initialize the Xml document with the root node. doc.AppendChild(doc.CreateNode(XmlNodeType.Element, App.ROOT_NODE_NAME, string.Empty)); data.Serialize(doc, doc.SelectSingleNode(App.ROOT_NODE_NAME)); doc.Save(fileName); } App.ROOT_NODE_NAME is the name of the root node, "Database". The Question object serializes itself into the new XmlDocument at the root node, and starts serializing the Yes and No properties. This will force all of the objects in the hierarchy to create XmlNodes for themselves in the master document, and gives a complete representation of the knowledge tree with the new question and answer. App.ROOT_NODE_NAME void Borg.IBorgElement.Serialize(XmlDocument doc, XmlNode node) { XmlNode question = doc.CreateNode(XmlNodeType.Element, Question.NodeName, string.Empty); XmlAttribute text = doc.CreateAttribute(string.Empty, Question.TEXT_ATTRIBUTE_NAME, string.Empty); text.InnerText = _text; // Append the Text attribute to the new Question node. question.Attributes.Append(text); XmlNode yesNode = doc.CreateNode(XmlNodeType.Element, Question.YES_NODE_NAME, string.Empty); XmlNode noNode = doc.CreateNode(XmlNodeType.Element, Question.NO_NODE_NAME, string.Empty); _yes.Serialize(doc, yesNode); // Serialize whatever's on the "Yes" side. _no.Serialize(doc, noNode); // Serialize whatever's on the "No" side. question.AppendChild(yesNode); // Append the Yes node to the Question node question.AppendChild(noNode); // Append the No node to the Question node // Append the Question node to where // it goes in the master document. node.AppendChild(question); } The resulting XmlDocument gets saved over the old one, and the game asks if the user wants to play again. I realize not everyone will want to start with my root question ("Is it alive") with my super-creative nouns. I also realize that creating initial XML documents to serve as the database is a tedious and error prone process. The App class allows you to create your own seed databases by running the application with some command line switches. If you run with four parameters, and those parameters are /db:, /question:, /yes: and /no:, you can have it create your own root database. The order of the parameters does not matter. /db: /question: /yes: /no: borg /db:"c:\birds.xml" /question:"Does it fly" /yes:"sparrow" /no:"penguin" That command line will create a new database in the root of c:\ called birds.xml, seeded with the initial question and nouns as specified, and will open it for running (if it was created successfully). Sorry about the animal bias in the examples, but my degree is in Zoology... You can see that the Sith game exploits the same sort of engine, but with a larger number of directions to travel in from each question. Instead of "yes" and "no", the Sith game allows for a multitude of options. Limiting the choices to "Yes" and "No" as I have done here appeals to my logical, binary side, and results in less ambiguity in the data relationships generated. Not coincidentally, it is also much easier to code. Back before the Internet, USB and diskettes, back when only rich kids had 300 baud modems (when dinosaurs ruled the earth), nerds had limited access to application sharing mechanisms. I had to type the source code for the original game myself from a magazine, before I could save it to my cassette drive. You really had to pick interesting programs before you typed them in, because it was a major investment of time to bang out the source code for an application, and debug the inevitable typos. It's probably why I remember playing this game so clearly. All on a 32X16 screen. Good times... I've been on a console app writing kick lately, and am interested in making it easier for myself and others to write decent interfaces for the console. I put some code in to do colour output here, and am writing a comprehensive library for console manipulation which should be on CodeProject in 2-3 weeks. A small subset of the code is included in this project in the ConsoleEx class. ConsoleEx Each of the objects I've written know how to serialize and deserialize themselves. I know a lot of people who detest doing this, and prefer to decorate classes with the [Serializable] attribute, and let the framework deal with this. I've tried to do serialization and deserialization automagically with the framework often enough to come to hate it, though. For the sake of a little extra code, you gain an incredible amount of flexibility in processing, so I create and parse XML documents myself. Don't get sloppy when you're handling XmlNodes and attributes and the like in your [de]serialiation code and start fiddling with your objects as string data. Only use real XML objects, and you won't be caught up when some user starts sticking angle brackets and ampersands into their data. [Serializable] Additionally, you can throw really accurate, context sensitive exceptions if there are errors in the document you're parsing to help people diagnose their problem with input files. Putting your run-time settings into App.Config is a well known shortcut, and allows you to reduce a small amount of XML parsing into an even smaller amount of code and read your settings like this: fileName = System.Configuration.ConfigurationSettings.AppSettings.Get("LastDBPath"); What it is not supposed to be used for, evidently, is re-writing those same settings. There are lots of people on the net who strongly advise against this, as the application folder (where the App.Config resides) may not be writable by the application for security purposes. The framework is prejudiced against this concept too, since it lets you read but not write to this file. I specifically wrote XML parsing code in this project to update the App.Config at run-time, going against the best practice. I wanted to save the path to the last database successfully loaded, so the end-user wouldn't have to specify the path on the command line every time. They only have to specify it if they're changing databases. If you want to save a tiny bit of data between program executions, what are you supposed to do? Registry, I guess, but it's fraught with its own security perils. INI files? I'm not going back there. What happened to XCOPY deployment? You can't do it if you're copying config files all over the hard drive... A strategy I like to use when I write console applications is to put long stretches of boilerplate text into embedded resources in the executable, and stream them out at run-time when I need to show them. Good candidates for this technique are command line switch parameters and instructions for what to do once the application is running, as I have done in this project. The files CLIText.txt and Instructions.txt are both embedded into the executable and are displayed when necessary by calling the following function: private static string ReadResource(string resource) { Assembly me = Assembly.GetExecutingAssembly(); string res = me.GetName().Name + "." + resource; StreamReader sr = new StreamReader(me.GetManifestResourceStream(res)); string data = sr.ReadToEnd(); sr.Close(); return data; } Doing this avoids a lot of messy and hard-to-edit System.Console.WriteLine() calls at the start of the Main() method. System.Console.WriteLine() Main() Just by way of warning, the project uses a post-build step to copy the Borg.xml file from the project folder into the run-time folder, so if you run the app repeatedly in the IDE, any facts you add to the database will get overwritten on the next compile. Last but not least, to parse the command line parameters here, I use my Yet Another Command Line Argument Parser (YACLAP) library, which you can read about here. This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below. A list of licenses authors might use can be found here SharpenedC wrote:I've had quite a bit of fun with this, thanks. General News Suggestion Question Bug Answer Joke Rant Admin Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
http://www.codeproject.com/Articles/11092/Borg-Knowledge-Assimilator?msg=2875038
CC-MAIN-2015-11
refinedweb
3,133
62.27
. public bool CreateDirectory(string remoteDir, string MachineName, string UserName, string Password) { string TempName = remoteDir; int Index = TempName.IndexOf(":"); string DriveLetter = "C"; if (Index != -1) { string[] arr = TempName.Split(new char[] { ':' }); DriveLetter = arr[0]; TempName = TempName.Substring(Index + 2); } ManagementPath myPath = new ManagementPath(); myPath.NamespacePath = @"root\CIMV2"; ConnectionOptions oConn = new ConnectionOptions(); oConn.Username = UserName; oConn.Password = Password; oConn.EnablePrivileges = true; myPath.Server = MachineName; ManagementScope scope = new ManagementScope(myPath, oConn); scope.Connect(); //without next strange manipulation, the os.Get().Count will throw the "Invalid query" exception remoteDir = remoteDir.Replace("\\", "\\\\"); ObjectQuery oq = new ObjectQuery("select Name from Win32_Directory where Name = '" + remoteDir + "'"); using (ManagementObjectSearcher os = new ManagementObjectSearcher(scope, oq)) { if (os.Get().Count == 0) //It don't exist, so create it! { ManagementPath path2 = new ManagementPath(); path2.Server = MachineName; path2.ClassName = "Win32_Process"; path2.NamespacePath = @"root\CIMV2"; ManagementScope scopeProcess = new ManagementScope(path2, oConn); using (ManagementClass process = new ManagementClass(scopeProcess, path2, null)) { string commandLine = String.Format(@"cmd /C mkdir {0} ", TempName); using (ManagementBaseObject inParams = process.GetMethodParameters("Create")) { inParams["CommandLine"] = commandLine; inParams["CurrentDirectory"] = DriveLetter + @":\\"; inParams["ProcessStartupInformation"] = null; using (ManagementBaseObject outParams = process.InvokeMethod("Create", inParams, null)) { int retVal = Convert.ToInt32(outParams.Properties["ReturnValue"].Value); return (retVal == 0); } } } } else return true;//if exists, return true; you may want to return false, of course } return false; } } $174.99. Premium members get this course for $349.00. Premium members get this course for $62.50. Premium members get this course for $25.00. Premium members get this course for $87.50. Premium members get this course for $47.20. As you say you can move a folder using Rename, but you can also copy a Directory and its contents using the Copy method. The CopyEx method with the correctly set parameters will ignore child folders and only copy the child files for the specified folder. If you pick a folder that usually contains no immediate files then you will be able to create an empty directory in the required location. In the example below, I used the Inetpub folder. (Tested on Windows 2000) using System.Management; ... //Connection credentials to the remote computer ConnectionOptions oConn = new ConnectionOptions(); oConn.Username = "someusername"; oConn.Password = "somepassword"; oConn.EnablePrivileges = true; //Set Machine Name and Directory Location string MachineName = @"\\somemachinename"; string DirectoryName = @"c:\Inetpub"; //Set Arguments for WMI Method Invocation object[] MethodArgs = {@"c:\Test", "", "", false}; //Set scope for WMI call ManagementScope oMs = new System.Management.Manageme // Get Directory to be copied - will throw exception if cannot be found using (ManagementObject dir = new ManagementObject (oMs, new ManagementPath(String.Form { //Invoke CopyEx Method dir.InvokeMethod("CopyEx", } Once you have created the folder, you can then use the Create method of the Win32_Share WMI Class to set share settings. (Although this is a lot more complicated) Hope this is of some help. Thanks ;) Max I spend more hours researching. I come to conlusion that you cannot create a folder on remote server using WMI. Although there is a Win32_Directory WMI class. You can also move directories using WMI like this. strComputer = "." Set objWMIService = GetObject("winmgmts:" _ & "{impersonationLevel=imper Set colFolders = objWMIService.ExecQuery _ ("Select * from Win32_Directory where name = 'c:\\Scripts'") For Each objFolder in colFolders errResults = objFolder.Rename("C:\Admin Wscript.Echo errResults But I don't see how u can create one... No methods for that. Pretty lame if you aks me... Allow such an extensive management, and assume that system administrators will not want to create a folder??? Its not even a security risk, since if u have proper rights you can do much more damage than creating a folder with other WMI directives..... I guess the way to go is to impersonate in .NET using some user account. And then have a share with access right to only that user. I will give fullpoints for this kind of answer as well now. Please include code samples if possible. I am also curious how can I create a username to be used by my application and also to use for permissions on a remote computer. I think there are complicatiomns with different domains etc.... Basically stuff that you can find out in several days, but I don't have this luxury at the moment. I am sure someone has done this kind of thing before (not using WMI, but using a impersonation)... Please help! Max With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you. Else you could allow the ASPNET user to create the folders (low security). You can also do the impersonating in a service and control it by .net remoting. I considered using ASP.NET user however this is low security, especially in my case. What I am doing is creating a website folder on drive d, where there are other 100+ websites. If I allow ASP.NET user to write to such share, that mean no security whatsoever. (espcially as we do not want other developers to access the server. All applications are written in .net, meaning that anyone with their head screwed on and some time can easily gain access to drive d.) If you could, please expand your though on your last point about impersonating in a service, as I don't quite understand what u meant. Thanks, Max In a service running under SYSTEM or Administrator account you can use the Win32 API to impersonate the current thread. Thanks a lot for your code, looks like just what I need. I mamanged to get it running on my machine no problem, I just had to remove the connection object. However when I am trying to make it work on the remote Windows 2000 machine, I get an exception and it sais "Access Denied". I am using my administrators account, which I am able to use on many servers since in the admin group. I can log in to the machine with full rights with that account. However using those credentials I cannot use the code. Should I specificly add this account to some group that enabled me to use WMI? O rmay be WMI uses some other credentials. I am trying to find something out at the moment. But if you have any ideas or know what might be wrong, could you please post it here :) Thanks, Max I read through MSDN about the connection object. I had to specify the domain as well as username i.e. I was using "username" And it had to be "domain\username" All works now! Amazing thank you so much, you might just have made my project meet the timeline :D I will award the points right now. Max Something like: try { // Check to see if folder already exists using (ManagementObject dir = new ManagementObject (oMs, new ManagementPath(String.Form { //Attempt to access a property String dirTest = dir.Properties["Name"].ToS } } catch (Exception ex) { if(ex.Message="Not Found") { // Directory not found so create } } This should solve your problem. Tom It works for me, and I don't want to modify my code unless I know why. :) Basically, I've created a simple batch or command file (createfolder.cmd in this example) on the remote server that has just this single line in it: mkdir %1 Then used WMI to create a process on the remote server to call that cmd file. The reason being, you can't call "mkdir" directly using Win32_Process since it expects a proper path to file. My WMI code for calling the cmd file goes something like so: string remoteDir = "newfolder"; ManagementPath myPath = new ManagementPath(); myPath.NamespacePath = @"root\CIMV2"; ManagementScope scope = new ManagementScope(myPath, oConn); ObjectQuery oq = new ObjectQuery("select Name from Win32_Directory where Name = '" + remoteDir + "'"); using (ManagementObjectSearcher os = new ManagementObjectSearcher(s { if (os.Get().Count == 0) //It don't exist, so create it! { ManagementPath path2 = new ManagementPath(); path2.Server = "ServerName"; path2.ClassName = "Win32_Process"; path2.NamespacePath = @"root\CIMV2"; ManagementScope scopeProcess = new ManagementScope(path2, oConn); using (ManagementClass process = new ManagementClass(scopeProce { string commandLine = "C:\\createfolder.cmd \"" + remoteDir + "\""; ManagementBaseObject inParams = null; inParams = process.GetMethodParameter inParams["CommandLine"] = commandLine; inParams["CurrentDirectory inParams["ProcessStartupIn ManagementBaseObject outParams = process.InvokeMethod("Crea int retVal = Convert.ToInt32(outParams. inParams.Dispose(); outParams.Dispose(); } } } After this u can use the searcher again to determine if it the folder was created: //Now query again to see if it's created using (ManagementObjectSearcher os = new ManagementObjectSearcher(s { if (os.Get().Count == 0) throw new Exception("Cannot create directory at \"" + remoteDir + "\" on ServerName"); } Nguyen The variable "remoteDir" needs a full path, so instead of: string remoteDir = "newfolder"; It should be: string remoteDir = @"C:\newfolder"; And the line: ObjectQuery oq = new ObjectQuery("select Name from Win32_Directory where Name = '" + remoteDir + "'"); should be: ObjectQuery oq = new ObjectQuery("select Name from Win32_Directory where Name = '" + remoteDir.Replace(@"\", @"\\") + "'"); May be it's irrelevant, but I've found an easy way to create directories on remote machine just using the "cmd" (command line) without creating batch files or enything else. Here is a code, may be it'll be helpful for anybody. Open in new window
https://www.experts-exchange.com/questions/20954541/URG-Creating-a-folder-on-a-remote-machine-WMI-ADSI-FSO-etc.html
CC-MAIN-2018-09
refinedweb
1,499
50.53
Elixir is a fast, dynamic and scalable language which is fast becoming adopted by the startup crowd and established businesses alike for production applications. Pinterest, Brightcove, Discord, and Canvas, to name a few, all run on Elixir, which in turn leverages the low-latency, fault-tolerant Erlang VM, meaning complete access to the Erlang ecosystem used by companies such as Heroku, WhatsApp, Klarna, and Basho. Starting with this tutorial, you'll learn the fundamental knowledge to get yourself started in Erlang and coding with Elixir. What's the Syntax Like? The syntax is functional and promotes a short, fast coding style, which allows users easy abstraction to their data: %User{name: name, age: age} = User.get("John Doe") name #=> "John Doe" When combined with guards, we have a powerful structure: def serve_drinks(%User{age: age}) when age >= 21 do # Code that serves drinks! end serve_drinks User.get("John Doe") #=> Fails if the user is under 21 Can It Scale? Affirmative; Elixir was built with scalable, distributed systems in mind. Elixir features threaded execution (referred to as processes) in an environment in which multiple processes can communicate with one another via messages. These light-weight threads can be run in the hundreds of thousands concurrently. Elixir's excellent garbage collector works for each isolated thread, ensuring performance is optimal system-wide and preventing resource lock-ups. Fault Tolerance Elixir has Supervisors which can restart parts of your system if things go wrong and revert your system to an initial state that is known to work. How to Get Elixir Install Elixir on your machine before we continue: Mac OS X - - FreeBSD - From ports: cd /usr/ports/lang/elixir && make install clean - From pkg: pkg install elixir - Ubuntu 12.04 and 14.04 / Interactive Development Elixir has an interactive mode, which we can access via the command-line prompt as so: $ To output from a script to the terminal, we need to use the following IO class: IO.puts "Hello world from Elixir" What About Modules? Modules are available for Elixir so that developers can expand the language in many ways. Here is an example of using Elixir's test framework ExUnit: defmodule MathTest do use ExUnit.Case, async: true test "can add two numbers" do assert 1 + 1 == 2 end end You can run the tests in parallel by setting async: true. In this setting, Elixir uses as many CPU cores as possible. Meanwhile, assert can check for assertion failures in your code. Those features are built using Elixir macros, making it possible to add entire new constructs as if they were part of the Elixir language itself, meaning total customisation for whatever productivity (unit testing in this case) you may need. More to Come! Elixir is a powerful and versatile language used by some of the biggest apps in the world right now. Its fast compile times, light-weight threaded processes, extensibility with DSL modules, and fault tolerance provided with Supervisor make it ideal for any serious web development team. Clearly, when Elixir is fully utilised, there are massive gains to be made. In the next part, we will continue on the available Data Types of Elixir and how to write more code, and we'll finally get down to compiling<<
https://code.tutsplus.com/tutorials/introduction-to-erlang-and-elixir--cms-27509
CC-MAIN-2021-17
refinedweb
541
61.26
A. Deep Learning DevCon 2021 | 23-24th Sep | Register>>. Implementation of Tkinter Python GUI Toolkit As Tkinter comes pre-installed with standard python installation so we will not be installing it although if you don’t have it installed you can install it using pip install tkinter. - Importing required libraries We will create a form using Tkinter and the widgets it provides. So we will import Tkinter. Also, we will create a window that will initiate the Tk class. import tkinter as tk window = tk.Tk() - Creating a form step by step Now we will create the form using different widgets and wrapping them in a single loop. - Setting the Title. - Adding Label and Textbox. #Setting the Label label = tk.Label(window, text = "Welcome to Analytics India Magazine").pack() #Setting Window Size window.geometry("800x500") #creating labels name = tk.Label(window, text = "Name").place(x = 30,y = 50) email = tk.Label(window, text = "Email").place(x = 30, y = 90) phone = tk.Label(window, text = "Ph. Number").place(x = 30, y = 130) #creating text box boxes for the labels a1 = tk.Entry(window).place(x = 80, y = 50) a2 = tk.Entry(window).place(x = 80, y = 90) a3 = tk.Entry(window).place(x = 100, y = 135) window.mainloop() - Adding Radio Button Now we will create radio buttons to take the user input for ‘Gender. We use radio buttons when the user is allowed to select only one option. gender = tk.Label(window, text = "Gender").place(x = 30, y = 165) radio1 = tk.Radiobutton(window, text="Male").place(x = 80, y = 165) radio2 = tk.Radiobutton(window, text="Female", state='disabled').place(x =80,y = 185) radio3 = tk.Radiobutton(window, text="Other", state='disabled').place(x = 80, y = 205) window.mainloop() - Adding Checkbox We will create a skills section and add a checkbox for different skills. Checkboxes are used when users are allowed to select more than one value. skill = tk.Label(window, text = "Skills").place(x = 30, y = 225) check1 = tk.Checkbutton(window, text = "Artificial Intelligence", height =1, width = 15).place(x= 80, y = 225) check2 = tk.Checkbutton(window, text = "Machine Learning", height = 1, width = 13).place(x= 80, y = 245) check3 = tk.Checkbutton(window, text = "Data Science", height = 1,width = 9).place(x= 80, y = 265) window.mainloop() - Creating Button This is the final step where we will create the submit button. Also, we will create a pop-up window when we click the submit button. from tkinter import messagebox def onClick(): messagebox.showinfo("Thank You","Our Team Will Get Back to you") click1 = tk.Button(window,text = "Submit", command = onClick).place(x= 150, y=380) window.mainloop() Now when we click the submit button the onclick function will be called and a message box will be displayed. In the image above you can see how a pop-up window is opened with the title and message as we defined. Conclusion: In this article initially, we started with creating a basic layout window using the Tkinter. After that, we explored different widgets that are there in the Tkinter library and used them into creating a form. We saw how we can place different widgets on the application window using the place function and in the end, we created a pop-up window that opens as soon as we click submit. This is how you can create beautiful applications using many more widgets that are there in Tkinter in just a few lines of code.
https://analyticsindiamag.com/complete-guide-to-develop-an-interface-using-tkinter-python-gui-toolkit/
CC-MAIN-2021-39
refinedweb
572
62.24
Hi all I'm currently looking at different structs that can represent an IP header. Now I found the following two things: As one can see, the first version uses bitfields to access the IP-version and IP header length. It also seems to care about Big/Little Endian.As one can see, the first version uses bitfields to access the IP-version and IP header length. It also seems to care about Big/Little Endian.Code:/* * From /usr/include/netinet/in.h */ struct iphdr { #if __BYTE_ORDER == __LITTLE_ENDIAN unsigned int ihl:4; unsigned int version:4; #elif __BYTE_ORDER == __BIG_ENDIAN unsigned int version:4; unsigned int ihl:4; #else # error "Please fix <bits/endian.h>" #endif ... ... } /* * From "ip.h" of the tcpdump source */ struct ip { u_int8_t ip_vhl; /* header length, version */ #define IP_V(ip) (((ip)->ip_vhl & 0xf0) >> 4) #define IP_HL(ip) ((ip)->ip_vhl & 0x0f) ... ... } The second uses a u_int8_t to access the byte holding both header length and version and separates the two via the '&' and bitshifting. The second one makes sense to me, it doesn't care about byte order, why should it? But why does the first version has to care about byte order? Isn't it true that anyway the first four bits are the IP version, the next 4 bits are IP header length?... Rafael
http://cboard.cprogramming.com/c-programming/95463-bitfields-bit-little-endian.html
CC-MAIN-2015-32
refinedweb
217
72.05
This action might not be possible to undo. Are you sure you want to continue? Fundamentals of C Programming CS 102 - Introduction to Programming Department of Computer Science and Engineering Faculty of Engineering University of Moratuwa Sri Lanka By: Dilum Bandara, Dr. Sanath Jayasena, Samantha Senaratna © Department of Computer Science and Engineering Faculty of Engineering University of Moratuwa Sri Lanka ∗∗∗ Table of Content Chapter 1 – Introduction 1.1 Introduction to Programming 1.2 Program Development 1.2.1 Define the Problem 1.2.2 Outline the Solution 1.2.3 Develop the Algorithm 1.2.4 Test the Algorithm for Correctness 1.2.5 Code the Algorithm 1.2.6 Compile 1.2.7 Run the Program 1.2.8 Test, Document and Maintain the Program 1.3 Running a Program 1.4 Programming Languages 1.5 Overview of C 1.6 Steps in Developing a Program in C 1 1 1 2 2 2 2 2 2 3 3 4 5 5 Chapter 2 – Introduction to C Programming 2.1 An Example C Program 2.2 Your First C Program 2.3 C Tokens 2.4 Displaying Text 2.4.1 Escape Codes 2.5 Data Types 2.5.1 Primitive Data Types 2.5.2 Modifiers 2.6 Variables 2.6.1 Declaring Variables 2.6.2 Constants 2.7 Displaying Numbers 2.8 Formatted Input 7 7 8 9 10 10 11 11 12 12 12 13 15 Chapter 3 – Operators in C 3.1 Assignment Operator 3.2 Arithmetic Operators 3.2.1 Increment and Decrement Operators 3.2.2 Precedence and Associatively of Arithmetic Operators 3.3 Relational and Logical Operators 3.3.1 Precedence of Relational and Logical Operators 3.4 Bitwise Operators 3.4.1 Shift Operators 16 17 17 18 18 18 19 21 © Department of Computer Science and Engineering i 1 Opening a Connection to a File 9.4 Passing Variables to Functions 7.5 Conditional Operator 4.3 The do-while Loop 5.2 The while Loop 5.Chapter 4 – Conditional Control Structures 4.1.3 Function Definition 7.1.3 The if-else-if Ladder 4.6 The continue Keyword 5.1 Declaring Pointers 8.4 Nesting of Loops 5.1 A Function 7.1.2 Function Prototypes 7.5 The break Keyword 5.4 Writing Data to a File 46 46 47 47 48 ii © Department of Computer Science and Engineering .4.1 The if Statement 4.1 The File Protocol 9.4 Nesting Conditions 4.2 Text Strings and Pointers 8.1 Initialising an Array 6.2 The if-else Structure 4.1 The for loop 5.3 Pointers and Arrays 43 44 45 Chapter 9 – Handling Files 9.2 Closing the Connection to a File 9.1.7 The exit Function 30 31 32 33 34 35 35 Chapter 6 – Arrays 6.1 The Scope of a Variable 7.2 Default Parameters 38 39 39 41 41 41 Chapter 8 – Pointers 8.6 The switch Construct 22 24 24 26 26 27 Chapter 5 – Control Structures 5.2 Multidimensional Arrays 36 37 Chapter 7 – Functions 7.3 Reading Data from a File 9.4. Annex A – Lab 2 & 3 Annex B – Lab 4 Annex C – Lab 5 Annex D – Lab 6 Annex E – Lab 7 Annex F – Lab 9 Annex G – Lab 10 Annex H – Library Functions 50 55 56 60 61 62 63 64 © Department of Computer Science and Engineering iii . 5 – The printf conversion specifies Table 3.1 – The C language keywords Table 2.5 – Bitwise operators Table 3.4 – Basic C data types and modifiers (on a 32-bit machine) Table 2.2 – Escape codes Table 2.1 – Arithmetic operators Table 3.4 – Precedence of relational and logical operators Table 3.2 – Precedence of arithmetic operators Table 3.List of Figures Figure 2.3 – Relational and logical operators Table 3.3 – Basic C data types (on a 32-bit machine) Table 2.1 – File access modes 8 10 11 11 13 16 18 18 19 19 20 21 46 iv © Department of Computer Science and Engineering .7 – Precedence of C operators Table 9.6 – Precedence of bitwise operators Table 3.1 – C Tokens 9 List of Tables Table 2. 8. Programming is rather like a recipe. document and maintain the program Developing a program involves a set of steps: Most of these steps are common to any problem solving task. weeks. several years or even several decades. A program is simply a set of instructions that tells a computer how to perform a particular task. The problem can be divided into three components: Programmers should clearly understand “what are the inputs to the program”. 2. Program development (software development) may take several hours. © Department of Computer Science and Engineering 1 . Consider an example where a computer program is to be written to calculate and display the circumference and area of a circle when the radious . Programs are developed using programming languages. 1.2. Systems software includes operating systems and various device drivers. A person who writes a program using a programming language is called a programmer. days. a set of instructions that tells a cook how to make a particular dish. While in use the system needs to be maintained.2 1. • • • Inputs – the radius (r) Outputs – circumference (c) and area (a) Processing § 1 c = 2pr. Application software are used to perform real-world tasks and solve specific problems.e. It describes the ingredients (the data) and the sequence of steps (the process) on how to mix those ingredients. 4. After development. 3. Computer programming is the art of developing computer programs. customers will make use of the system. 1.Introduction 1. algorithm) into set of instructions understood by a computer. Therefore software development is not a onetime task. 5. months or years. His/her job is to convert a solution to a problem (i. “what is expected as output(s)” and “how to process inputs to generate necessary outputs”. The programmer should also test the program to see whether it is working properly and corrective actions should be taken if not. 6.1 . The steps are discussed in the following. Program Development Define the problem Outline the solution Develop an algorithm 1 Test the algorithm for correctness Code the algorithm using a suitable programming language Compile and correction of compile errors Run the program on the computer Test. A programming language provides a set of rules to develop a program.1 • • • Define the Problem Inputs – what do you have? Outputs – what do you want to have? Processing – how do you go from inputs to outputs? First of all the problem should be clearly defined. 7. The maintenance phase will continue for several months.1 Introduction to Programming Software refers to a program or set of instructions that instructs a computer to perform some task. Software can be divided into two major categories called system software and application software. it is a lifecycle where some of the above steps are reformed again and again. a = pr2 An algorithm is a sequence actions that is used to solve a problem. A suitable algorithm for our example would be: Start Input r Calculate circumference c = 2 * PI* r Calculate area a = PI* r^2 Output c & a End In here PI is a constant that represents the value of p. and the order in which they are to be carried out to solve a problem. The objective is to identify major logic errors early. missing punctuations . Runtime errors occur while executing the program and those are mostly due to incorrect inputs.2.2.4 Test the Algorithm for Correctness The programmer must make sure that the algorithm is correct. symbols. Pseudocode (a structured form of the English language) can be used to express an algorithm. Test data should be applied to each step. When the written program does not adhere to the programming language rules those are called syntax errors. 1. circumference (c) Calculation – c = 2pr Variables – radius (r). to check whether the algorithm actually does what it is supposed to. etc. In order to calculate the circumference: In order to calculate the area: The next step is to develop an algorithm that will produce the desired result(s). so that they may be easily corrected.1.5 Code the Algorithm After all the design considerations have been met and when the algorithm is finalised code it using a suitable programming language. These errors occur mostly due to miss typed characters. 2 Will be introduced later.2.6 Compile The next step is to compile (section 1. selection.3 Outline the Solution the major steps required to solve the problem any subtasks the major variables and data structures the major control structures (e. sequence. An algorithm is a segment of precise steps that describes exactly the tasks to be performed. While the program is running runtime errors and sometimes logic errors can be identified. 2 © Department of Computer Science and Engineering . 1. Our simple example can be quite easily check by submitting some values for radius (r) and walking through the algorithm to see whether the resulting output is correct for each input. area (a) Calculation – a = pr2 Develop the Algorithm The programmer should define: Consider the above mentioned example . repetition loops)2 in the algorithm the underlined logic Variables – radius (r). If there are no syntax errors the program gets compiled and it produces an executable program. While compiling syntax errors can be identified.3) the program.2.g.2. 1.2 • • • • • • • • • 1.2. 1.7 Run the Program Executable program generated after compiling can then be executed. it should be executed by the computer. what is understood by the hardware).8 Test. During this phase logic errors can be found. Programs written in programming languages such as FORTRAN.2 – Compiling and executing a program Figure 1. The saving on the compilation time is an advantage that is gain from compiling and therefore these programs run much faster.3). All the steps involved in developing the program algorithm and code should be documented for future reference. However. the interpreter converts high-level language instructions and input data to a machine readable format and executes the program. Therefore we need to convert the human readable programs into a machine language before executing. Programmers should also maintain and update the program according to new or changing requirements. into machine language programs. Document and Maintain the Program Test the running program using test data to make sure program is producing correct output(s). COBOL. This process can be slower than the process which 3 Machine language is the native language of the computer (i. C.3 Running a Program After a program is developed using a programming language. the computer understands only 1’s and 0’s (referred as the machine language3 or machine code). © Department of Computer Science and Engineering 3 . no compilation is needed again unless the source program is modified. These programs convert the high-level language program. Figure 1.2 when the executable file is available it can be executed by providing necessary input data so that it produces the desired outputs.2. This is conversion is achieved by a special set of programs calle d compilers (or interpreters). Since the source program is already compiled. Figure 1.1. Interpreters convert a source program and execute it at the same time (Figure 1.1 – Converting a human readable program into machine language Compilers translate a source program (human-readable) into an executable (machine-readable) program (Figure 1. Logic errors occur due to incorrect algorithms (although you provide correct inputs you do not get the correct outputs). Executable machine code produced by a compiler can be saved in a file (referred as the executable file) and used whenever necessary. 1.2).e. C++ and Pascal must be compiled before executing. Each time the program runs. Programmers write programmes in human readable languages called high-level languages.3 – Interpretation of a program As in Figure 1. C# and Visual Basic can be used to develop a variety of applications. However even the Assembly language programs tend to be lengthier and tedious to write. On the other hand FORTRAN was initially developed for numerical computing.4 Programming Languages Programming languages were invented to make programming easier.compiles the source program before execution. They are much closer to natural languages. these languages are general enough to be used for a wide range of problems. 5 Running the same program on machines with different hardware configurations. Most of these 4GL support development of Graphical User Interfaces (GUIs) and responding to events such as movement of the mouse. These languages allowed programmers to ig nore the details of the hardware. They became popular because they are much easier to handle than machine language. Lisp for artificial intelligence. Programs developed in Assembly runs only on a specific type of computer. A compiler or an interpreter was used to translate the high-level code to machine code. It is general purpose if it can be applied to a wide range of situations. They consume large amount of processing power and memory and they are generally slower than the programs developed using languages belonging to other generations. C++. A language is high-level if it is independent of the underlying hardware of a computer.e. Lisp and VB Script are interpreted. All the modern languages such as Visual Basic. how to make use of registers. Perl. Programs written in languages like BASIC. etc. Programs written using machine language belongs to the first generation of programming languages. As microprocessors. Writing and understanding Assembly language programs were easier than machine language programs. instruction format. 4 © Department of Computer Science and Engineering . Languages such as C. 4 Computer organization describes. With the introduction of third generation (also referred as 3GL) high-level languages were introduced. The program need to be converted as well as executed at the same time. the internal organization of a computer. Programs written in these languages were more readable and understandable than the 3GL. C# and MatLab belong to the fourth generation (4GL). Assembly language programs were automatically translated into machine language by a program called an assembler. Each Assembly language instruction directly maps into a machine language instruction (there is a 1-to-1 mapping). COBOL. VB Script. Programming languages are designed to be both high-level and general purpose. clicking of mouse or pressing a key on the keyboard. These programs were hardly human readable. Later programs were written in a human readable version of machine code called Assembly language. Smalltalk. allocate and de allocate memory. the instruction set. a single high level language instruction maps into multiple machine language instructions). Source code of the programs written in these languages is much smaller than other generation of languages (i. Languages such as FORTRAN. C and Pascal belong to the third generation. programs developed in 4GL generally do not utilize resources optimally. However. programming languages also can be grouped into several generations and currently we are in the fourth generation. computers were programmed using machine language instructions that the hardware understood directly. Java. Further. programmers were required to have a sound knowledge about computer organization4 . 1. Some people think that fifth generation languages are likely to be close to natural languages. The programs written using those languages were portable 5 to more than one type of hardware. Java. talking to various I/O devices. therefore understanding and modifying them was a difficult task. Assembly language belongs to the second generation of programming languages. In the early days. Simula for simulation and Prolog for natural language processing (yet. There are more than two thousand programming languages and some of these languages are general purpose while others are suitable for specific classes of applications. Such languages are one of the major research areas in the filed of Artificial Intelligence. C is also suitable for many complex engineering applications. C was used mainly in academic environments. Figure 1. The compilation of a C program is infact a three stages process. Java and C# inherit C coding style . Linux. Since C was developed along with the UNIX operating system it is strongly associated with UNIX. For many years. The syntax and coding style of C is simple and well structured. Windows and Apple Mac. If the compiler finds no errors in the source code it produces a file containing the machine code (this file referred as the executable file).1. 1. Programs written in C are efficient and fast. C is a robust language whose rich set of built-in functions and operations can be used to write any complex program. Due to this reason most of the modern languages such as C++. preprocessing. UNIX was developed at Bell Laboratories and it was written almost entirely in C. C is well suited to write both commercial applications and system software since it incorporates features of high-level languages and Assembly language. After a C source file has been created. C was introduced by Dennis Ritchie in 1972 at Bell Laboratories as a successor of the language called B (Basic Combined Programming Language – BCPL). Java and C# have branched away from C by adding object-orientation and GUI features. Today C compilers are available for a number of operating systems including all flavours of UNIX. Visual C++. that is with little or no modification and compiling. Therefore it is one of the best languages to learn the art of programming. the programmer must invoke the C compiler before the program can be executed. Most C programs are fairly portable .4 – Compilation process © Department of Computer Science and Engineering 5 . A file containing source code is called a source file (C source file s are given the extension . MS-DOS.5 Overview of C “C’ seems a strange name for a programming language but it is one of the most widely used languages in the world. C programs can be executed on different operating systems. it began to gain wide-spread interest among computer professionals. However with the release of C compilers for commercial use and increasing popularity of UNIX.c ).6 Steps in Developing a Program in C A programmer uses a text editor to create and modify files containing the C source code. compiling and linking. Various languages such as C++. If the compiler finds any non-standard codes or conditions which are suspicious but legitimate it will notify to the programmer as warnings and it continues to compile . Preprocessor does not modify the source code stored on disk. Linking is the final step and it combines the program object code with other object codes to produce the executable file. If any linker errors are encountered the executable file will not be generated. It also strips comments and unnecessary white spaces from the source code. or object files that the programmer has created. The compiler translates the preprocessor-modified source code into object code (machine code). 6 © Department of Computer Science and Engineering . While doing so it may encounter syntax errors. A well written program should not have any compilation errors or warnings. If errors are found it will be immediately notifie d to the programmer and compiling will discontinue. It modifies the source code (in memory) according to preprocessor directives (example: #define ) embedded in the source code. Finally it saves the executable code as a file on the disk.Preprocessing is performed by a program called the preprocessor. The other object codes come from run-time libraries. every thing is done on the copy loaded into the memory. Compilation really happens then on the code produced by the preprocessor. other libraries. My First Program */ #include <stdio. The function printf is embedded into a statement whose end is marked by a semicolon (. World!” on the screen. Use of prewritten functions makes the programmers life easier and they also allow faster and error free development (since functions are used and tested by many programmers) development.h includes information about the printf( ) function. A C program written for the Linux platform (or for UNIX) is slightly different to the program shown earlier. Most of the programs that people write needs to be modified after several months or years. it is best to start with a simple program. the header file stdio.h> main() { printf("Hello World!"). Lines that start with a pound (#) symbol are called directives for the preprocessor. Some of the special words may be written in uppercase letters. Comments are of two types. Comments are used by programmers to add remarks and explanations within the program. Compiler ignores all the comments and they do not have any effect on the executable program. Comments are useful in program maintenance. Here.1 An Example C Program In order to see the structure of a C program. /* Program-2. Semicolon indicates the end of a statement to the compiler.1 . The C preprocessor is used to insert the function definitions into the source files and the actual library file which contains the function implementation is linked at link time. single line comments and block comments. In such cases comments will make a programmer’s life easy in understanding the source code and the reasons for writing them. which actually does the work.2 – Introduction to C Programming 2. The directive #include appears in all programs as it refers to the standard input output header file (stdio. followed by the block containing the function(s) which is marked by braces ( ). The C language is built from functions like printf that execute different tasks. Block comments start with characters /* and end with characters */. © Department of Computer Science and Engineering 7 .2 Your First C Program Let us write our first real C program. it is used as a command to the preprocessor to direct the translation of the program. A header file does not include any implementation of the functions declared. It is always a good practice to comment your code whenever possible.h). There are prewritten libraries of functions such as printf() to help us. The following code is a C program which displays the message “Hello. } The heart of this program is the function printf.). When using more than one directive each must appear on a separate line. The main() is a special function that is required in every C {} program. A header file includes data types. Any text between those characters is considered a block of comments. In such cases they may not remember why they have written a program in such a manner. Single line comments start with two slashes {//} and all the text until the end of the line is considered a comment. function prototypes. The first line starting with characters /* and ending with characters */ is a comment. macros. 2. The functions must be used in a framework which starts with the word main() . Throughout this course students will be using Linux as the development platform. inline functions and other common declarations. The C language is case sensitive and all C programs are generally written in lowercase letters. A directive is not a part of the actual program. A modified version of the Hello World program is given next. Some of these functions are very complex and long. Keywords are also called as reserved words. Most functions return some value and sometimes this return value indicates the success or the failure of a function. When you execute your program it should display “Hello World!” on the screen. main() is placed as the first function.e. Use your favorite text editor in Linux and type the above program.1 lists keywords supported by the C language.3 C Tokens The smallest element identified by the compiler in a source file is called a token.” does that.My First Program */ #include <stdio. } Similar to the previous program. Language specific tokens used by a programming language are called keywords. Literals can be further classified as numeric constants.out (i. Tokens can be classified as keywords. return 0. The keyword int indicates that main() function returns an integer value.h> int main() { printf("Hello World!\n"). They are defined as a part of the programming language therefore cannot be used for anything else. $ vim HelloWorld. Table 2. character constants and string constants.out. operators. literals. in this case it returns zero (conventionally 0 is returned to indicate the success of a function).c $ gcc HelloWorld./* Program-2.3 .My First Program */ #include <stdio./a.c). however with a slight difference. there must be a statement that indicates what this value is. Save it as HelloWorld.c (all C source files are saved with the extension . return 0. etc. Table 2. It may be a single character or a sequence of characters to form a single item.c $ . Then your modified program should look like the following: /* Program-2.c to compiler your program. The statement “return 0.1 – The C language keywords auto double int struct break else long switch case enum register typedef char extern return union const float short unsigned continue for signed void default goto sizeof volatile do if static while 8 © Department of Computer Science and Engineering . identifiers. The keyword int is added before the function main. to execute the a. If there are no errors an executable file will be created in the same location with the default file name a. } 2.h> int main() { printf("Hello World!").2 . Use the command gcc HelloWorld. To execute the program at the prompt type . Then use the shell and go to the directory that you have saved your source file. Any user defined literals or i entifiers should not conflict with keywords or d compiler directives.out file in current directory)./a. Because function main() returns an integer value.out Hello World!$ However you will see the prompt ($) appearing just after the message “Hello World! ” you can avoid this by adding the new line character (\n) to the end of the message. The C language uses several symbols such as semicolons (. .99 are examples. Figure 2. braces ([]). A sequence of characters surrounded by double quotation marks (inverted comma “”) is called a string constant. C supports large number of mathematical and logical operators such as +. One such standard is the use of underscores symbol (_) to combine two words (example: sub_total).” is a string constant. 10000 and 99. It has two parentheses which contains the string to be displayed. and parentheses (()) to group block of code as a single unit.4 */ #include <stdio. For example “4+5” is an expression containing two operands (4 and 5) and one operator (+ symbol). While defining identifiers programmers should follow some of the naming standards for better readability of the program. } If you compile this program and run it. C identifiers can be very long and so it allows descriptive names like “number_of_students” and “Total_number_of_cars_produced_per_year”. the second time printf function starts printing the second string from next position on the screen. ^. return 0. brackets ({}). % .h> int main() { printf("Hi there"). digits or underscores. quotation marks (“”). Numeric constants are an uninterrupted sequence of digits (possibly contain ing a period).. colons (:).4 given below. A statement such as “I like ice cream. Character constants represents a single character and it is surrounded by single quotation mark (‘).4 Displaying Text The printf is the most important function used to display text on the screen. apostrophes (‘). *. Operators will be discussed in chapter 3. | .Literals are factual data represented in a language.1 – C Tokens 2. Operators are used with operands to build expressions. printf("How are you?"). || .). etc. It displays two successive statements using the printf function. Consider Program-2. Numerical values such as 123. This can be modified by © Department of Computer Science and Engineering 9 . ‘$’ and ‘4’ are examples. & .). ‘A’. /* Program-2. A valid identifier is composed of a letter followed by a sequence of letters. digits or underscore (_) symbols. && . Sometimes a C compiler may consider only the first 32 characters in an identifier. Characters such as ‘a’. Identifies are case sensitive. An identifier must begin with a letter and the rest can be letters. enclosed in quotation marks. commas (. the displayed output is: Hi thereHow are you? $ How does this happens? The printf function first prints the string “Hi there”. /. therefore the identifier abc is different from ABC or Abc. Identifiers are also referred as names. h> int main() { printf("Hi there\n").h> int main() { printf("Hi there "). Sri Lanka --------------------- Data Types A data type in a programming language is a set of data with values having predefined characteristics such as integers and characters. Moratuwa. return 0. Table 2.4. } Now the output is Hi there How are you?$ By adding another \n at then end of the second string you can move the prompt ($) to the next line. } /* Program-2. printf("\nHow are you?").adding the new line (\n) character before the start of the second string or at the end of the first string. Therefore the modified program can either be Program-2. University of Moratuwa Katubedda.lk 2.5b. /* Program-2. Note that each of these escape codes represents one character.mrt.5b */ #include <stdio.1 Escape Codes Escape codes are special characters that cannot be expressed otherwise in the source code such as new line. All of these characters or symbols are preceded by an inverted (back) slash (\). The language usually specifies the range of values for a given data 10 © Department of Computer Science and Engineering . although they cons ists of two characters. return 0. tab and single quotes. List of such escape codes are given in Table 2.2.1: Write a C program to display the following text on the screen.ac. printf("How are you?").5a or Program-2. 2 – Escape codes Escape Code \a \b \f \n \t \v \’ \” \? \\ Meaning Audible alert (bell) Back space Form feed New line Horizontal tab Vertical tab Single quote (‘) Double quote (“) Question mark (?) Backslash (\) 2. Exercise 2.5a */ #include <stdio. These include type defined data types (using typedef keyword) and enumerated types (using enum keyword).647 -2. double precision floating point numbers (double ). 3.967.295 -2. Each of these data types requires different storage capacities and has different range of values depending on the hardware (see Table 2. structures. Storage representations and machine instructions to handle data types differ form machine to machine. 2.483. Table 2.4e-38 to 3.483.7e+308 (accuracy up to 15 digits) 3. unsigned.4e-38 to 3. unions and pointers by combining several data types together.7e-308 to 1. namely integers (int) floating point numbers (float). These can be classified as integer types. characters (char) and void (void).type.147.647 0 to 4.3).647 3.4e-4932 to 1.648 to 2.5. if they are not enough programmers can also define their own data types.4e+38 1. 4 – Basic C data types and modifiers (on a 32-bit machine) Data Type Char unsigned char signed char Int signed int unsigned int Short Short int signed short int unsigned short int Long long int unsigned long signed long Float Double long double 2.5.1 Primitive Data Types The C language supports five primitive data types.294.648 to 2.2 Modifiers Size in Bits Range of values 8 8 8 32 32 32 8 8 8 8 32 32 32 32 32 64 80 -128 to +127 0 to 255 -128 to +127 -2147483648 to +2147483647 -2147483648 to +2147483647 0 to 4294967295 -128 to +127 -128 to +127 -128 to +127 0 to 255 -2. long and short .4e+38 (accuracy up to 7 digits) 1. how the values are processed by the computer and how they are stored.7e+308 (accuracy up to 15 digits) Without value (null) Table 2. The variety of data types available allows the programmer to select the type appropriate to the needs of the application as well as the machine. floating point types and character types.147. Character (char) type is considered as an integer type and actual characters are represented based on their ASCII value.147.147.7e-308 to 1.147. The modifiers are signed . For example short int represents fairly small integer values and require hal the amount of storage as f © Department of Computer Science and Engineering 11 . Derived data types – programmers can derive data types such as arrays.648 to 2. User defined data types – based on the fundamental data types users can define their own data types. Many of these data types can be further extended as long int and long double .483.483. 2. C supports a number of data types. Primitive (or basic) data types – these are the fundamental data types supported by the language.483. C supports three classes of data types: 1.147.1e+4932 (accuracy up to 19 digits) The basic data types can be modified by adding special keywords called data type modifiers to produce new features or new types.483. 3 – Basic C data types (on a 32-bit machine) Data Type Char Int Float Double Void Size in Bits Range of values 8 32 32 64 0 -128 to +127 -2147483648 to 2147483647 3. 2.4. just after declaring it or later within the code (before accessing/evaluating its value within an expression). Multiple variables belonging to the same data type can be defined as separate set of expressions or by listing variable names one after the other (should be separated by a coma sign ( )). The syntax to declare a new variable is to first write the data type then followed by a valid variable identifier as given in the following examples: int a.141. It is a memory location that can hold a value of a certain data type. Without having to refer to a variable such a constant can be defined simply by using the #define 12 © Department of Computer Science and Engineering . Programmers refer to a variable by its name (identifier) so that it can be accessed during the course of the program. 2.6. above variables can also be defined as: int a. or int a. 2.2 Constants The value of a constant cannot be changed after an initial value is assigned to it. After declaring a variable it should be initialised with a suitable value. “total” as a floating point number. float sub_total. namely declared constants and defined constants.regular int numbers. int b. --------------a = 10. an uninitialised variable can contain any garbage value therefore the programmer must make sure all the variables are initialised before using them in any of the expressions. With the const prefix the programmer can declare constants with a specific data type exactly as it is done with variables. const float pi = 3. a = 10. The C language supports two types of constants. the modifiers can be used with all the basic data types as shown in Table 2. the programmer must first declare it specifying the data type. unsigned int index_no. “index_no” as unsigned integer (since there are no negative index numbers) and “number_of_students” as a short integer. following example s: int a. In C. Initialising a variable can be done while declaring it.b. Programmers can define their own names for constants which are used quite often in a program. Declared constants are more common and they are defined using the keyword const. short int number_of_students. In initialising a variable any of the following three approaches are valid: int a. or int a=10. The most important restriction on using a variable in C is that they have to be declared at the beginning of the program. float total. Above set of expressions declared. float total.Consider the . variables “a” as an integer. float total.6 Variables A variable has a value that can change.6. Programmers cannot use any of the keywords as variable names. sub_total.1 Declaring Variables In order to use a variable in C. Except with void type. pre-processor directive. Table 2.128. Consider the example given below: /* Program-2. return 0.7 Displaying Numbers When displaying numbers special care must be given to the data type. Each data type has to be used with printf function in a specific format.8 which makes use of variables. In this program variables “ ” and “ ” are a b initialised with values 10.000000 The first number is of the type integer while the second number is of the type float.7.6 */ #include <stdio. These are called defined constants. Following expression illustrates the use of the #define pre-processor directive #define pi 3. which in turn determines the suitable memory storage locations. Consider Program-2. Exercise 2. Execute the program and observe the outputs.5 summarises conversion specifies supported by the printf function. They are used to instruct the compiler about the type of numbers appearing in the program. © Department of Computer Science and Engineering 13 . Exercise 2. Table 2. Run your program and observe the output.141 2. Conversion specifier %d stands for decimal while %f stands for float. 5 – The printf conversion specifiers Conversion Specifiers %c %d %e or %E %f %g or %G %i %o %p %s %u %x or %X %% Meaning of the output format Character Decimal integer Scientific notation Floating point Scientific notation or floating point (whichever shorter) Decimal integer Octal number Pointer String of characters Unsigned decimal integer Hexadecimal number Display the % sign The conversion specifiers are also referred as format characters or format specifiers.3: Identify the output of each printf function call given in Program-2. } Executing above program will display the following: 128 128. printf("%f\n".0).0 and 3 and the answer (b/a) is stored in variable “c”. In order to display the correct values using the printf function conversion specifiers should be used.2: Rewrite Program-2.h> int main() { printf("%d\n".3 and try swapping the %d and %f. Incorrect use of format characters would result in wrong outputs.128). The format %. float c. first_letter).a). first_letter).8 so that it displays an answer which is correct up to 2 decimal points.333333 In Program-2.9 illustrates the use of character variables.3 or 3. This can be achieved by using modifiers along with the format characters in order to specify the required field width.b).5: Write a program to assign the number 34. } //decimal value //decimal value //floating point value Executing Program-2.5678 to a variable named “number” then display the number rounded to the nearest integer value and next the number rounded to two decimal places. return 0.2f will display first two digits after that decimal point.9 */ #include <stdio.33 rather than 3. Exercise2. Exercise 2. printf("%f\n".0f will suppress all the digits to the right of the decimal point. c = b/a.h> int main() { printf("%d\n". printf("%d\n".65).h> int main() { char first_letter. printf("A is %d\n". Program-2.0. return 0.0/2).8 you may wish to see the answer appearing in a more manageable form like 3. while the format %.h> int main() { int a = 3. } Executing Program-2.9 will display the following: Character A ASCII value 65 14 © Department of Computer Science and Engineering . printf("Character %c\n".65. printf("B is %d\n".4: Modify Program-2.333333. //display character printf("ASCII value %d\n". first_letter = ‘A’. /* Program-2. printf("%x\n".8 */ #include <stdio.8 will display the following: A is 3 B is 0 Answer is 3. printf("Answer is %f\n". printf("%c\n".255). } /* Program-2.65/2). float b = 10. //display ASCII value return 0.7 */ #include <stdio./* Program-2.c).65*2). return 0. sum = a + b. The scanf function uses the same set of formatting characters as the printf function to describe the type of expected input. Consider the following line of code: scanf("%d%f". The supplied input values can be separated either by pressing Enter key or by leaving a blank space between the numbers. For such a program your inputs should be in the form: 2. Both of the following inputs are valid for Program-2.) rather than using the Enter key or a blank space. &b).&b). } // read 1st number // read 2nd number // total //display answer as float Three variables are declared (a. Note that the scanf function uses the variables “a” and “b”as “&a ” and “&b”. Program-2. &a). &a.10 */ #include <stdio. Values of “a” and “b” are to be read from the keyboard using the scanf function.sum. while the value of the variable “sum ” is calculated as the summation of “a” and “b”. sum). The scanf function accepts variable “a” as an integer and “b” as a floating point number. When the program executes. printf("a+b = %f\n". 2 3 Answer > 5. &a. scanf("%f". This will require use of an additional function like the printf in order to display a message as a prompt for the user reminding the required data item. The scanf function also supports mixed types of input data. b and sum ) in Program-2.10 demonstrates the use of the scanf function: /* Program-2. Exercise 2.10 so that it displays the following output when executed. The scanf is a similar function that is used to read data into a program. The string “&a ” represents the memory address containing variable “a” and is called a pointer (see Section 8).3 One deficiency of the scanf function is that it cannot display strings while waiting for user input. scanf("%f". The scanf function accepts formatted input from the keyboard.6: Modify Program-2. In such cases you must include the comma between format characters as: scanf("%f.h> int main() { float a. In certain cases you may want to separate your inputs using a comma (.000000 Exercise 2.7: Modify Program-2.10 so that it displays the answer with only two decimal points.b.%f". The symbol “&” is called the address of operator. Enter 1st number : 2 Enter 2nd number : 3 Answer > 5 © Department of Computer Science and Engineering 15 .000000 or 2 3 Answer > 5.2.8 Formatted Input We have already used printf function to display formatted output. it waits for the user to type the value of “a” followed by the Enter key and then it waits for the value of “b” followed by another the Enter key.10.&b).10. *.1 Assignment Operator The assignment operator is the simple equal sign (=). a*b. b. // // // // is is is is same same same same as as as as a a a a = = = = a-b. The assignment operator can be combined with the major arithmetic operations such as. The operators define how the variables and literals in the expression will be manipulated. 3. a%b. a = a + b. Therefore many similar assignments can be used such as: a a a a -= *= /= %= b. The assignment operation always takes place from right to left. // value b + c. the programmer may use the shorthand format: a += b. Consider the following set of examples: a a a a a = = = = = 5. variables and operators. For example. C supports several types of operators and they can be classified as: • • • • • • • Assignment operator Arithmetic operators Relational operators Logical operators Bitwise operators Special operators Pointer operators Pointer operators and special operators will not be covered in this chapter. The assignment operator is used to assign a value to a variable. or it may contain variables. -. a/b. They will be introduced later under relevant sections. The format of an assignment statement is: variable-name = expression. of of of of variable variable variable variable ‘a’ ‘a’ ‘a’ ‘a’ becomes becomes becomes becomes 5 15 5 + value of b value of b + value of c In C lots of shortcuts are possible. The expression can be a single variable or a literal. instead of the statement. // value 5+10.3 – Operators in C Expressions can be built up from literals. / and %. Such operators are called compound assignment operators.1 – Arithmetic operators Operator + * / % ++ -16 Action Addition Subtraction Multiplication Division Modulo division Increment (extended) Decrement (extended) © Department of Computer Science and Engineering . // value (x*x + y*y)/2. Table 3. . literals and operators. b. // value 5 + b. b. +. 3.2 Arithmetic Operators C supports five major arithmetic operators and two extended (shortcuts) operators (Table 3.1). Program-3.1 illustrates the usage of major arithmetic operators. /* Program-3.1 */ #include <stdio.h> int main() { int a,b; printf("Enter a: "); scanf("%d", &a); printf("Enter b: "); scanf("%d", &b); printf("\na+b = %d", a+b); printf("\na-b = %d", a-b); printf("\na*b = %d", a*b); printf("\na/b = %d", a/b); printf("\na%%b = %d", a%b); return 0; } //read value of a //read value of b //display sum of a & b //display subtraction of b from a //display multiplication of a & b //display division of a by b //display modulus of a divided by b Executing Program-3.1 with “a” as 5 and “b” as 2 will display the following: Enter a: 5 Enter b: 2 a+b a-b a*b a/b a%b = = = = = 7 3 10 2 1 3.2.1 Increment and Decrement Operators Increment and decrement operators are very useful operators. The operator ++ means “add 1” or “increment by 1”. Similarly operator -- mean “subtract 1” or “decrement by 1”. They are also equivalent to +=1 and -=1. For example, instead of using the following expression to increment a variable: a = a + 1; you may use: a +=1; or a++; Also expression: a = a - 1; can be written as: a -=1; or a--; Both increment and decrement operators can be used as a prefix or as a suffix . The operator can be written before the identifier as a prefix (++a ) or after the identifier as a suffix (a++). In simple operations such as a++ or ++a both have exactly the same meaning. However in some cases there is a difference. Consider the following set of statements: int a, x; a = 3; x = ++a; After executing above segment of code, “a” will be 4 and “x” will be 4. In line 3, first the variable “a” is incremented before assigning it to variable “x”. Consider the following segment of code. © Department of Computer Science and Engineering 17 int a, x; a = 3; x = a++; After executing above code segment “a” will be 4 and “x” will be 3. In the second approach in line 3 first “a” is assigned to “x” and then “a” is incremented. Exercise 3.1 – Predict the values of variables “a”, “b”, “sum1” and “sum2” if the following code segment is executed. int a, b; a = b = 2; sum1 = a + (++b); sum2 = a + (b++); 3.2.2 Precede nce and Associatively of Arithmetic Operators Precedence defines the priority of an operator while associativity indicates which variable(s) an operator is associated with or applied to. Table 3.2 illustrates the precedence of arithmetic operators and their associativity. Table 3. 2 – Precedence of arithmetic operators Operator ++, -*/% +– Precedence Highest ↓ Lowest Associativity Right to left Left to right Left to right In the same expression, if two operators of the same precedence are found, they are evaluated from left to right, except for increment and decrement operators which are evaluated from right to left. Parentheses can also be used to change the order of evaluation and it has the highest precedence. It is recommended to use parentheses to simplify expressions without depending on the precedence. 3.3 Relational and Logical Operators The relational operators are used to compare values forming relational expressions. The logical operators are used to connect relational expressions together using the rules of formal logic. Both types of expressions produce TRUE or FALSE results. In C, FALSE is the zero while any nonzero number is TRUE. However, the logical and relational expressions produce the value “1” for TRUE and the value “0” for FALSE. Table 3.3 shows relational and logical operators used in C. Table 3. 3 – Relational and logical operators Operator Relational Operators > >= < <= == != Logical Operators && || ! 3.3.1 Action Greater than Greater than or equal Less than Less than or equal Equal Not equal AND OR NOT Precedence of Relational and Logical Operators As arithmetic operators, relational and logical operators also have precedence. Table 3.4 summarises the relative precedence of the relational and logical operators. These operators are lower in precedence than arithmetic operators. 18 © Department of Computer Science and Engineering Table 3. 4 – Precedence of relational and logical operators Operator ! > >= < <= = = != && || Precedence Highest ↓ ↓ ↓ Lowest Associativity Right to left Left to right Left to right Left to right Left to right For an example consider the following expression: 10 > 8+1 is equivalent to the expression: 10 > (8+1) In order to understand how logical expressions are evaluated consider the following expression: a==b && c > d This expression says that; “(a is equivalent to b) AND (c is greater than d)”. In other words this expression is evaluated as TRUE if both the conditions are met. That is if a == b is TRUE and c > d is also TRUE. If AND (&&) is replaced by logical OR (|| ) operation then only one condition needs to be TRUE. Consider another expression (assume both “a” and “b” are integers and their value is 5) : !(a==b) In this case, since both “a” and “b” have similar value 5, the logical value of the expression within the parenthesis is TRUE. However the NOT operation will negate the result which is TRUE. Therefore the final result will be FALSE. In order to see the effect of precedence consider the following expression: a==b && x==y || m==n Since equal operator (==) has a higher precedence than the logical operators the equality will be checked first. Then the logical AND operation will be performed and finally logical OR operation will be performed. Therefore this statement can be rewritten as: ((a==b) && (x==y)) || (m==n) This expression is evaluated as TRUE if: • • a==b is evaluated as TRUE and x==y is evaluated as TRUE Or m==n is evaluated as TRUE. 3.4 Bitwise Operators Using C you can access and manipulate bits in variables, allowing you to perform low level operations. C supports six bitwise operators and they are listed in Table 3.5. Their precedence is lower than arithmetic, relational and logical operators (see Table 3.6). Table 3. 5 – Bitwise operators Operator & | ^ ~ >> << © Department of Computer Science and Engineering Action Bitwise AND Bitwise OR Bitwise XOR One’s complement Right shift Left shift 19 2 with character “b” as the input will display the following: Character to convert: b Converted character: B Executing Program-3.2 */ #include <stdio. printf("Character to convert: "). ASCII values of the uppercase and lowercase characters have a difference of 32. scanf("%c". /* Program-3. This is the concept used in Program 3. only difference between the two characters is the 5th bit. Bitwise XOR operation can be used to invert bits. 6 – Precedence of bitwise operators Operator ~ << >> & ^ | Precedence Highest ↓ ↓ ↓ Lowest Associativity Left to right Left to right Left to right Left to right Left to right Bitwise AND.Table 3.c. Therefore any ASCII value XOR with 32 will invert its case form upper to lower and lower to upper. 12. OR and XOR operations at the bit level.h> int main() { char input. 8. “A” is represented by 6510 while “a” is represented by 9710 (97-65 = 32). At the bit level.2 with character “Q” as the input will display the following: Character to convert : Q Converted character : q 20 © Department of Computer Science and Engineering . in ASCII. 65 = 0 1 0 0 0 0 0 12 97 = 0 1 1 0 0 0 0 12 32 = 0 0 1 0 0 0 0 02 Therefore by inverting the 5th bit of a character it can be changed from uppercase to lowercase and vice versa.&input).b. Consider following set of expressions: int a = b = c = a. The bitwise AND operation will be performed at the bit level as follows: a = 12 à 00001100 b = 8 à 00001000 & 00001000 Then the variable “c” will hold the result of bitwise AND operation between “a” and “b” which is 000010002 (810 ).2 which converts a given character from uppercase to lowercase and vice versa.1 – Write a C program to convert a given character from uppercase to lowercase and vice versa. } Executing Program-3. OR and XOR operators perform logical AND. For example . //input XOR 32 return 0. a & b. input ^ 32). //read character printf("Converted character: %c". Example 3. We know that 8 is represented in binary as: and when it is shifted by one bit to right. their precedences and associativit ies. therefore any additional bits are removed and missing bits will be filled with zero. we get: 16 = 00010000 ß 00001000 = 8 The C right shift (>>) operator shifts an 8-bit number by one or more bits to right while left shift (<<) operator shifts bits to left. as they use the same characters (for example .7 summarises all the operators supported by C. The unary operators (operators with only one operand such as &a (address of a)) have a higher precedence than the binary operators (operators with two operands such as a*b). * is used for multiplication and also to denote pointers). Table 3. Shifting a binary number to left by one bit will multiply it by 2 while shifting it to right by one bit will divide it by 2.4. In general the right shift operator is used in the form: variable >> number-of-bits and left shift is given in the form: variable >> number-of-bits In the following expression the value in the variable “a” is shift by 2 bits to right: a >> 2 Table 3. 7 – Precedence of C operators Operator ( ) [ ] -> . When operators have the same precedence an expression is evaluated left to right. After the shift operation the final result should also be a 8-bit number. ! ~ ++ -&* */% +<< >> < <= > >= = = != & ^ | && || ?: = += -= *= /= .3. we get: 8 = 00001000 à 00000100 = 4 Similarly when the number is shifted by one bit to left. Precedence Highest ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ Lowest Associativity Left to right Right to left Left to right Left to right Left to right Left to right Left to right Left to right Left to right Left to right Left to right Left to right Left to right Right to left Left to right © Department of Computer Science and Engineering 21 . However the following rule will reduce any confusion.1 Shift Operators 8 = 00001000 Shift operators allow shifting of bits either to left or right. However some operators can be confusing. This chapter introduces ifelse and switch constructs. the message “You have passed the exam! ” will not be displayed. } Executing Program-4. Example 4. In C.h> int main() { int marks. All these are done only if the condition is TRUE. In real life. there are many control structures that are used to handle conditions and the resultant decisions. Program 4. Then display the final amount that the customer has to pay.2 is an implementation of this. if it is the case a 5% discount should be given. printf("Enter marks: ").1 The if Statement if (condition) statement. Then the final amount needs to be displayed.1 with different inputs will behave as follows: Case 1: Enter marks: 73 You have passed the exam! Case 2:Enter marks: 34 Case 3:Enter marks: 50 In the second and third cases. If the amount is greater than or equal to 1000 rupees. The resulting statement is executed if the condition is evaluated as TRUE. &marks). A simple condit ion is expressed in the form: It starts with the keyword if. Program 4. /* Program-4.4 – Conditional Control Structures A Program is usually not limited to a linear sequence of instructions. Note that there is no semicolon (.) after the condition expression. If the value of the variable “marks ” is greater than 50.1 */ #include <stdio. followed by the result statement. So instructions which compute discount and final amount should be executed as a block. //get marks if (marks >50) // if marks >50 display message printf("You have passed the exam!"). Consider the following example: if (marks >50) printf("You have passed the exam!"). the message “You have passed the exam! ” is displayed on the screen. a programme usually needs to change the sequence of execution according to some conditions. More than one statement can be executed as a result of the condition by embedding set of statements in a block (between two braces {}). 22 © Department of Computer Science and Engineering . scanf("%d".1 illustrates the use of this in a C program.1 – Write a program which accepts a number (an amount of money to be paid by a customer in rupees) entered from the keyboard. followed by a condition (a logical expression) enclosed within parenthesis. 4. First the program needs to check whether the given amount is greater than or equal to 1000. return 0. a 5% discount is given to the customer. otherwise the statement is skipped and no message is displayed. printf("Enter amount: ").2 so that it displays the message “No discount…” if the amount is less than 1000.05. final_amount).2f". discount). /* Program-4. //get amount if (amount >= 1000) // if amount >= 1000 give discount { discount = amount* 0. printf ("\nTotal: %. printf ("Discount: %.2 to address this. discount.05. return 0. In such cases.discount. discount). scanf("%f"..final_amount. Another if clause is required to check whether the amount is less than 1000.final_amount.2f". printf("Enter amount: "). } Exercise 4.1 if the condition is TRUE.25 as the keyboard input display the following: Enter amount: 1250. } Executing Program-4. In example 4.2f". the if clause can be used to check the TRUE condition and act upon it.3 below has been modified from e Program-4. the set of statements inside the block are executed.1 – Modify Program-4.").1 so that it displays the message “You are failed!”. if marks are less than or equal to 50. © Department of Computer Science and Engineering 23 . The second if clause can be used before or after the first ( xisting) if clause.25 Discount: 62. Example 4.h> int main() { float amount. printf ("\nTotal: %. However it does not act upon the FALSE condition. If the condition is FALSE (if the amount is less than 1000) those statements will not be executed. //get amount if (amount >= 1000) // if amount >= 1000 give discount { discount = amount* 0.51 Total: 1187.2 – Modify Program-4.h> int main() { float amount. &amount).2 with 1250.2 when we wanted to identify the case where the amount is not greater than 1000 (the FALSE case) we were checking whether it is less than 1000 (<1000). final_amount). Therefore the expression resulting the FALSE condition needs to be reorganised. final_amount = amount . scanf("%f"./* Program-4. } return 0. discount. printf ("Discount: %. In many programs it is required to perform some action when a condition is TRUE and another action when it is FALSE. &amount).3 */ #include <stdio.2f".2 */ #include <stdio.discount.74 In Program-4. final_amount = amount .. } if (amount < 1000) // if amount < 1000 no discount printf ("No discount. Program-4. Blocks make it possible to use many statements rather than just one. if marks are greater than 50.05.final_amount. } Exercise 4. else if (condition-2) statement-2..3 The if-else-if Ladder In certain cases multiple conditions are to be detected.discount. You can include both the cases (TRUE and FALSE) using the if-else structure. 4.3 – Write a program to display the student’s grade based on the following table: 24 © Department of Computer Science and Engineering . scanf("%f".1 so that it displays the message “You have passed the exam!”. one of the two statements will be executed and then the program resumes its original flow.2f". &amount).3 can be modified as follows: /* Program-4.2 The if-else Structure if (condition) statement-1. else if (condition-3) statement-3.3 – Write a program to identify whether a number input from the keyboard is even or odd. If not display the message “You have failed!”. 4.The C language allows us to use the if-else structure in such scenarios. the program should display the message “Number is even”. } else // else no discount printf ("No discount. Example 4. printf("Enter amount: ").4 */ #include <stdio. else it should display “Number is odd”. printf ("Discount: %. else statement-2. The above construct is referred as the if-else-if ladder.. … else statement-n. printf ("\nTotal: %.h> int main() { float amount. Exercise 4. discount). final_amount = amount . the corresponding statement(s) are executed and the rest of the construct it skipped. The different conditions are evaluated starting from the top of the ladder and whenever a condition is evaluated as TRUE. If it is even. In such cases the conditions and their associated statements can be arranged in a construct that takes the form: if (condition-1) statement-1.2f". return 0. The if-else structure ta kes the form: When the condition is evaluated.2 – Modify Program-4. //get amount if (amount >= 1000) // if amount >= 1000 give discount { discount = amount* 0. final_amount). discount."). Then the Program-4. Therefore if-else-if ladder can be used to implement following program. printf("Enter marks: "). else if(marks >= 25 && marks <50) printf("Your grade is: C"). else printf ("Your grade is F"). /* Program-4. if(marks > 75) printf("Your grade is: A"). &marks). © Department of Computer Science and Engineering 25 .h> int main() { int marks.6. They combine several expressions with logical operators such as AND (&&) and OR (|| ). If marks is not greater than 75. the program evaluates the third expression and so on until it finds a TRUE condition.5 */ #include <stdio.Marks >=75 > 50 and <75 > 25 and <50 < 25 Grade A B C F In this case multiple conditions are to be checked. Due to the top down executio n of the if-else-if ladder Program-4. else if(marks >= 25 ) printf("Your grade is C"). If the second expression is not satisfied either.h> int main() { int marks. } //read marks // if over 75 // if between 50 & 75 // if between 25 & 50 // if less than 25 Notice that in Program-4. scanf("%d". printf("Enter marks: "). &marks). else if(marks >= 50 ) printf("Your grade is B"). These are called compound relational tests. Marks obtained by a student can only be in one of the ranges. else if(marks >= 50 && marks <75) printf("Your grade is: B"). scanf("%d".5 can also be written as follows: /* Program-4. return 0.5. if(marks > 75) printf("Your grade is A"). else printf ("Your grade is: F"). If it cannot find a TRUE expression statement(s) after the else keyword will get executed.6 */ #include <stdio. when the marks are entered from the keyboard the first expression (marks > 75) is evaluated. some of the conditional expressions inside the if clause are not as simple as they were earlier. } //get marks // if over 75 // if over 50 // if over 25 // if not In Program-4. the next expression is evaluated to see whether it is greater than 50. return 0. In nesting you must be careful to keep track of different ifs and corresponding elses. This can be accomplished by two approaches.4 Nesting Conditions Sometimes we need to check for multiple decisions.5 Conditional Operator Conditional operator (?:) is one of the special operators supported by the C language. An else matches with the last if in the same block. Therefore if both a >= 2 AND b >= 4 are TRUE “Result 1” will be displayed. 26 © Department of Computer Science and Engineering . to find the correct acceleration t has to be non zero and positive (since we cannot go back in time and a number should not be divided by zero).7 calculates the acceleration given u. v and t can be given as v = u + at . if else is to be associated with the first if then we can write as follows: if (a>=2) { if (b >= 4) printf("Result 1"). The conditional operator evaluates an expression and returns one of two values based on whether condition is TRUE or FALSE. if a>= 2 is TRUE but if b >= 4 is FALSE “Result 2 will be displayed. The Program-4. } else printf("Result 2"). When conditions are nested the if-else/ifelse-if construct may contain other if-else/if-else-if constructs within themselves. Therefore the acceleration can be found by the formula a = v −u . However. v and t. In this example the else corrosponds to the second if. It has the form: condition ? result-1 : result-2. v and t. In the program we implement users can input t any values for u. If a >= 2 is FALSE nothing ” will be displayed. Consider the following example: if (a>=2) if (b >= 4) printf("Result 1"). So our program should make sure it accepts only the correct inputs. The relationship among acceleration (a).4 – Rewrite the program in Example 4. u. using braces ‘{‘ and ‘}’. 4. Therefore the above can be rewritten as follows: if (a>=2) { if (b >= 4) printf("Result 1").5 – Consider the following example which determines the value of variable “b” based on the whether the given input is greater than 50 or not. To reduce any confusion braces can be used to simplify the source code.e. using compound relational tests or using nested conditions.4 – A car increases it velocity from u ms-1 to v ms-1 within t seconds. If the condition is TRUE the expression returns result-1 and if not it returns result-2. Example 4. Write a program to calculate the acceleration. } In the above. Example 4.3 using nested conditions (i. else printf("Result 2"). else printf("Result 2").4. Exercise 4. Conditional operator can be used to implement simple if-else constructs. printf("acceleration is: %. 4. &a). return 0.6 The switch Construct Instead of using if-else-if ladder. &v). //get starting velocity printf("Enter v (m/s): "). The syntax of the switch construct is different from if-else construct. &u). scanf("%f". //get current velocity printf("Enter t (s) : "). printf("Enter value of a: ").a. such as menu options. } /* Program-4.2f m/s". b). printf("Value of b: %d".v. //get starting velocity b = a > 50 ? 1 : 2. return 0.b. the switch construct can be used to handle multiple choices.8 */ #include <stdio.7 */ #include <stdio.h> int main() { int a. break. scanf("%f". scanf("%d". } Executing Program-4.t./* Program-4. &t). case constant-2: statement(s). break. The objective is to check several possible constant values for an expression. } else printf ("Incorrect time"). printf("Enter u (m/s): "). It has the form: switch (control variable) { case constant-1: statement(s). … © Department of Computer Science and Engineering 27 .h> int main() { float u. a).8 display the following: Enter value of a: 51 Value of b: 1 Enter value of a: 45 Value of b: 2 If the input is greater than 50 variable “b” will be assigned “1” and if not it will be assigned “2”. However use of conditional operator is not recommended in modern day programming since it may reduce the readability of the source code. scanf("%f". //get time if(t >= 0) { a = (v-u)/t. 9 */ #include <stdio.h> int main() { int a.6 – Write a program to display the following menu on the screen and let the user select a menu item.Microsoft Word"). //read input switch (a) { case 1: //if printf("\nPersonal Computer Software"). printf("\n-----------------------------------"). long or char (any other datatype is not allowed). Menu ----------------------------------1 – Microsoft Word 2 – Yahoo messenger 3 – AutoCAD 4 – Java Games ----------------------------------Enter number of your preference: Program-4. printf("\n4 . This process continuous until it finds a matching value. When the break keyword is found no more cases will be considered and the control is transferred out of the switch structure to next part of the program.Yahoo messenger"). If the value of the expression is not equal to constant-1 it will check the value of constant-2. break. scanf("%d". Based on the user’s selection display the category of software that the user selected program belongs to.case constant-n: statement(s). case 3: //if input printf("\nScientific Software").&a). printf("\n1 . break. The control variable of the switch must be of the type int. printf("\n2 . default: statement(s). printf("\t\tMenu"). break. case 4: //if input printf("\nEmbedded Software"). if it is the case. If a matching value is not found among any cases.AutoCAD"). printf("\nEnter number of your preference: "). } The switch construct starts with the switch keyword followed by a block which contains the different cases. input is 1 input is 2 is 3 is 4 28 © Department of Computer Science and Engineering . then it executes the statement(s) following that line until it reaches the break keyword. case 2: //if printf("\nWeb based Software"). Switch evaluates the control variable and first checks if its value is equal to constant-1.9 implements a solution to the above problem: /* Program-4. printf("\n-----------------------------------"). If they are equal it will execute relevant statement(s). Also note that the value we specify after case keyword must be a constant and cannot be a variable (example: n*2). printf("\n3 . Example 4. break. the statement(s) given after the default keyword will be executed.Java Games"). } return 0. } © Department of Computer Science and Engineering 29 . default: printf(“Invalid input”). default: printf("\nIncorrect input"). A sample run of you program should be similar to the following: Enter number 1: 20 Enter number 2: 12 Mathematical Operation ----------------------------------1 . break. break.AutoCAD 4 .5 – Develop a simple calculator to accept two floating point numbers from the keyboard.Microsoft Word 2 .break. Then display the answer. Then display a menu to the user and let him/her select a mathematical operation to be performed on those two numbers. In such cases several cases can be grouped together as follows: switch (x) { case 1: case 2: case 3: printf(“Valid input”).Add 2 .Subtract 3 . } Executing Program-4.Divide ----------------------------------Enter your preference: 2 Answer : 8.00 In certain cases you may need to execute the same statement(s) for several cases of a switch block.Multiply 4 .Yahoo messenger 3 .9 will display the following: Menu ----------------------------------1 .Java Games ----------------------------------Enter number of your preference: 1 Personal Computer Software Exercise 4. but you have to use suitable control expression and an initial value. The construct includes the initialization of the counter. Since the “counter” is “2” the expression will be TRUE. The C language supports three constructs. The third expression is the incrimination of the counter. } //loop 5 times Execution of program-5.1 displays: This This This This This is is is is is a a a a a loop loop loop loop loop In the above example . 5. Then the loop will terminate and the control is given to rest of the instructions which are outside the loop. } return 0. In addition it provides ways to initialize the counter and increment (or decrement) the counter. Then the “counter” is incremented by the ++ operator and now its new value becomes “2”. “as long as the counter is less than or equal to 5 repeat the statement(s)”. Therefore the printf function gets executed for the second time. It reads as. Exercise 5. This process continues for another 2 rounds. counter <= 5. Then the expression “counter <= 5” is evaluated. for(counter=1.h> int main() { int counter. At this point the first round of the loop is completed. In the first round of execution the “counter” is set to “1”. When the expression is evaluated at the 6 beginning of the sixth round the “counter” is greater than 5 therefore expression becomes FALSE.1 – Write a C program to display all the integers from 100 to 200. namely for. Therefore the printf function gets executed. The main function of the for loop is to repeat the statement(s) while the condition remains true. Example 5. Consider the following example: /* Program-5. the variable “ counter” starts with an initial value of “1”. Rest of this chapter introduces these control structures.1 */ #include <stdio. The general form of a for loop is: for (counter-initialization.while loops. increment) statement(s).1 – Write a program to calculate the sum of all the even numbers up to 100.1 The for loop The for loop construct is used to repeat a statement or block of statements a specified number of times. These repetitive constructs are called loops or control structures.5 – Control Structures A Program is usually not limited to a linear sequence of instructions or conditional structures and it is sometimes required to execute a statement or a block of statements repeatedly. Therefore the for loop is designed to perform a repetitive action for a pre-defined number of times. it is achieved by the ++ operator. You may also decrement the counter depending on the requirement. Then the “counter” is incremented once more and its new value becomes “3”. 30 © Department of Computer Science and Engineering . Since the current value of the “counter” is “1” expression is evaluated as TRUE. while and do. the condition and the increment. counter++) { printf("This is a loop\n"). Then in the second round the expression is evaluated again. After a total of five rounds the “ counter” becomes “ ”. The condition should check for a specific value of the counter. The second expression inside the parenthesis determines the number of repetit ions of the loop. condition. h> int main() { int counter. the only thing you can do is to abort the program (a program can be aborted by pressing Ctrl+Break). By adding 2 to an even number the next even number can be found. printf("Enter second number: ").3 – Write a program to compute the sum of all integers form 1 to 100. sum. (counter += 2)) //increment by 2 { sum += counter.First even number is 0 and the last even number is 100. /* Program-5. for(. Exercise 5. num1++) { sum += num1. You can omit even all the expressions as in the following example: for(. Program-5. for(counter=0. scanf("%d". This loop is an infinite one (called an infinite loop). Even the statement(s) inside the loop are optional. &num1). num1 <= num2.) printf("Hello World\n"). Each of the three parts inside the parentheses of the for statement is optional. } printf("Total : %d".. The general form of the while loop is: 31 © Department of Computer Science and Engineering . } //read num1 //read num2 //sum = sum+num1 5. It is repeated continuously unless you include a suitable condition inside the loop block to terminate the execution. Example 5. In this program both inputs should be given from the keyboard.2 such that it computes the sum of all the odd numbers up to 100. The programmer has to take care about the other elements (initialization and incrementing). return 0.. /* Program-5.2 – Modify Program-5. sum=0. printf("Enter first number: ").2 is an implementation of the above requirement. Therefore at the time of development both initial value and the final value are not known. num2. scanf("%d". You may omit any of them as long as your program contains the necessary statements to take care of the loop execution. sum. } printf("Total : %d". Therefore the counter should be incremented by 2 in each round.2 – Write a program to compute the sum of all integers between any given two numbers. return 0.4 – Write a program to calculate the factorial of any given positive integer. If there is no such condition.h> int main() { int num1. &num2). } Exercise 5. Exercise 5.2 The while Loop The while loop construct contains only the condition.3 */ #include <stdio. sum). sum = 0.2 */ #include <stdio. sum). counter <= 100. Next we need to make sure that the program loops only 5 times. You need to make sure that the expression will stop at some point otherwise it will become an infinite loop. Consider the following example: 32 © Department of Computer Science and Engineering .4 with 5 as the input will display the following: Enter Hello Hello Hello Hello Hello number of times to repeat: 5 World! World! World! World! World! In Program-5. } while (condition).) at each round. Exercise 5. printf("Enter number of times to repeat: "). while (num != 0) { printf("Hello World!\n"). Consider the following example: /* Program-5. It takes the following form: do { statement(s).while loop. scanf("%d". 5.4 */ #include <stdio. That is achieved by decrementing the counter (num-. The only difference between the do-while loop and other loops is that in the do. If the counter is not decremented the program will loop forever. } Execution of Program-5.while (condition) { statement(s). The loop continues as long as the expression is TRUE.5 – What would happen if we enter -1 as the number of times to loop in Program-5. In such cases use of while loop is desirable than the for loop. { The loop is controlled by the logical expression that appears between the parentheses.4 so that it works only for positive integers.4 variable “num” act as the counter. The while loop is suitable in cases where the exact number of repetitions is not known in advance. } return 0. In program-5.3 The do-while Loop Another useful loop is the do.4 the number of times to loop. num--. This means that the statement(s) inside the loop will be executed at least once regardless of the condition being evaluated. depends on the user input. It will stop when the condition becomes FALSE it will stop. The conditions inside the while loop check whether the counter is not equal to zero (num != 0) if so it will execute the printf function.while loop the condition comes after the statement(s).4? Modify Program-5.h> int main() { int num. &num). } while (price > 0). return 0. Therefore first you need to fully complete the first row and then you should go to the next. Example 5.h> int main() { float price. the for loop is recommended for cases where the number of repetitions is known in advance. The program should exit when the user enter 0. total.5 with some inputs will display the following: Enter Enter Enter Enter Total price (0 price (0 price (0 price (0 : 122. } Execution of Program-5. After displaying the correct message it should again display the menu.5 accepts prices of items from the keyboard and then it computes the total.4 Nesting of Loops Like the conditional structures loops can also be nested inside one another. Therefore in this type of a program do-while loop is recommended than the while loop. The while loop is recommended for cases where the number of repetitions are unknown or unclear during the development process. However.3 – Write a C program to display the following pattern: $$$$$$$$$$ $$$$$$$$$$ $$$$$$$$$$ $$$$$$$$$$ $$$$$$$$$$ There are 10 “$” symbols in a single row (10 columns) and there are 5 rows. The do-while loop is recommended for cases where the loop to be executed needs to run at least once regardless of the condition. 5. Exercise 5. Therefore the loop which handles printing of individual rows should be the outer loop and one which prints elements within a row (columns) should be the inner loop. Then based on the user selection it should display the correct message.2f". // if valid price continue loop printf("Total : %. © Department of Computer Science and Engineering 33 . each type of loop can be interchanged with the other two types by including proper control mechanisms.8 such that it first displays the menu.99 0 Program-5. User can enter any number of prices and the program will add them up. However the printf function does not support displaying text on a row that you have already printed. This can be implemented by having a two loops one nested inside another which print individual “$” symbols. Program-5. However having large number of nesting will reduce the readability of your source code. You can nest loops of any kind inside another to any depth you want. //set initial value to 0 do //request for price { printf("Enter price (0 to end): ")./* Program-5. //get price total += price. scanf("%f".5 */ #include <stdio.49 to to to to end): end): end): end): 10 12. &price).6 displays the above symbol pattern. It will terminate only if zero or any negative number is entered. In summary. total). In order to calculate the total or terminate the program there should be at least one input from the keyboard.50 99. total = 0 .6 – Modify Program-4. During the first 5 iterations the program executes normally displaying the message “Hello World! ”. If you have nested loops. Consider the following example: /* Program-5. then the break statement inside one loop transfers the control to the immediate outer loop. Therefore the if condition which evaluates whether “ n==5” becomes TRUE. At this point the loop will terminate because of the break keyword.h> int main() { int n. The control will be transferred to the first statement following the loop block. } } return 0. } Under normal circumstances the Program-5. break.7 – Write a C program to display the following symbol pattern: * ** *** **** ***** ****** 5. 34 © Department of Computer Science and Engineering . for(i=0.h> int main() { int i.j.7 */ #include <stdio.n>0. Then at the beginning of the sixth iteration variable “n” becomes “5”. } return 0. The program should allow users to terminate the program at any time by pressing any key before it displays all the 10000 messages.j++) { printf("$")./* Program-5. Example 5. Notice that in this example the for loop is written as a decrement rather than an increment. The break statement can be used to terminate an infinite loop or to force a loop to end before its normal termination. if(n == 5) { printf("Countdown aborted!"). for(n=10. immediately bypassing any conditions.7 will display the “ Hello World! ” message 10 times.j<=10.4 – Write a C program to display the message “Hello World!” 10000 times.6 */ #include <stdio.i<=5.n--) { printf("Hello World!\n"). } printf("\n").i++) { for(j=0. } //outer loop // inner loop // end of inner loop //end of outer loop Exercise 5. so it will execute the printf function and then the break instruction.5 The break Keyword The break keyword is used to terminate a loop. Exercise 5. © Department of Computer Science and Engineering 35 . However a number should not be divided by 0. for(i=0. i.i). By convention. when “i” is 0 (when the if condition is TRUE) the continue keyword is used to skip the rest of the iteration which will skip the printf function. In Program-5. statement in within the main function following code can be used: exit (0).9 */ #include <stdio. } return 0.h. for(i=-5.9.8 – Write a C program to display a sine table.2f \n". /* Program-5. The kbhit function is defined in the header file conio. The program should display all the sine values from 0 to 360 degrees (at 5 degrees increments) and it should display only 20 rows at a time. } 5.i<=5. If a key has been pressed. printf("5 divided by %d is: \t %. break.i++) // loop from -5 to 5 { if (i == 0) // if 0 skip continue. (5.h> #include <conio.i++) // loop 10000 times { printf("Hello World! %d\n". 5. /* Program-5.The C function kbhit can be used to check for a keystroke. it returns the value “1” otherwise it returns “0”. causing it to jump to the next iteration. If a program is to be terminated before the return 0. It takes the following form: exit (int exit-code) The exit-code is used by the operating systems and may also be used by the calling program.i<=10000.0/i)).7 The exit Function The exit function (defined in the header file stdlib.9. if(kbhit() != 0) // if a key is pressed { printf("Loop terminated").6 The continue Keyword The keyword continue causes the program to skip the rest of the loop in the current iteration. } In program-5. Consider the following example.h> int main() { int i.h) is used to terminate the running program with a specific exit code. 5 is divided by all the integers from -5 to +5. an exit-code of 0 indicates a normal exit where as any other value indicates an abnormal exit or an error. //terminate loop } } return 0.8 */ #include <stdio.h> int main() { int i. 81. 36 © Department of Computer Science and Engineering . This approach makes use of the format: array-name[index]. such as grades received by the students.) is used to separate one value from another. &marks[i]).h> int main() { int i. 86.sum. 33. scanf("%d". For example: marks[5] = {55. i+1). When declaring an array. the compiler must be able to determine exactly how much memory to allocate at compilation time. 6. 67. int marks[5]. //array of 5 elements float average.i++) //total marks { sum +=marks[i]. 67}.1 */ #include <stdio. int marks[5]. In the first approach. sum=0. The elements of an array can be initialised in two ways. The typical declaration of an array is: data-type array-name[no-of-elements]. In the second approach elements of the array can be initialised one at a time. For example: marks[0] marks[1] marks[2] marks[3] marks[4] = = = = = 55. 86. The following array can hold marks for five subjects. Like any other variable in C an array must be declared before it is used. As arrays are blocks of static memory locations of a given size. sine values of a series of angles. etc. 33. Arrays are useful when you store related data items. the number of array elements should be constant. Notice that the array name must not be separated from the square brackets containing the index. the value of each element of the array is listed within two curly brackets ({}) and a comma (.i<=5. Therefore in an array with “n” elements first index is “ and the last index is “ 0” n-1”.1 Initialising an Array An array will not be initialised when it is declared.i++) { printf("Enter marks for subject %d: ". Using an array we can store five values of type int with a single identifier without having to declare five different variables with a different identifier. 81.6 – Arrays Arrays are a series of elements of the same data type placed consecutively in memory that can be individually referenced by adding an index to a unique name. Consider the following example: /* Program-6.i<5. for(i=0. In an array index of the first element is considered as zero rather than one. //get the marks } for(i=0. therefore its contents are undetermined until we store some values in it. This confusion can be overcome by initialising an array with “n+1” elements and neglecting the first element (element with zero index). 2 Multidimensional Arrays The type of arrays that we discussed up to now is called a one-dimensional (or single dimensional) array. 59. //5. © Department of Computer Science and Engineering 37 . 86. 33.0.1 hold only marks of one student. 81. 82. Marks[0][0] marks[0][1] marks[0][2] marks[0][3] marks[0][4] = = = = = 55. 30. {45.} average = sum/5. Similarly we can define arrays with n dimensions and such arrays are called n-dimensional or multidimensional arrays. return 0. 33. as it takes one index and store only one type of data.0 indicates a float value printf("Average : %. The array that was used in Program-6. 46. You can declare an array to hold marks of 100 students with store marks of 5 subjects as in the following example: int students[100][5]. 57.2f". Altogether it declares 500 (100×5) memory locations. It can be extended to store marks of many students using a twodimensional array. Such an array is declared in the following form: data-type array-name[size-1][size-2].1 displays the following: Enter marks for Enter marks for Enter marks for Enter marks for Enter marks for Average : 64. 67. 86.1 – Write a program to store marks of 5 students for 5 subjects given through the keyboard. 60} }. {39. int students[3][5]= { {55. Initialising marks of the first student can be performed in the following manner. 6.60 subject subject subject subject subject 1: 2: 3: 4: 5: 55 33 86 81 67 The Program-6. 67}. Exercise 6. average). 86. A two-dimensional array is initialised in the same way. 47}. The first index defines the number of students and the second index defines the number of subjects. 81. Then in the second loop it computes total of all marks stored in the array and finally it computes the average. Calculate the average of each students marks and the average of marks taken by all the students. } Execution of Program-6. The following statement declares and initialises a two-dimensional array of type int which holds the scores of three students in five different tests.1 accepts marks for 5 subjects from the keyboard and stores them in an array named marks . Prototypes of functions int main( ) { ………. Well designed functions perform a specific and easily understood task. Complicated tasks should be broken down into multiple functions and then each can be called in the proper order. Therefore functions can be classified as built-in and user defined. but you can also write your own functions. followed by the #define directive (if any) then followed by the proto types of functions. some may return a value of a certain data type (such as kbhit ) and some may accept as well as return a value (sqrt ). Then comes the program building block which includes the main( ) function and implementation of the user defined functions. The prototype is a declaration of a function used in the program. 7. A modular program is usually made up of different functions. } function_1( ) { ………. } ………… function_n( ) { ………. each one accomplishing a specific task such as calculating the square root or the factorial.1 A Function A function is a subprogram that can act on data and return a value.. It starts with the #include directive. In general a modular program consists of the main( ) function followed by set of user defined functions as given below: #include …… #define …. 38 © Department of Computer Science and Engineering . Each function has a unique name and when the name is encountered while in execution the control of the program is transferred to the statement(s) within the function... When a program is executed the main( ) is called automatically. } The source code contains other elements in addition to the function blocks. When the function is ended (returns) the control is resumed to the next statement following the function call. the main( ).. } function_2( ) { ……….7 – Functions The C functions that you have used so far (such as printf and scanf) are built into the C libraries. Some functions may accept certain input parameters (such as printf). The main( ) may call other functions and some of them might call other functions. Every C program has at least one function. The function returns the square as the value of “y ”. The function “type” is the data type of the return value.&radius). double power(double x. type argument-2. /*Program-7. scanf("%f". b = square(a). Function definition takes the form: Return-type function-name(type argement-1. //read radius © Department of Computer Science and Engineering 39 .1 */ #include <stdio.). int kbhit( ). type argument-2. The function name is any legal identifier followed by the function parenthesis without any space in between.. A function prototype takes the form: type function-name(type argement-1. The variable “b” in the calling function receives the return value. 7. return y. return type and parameters) of a function. The function prototype is a statement that ends with a semicolon.141.. If the function does not any parameters. The first function returns no value and it takes an integer argument. The arguments (or parameters) come inside the parenthesis. If they do not match the compiler will issue error messages during compilation. the data type is defined as void. The function prototype and the definition must have exactly the same return type. The prototype tells the compiler in advance about some characteristics (name of the function. which is the same as the function prototype but does not end with a semicolon. If the function does not return a value.2 Function Prototypes Using functions in your program requires that you first declare the function (the prototype). Second prototype returns an integer value and has no inputs. …. …. //function prototype int main() { float radius. preceded by their types and separated by the commas. float area(float r).3 Function Definition The definition of a function is the actual body of the function. printf("Enter radius: "). } Whenever you want to call this function you can include a statement like the following in the program. where it is received by the function as the value of variable “x”. Following are some examples for prototypes: void exit(int x). Third function returns a double value and takes two double values. Later you can implement the function. double y). Here. int square(int x) { int y.h> const float pi = 3. y = x*x. name and parameter list. Example 7. the value of variable “a” is passed to the function. which accepts an integer as the input and returns its square. Implement calculation of circumference and areas as separate functions.7. it is either kept blank or the word void is used inside the parenthesises. //function prototype float circumference(float r). It starts with function header. } Consider the following function. ) { Statement(s).1 – Write a C program to calculate the circumference and area of a circle given its radius. printf("\nArea is: %.141. Both these functions calculate the area of a circle given the radius. } void area(int r) { printf("\nInteger input"). return 0. area((float)radius). scanf("%d". return 0. } /* Function computes the area of a circle given its radius*/ float area(float r) { return (pi*r*r). (pi*r*r)). } //define pi // function prototype // function prototype //convert to float Execution of Program-7. As given below: float area(int r).2 */ #include <stdio. void area(int r). Based on the type of the given input the program dynamically calls the correct function. float area(float r). } void area(float r) { printf("\nFloating point input").2f". } It is also possible to define several functions with the same name but with different parameters.printf("\nArea : %. printf("\nCircumference : %. } /* Function computes the circumference of a circle given radius*/ float circumference(float r) { return (2*pi*r). printf("Enter radius: ").2f". int main() { int radius.14 Floating point input Area is: 3.2f".&radius). (pi*r*r)). area(radius). void area(float r). printf("\nArea is: %. Consider the following program: /*Program-7. area(radius)).2 displays: Enter radius: 1 Integer input Area is: 3.14 40 © Department of Computer Science and Engineering .2f". circumference(radius)).h> const float pi = 3. However the first function accepts an integer as the input while the second function accepts a floating point number. 4. 7. The program accepts an integer from the keyboard and when the expression area(radius). A well written C source code should not have any global variables unless they are specifically required since an accidental change to a global variable may produce erroneous results. The value passed must be of the declared type. converts the integer value to a floating point number (this process is called casting) before calling the function..2 executes each function based on the given input. Scope of a local variable is limited to the function. you still have two local variables isolated from each other. //global variable float sub_total(float total). It is also possible to have the same name for functions with different behaviour with different input parameters. Thus if you have a function declared as: long my_function(int a).1 The Scope of a Variable A variable has a scope. If the function definition differs or if you pass a value of a wrong data type you will get a compilation error. For example you can define a global variable “discount” as follows: #include <stdio. 7. You can modify its value in either place and read it from another place. In order to avoid errors when using functions. The global variable can be defined within the program but anywhere outside function block including the main function.2 Default Parameters For every parameter you declare in a function prototype and declaration the calling function must pass in a value. you cannot have functions with the same name with a different output parameter.h> float discount. the function must in fact take an integer value as an input. however best practices suggest that no two functions should have the same name unless they perform identical tasks. but not the variable it self. you have to have a clear understanding about the mechanism of passing variables from one function to another. The expression area((float)radius). This means that the value of the passed variable cannot be changed by any other function. On the other hand you can also define global variables which are accessible from any function within the same source file. is executed it calls the function which accepts and integer as the input parameter and it display the message “ Integer input” and the area. © Department of Computer Science and Engineering 41 . When it is called since the input is a floating point value it executes the function which displays the message “Floating point input”. A variable declared inside a function is called a local variable . Although you can have multiple functions with the same name but with different input parameters. A variable defined in such a manner is visible to the main function and the “sub_total” function.. When you pass a variable to a function (such as the variable radius in Program-7. which determines how long it is available to your program (or function) and where it can be accessed from.Program-7.1). Variables declared within a block are scoped only to that block.. you are actually passing a copy of the variable (called passed by value). Even if you use another variable with the same name in the function. they can be accessed only within that block and go out of existence when the execution of the block is completed. //function prototype int main() { .4.4 Passing Variables to Functions You can use as many functions as you need in your programs and you can call a function from another or even from it-self. 7. However when you declare the function prototype you can define a default value for the parameter as follows: long my_function(int a = 50). Such variables are not seen by any other functions including the main function. z = x.c). a=5. void swap2(int x). } void swap2(int x) { int z. swap2(b). int y) { int z. Exercise 7.int y). printf("\nValue after 2nd function a= %d. } 42 © Department of Computer Science and Engineering . b= %d c= %d" . b= %d c= %d" .3. b=10. printf("\nValue before 1st function a= %d.c).c). /*Program-7. c=15. y = z. Similarly a function with many input parameters can have a default value for each parameter.The default value is used if no input is supplied to the function.a.c. a = z. } void swap1(int x. printf("Test"). swap1(b. x = a.b.a. int main() { int b.3 */ #include <stdio.h> void swap1(int x. printf("\nValue after 1st function a= %d. z = x.b. int a. return 0. x = y.1 – Predict the output of each printf function in Program-7.c).b. b= %d c= %d" .a. Such memory location can be accessed by providing the memory address. Although it may appear a little confusing for a novice programmer they are a powerful tool and handy to use once they are mastered. The power of C compared to most other languages lies with proper use of pointers. © Department of Computer Science and Engineering 43 . &pnt). The typical declaration of a pointer is: If a pointer “a” is pointing to an integer. Pointers are more efficient in handling data tables and sometimes even arrays. Therefore a pointer is nothing but a variable that contains an address which is a location of another variable in memory.1 */ #include <stdio. The address operator (&) allow us to retrieve the address from a variable associated with it. Suppose the address of that memory location is 2000. 8. number). The location of a variable in memory is system dependent and therefore the address of a variable is not known directly. pointer is: %d". Use of pointers allows easy access to character strings. printf("\nThe printf("\nThe printf("\nThe printf("\nThe printf("\nThe number is: %d". Computers use memory to store both instructions and values of variables of a program.8 – Pointers Pointers are another important feature of the C language. it is declared as: int *a. Since memory addresses are simple numbers. &number). value of the pointer is: %d". Consider the following example: int number = 35. they can also be assigned to some variables. *pnt). int *pnt. the system always associates the name “number” with the memory address 2000. pnt = &number. Therefore in computation even the address of the pointer can be used. Pointers are useful due to following reasons: • • • • • They enable us to access a variable that is defined outside a function. Pointers tend to reduce the length and complexity of a program. Each of these memory cells has an address associated with it. Then after executing above expression the memory address 2000 should hold 35. We may have access to the value “35” by using either the name “number” or the address 2000. address of the pointer is: %d". its value is also stored in another memory location. During execution of the program. Consider the following example: /* Program-8.h> int main() { int number = 20. A pointer is declared using the indirection (*) operator. Such variables that hold memory addresses are called pointers. They increase the execution speed. The above expression allocates a memory location to hold the value of variable “number” that can hold an integer (4 bytes) and it also initialises the variable. address of the number is: %d".1 Declaring Pointers data-type *pointer-name. The computer’s memory is a sequential collection of storage cells with the capacity of a single byte. pnt). Whenever a variable is declared the system allocates some memory to hold the value of the variable. Since a pointer is a variable. 2 displays: Before swapping a= 5: b= 10 After swapping a= 10: b= 5 8. Example 8. &b). a = "Hello World!". a.b. b = 10. The final statement displays the value of the pointer “pnt” which holds the value of the variable “number”.int *b). Consider the following example: 44 © Department of Computer Science and Engineering . } void swap(int *a. Strings in C are handled differently than most other languages.return 0.2 Text Strings and Pointers An array of characters is called a string. the program can locate it. //call function printf("\nAfter swapping a= %d: b= %d". It will point to the first character of the string. The fourth printf function displays the address of the pointer.1 displays: The The The The The number is: 20 address of the number is: 1245064 pointer is: 1245064 address of the pointer is: 1245060 value of the pointer is: 20 The first printf function displays the value of variable “number”. x = *b.2 */ #include <stdio. int *b) { int x. A pointer is used to keep track of a text string stored in memory. } Execution of Program-8. b). } Execution of Program-8.1 – Write a program to swap two integer numbers using pointers. printf("\nBefore swapping a= %d: b= %d". *a = x. a. swap(&a. int main() { int a. *b = *a. The third statement displays the value of the “pnt” which is assigned by the expression pnt = &number. A character pointer is used to point to the first character of a string as given in the following example: char *a. return 0. /* Program-8. By knowing the beginning address and the length of the string. The second printf statement displays the address of the memory location occupied by the variable named “number”. a = 5.. Note that now the address of variable “number” and value of pointer “pnt” is the same. b).h> void swap(int *a. *a). a). printf("First character: %c\n".3 the first printf function displays the string pointed by pointer “a”.. you can point to the first element of the array using either one of the following pointers: marks &marks[0] //first element //first element Also the following pairs of pointers are equivalent: marks+1 == &marks[1] . } Exaction of Program-8. /* Program-8. a).. 73. The name of an array points to the first element of the array. The second printf function display the value pointed by pointer “a” which is the first character of the string.3 */ #include <stdio. printf("Starting memory address: %d\n". 98. *a).3 Pointers and Arrays An array is a series of elements of the same data type. printf("String: %s\n"..h> int main() { int marks[5]= {89. } marks). index and pointers. printf("%d\n". printf("First character: %d\n". *marks). marks+4 == &marks[4] Or you can use the array name to refer to the contents of the array elements like: *(marks) *(marks+1) //value of 1st element //value of 2nd element Program 8. 39}. //memory address pointed by pointer //memory address of 1st element //value pointed by pointer //value of 1st array element © Department of Computer Science and Engineering 45 .3 will display: String: Hello World First character: H Starting memory address: 4235496 First character: 72 In Program-8. If you declare an array in the following manner: int marks[5]. printf("%d\n". The final printf function displa ys the ASCII value of the first character in the string.4 illustrates the use of array name... Pointers can be used to manipulate arrays rather than using an index. 8.h> int main() { char *a. The third printf function displays the starting memory address of the string which is the value of pointer “a”. &marks[0]). return 0. printf("%d\n"./* Program-8. a = "Hello World". marks[0]). return 0. printf("%d\n".4 */ #include <stdio. 45. The common operations associated with a file are: • • • • • • • Read from a file (input) Write to a file (output) Append to a file (write to the end of a file) Update a file (modifying any location within the file) In C language data is transferred to and from a file in three ways: Record input/output (one record at a time) String input/output (one string at a time) Character input/output (one character at a time) 9. The function fopen returns a pointer (referred as the file pointer) to the structure6 FILE which is defined in the stdio.9 – Handling Files The programs that we developed up to now were neither able to produce permanent output nor were they able to read data inputs other than from the keyboard. Table 9. Open an existing file for reading and writing Open a new file for reading and writing Open a file for reading and appending. When you open a file it would be better to make sure that the 6 Structures are used to store records with different data types. The access_mode defines whether the file is open for reading.1 summarises the access modes supported by fopen function. “subjects registered”.1 Opening a Connection to a File In order to use a file on a disk you must establish a connection with it. employee salaries.txt". such as “student name”.txt” in the current directory for appending data: FILE *fp. Using files you can save your output data permanently and retrieve them later. A connection can be established using the fopen function. The function takes the general form: fopen(file_name.1 – File access modes Access mode “r” “w” “a” “r+” “w+” “a+” Description Open an existing file for reading only. If the file does not exist create a new one. marks obtained in an exam. If the file does not exist create a new one. Open a file for writing only. New data will be added to the end of the file. etc.1 The File Protocol • • • Opening a connection to a file Reading/writing data from/to the file Closing the connection Accessing a file is a three step process: 9. Open a file for appending only. such as student information. Each record is a collection of related items called fields. If the file does not exist create a new one.h headier file. 46 © Department of Computer Science and Engineering .1. fp = fopen("my file. access_mode) The file_name is the name of the file to be accessed and it may also include the path. A file in general is a collection of related records. writing or appending data. If the file exists it will be overwritten. Table 9. etc. The following code opens a file named “my file. “date of birth”. "a"). Then the expression if(fp != NULL) evaluates whether the connection is successful.txt” one character at a time and displays it on the screen.1 */ #include <stdio.. return 0. 9. The functio n fclose is used to close the file.h> int main() { FILE *fp."). "r").2 Closing the Connection to a File After a connection to a file is established it can be used to read or write data. When all the file processing is over the connection should be closed.1 – Write a program to read the file “my file. Example 9. /* Program-9. If it is not successful the program will display the message “Error while opening file.. Closing the connection is important as it writes any remaining data in the buffer to the output file. //close the file } else printf("\nError while opening file.1 will display Hello World! This is my first file In Program-9.c).1. //read next character } fclose(fp).1 a connection is first established to the file. c= getc(fp).” If it is successful it reads the first character from the file.3 Reading Data from a File When reading data from a ASCII file you can either read one character or one string at a time. //read the 1st character while ( c != EOF) //if not the end of file { printf("%c". For example: fclose(fp) When closing the file the file pointer “ ” is used as an argument of the function. If the establishment of a connection is successful the function returns a pointer to the file.operation is successful.txt” which has the message: Hello World! This is my first file The following program reads the file “my file.. If an error is encountered while establishing a connection the functions returns NULL. Reading Characters from a File To read one character at a time you can use the getc function. It takes the form: getc(file_pointer) You can assign the output of the function getc to an int or char variable. If the character is not the end of the file (indicated by the End Of File (EOF) mark) it displays the © Department of Computer Science and Engineering 47 . char c..1. When a file is fp successfully closed the function fclose returns a zero and any other value indicates an error. 9. fp = fopen("my text. //open read-only if(fp != NULL) { c = getc(fp). } Execution of Program-9.txt". h> int main() { FILE *fp.txt". //close the file } else printf("\nError while opening file"). therefore you need to know in advance the maximum number of characters in a string.buffer). "r"). } 9. fp). if not it returns EOF mark. Then the program continues to read the rest of the characters in the file until it finds the EOF mark. The function generally takes the form: fgets(string. fp). Reading a String from a File In real-life applications it is more useful to read one string at a time rather than one character. Example 9. char buffer[100]. the program has to check for the line feed (LF) character so it can find the end of each string. Afterwards the connection to the file is closed using the fclose function.3 – Write a C program to store the message “Introduction C Programming” in a file named “message. /* Program-9.1 such that it uses the fgets function instead of fgetc function. Also it must check for the EOF mark which comes at the end of the file . result = fgets(buffer. fp) where c is the character while fp is the file pointer. It returns an int value which indicates the success or the failure of the function.character. 100. It has the form: putc(c.3 is an implementation of the above requirement. Program-9. 100. max_characters. return 0. Example 9. Suppose the file does not have more than 100 characters in a line. One deficiency in fgets is that it can only read to a fixed character buffer.2 */ #include <stdio. The function fgets returns a char pointer.2 – Modify Program-9. //char array with 100 elements // hold the result of the fgets function fp = fopen("my text. The function putc is used to write characters in the message to the file. It returns the int value of the character if it is successful. //read the next string } fclose(fp). It returns NULL if EOF mark is encountered. Writing Character to a File To write a character to a file the putc function can be used. To find the number of characters in the message the strlen 48 © Department of Computer Science and Engineering . The fgets function can be used to read a string at a time.txt”. With every read. //open read-only if(fp != NULL) { result = fgets(buffer. //read the 1st string while(result != NULL) //if not the end of file { printf("%s". file_pointer) The “string” is a character array (also called a character buffer) and “max_characters ” define the maximum number of characters to read form a line.4 Writing Data to a File You can also write data to file either one character at a time or a string at a time.1. char *result. ac. //write character pointed by pointer fclose(fp). namely fputs and fprintf can be used for this purpose.fp). 2. //loop counter char *message. Add new friend.txt file as follows: --------------Contact info--------------Name Tel-No e-Mail Kamala 077-7123123 kamala@yahoo.ac.2 – Develop a simple telephone directory which saves your friends contact information in a file named directory. file_pointer) fprintf(file_pointer. A pointer is used to point to the string and the pointer is incremented by one memory location at a time. } Writing a String to a File The advantage of putc is that it allows you to control every byte that you write into the file. Exit -----------------------------------------------Enter menu number: When you press “1” it should request you to enter following data: ---------New friend info-------Name : Saman Phone-No: 011-2123456 e-Mail : saman@cse.h> int main() { FILE *fp.com Saman 011-2123456 saman@cse. 3. /* Program-9. The program should have a menu similar to the following: ----------------Menu------------------------1.lk ----------------------------------------- © Department of Computer Science and Engineering 49 . Two functions . “%s”.txt. The format of each function is: fputs(string.i++) putc(*(message+i).function which returns the number of characters in a string is used. i < strlen(message). Exercise 9.com Kalani 033-4100101 kalani@gmail.3 such that it uses the fputs rather than the fputc function to write the message to the file . "w").1 – Modify Program-9.mrt.3 */ #include <stdio. However sometimes you may want to write one string at a time. message = "Introduction C Programming".mrt.lk After adding new contact information it should again display the menu. //open for writing if(fp != NULL) //if success { for (i =0 . //close the file } else printf("\nError while opening file"). return 0. fp = fopen("c:\\message.h> #include <string. When you press “2” it should display all the contact information stored in the directory. string) Exercise 9.txt". The fprintf function is identical to the printf function only difference being that it writes to a file rather than to the screen. int i. Display contact info. For example. Start Kwrite as follow. Then the output consists of object files output by the assembler. linking and debugging software (will cover in Lab5). Step 1: Type the C program given below using text editor such as Kwrite and then save it as test1. Requirements • The GNU C and C++ compiler .gnu. } //End main Step 2: Open a new terminal with the shell prompt by right-clicking on the Desktop area and selecting “new Terminal”. it normally does pre-processing. compilation.h> //Comments //Pre-processor directives int main() //Start main function { printf("Hello world!\n"). No evaluation will be done based on these lab sessions. Go to the Lab2_3 directory where you saved the program source file test1. When you invoke gcc. All the source codes and executables related to this lab session should be saved in a folder named Lab2_3 which should be created within your home directory.Annex A – Lab 2 & 3 Introduction to C Programming Objectives • • • • Compile/link C programs on Linux using gcc. The overall options allow you to stop this process at an intermediate stage. the source code must be first compiled and then linked with the necessary libraries to produce an executable program. //use printf function to display message return 0. Integrated Development Environments (IDEs) are software tools which provide facilities for. assembly and linking. Now you can enter any Linux shell command using the shell. Learn how to detect programming errors through program testing. 7 Remarks • • This assignment will be continued next week as well.c using cd command.org/ 50 © Department of Computer Science and Engineering .c in your home directory. editing. input output function is recommended. No other tools will be used. 7. Knowledge in area such as C language syntax. The process of compiling and linking depends on the environment in which it is carried out. In this section we shall learn how to compile and link a C program using the GNU C and C++ compiler. compiling. Main Menu à Accessories à More Accessories à Kwrite /*display Hello World */ #include <stdio.1 Compiling and Linking In compiler based programming languages like C. the -c option says not to run the linker. A basic understanding of compiling and linking in concept. Prerequisites • • • Students are expected to be familiar with a text editor on Linux (such as vi or vim). gcc. • A. Debug programs through program testing. the particular compiler or the linker involved and tools used if any. Correct/fix syntax errors and bugs taking clues from compiler error messages and warnings. Step 1: The program given below calculates the roots of the quadratic equation provided that ax 2 + bx + c = 0 b 2 − 4ax ≥ 0 .2f\n". scanf("%lf %lf %lf". Some of these errors result in source code that does not confirm to the syntax of the programming language and are caught by the compiler at compile time. enter the following command. 8 Why is it that we have to type . go ahead and modify the program given above to display its source code on standard output.out Hello world! $ Step 5: Now.e. &c). b. b and c //if complex roots //if roots are not complex //get the square root //end main Step 2: Now.out file is created. #include <stdio. surface only at runtime and cause programs to fail at performing their intended tasks. execute the file a. //Pre-processor directives Type the following program using a text editor and then save it as test2. to compile and link the program saved in Step 1. Such defects in programs are called bugs and the process of eliminating them is called debugging. $ gcc test1./a. double r1 = (-b -t) / (2*a). printf("Enter a.out as shown below. printf("%.4*c.c $ Step 4: Lastly. The text below also shows what you may expect next! Notice that we are not trying to link the output of the compiler yet. Use the ls command to see whether a. &b. double delta = b*b . else { double t = sqrt(delta). } //read a. enter the command gcc -c test2. why won’t typing a.2 Syntax Errors and Bugs Programmers been humans more often than not they end up writing incorrect source code. c.c.out to execute the file a.Step 3: Next.c.out alone work?) © Department of Computer Science and Engineering 51 . $ ls a.h> #include <math. double r2 = (-b + t) / (2*a). c: ). Some others however. r1.out test1. to compile the program. b.out in the working directory. $ . r2) } return 0.2f %. 8 A. delta.c $ By default.out in the working directory? (i. Hint: Study the use of escape sequences (escape codes) \n and \t with printf. to run the new program./a.h> int main() //Start main Function { double a. the output of the linker will be saved as a file named a. if (delta < 0) printf("complex roots!\n"). &a. c:9:20: warning: multi-line string literals are deprecated test2. In this case we are not using any IDE and the compiler used is GNU C compiler.c:8: stray ’\’ in program test2. test1. modify the line 10 to be like as shown below.c again and see whether it compiles without errors now. test2. If you corrected the error on line 8 properly. Warnings on the other hand indicate bad coding practices on part of the programmer such as unused variables. you should now get set of messages similar to the following: test2. delta = b*b . Errors.c:19:22: warning: multi-line string literals are deprecated test2.c:8: (Each undeclared identifier is reported only once test2.c:8:16: possible start of unterminated string literal After fixing line 8.c: In function ‘main’: test2. there will be two types of messages reported errors and warnings.c.c) try to figure out what is wrong and correct it on your own.c:8: parse error before string constant test2. the compiler reports the file name and the line number where it found the error.c:14:27: warning: multi-line string literals are deprecated test2.c:8: stray ’\’ in program test2. This is because of the errors in the source code.c: In function ‘main’: test2. Typically. you should not get any more error messages.c:8: for each function it appears in. test2.e.c:6: ‘delta’ previously declared here test2.c:8:16: warning: multi-line string literals are deprecated test2.c:6: ‘delta’ previously declared here Both the first and the second error messages are in fact caused by the same error.c:19:22: missing terminating " character test2.c:20: parse error before ’}’ token test2. You may also want to take in to consideration the following warning: test2.) test2. make an attempt to correct it on your own by comparing this particular printf statement with other printf statements that you know to be correct. The way errors are reported depends on the compiler and the IDE used. Notice that for each syntax error.c:10: redeclaration of ‘delta’ test2. recompile the program. Open the file test2.c test2. i.c:8: ‘lf’ undeclared (first use in this function) test2.c:8:16: possible start of unterminated string literal $ All of the above messages are reported by the C compiler when it attempted to compile the source file.4*c.$ gcc -c test2. Step 3: Lets.c in Kwrite editor and to jump straight to line 8 Comparing the printf statement on line 8 with what you found in the earlier program (i. go back to command mode and locate the cursor at the point of first error. Now. After correcting the error.c:20: parse error before ’}’ token Given the fact that this error concerns the printf statement on line 19. Notice that most of the error messages are concerned with line 8. To correct it.e. try to correct some of the errors reported above. go back and try compiling test2. 52 © Department of Computer Science and Engineering . If you correctly followed all the above instructions.c:10: redeclaration of ‘delta’ test2. are cases where the supplied source code does not confirm to the syntax of the language. However any other libraries must be specified to the linker if they are to be linked with your program. c: 1 -7 12 3. To obtain an executable program. syntax errors are probably the easiest to detect and eliminate. b. go ahead and correct the expression on your own./a. Step 6: When developing software. this file must be linked with any necessary libraries using an appropriate linker./a.out enter a. did the program work correctly? If you tried a test case where a is not equal to 1.out enter a. b and c.o: In function ‘main’: test2. © Department of Computer Science and Engineering 53 . line by line and program testing. Step 8: Next. try the following test case against your program and see how it behaves when a is equal to zero.00 $ . This is the object file that the compiler/assembler produced from your source code file.00 $ Try the program with several more sets of values for a.Step 4: Now./a. any C program needs to be linked with the standard C library and this is usually done automatically without you having to specify it explicitly. sqrt. it fails to use the proper formula in calculation.00 $ Step7: Had you paid attention to the expression on line 10. get back to the shell and look for a file with the same file name as your source code file but having the . you would have noticed a slight fault. Press Enter key after typing the three values for the coefficients a.4 * c. Code inspection. $ . $ gcc -lm test2./a. you may run the program by entering the following command. etc. you would notice that it fails.e.text+0x96): undefined reference to ‘sqrt’ collect2: ld returned 1 exit status $ Here the linker has reported errors.o extension instead. sin.o $ Step 5: If you do not get any errors from the linker. $ . where one or more people read someone else’s program.out Enter a. c: 1 -7 12 3. c: 2 -14 24 1. any mathematical functions (i.o with the standard C library enter the following command: $ gcc test2. $ .00 4. the math library needs to be linked with your program in addition to the standard C library. c: 0 -7 12 inf inf $ 2 − 4ac ) of the quadratic equation. b and c. Whenever. The expression concerned.00 6.o(. To link the object file test2. The cause of the problem is the sqrt function. cos. Referring to the previous step. b. try the test case(s) for which the program failed earlier and see whether it works correctly now. b. Now.) are used. running the program on sample input data (like we did above) are two techniques which are standard practice in Software Engineering. calculates the discriminator ( ∆ = b However. This is an example of a programming error or a bug. Normally. b. delta = b * b . Detecting bugs in programs is not an easy task. Once you compile and link the program.out enter a.o test2.00 4. Such sets of values used for testing a program are known as test cases. b and c if (a ==0. What are the output files produced by this command? c. b. printf("Enter a. &b. 6. double r2 = (-b + t) / (2 * a). r2). e. it is called a run-time error. else // if a not zero { delta = b * b . What would happen if a program uses library other than the standard C library and the particular library was not specified to the linker when linking the program? 7. c: ").h> int main() { double a. b. else { double t = sqrt(delta).4 * a * c. with the math library in addition to the standard C library.c. } } return 0. Since we check before we divide. even if the user enters a value of zero. //read a. 5. 1. #include <stdio. To compile (compile only) the file using gcc. } Discussion Try to find answers to following questions (no need of submission).When a program performs an illegal operation at run-time (when it is executing). To link the object file produced in (a) above.\n"). In the last example. Are all languages compiler based like C? Explain the difference between a compiler error and a warning? What is a bug with reference to software? Does program testing show the presence of bugs or their absence? Explain your answer. delta.0 a) // if a zero printf("Coefficient a should be non-zero. r1. 3. 12}. if(delta < 0) printf("complex roots!\n"). &c). Modify the command in (c) to change the name of the executable file to test from its default name. it does not lead to a division by zero. One possible solution is to check the value the user entered for coefficient a using an if statement.2f %. c. Given that you have the C source file test3. -7. &a. the program performed a division by zero for the data set {0. 4. b. double r1 = (-b .h> #include <math. What does GNU stand for? 54 © Department of Computer Science and Engineering . What is the name of the executable produced? d. printf("%. this leads to a division by zero on later in the program (lines 17 and 18).2f\n". To compile and link the file with the standard C library. 2. it is clearly evident that if the user enters a value of 0 for a. scanf("%lf %lf %lf". write down the commands for the following: a.t) / (2 * a). Looking at the source code. 2 – Given a date as a triplet of numbers ( m. If not zero marks will be given./a. the corresponding day of the week f (f = 0 for Sunday. } © Department of Computer Science and Engineering 55 . if (a > b ) if (b < c) { .out Temperature reading: 100F 37C Exercise B./a. f = 1 f r Monday. Exercises Exercise B. } else { .. No need of submission. The temperature reading consists of a decimal number followed by letter ”F” or ”f” if the temperature is in Fahrenheit scale or letter ”C ” or ”c” if it is in Celsius scale. Before you leave the lab make sure you show your instructor that you have saved your file in Lab4 folder.out Temperature reading: 100C 212F $ . with y indicating the year.Annex B – Lab 4 Conditional Structures (1) Remarks • • • This lab session will be evaluated and it will carry 4% of your final marks. month (m = 1 for January. All divisions indicated above are integer divisions.1 (c) let a = 2m + 6 (m + 1) / 10 (d) let b = y + y/4 – y/100 + y/400 (e) let f1 = d + a + b + 1 (t) let f = f1 mod 7 (g) stop. int a. m the y. m = 2 for February. write down 2 possible ways in which it can be implemented properly.. b. . etc. and d the day of the month. Discussion Given that the else clause in the following code fragment belongs to the outer statement. All the source codes and executables related to this lab session should be saved in a folder named Lab4 which should be created within your home directory. .1 – Write a program to input a temperature reading in either Celsius(c) or Fahrenheit(f) scale and convert it to the other scale. Note: c= 5( f − 32) 9 $ .). c. . You may use a similar format for the output of the program. d)..) can be found as o follows: (a) if m < 3 (b) let m = m + 12 and let y = y . etc. Write a program that will read a date and print the corresponding day of the week.. 1 Using KDevelop Step 1: To launch KDevelop use the menu sequence Start Menu à Programming à KDevelop. Prerequisites • • Students are expected to be familiar in developing C program on a Linux platform. Just read it and click the Next > button. When you use KDevlop for the first time you need to do bit of initial configuration through the KDevelop Setup window. First it displays the Welcome message. warnings and debug features provided by the IDE. and in some cases test and debug within an integrated. However if you prefer you may select any of the other two layouts given. compile. Correct/fix syntax errors and bugs taking clues from error messages. C. It may take sometime for you to understand each and every feature provided by the IDE but it will certainly enhance your productivity. Close the message box by clicking on the Close button. Some of these tools go beyond conventional program development and testing and even provide facility to manage various documents related to the project or source code and to keep track of different versions of the source code. Step 3: Then it asks you to select the most common syntax highlighting style. From this lab session onwards if you prefer you can use KDevelop for program development. Select the radio button labelled KDevelop 2. Finally click on the Finish button. Then press the Next > button. Try to identify some of those tools and the press the Next > button. All the source codes and executables related to this lab session should be saved in a folder named Lab5 which should be created within your home directory. edit. These tools provide lot of features that make programming a fun. Step 5: Then you will see list of tools that is installed in your computer. Then Tip of the Day message appears. Step 4: Then it asks you to select the layout of the user interface. Remarks • • This lab session will not be evaluated. Step 2: Then the KDevelop Setup window appears. Select the radio button with the label Childframe Mode (this is the commonly used layout).0 style and click the Next > button. interactive environment. Then press Next > button three times. 56 © Department of Computer Science and Engineering . Integrated Development Environment (IDE) is a GUI based application or set o tools that allows a f programmer to write. Requirements The KDevelop IDE. KDevelop is one of the heavily used IDE for developing C/C++ programs in the Linux platform. If you do not wish to receive any more such tips uncheck the checkbox labelled Show tips on startup.Annex C – Lab 5 Conditional Structures (2) Objectives • • Develop C programs using an Integrated Development Environment (IDE). Then click on Next button. Step 3: Then it requests you to enter Generate Settings. Use Build à Compile File menu or click on the Compile File icon ( toolbar. © Department of Computer Science and Engineering 57 . toolbar. If you need any clarification about any icon or button in KDevelop you can access the "The User Manual to KDevelop" by pressing F1 key or using the menu Help à The User Manual to KDevelop. Finally click on the Create button. return 0. contents in the project directory. If you have not already created the Lab5 folder you need to create it. header files. help system. When it is finished click the Exit button. Step 4: Then KDevelop will create a list of files that are required to develop and run your program. Your changed code should be similar to the following: #ifdef HAVE_CONFIG_H #include <config. If you are developing GUI based applications you can select KDE or GNOME. For the moment forget about it. etc. This process may take few minutes (depending on the type of the application that you are developing). So if you want you can change some of the code. from the tree select the branch labelled Terminal and then select C. ) on the While compilation you may get waning message about a make file. Then do the following changes to the code (these changes are done just to simplify the code). Step 5: KDevelop will automatically write a part of the program. Step 6: Now go back to your source file named main.h> #include <stdlib. } Step 7: Now its time to run your first C program using KDevelop. Using the Application Wizard you can select the type of the application you are developing. functions in your program. world!\n"). class tree. You may also use the keyboard shortcut Shift+F8 as well.h> int main() { printf("Hello. Type FirstIDE in the Project name: textbox.c. Set the Project directory: to /home/firstyear/Lab5/firstide.2 Your First Program with KDevlop Step 1: In order to work with KDevlop first you need to create a new project. The code generated by KDevelop may not be in the same format that we are used to. Step 2: Then Application Wizard window appears. Before you do any changes to the code get familiar with the KDevelop user interface.h> #endif #include <stdio.C. Identify various components in your project such as source files. First you need to compile your program. From the menu select Project à New. Since we are developing shell based C programs. In the Author: textbox type your name then type your e-Mail address in the Email: textbox. return 0. If you correct both errors now your program should compile without any error or warning and you should see the message "success". -I. Hello. world! Press Enter to continue! Step 9: Press the Enter key to terminate your program./'`main. scanf("%d". Step 6: Then execute your program by selecting Build à Execute menu or by pressing F9 key. fact.o] Error 1 *** failed *** -f It informs you about 2 errors in line 31 and 36 (line number may be different in your program).Step 8: Then to execute your program select the Build à Execute menu or click on the Run icon ( ) on the toolbar. Step 3: Correct the error in the program./admin/depcomp \ gcc -DHAVE_CONFIG_H -I. fact). Then your cursor will move to the appropriate line within the program.c main.Po' tmpdepfile='. printf("Enter number to find factorial: ").deps/main.3 Locating Errors in a Program Let us write a program to calculate the factorial of a given number. } Step 2: Compile the program by clicking the Compile File icon on the toolbar. C.deps/main. Correct the error. Executing about program with 5 as the input will display: Enter number to find factorial: 5 Factorial of 5 is: 0 Press Enter to continue! 58 © Department of Computer Science and Engineering . fact=0.o' libtool=no \ depfile='. Step 5: Then compile your program again. If you program get successfully executed you should see the following message appearing in the shell. Step 1: Create a new C Terminal project named FactIDE.c' || echo '. To go to the line having an error double click on the message "main.c' object='main. Then you may see a list of message (in the messages tab) appearing which may look like the follwoing: source='main. num.c:31: warning: format argument is not a pointer (arg 2) main. Then type the follwoing program as it is.c:36: parse error before '}' token gmake: *** [main.. -I.TPo' \ depmode=gcc3 /bin/sh . i++) { fact *= i } printf("Factorial of %d is: %d".c:31: warning: format argument is not a pointer (arg 2)". i <=num. int main() { int num.num). -O2 -O0 -g3 -Wall -c `test 'main.c: In function `main': main. for(i=1 . Step 4: Then go to the next error message and double click on it. You may also use the function key F9. Then the cursor automatically moves to the line..i. ) on the If you do not see the shell appearing select Debug à Stop from the menu or click on the Stop icon.. Exercise C. menu open the KDevlop Setup window locate Debugger and check the checkbox labelled Enable sepa rate terminal for application i/o. C.4 Debugging a Program Step 1: Go back to the source code and place a Breakpoint on the line with the expression fact *= i. Similarly do it for variables i and fact. This will indicate the current line that is in execution. Tuesday. Step 4: Highlight the token num and then right click. To clear a Breakpoint select Clear All breakpoints or Disable breakpoint from the pop-up menu (to get the pop-up menu you need to right click it. Then go back to the IDE and locate the small Yellow triangle. If not. Step 2: To debug you program select Debug à Start menu or click the Debug icon ( toolbar. Step 5: Then from the Debug menu select Run. Do you remember that the starting value of fact is 0.. Then click on the OK button. This will allow you to check the value of variable num while in debugging mode. On the left hand side of the window you should be able to see the current values of variables num. These errors can be tracked by debugging a program. which is supposed to change the value of variable fact. Then the error should be with the value of fact. So regardless of the value of i the multiplication is always 0.. Repeat Debug à Run menu until you complete all the 5 loops. Now enter 5 and see whether you are getting the correct answer. Monday. Then use the Options à KDevlop Setup. is it 0? Although your program gets compiled successfully now you have a run-time error. debug your program again and see that fact is always 0. Step 3: When the program request you to enter a number to find the factorial type 5 and press Enter key. using the value f derived from the given algorithm. However you did observe that variable i is getting changed.If you get something similar as above your program is ok.2. But what about the factorial of 5. Then from the pop-up menu select Watch: num. Now try to debug your program again. Y ou will still see only variable i is getting changed where as variable fact should also get changed. So this is the error. Notice that the value of variable i get changed but not other variables. fact and i.1 – Consider Exercise B. Modify it so that you u the switch statement to print the se days as Sunday. Then select Debug à Stop menu or click the Stop icon ( program. Step 6: Again select the Run from Debug menu. To place a Breakpoint move your mouse pointer near the shaded pane in front of the Editor window (area that your write you code) and click on it. . Try your program with several other inputs. © Department of Computer Science and Engineering 59 . Change initial value of variable fact to be 1 and Run your program again. ) to stop debugging your Now you should be able to understand that there is some error in the statement fact *= i. Then you should see a small Blue spot appearing. You can either use a simple text editor or IDE such as KDevelop. Exercises Exercise D. ****** ***** **** *** ** * ** *** **** ***** ****** 60 © Department of Computer Science and Engineering . All the source codes and executables related to this lab session should be saved in a folder named Lab6 which should be created within your home directory.1 – Write a program to input a series of positive integers and determine whether they are prime. If not zero marks will be given. 28 = 1 + 2 + 4 + 7 + 14 $ . A perfect number is a number whose factors other than itself add up to itself./a.out 1 2 Prime 3 Prime 4 5 Prime 6 -1 $ Exercise D. The program should terminate if a negative integer is given as the input. A prime number is a number that is divisible by only one and itself.3 – Write a program to display the following symbol pattern. Execution of your program should produce something similar to the following: $ . Example: 6 = 1 + 2 + 3. 2 – Write a program to find out whether a given number is a perfect number. The program should terminate if a negative integer is given as the input./a. Before you leave the lab make sure you show your instructor that you have saved your file in Lab6 folder.Annex D – Lab 6 Control Structures (1) Remarks • • • • This lab session will be evaluated and it will carry 4% of your final marks.out 6 Perfect 7 28 Perfect 11 -1 $ Exercise D. You must use loops. However one is not considered a prime number. 8 9.Annex E – Lab 7 Control Structures and Arrays Remarks • • • This lab session will be evaluated and it will carry 4% of your final marks. on four rows: 80 90 99 67 Total marks of four students: 190 225 178 191 © Department of Computer Science and Engineering 61 . The numbers can be non-integers. If not zero marks will be given.2 Exercise E. An example would be as follows: Enter 50 60 60 75 30 49 66 58 the marks of four students.2 Maximum = 54 Exercise E. Write a program to read the marks from the keyboard and calculate and display the total marks of each student.6 54 3. An example would be as follows: Enter 10 numbers: 5 7. Use a single-dimensional array to store the numbers entered. An example would be as follows: Enter 10 integers: 5 78 96 54 34 12 3 7 88 5 Total = 382 Average = 38. Before you leave the lab make sure you show your instructor that you have saved your file in Lab7 folder.2 – Write a program to find and display the minimum and the maximum among 10 numbers entered from the keyboard. All the source codes and executables related to this lab session should be saved in a folder named Lab7 which should be created within your home directory.1 – Write a program to calculate and display the total and the average of 10 integer numbers input from the keyboard. Exercises Exercise E. Use a 2D (two-dimensional) array to store the marks.2 3 7 8.4 1.3 – Suppose there are 4 students each having marks of 3 subjects.8 5 Minimum = 1. Break down the program in to three main functions to: • • • Read in the elements of matrices A and B Compute the product of the two matrices Display the resultant matrix AB 62 © Department of Computer Science and Engineering . Before you leave the lab make sure you show your instructor that you have saved your file in Lab0 folder. Assume that the elements of the matrices are integers.Annex F – Lab 9 Functions Remarks • • • This lab session will be evaluated and it will carry 4% of your final marks. and compute and display their product AB (of dimensions 3×3). Exercises Exercise F. $ . All the source codes and executables related to this lab session should be saved in a folder named Lab9 which should be created within your home directory. If not zero marks will be given./a. Use functions to while implementing this program.out Matrix A: 1 2 4 5 3 3 4 4 4 4 5 5 Matrix B: 1 3 5 7 7 7 3 4 5 3 4 5 Matrix AB: 42 53 64 48 62 76 62 80 98 $ Hint: Define global variables of two-dimensional arrays to store the values of the matrices.1 – Write a program to read in two matrices A and B of dimensions 3 ×4 and 4 ×3 respectively. a semicolon and a colon. in S. Exercises Exercise G. a question mark. Use file-handling mechanism of C language to access the files.e. Further. N. the number of characters in S (i./a. length of S).out Number of words: 4 © Department of Computer Science and Engineering 63 . you may assume that there may be only one word delimiter at most between any two words in S. The input will be given in the text file problem. All the source codes and executables related to this lab session should be saved in a folder named Lab10 which should be created within your home directory.in and the output should be written to the text file problem.out.Annex G – Lab 10 File Handling Remarks • • • This lab session will be evaluated and it will carry 4% of your final marks. an exclamation mark. a period.1 – Given a string S of length N from a text file. count the total number of words T. will be at least 1 and at most 100. If not zero marks will be given. a comma. Before you leave the lab make sure you show your instructor that you have saved your file in Lab10 folder. $ . An example would be as follows: problem. Assume words to be delimited by a space.in This is a test. For a more complete list reader should refer to the manual (or help) of the version of C compiler that is being used.h Prototype int isalnum(int character) int isalpha(int character) int isascii(int character) int isdigit(int character) int islower(int character) int ispunct(int character) int isspace(int character) int isupper(int character) int isdigit(int character) int toascii(int character) int tolower(int character) int toupper(int character) description Determines if the character is alphanumeric.h Prototype int abs(int x) double acos(double radians) description Return absolute value of x. else 0.h ctype. else 0. Determines if the character is a punctuation character. Return negative value if str1 < str2.2 String Manipulation Functions Header file string. Determines if the character is a h exadecimal digit. else 0. Convert a character to uppercase. If true return nonzero value. Determines if the character is a whitespace.h ctype. else 0. If true return nonzero value.h ctype.Library Functions The C language is accomplished by a number of library functions that performs various tasks. If true return nonzero value. else 0. else 0.h ctype. Copy str2 to str1. If true return nonzero value. return positive value is str1 > str2 and if both are identical return 0. Function abs acos 64 © Department of Computer Science and Engineering . Compare 2 strings without considering the case. If true return nonzero value.char *str2) strcpy strlen string. Determines if the character is an ASCII character. If true return nonzero value.h ctype. Convert a character to lowercase. char *str2) description Compare 2 strings.1 Character Manipulation Functions Header file ctype.h int strcmpi(char *str1. If true return nonzero value.h ctype. Function isalnum isalpha isascii isdigit islower ispunct isspace isupper isxdigit toascii tolower toupper H. char *str2) int strlen(char *str) H.h math.h ctype. return positive value is str1 > str2 and if both are identical return 0. Return negative value if str1 < str2.3 Mathematical Functions Header file stdlib. else 0. If true return nonzero value. If true return nonzero value. Function strcmp strcmpi string. Count the number of characters in a string. Determines if the character is a uppercase.h char *strcpy(char *str1.h Prototype int strcmp(char *str1. Following is a list of commonly used functions. Determines if the character is a lowercase. Convert value of argument to ASCII.h ctype.h ctype. H. Determines if the character is a decimal digit. else 0.h string. Return the arc cosine. else 0.Annex H .h ctype.h ctype. Determines if the character is alphabetic. .h math.h stdio. double y) double sin(double radians) double sqrt(double x) double tan(double radians) Return the arc sine. Return the arc tangent.h math. Function fclose feof fgetc fgets fopen fprintf fputc fputs getc gets puts H.h math. Read single string from file Open file. Is a key press. Return the absolute value of x. Raise e to the power x.h stdio. Enter string from standard input.5 Miscellaneous Functions Header file stdlib.h stdio.h math. Return the sine.asin atan ceil cos exp fabs log log10 pow sin sqrt tan math. Function exit kbhit © Department of Computer Science and Engineering 65 .h math. char *accessmode) int fprintf(FILE *fp. Send string to standard output. arg1.h stdio.h stdio. Determine whether end of file is reached. Read single character from file.h stdio.h math.h math. int sizeofbuffer.h Prototype void exit(int number) int kbhit(void) description Close all files and buffers and terminate the program.h math. Return the tangent. FILE *fp) int getc(FILE *fp) char *gets(char *string) int *gets(char *string) Description Close file pointed by fp. Send character to file. H. If so return none zero else zero is returned. Enter single character from file.h double asin(double radians) double atan(double radians) double atan(double value) double cos(double radians) double exp(double x) double fabs(double x) double log(double x) double log10(double x) double pow(double x. Return xy. FILE *fp) FILE *fopen(char *filename. Return a value rounded up to the next higher integer Return the cosine. char *format.4 I/O Functions Header file stdio..) to file of the given data format.h stdio. arg2.h Prototype int fclose(FILE *fp) int feof(FILE *fp) int fgetc(FILE *fp) char *fgets(char *buffer.h stdio.h math. arg2. Return the natural logarithm of x. If key is pressed return nonzero and if not return 0. Return square root of x.h math. FILE *fp) Int fputs(char *string. Send string to file.h stdio. Return the logarithm of x (base 10).h stdio. …) Int fputc(char c.h math. Send data (arg1.h conio. Second Edition by E.Acknowledgements Some sections in this handout are extracted from: • • Learn C in Three Days by Sam A. Abolrous. BPB Publications Programming in ANSI C. Tata McGraw-Hill 66 © Department of Computer Science and Engineering . Balagurusamy.
https://www.scribd.com/doc/61204427/Handbook-Fundamentals-of-C-Programming
CC-MAIN-2017-26
refinedweb
25,816
68.36
SWTBot/FAQ - 14 Can I test a custom swt control with swtbot? - 15 Can I run SWTBot tests using Hudson/CruiseControl/Whatever? - 16 Can I get more details on a particular widget? Can SWTBot be used to test RCP Applications? Yes SWTBot can be used to test any kind of SWT apps -- SWT, Eclipse plugins and RCP applications. What platforms is SWTBot tested on? SWTBot is continuously tested on a grid of cruise servers that run windows XP/2003, linux/gtk 32 bit and 64 bit and macosx(carbon).. How do I execute parts of tests that need UI thread?); } Why do I have to run tests as SWTBot tests, instead of PDE-JUnit tests? PDE-Junit tests run on the UI thread. SWTBot needs that tests run on a non-UI thread, hence a new run configuration. See Why do tests run on a non-UI thread? for more info. Can I slow down the execution speed of SWTBot tests? Yes you can! To slow down the speed of execution of SWTBot, you need to set the system property "org.eclipse.swtbot.playback.delay". This delay is in milliseconds. You can also set this property in code as follows: // slow down tests SWTBotPreferences.PLAYBACK_DELAY = 10; // set to the default speed SWTBotPreferences.PLAYBACK_DELAY = 0; Can I change the timeout for execution of SWTBot tests? Yes you can! To change the timeout, you need to set the system property "org.eclipse.swtbot.search.timeout". The timeout is specified in milliseconds. You can also set this property in code as follows: // increase timeout to 10 seconds SWTBotPreferences.TIMEOUT = 10000; // set to the default timeout of 5 seconds SWTBotPreferences.TIMEOUT = 5000; Can I change the poll delay for evaluating conditions in SWTBot tests? Yes you can! To change the poll delay, you need to set the system property "org.eclipse.swtbot.playback.poll.delay". The poll delay is specified in milliseconds. You can also set this property in code as follows: // increase timeout to 1 second SWTBotPreferences.DEFAULT_POLL_DELAY = 1000; // set to the default timeout of 500ms. SWTBotPreferences.DEFAULT_POLL_DELAY = 500;. Does SWTBot support my keyboard layout? Yes it does. See SWTBot/Keyboard_Layouts for how to configure SWTBot for your own keyboard layout.. How do I test a login dialog using SWTBot You can't! The login dialog pops up before SWTBot gets an opportunity to initialize itself. A good workaround is to make the license dialog a bit intelligent so you can bypass it by setting the username and password as a system property. A login dialog like this is a good choice: public class LoginDialog { ... public void open() { String username = System.getProperty("com.yourapp.username"); String password = System.getProperty("com.yourapp.password"); if (isValid(username, password){ // the password is good, continue doing whatever ? } else { // revalidate password ? } } ... } You can then start SWTBot tests with the following JVM arguments. You may set these JVM args in the target platform(preferred) or the launch configuration for the SWTBot test. -Dcom.yourapp.username=joe -Dcom.yourapp.password=secret SWTBot headless feature This is the prefered method when your product is p2-ready. Use the Equinox p2 director application to install the headless feature, and eventually some other SWTBot module you need (GEF, Forms...) to your product. From your product main directory $ java -jar plugins/org.eclipse.equinox.launcher_*.jar \ -application org.eclipse.equinox.p2.director \ -repository \ -installIU org.eclipse.swtbot.eclipse,get.feature.group,org.eclipse.swtbot.eclipse.test.junit4.feature.group \ -consoleLog.
http://wiki.eclipse.org/index.php?title=SWTBot/FAQ&oldid=230376
CC-MAIN-2015-22
refinedweb
576
52.76
- 18 Nov, 2020 1 commit - 21 Sep, 2020 1 commit - 16 Sep, 2020 1 commit - 15 Sep, 2020 1 commit gcc-9 gcc-10, clang-10 packages with C++20 shared/no shared are now generated and uploaded. - 06 Aug, 2020 1 commit Calls to ``::ranges::views::filter(rng, func)`` were ambiguous with the overload ``::ranges::views::filter(Predicate, Projector)`` Calls are replaced by the non-conflicting declaration ``::ranges::cpp20::views::filter``. - 10 Jul, 2020 2 commits - 09 Jul, 2020 2 commits - - 18 Jun, 2020 7 commits - - 17 Jun, 2020 1 commit Do not rely on cmake to build. - 16 Jun, 2020 6 commits Rename mln_foreach_new -> mln_foreach. Rename new_pixel/new_pixel_type -> pixel/pixel_type. - 07 May, 2020 5 commits See merge request !99 * Add clang 10, gcc 10 build in gitlab-ci. * Make only debug build automatic * Readme support section updated * Tag final classes as final. * Fix concept-based specialization * Fix warnings * Rename deprecated GTest TEST_CASE in TEST_SUITE. * GTest is set as a conan build depedancy * Fix namespace ::ranges::view -> ::ranges::views. * Fix bad concept checking in extensions. - 21 Apr, 2020 1 commit - 20 Apr, 2020 3 commits - - 25 Nov, 2019 2 commits - - 08 Feb, 2019 2 commits - 14 Nov, 2018 2 commits Deactivate benchmark option on this branch. They were not build anyway. - 27 Aug, 2018 2 commits - Michaël Roynard authored Set C++17 as new standard See merge request !15
https://gitlab.lrde.epita.fr/olena/pylene/-/commits/master
CC-MAIN-2021-04
refinedweb
230
64.81
>> I scroll a web page using selenium webdriver in python? The Complete Selenium WebDriver with Java Course 192 Lectures 20 hours Mastering XPath and CSS Selector for Selenium 47 Lectures 3 hours Sometimes we need to perform action on an element which is not present in the viewable area of the page. We need to scroll down to the page in order to reach that element. Selenium cannot perform scrolling action directly. This can be achieved with the help of Javascript Executor and Actions class in Selenium. DOM can work on all elements on the web page with the help of Javascript. Selenium can execute commands in Javascript with the help of the execute_script() method. For the Javascript solution, we have to pass true value to the method scrollIntoView() to identify the object below our current location on the page. We can execute mouse movement with the help of the Actions class in Selenium. Example Code Implementation with Javascript Executor. import time from selenium import webdriver driver = webdriver.Chrome (executable_path="C:\chromedriver.exe") driver.get("") # identify element l= driver.find_element_by_xpath("//*[text()='About Us']") # Javascript Executor driver.execute_script("arguments[0].scrollIntoView(true);", l) time.sleep(0.4) driver.close While working with Actions class to scroll to view, we have to use the moveToElement() method. This method shall perform mouse movement till the middle of the element. Example Code Implementation with Actions. from selenium.webdriver import ActionChains from selenium import webdriver driver = webdriver.Chrome (executable_path="C:\chromedriver.exe") driver.get("") # identify element I=driver.find_element_by_xpath("//*[text()='About Us']") # action object creation to scroll a = ActionChains(driver) a.move_to_element(l).perform() Output - Related Questions & Answers - How to scroll a Web Page using coordinates of a WebElement in Selenium WebDriver? - How to Scroll Down or UP a Page in Selenium Webdriver? - How to scroll down the page till page end in the Selenium WebDriver? - How to scroll the Page up or down in Selenium WebDriver using java? - How can I clear text of a textbox using Python Selenium WebDriver? - Save a Web Page with Python Selenium - How to scroll down using Selenium WebDriver with Java? - How to scroll a specific DIV using Selenium WebDriver with Java? - How to scroll to element with Selenium WebDriver using C#? - How to scroll up/down a page using Actions class in Selenium? - How can I handle multiple keyboard keys using Selenium Webdriver? - How can I close a specific window using Selenium WebDriver with Java? - How can I verify Error Message on a webpage using Selenium Webdriver? - How can I select date from a datepicker div using Selenium Webdriver? - How can I capture network traffic of a specific page using Selenium?
https://www.tutorialspoint.com/how-can-i-scroll-a-web-page-using-selenium-webdriver-in-python
CC-MAIN-2022-40
refinedweb
443
50.73
English | Arabic Bengali Brazilian Portuguese German Greek Italian Korean Persian Polish Russian Spanish Thai Turkish Vietnamese | Add Translation Learn how to design large-scale systems. Prep for the system design interview. scale. This is a continually updated, open source project. Contributions are welcome! In addition to coding interviews, system design is a required component of the technical interview process at many tech companies. Practice common system design interview questions and compare your results with sample solutions: discussions, code, and diagrams. Additional topics for interview prep: The provided Anki flashcard decks use spaced repetition to help you retain key system design concepts. Great for use while on-the-go. Looking for resources to help you prep for the Coding Interview? Check out the sister repo Interactive Coding Challenges, which contains an additional Anki deck: Learn from the community. Feel free to submit pull requests to help: Content that needs some polishing is placed under development. Review the Contributing Guidelines. Summaries of various system design topics, including pros and cons. Everything is a trade-off. Each section contains links to more in-depth resources. Suggested topics to review based on your interview timeline (short, medium, long). Q: For interviews, do I need to know everything here? A: No, you don't need to know everything here to prepare for the interview. What you are asked in an interview depends on variables such as: More experienced candidates are generally expected to know more about system design. Architects or team leads might be expected to know more than individual contributors. Top tech companies are likely to have one or more design interview rounds. Start broad and go deeper in a few areas. It helps to know a little about various key system design topics. Adjust the following guide based on your timeline, experience, what positions you are interviewing for, and which companies you are interviewing with.. Gather requirements and scope the problem. Ask questions to clarify use cases and constraints. Discuss assumptions. Outline a high level design with all important components. Dive into details for each core component. For example, if you were asked to design a url shortening service, discuss: Identify and address bottlenecks, given the constraints. For example, do you need the following to address scalability issues? Discuss potential solutions and trade-offs. Everything is a trade-off. Address bottlenecks using principles of scalable system design. You might be asked to do some estimates by hand. Refer to the Appendix for the following resources: Check out the following links to get a better idea of what to expect: Common system design interview questions with sample discussions, code, and diagrams. Solutions linked to content in the solutions/folder. View exercise and solution View exercise and solution View exercise and solution View exercise and solution View exercise and solution View exercise and solution View exercise and solution View exercise and solution Common object-oriented design interview questions with sample discussions, code, and diagrams. Solutions linked to content in the solutions/folder. Note: This section is under development New to system design? First, you'll need a basic understanding of common principles, learning about what they are, how they are used, and their pros and cons. Scalability Lecture at Harvard Next, we'll look at high-level trade-offs: Keep in mind that everything is a trade-off. Then we'll dive into more specific topics such as DNS, CDNs, and load balancers.: Latency is the time to perform some action or to produce some result. Throughput is the number of such actions or results per unit of time. Generally, you should aim for maximal throughput with acceptable latency. Source: CAP theorem revisited In a distributed computer system, you can only support two of the following guarantees: Networks aren't reliable, so you'll need to support partition tolerance. You'll need to make a software tradeoff between consistency and availability. Waiting for a response from the partitioned node might result in a timeout error. CP is a good choice if your business needs require atomic reads and writes.. With multiple copies of the same data, we are faced with options on how to synchronize them so clients have a consistent view of the data. Recall the definition of consistency from the CAP theorem - Every read receives the most recent write or an error.. After a write, reads will eventually see it (typically within milliseconds). Data is replicated asynchronously. This approach is seen in systems such as DNS and email. Eventual consistency works well in highly available systems. After a write, reads will see it. Data is replicated synchronously. This approach is seen in file systems and RDBMSes. Strong consistency works well in systems that need transactions. There are two main patterns to support high availability: fail-over and replication.. This topic is further discussed in the Database section: Source: DNS security presentation). CNAME(example.com to) or to an Arecord. Services such as CloudFlare and Route 53 provide managed DNS services. Some DNS services can route traffic through various methods::. Pull CDNs grab new content from your server when the first user requests the content. You leave the content on your server and rewrite URLs to point to the CDN. This results in a slower request until the content is cached on the CDN.. Source: Scalable system design patterns Load balancers distribute incoming client requests to computing resources such as application servers and databases. In each case, the load balancer returns the response from the computing resource to the appropriate client. Load balancers are effective at: Load balancers can be implemented with hardware (expensive) or with software such as HAProxy. Additional benefits include: To protect against failures, it's common to set up multiple load balancers, either in active-passive or active-active mode. Load balancers can route traffic based on various metrics, including:. A reverse proxy is a web server that centralizes internal services and provides unified interfaces to the public. Requests from clients are forwarded to a server that can fulfill it before the reverse proxy returns the server's response to the client. Additional benefits include: Source: Intro to architecting systems for scale... Source: Scaling up to your first 10 million users A relational database like SQL is a collection of data items organized in tables. ACID is a set of properties of relational database transactions. There are many techniques to scale a relational database: master-slave replication, master-master replication, federation, sharding, denormalization, and SQL tuning.. Source: Scalability, availability, stability, patterns Both masters serve reads and writes and coordinate with each other on writes. If either master goes down, the system can continue to operate with both reads and writes. Source: Scalability, availability, stability, patterns Source: Scaling up to your first 10 million users. Source: Scalability, availability, stability, patterns. SQL tuning is a broad topic and many books have been written as reference. It's important to benchmark and profile to simulate and uncover bottlenecks. Benchmarking and profiling might point you to the following optimizations. CHARinstead of VARCHARfor fixed-length fields. CHAReffectively allows for fast, random access, whereas with VARCHAR, you must find the end of a string before moving onto the next one. TEXTfor large blocks of text such as blog posts. TEXTalso allows for boolean searches. Using a TEXTfield results in storing a pointer on disk that is used to locate the text block. INTfor larger numbers up to 232 or 4 billion. DECIMALfor currency to avoid floating point representation errors. BLOBS, store the location of where to get the object instead. VARCHAR(255)is the largest number of characters that can be counted in an 8 bit number, often maximizing the use of a byte in some RDBMS. NOT NULLconstraint where applicable to improve search performance. GROUP BY, ORDER BY, JOIN) could be faster with indices. NoSQL is a collection of data items represented in a key-value store, document store, wide column store, or a graph database. Data is denormalized, and joins are generally done in the application code. Most NoSQL stores lack true ACID transactions and favor eventual consistency. BASE is often used to describe the properties of NoSQL databases. In comparison with the CAP Theorem, BASE chooses availability over consistency. In addition to choosing between SQL or NoSQL, it is helpful to understand which type of NoSQL database best fits your use case(s). We'll review key-value stores, document stores, wide column stores, and graph databases in the next section. Abstraction: hash table A key-value store generally allows for O(1) reads and writes and is often backed by memory or SSD. Data stores can maintain keys in lexicographic order, allowing efficient retrieval of key ranges. Key-value stores can allow for storing of the basis for more complex systems such as a document store, and in some cases, a graph database. Abstraction: key-value store with documents stored as values A document store is centered. Source: SQL & NoSQL, a brief history Abstraction: nested map ColumnFamily<RowKey, Columns<ColKey, Value, Timestamp>>. Abstraction: graph: Transitioning from RDBMS to NoSQL Reasons for SQL: Reasons for NoSQL: Sample data well-suited for NoSQL: Source: Scalable system design patterns Caching improves page load times and can reduce the load on your servers and databases. In this model, the dispatcher will first lookup if the request has been made before and try to find the previous result to return, in order to save the actual execution. Databases often benefit from a uniform distribution of reads and writes across its partitions. Popular items can skew the distribution, causing bottlenecks. Putting a cache in front of a database can help absorb uneven loads and spikes in traffic. Caches can be located on the client side (OS or browser), server side, or in a distinct cache layer. CDNs are considered a type of cache. Reverse proxies and caches such as Varnish can serve static and dynamic content directly. Web servers can also cache requests, returning responses without having to contact application servers. Your database usually includes some level of caching in a default configuration, optimized for a generic use case. Tweaking these settings for specific usage patterns can further boost performance.: There are multiple levels you can cache that fall into two general categories: database queries and objects: Generally, you should try to avoid file-based caching, as it makes cloning and auto-scaling more difficult. Whenever you query the database, hash the query as a key and store the result to the cache. This approach suffers from expiration issues: See your data as an object, similar to what you do with your application code. Have your application assemble the dataset from the database into a class instance or a data structure(s): Suggestions of what to cache: Since you can only store a limited amount of data in cache, you'll need to determine which cache update strategy works best for your use case. Source: From cache to in-memory data grid The application is responsible for reading and writing from storage. The cache does not interact with storage directly. The application does the following: def get_user(self, user_id): user = cache.get("user.{0}", user_id) if user is None: user = db.query("SELECT * FROM users WHERE user_id = {0}", user_id) if user is not None: key = "user.{0}".format(user_id) cache.set(key, json.dumps(user)) return user Memcached is generally used in this manner. Subsequent reads of data added to cache are fast. Cache-aside is also referred to as lazy loading. Only requested data is cached, which avoids filling up the cache with data that isn't requested. Source: Scalability, availability, stability, patterns The application uses the cache as the main data store, reading and writing data to it, while the cache is responsible for reading and writing to the database: Application code: set_user(12345, {"foo":"bar"}) Cache code: def set_user(user_id, values): user = db.query("UPDATE Users
https://recordnotfound.com/system-design-primer-donnemartin-148848
CC-MAIN-2020-40
refinedweb
1,981
56.86
Before we begin writing our tests, we'll need to add Babel to our application. Babel is a tool that is most commonly used for transforming newer versions of JavaScript into older versions of JavaScript that are compatible with browsers such as Chrome, Safari and Internet Explorer. Babel is essential because there are many newer features in JavaScript that older browsers don't understand. However, we still want to use these features because they will make our code cleaner, more efficient and easier to read. In fact, we'll be covering some of these newer JavaScript features over the next few weeks. Fortunately, we don't have to worry about Chrome understanding many of these newer features - that's because Chrome is an evergreen browser that's already compatible with the features we will be using. However, if we were working on an enterprise application where it's likely some of our customers are using outdated browsers, we'd need to use tools like Babel to make our sites compatible with those browsers. However, that's not why we need Babel for our projects. After all, we know Chrome is good to go with any new features of JavaScript we'll be using. Our issue is that Jest uses NodeJS's require() statements instead of ES6's import and export syntax. However, we are using import and export in our applications. Babel can solve this problem for us by transforming ES6 module syntax to the require() syntax that Jest needs. So we aren't transforming our code for other users - we are transforming our newer JavaScript syntax into syntax that our tests will be able to read. Let's start by adding Babel to our application: npm install @babel/[email protected] --save-dev Next, we'll need to install a specific Babel plugin that will transform ES6 module syntax: npm install @babel/[email protected] --save-dev Finally, we need to set up our Babel configuration. Just as we use an .eslintrc file to configure ESLint, we'll use a .babelrc file to configure Babel. The file should go in the root directory of the project. { "env": { "test": { "plugins": ["@babel/plugin-transform-modules-commonjs"] } } } The configuration above states that our test environment should use the plugin we just installed to transform ES6 modules into CommonJS modules, which is what Node uses. This is the only Babel configuration we'll do in this course. Even though we are doing very little with it, it's good to have some exposure since this tool is very common in real world applications. If you are interested in learning more about using Babel with webpack, check out webpack's Babel documentation. Now we're ready to start writing tests! Lesson 27 of 48 Last updated more than 3 months ago.
https://www.learnhowtoprogram.com/intermediate-javascript/test-driven-development-and-environments-with-javascript/setting-up-babel
CC-MAIN-2021-17
refinedweb
465
61.46
The.Enterprise metadata management (EMM) is a set of features introduced in Microsoft SharePoint Server 2010 that enable taxonomists, librarians, and administrators to create and manage terms and sets of terms across the enterprise. A new Managed Metadata Service provides consistent metadata and shared taxonomies across multiple SharePoint Server sites in the enterprise. The Managed Metadata Service is a single term store. Term stores are databases that contain one or more taxonomies. Multiple managed metadata services (term stores) can be associated with a single Web application. Taxonomies are hierarchical groupings of metadata, hierarchy, and other elements that provide meaning (such as descriptions, synonyms, and translations). The Term Management tool, which provides:Service management: Access all available term store databases from one location.Security groups: Control how users can create, edit, or delete by using SharePoint Server users and groups. Term sets: Containers that you can use to organize, group, and share hierarchies of terms. The ability to apply metadata in the Web browser, through Microsoft Office 2010 client applications and through third-party custom applications, by using the Taxonomy object model creating the service application requires the administrator to specify the database to be used as the term store. When you create new managed terms, or when users add managed keywords, these terms are stored in the database. Like other service applications, the managed metadata service can be published to provide access to other Web applications. When a service application is published, a URL to the service is created. The administrator of another Web application can create a connection to your service by using this URL.In addition to sharing metadata, you can also use the managed metadata service to share content types. By creating a new managed metadata service and specifying a site collection as the content type hub, you can share all content types in the site collection's content type gallery. You can create multiple managed metadata service applications. This provides the capability to share multiple term stores and content types from multiple site collections. Each service must specify a different term store during the creation process, and a new database will be created if it does not exist.Most of the APIs used to develop EMM solutions are in the Microsoft.SharePoint.Taxonomy namespace. This article focuses on some of the most commonly used classes, methods, and properties: TaxonomySession class TermStore class Group class TermSet class Configuring Managed Metadata service1. Go to the SharePoint central administration Application management and click on the Manage Service Applications. 2. Click on new and select Managed Metadata service; you will get the following screen:3. When you are done with the details, click Save: 4. When you are done you will be redirected to the service page and you can see that the manages meta data Service is started:5. Select Managed metadata Service and click on Manage: 6. You will get the following screen.7. Give Term Store Administrator Name.8. Click Save. 9. From the left hand side menu click on New Group: 10. You will get the following screen; fill in the details:11. After adding the above details, click on Save:12. Next right-click on the group we created and select a TremSet.13. I have created two Term Sets named Functions and Region.14. Here we will identify the owner of this Term set, optionally specify an email address for "term suggestion" and list the Stakeholders who are notified before major changes are made to the term set.15. We can also set the Submission Policy which dictates whether we allow users to contribute to the Term Set (commonly referred to folksonomy) or restrict it to only metadata managers (Taxonomy).16. Our last option determines whether we will allow our end users to utilize the term set for tagging.17. Once you have specified your options, click Save. I will now proceed to create a second Term Set labeled City as in the above instructions. Once finalized, our Term Sets will be listed under our Group as in the following screen capture.18. We will now proceed to create our Terms below our Term Sets. We'll begin by selecting the first Term Set "Function" and then selecting Create Term.19. Here we can specify whether the Term is available for Tagging; add a Description to assist users and add "Other Labels" in which we can enter synonyms and abbreviations relating to the Term:20. Click Save once you have completed the modifications: 21. We will proceed to create a Term for each Function and Region following the steps shown above.22. You should have something similar to the following once you have finished.23. Now you go to your website and click view all site contents.24. Click Create:25. Select and Create a Custom list:26. Once the list is created, click on create column from the ribbon.27. Give a name for the column.28. Select the type as Managed Metadata.29. Give the term set as region and select the Search Icon: 30. Select region from the Term set Settings.31. Click OK.32. Now we are almost done. Just click on the new item of the list.33. Type some data we added in the term.34. You can see the data populating such as shown in the following screen:35. Thank you, we are done with the managed meta data:See you all in MVP Summit. View All
http://www.c-sharpcorner.com/UploadFile/Roji.Joy/configure-managed-meta-data-service-application-in-sharepoin/
CC-MAIN-2017-51
refinedweb
910
55.95
Rewriting a C program using functions and top-down design Program Functions Design and code an ANSI Standard C program which enhances the code below only so as to make it a modular program. (each of the program four tasks of ask, get, alter and display are now separate functions). This will necessitate designing appropriate ask, get, alter and display functions. It will also necessitate coding four ANSI Standard function prototypes, function calls in main() and single-task function definitions. Explain in a brief function comment, what the function's task is and if it needs to have data passed into it, if it needs to return a value to the method that called it (main) or possibly both or neither. Do not use any global variables, only local variables - in other words, declare all your variables inside and at the top of your functions, to include main(). =============== Code to enhance: #include <stdio.h> int main() { float fahrenheit; float celsius; printf("Enter the Fahrenheit temperature as a whole number: "); scanf("%f",&fahrenheit); celsius = 5.0/9.0*(fahrenheit - 32); printf("Fahrenheit temperature %0.2fn",fahrenheit); printf("Celsius temperature %0.2fn",celsius); } Solution Preview Using functions is a useful and powerful aspect to a C program. To use a function you must first declare the function using a function prototype. Then you must provide an implementation for the function. The function prototype includes the name of the function, the return type, and a list of any parameters that the function takes. This posting requires four ... Solution Summary This solution starts with a C program that converts Fahrenheit to Celsius temperatures using the standard simple approach. It then shows how to rewrite the program using functions for the basic steps in the algorithm. Complete C source code is provided.
https://brainmass.com/computer-science/c/rewriting-a-c-program-using-functions-and-top-down-design-202242
CC-MAIN-2017-39
refinedweb
297
55.64
The verdi commands¶ For some the most common operations on the AiiDA software, you can work directly on the command line using the set of verdi commands. You already used the verdi install when installing the software. There are quite some more functionalities attached to this command, here’s a list: - calculation: query and interact with calculations - code: setup and manage codes to be used - comment: manage general properties of nodes in the database - completioncommand: return the bash completion function to put in ~/.bashrc - computer: setup and manage computers to be used - daemon: manage the AiiDA daemon - data: setup and manage data specific types - devel: AiiDA commands for developers - export: export nodes and group of nodes - group: setup and manage groups - import: export nodes and group of nodes - install: install/setup aiida for the current user - node: manage operations on AiiDA nodes - run: execute an AiiDA script - runserver: run the AiiDA webserver on localhost - shell: run the interactive shell with the Django environment - user: list and configure new AiiDA users. - workflow: manage the AiiDA worflow manager Following below, a list with the subcommands available. verdi calculation¶ - kill: stop the execution on the cluster of a calculation. - logshow: shows the logs/errors produced by a calculation - plugins: lists the supported calculation plugins - inputcat: shows an input file of a calculation node. - inputls: shows the list of the input files of a calculation node. - list: list the AiiDA calculations. By default, lists only the running calculations. - outputcat: shows an ouput file of a calculation node. - outputls: shows the list of the output files of a calculation node. - show: shows the database information related to the calculation: used code, all the input nodes and all the output nodes. - gotocomputer: open a shell to the calc folder on the cluster - label: view / set the label of a calculation - description: view / set the description of a calculation Note When using gotocomputer, be careful not to change any file that AiiDA created, nor to modify the output files or resubmit the calculation, unless you really know what you are doing, otherwise AiiDA may get very confused! verdi code¶ - show: shows the information of the installed code. - list: lists the installed codes - hide: hide codes from verdi code list - reveal: un-hide codes for verdi code list - setup: setup a new code - relabel: change the label (name) of a code. If you like to load codes based on their labels and not on their UUID’s or PK’s, take care of using unique labels! - update: change (some of) the installation description of the code given at the moment of the setup. - delete: delete a code from the database. Only possible for disconnected codes (i.e. a code that has not been used yet) verdi comment¶ Manages the comments attached to a database node. - add: add a new comment - update: change an existing comment - remove: remove a comment - show: show the comments attached to a node. verdi completioncommand¶ Prints the string to be copied and pasted to the bashrc in order to allow for autocompletion of the verdi commands. verdi computer¶ - setup: creates a new computer object - configure: set up some extra info that can be used in the connection with that computer. - enable: to enable a computer. If the computer is disabled, the daemon will not try to connect to the computer, so it will not retrieve or launch calculations. Useful if a computer is under mantainance. - rename: changes the name of a computer. - disable: disable a computer (see enable for a larger description) - show: shows the details of an installed computer - list: list all installed computers - delete: deletes a computer node. Works only if the computer node is a disconnected node in the database (has not been used yet) - test: tests if the current user (or a given user) can connect to the computer and if basic operations perform as expected (file copy, getting the list of jobs in the scheduler queue, ...) verdi daemon¶ Manages the daemon, i.e. the process that runs in background and that manages submission/retrieval of calculations. - status: see the status of the daemon. Typically, it will either show Daemon not runningor you will see two processes with state RUNNING. - stop: stops the daemon - configureuser: sets the user which is running the daemon. See the installation guide for more details. - start: starts the daemon. - logshow: show the last lines of the daemon log (use for debugging) - restart: restarts the daemon. verdi data¶ Manages database data objects. - upf: handles the Pseudopotential Datas - listfamilies: list presently stored families of pseudopotentials - uploadfamily: install a new family (group) of pseudopotentials - import: create or return (if already present) a database node, having the contents of a supplied file - structure: handles the StructureData - list: list currently saved nodes of StructureData kind - show: use a third-party visualizer (like vmd or xcrysden) to graphically show the StructureData - export: export the node as a string of a specified format - parameter: handles the ParameterData objects - show: output the content of the python dictionary in different formats. - cif: handles the CifData objects - list: list currently saved nodes of CifData kind - show: use third-party visualizer (like jmol) to graphically show the CifData - import: create or return (if already present) a database node, having the contents of a supplied file - export: export the node as a string of a specified format - trajectory: handles the TrajectoryData objects - list: list currently saved nodes of TrajectoryData kind - show: use third-party visualizer (like jmol) to graphically show the TrajectoryData - export: export the node as a string of a specified format - label: view / set the label of a data - description: view / set the description of a data verdi devel¶ Here there are some functions that are in the development stage, and that might eventually find their way outside of this placeholder. As such, they are buggy, possibly difficult to use, not necessarily documented, and they might be subject to non back-compatible changes. verdi export¶ Export data from the AiiDA database to a file. See also verdi import to import this data on another database. verdi install¶ Used in the installation to configure the database. If it finds an already installed database, it updates the tables migrating them to the new schema. verdi node¶ - repo: Show files and their contents in the local repository - show: Show basic node information (PK, UUID, class, inputs and outputs) verdi run¶ Run a python script for AiiDA. This is the command line equivalent of the verdi shell. Has also features of autogroupin: by default, every node created in one a call of verdi run will be grouped together. verdi runserver¶ Starts a lightweight Web server for development and also serves static files. Currently in ongoing development. verdi shell¶ Runs a Python interactive interpreter. Tries to use IPython or bpython, if one of them is available. Loads on start a good part of the AiiDA infrastructure. verdi user¶ Manages the AiiDA users. Two valid subcommands. - list: list existing users configured for your AiiDA installation. - configure: configure a new AiiDA user.
https://aiida.readthedocs.io/projects/aiida-core/en/v0.4.1/verdi/verdi_user_guide.html
CC-MAIN-2020-50
refinedweb
1,170
51.28
Team Services (VSTS) is a cloud based service which provides features like Work Item Tracking, Source and Version Control (with Team Foundation Version Control as well as Git), Build and Release Management and Test Management. It is a fast and easy way for software and project creation, as a team. It is a common perception that VSTS is a set of DevOps tools for developing software only on the Microsoft stack. But that is a misconception! VSTS is not just for the Microsoft platform, but for many others as well, for eg: for Java Development. In this article I will show you how VSTS can be effectively used for CI/CD and Continuous Testing (CT) using a non-Microsoft tool like Selenium. This article will provide the following guidance: We will use Source Control, Build and Release Management Services of VSTS for executing the above mentioned activities. We will also use the Microsoft Azure Portal to create a Java Web App Service. I will use Ant for building Java Application. Here are the pre-requisites for this article: 1. Visual Studio Team Services (VSTS) Account with one Team Project created in it (it can be of any process template) 2. Account for Azure Portal to create Java Web App 3. Java SDK installed and added in JAVA_HOME environment variable. 4. Eclipse IDE, Ant and Apache Tomcat (if we want to view the application using Tomcat) 1. Using Eclipse IDE create a Dynamic Web Project 2. I have added index.jsp in the WebContent folder which is in the src folder 3. Let us add some code to the project. I have written a Validate method in the Validator class. I have also written code to call the method. Just some very basic functionality. 4. As we are going to use Visual Studio Team Services as our code repository, we need to connect to VSTS. Go to help in Eclipse, browse to the Eclipse Marketplace and search for Team Explorer Everywhere. Install and then you can open perspective for Team Foundation Server Exploring. 5. After adding code, we need to connect to VSTS and use TFVS as Source Control. Connect to VSTS and the Team Project in it. 6. Right click on the project > select Team > Check in pending changes. Provide the comment for check in and check in your code. 7. We have created and checked in code for our Web Project. Now is the time to write the JUnit test. JUnit is a framework for Java Programming Language. It helps in writing tests for functionality tests, and also for Test Drive Development (TDD). If you are new to Unit Testing, check these tutorials: Live Unit Testing in Visual Studio 2017 NUnit Testing with Visual Studio 2015 Smart Unit Tests in Visual Studio 2015 8. There are a few annotations for writing JUnit Tests. Firstly, we need to download the .jar files for JUnit. Provide the required import statements. import static org.junit.Assert.assertEquals; import org.junit.Test; import org.junit.runner.JUnitCore; import org.junit.runner.Result; 9. Let us write the actual code for the JUnit test. public class ValidatorTest { public static void main() @Test public void TestValidate() { Boolean actual, expected=true; Validator val = new Validator(); actual = val.Validate("Gouri", "Sohoni"); assertEquals(expected,actual); } } 10. We can execute the JUnit in Eclipse IDE itself. Right click on the test > select Run As > JUnit Test and you can see the result in runner. The result looks as follows: 11. As I have already mentioned, I will be using Ant to build the code. We can Export the Ant Build files by right clicking on project and selecting Export > Ant Buildfiles Ant provides build.xml file which consists of target and tasks. It has a project, which can have any number of targets and various tasks in it. We can specify which is the default target (required) and the dependent target for the same. The build will then go on fetching the dependent target and execute the tasks in each one of them. The build target can have tasks for compiling, the test target can have tasks for test execution and report task can be for creating test reports. Following is an example of java compilation task: 12. Following is the example for a test target: Observe this target depends on the pack target. The location to the .jar files is specified. I am creating a directory where the test results are stored. The test results will be put in an xml file. Do not forget to check-in this file. 13. I have deployed the web app to Apache Tomcat server (optional) and started the server (to deploy and check if required). 14. Let us add code for Selenium test. Download selenium jar files from and unzip the files. Add support to external jar files. 15. The code for selenium test looks as follows: @Test public void TestSSGSWeb() throws InterruptedException{ ChromeOptions options = new ChromeOptions(); options.addArguments("--start-maximized"); WebDriver driver = new ChromeDriver(options); driver.get(""); WebElement elementName = driver.findElement(By.name("uname")); elementName.sendKeys("Gouri"); elementName.sendKeys(Keys.TAB); WebElement elementPwd= driver.findElement(By.name("pwd")); elementPwd.sendKeys("Sohoni"); elementPwd.sendKeys(Keys.TAB); WebElement elementLogin = driver.findElement(By.name("submoit")); elementLogin.sendKeys(Keys.ENTER); Thread.sleep(4000); driver.quit(); } This code creates instance for chrome driver, navigates to the local tomcat server (later I will change the url to Java Web Service created using Azure). It also enters values for user name and password and clicks on the submit button. This test can be executed with Eclipse IDE, it will be running on the local tomcat server (if you have installed and started the server). Next step is to create a server-side build. 16. We can create a build definition in VSTS by using the template for Ant. In order to execute the build, we need a build agent. Build Agent is a computer where a specialized software is installed to run the workflow containing many tasks, as the steps for build or the release process. VSTS can use an agent which is on premises of the customer or hosted in Azure. Build, Release Management and Test all can use the same agent. In this case I am going to use on premises build agent and not in cloud (as we need to execute JUnit tests as well as Selenium Test later). We also will have to add the capability for running ant script. 17. In order to install build agent, we have to download the zip file for agent from Agent Queues. After un zipping the file, we can configure the agent by running config from command prompt. Provide the url for VSTS account, PAT (Personal Access Token), the work folder, pool name. Run it as an interactive process and not as a service (this is required because we will be running UI test later). 18. In the build definition for Ant, it will add tasks for Get Sources, Ant, Copy and Publish files. Provide the link to the build.xml file in ant task as follows: 19. Click the check box for publishing test results. This will execute the tests and publish the result in the xml file. 20. Let us create a Java Web App Service for Azure. Login to azure portal, select New and select Web + Mobile and select Web App. 21. As we are going to use this web app service for Java, we do the following configuration: I have selected Java version as 8.0, minor as latest and Tomcat version 9.0.0. I have also provided the deployment credentials for the web app service. Now is the time to change the url for Selenium Test to the newly created Web Service App and check in this changed code. 22. Trigger the build so as to create and publish the artifacts. Now we will proceed to deploying of the Web app by creating a Release. 23. Let us create a release definition and add FTP upload task. This task will upload the application to the Web App Service. We need to provide the credentials as variables so that the actual values will not be displayed. You can add variables by selecting Variables tab. Source folder is the artifact drop folder where we need to copy the .war file. Tomcat Server requires the path to be site/wwwroot/WebApps as shown in remote directory. 24. We need the test results to be published so we will use ant specific build file which will not do any compilation, but will only run tests and publish reports. Add another .xml file for ant and change the targets so as to have only test and reports related targets in it. Check in the file. Ensure that this file gets dropped in the drop artifacts via build. 25. Add Ant build task and configure it to execute the new .xml file (the one which has targets for only test and report). Save the release definition. The release definition looks as follows: 26. Create a release. After successful upload of the web app to Web App Service, the Selenium test gets executed. The test results can be found from the Test tab of release. I have purposely failed one of the tests. The result is shown in the summary. The zip file which is provided as attachment shows the following: In this article I discussed We also discussed how build, release definitions can be created and triggered. We have seen how Ant build file can be used with the build as well as release!
https://www.dotnetcurry.com/visualstudio/1403/continuous-testing-java-using-vsts-selenium
CC-MAIN-2022-27
refinedweb
1,598
66.84
... which is why I think I need to write a few lines about it in the context of .NET. This short article will not talk about the known format for 32-bit floating point numbers stored and used according to the IEEE-754 specification, but about the magic of .NET to let such numbers look as expected (without errors). Let's start by considering the following piece of code: Single s = 1.22F; Debug.Assert(s == 1.22F); Debug.Assert(s == 1.22); While the first assert is certainly true, the second one is false. Why is that? Well, here we are comparing the value of a single precision floating point ( Single) with the value of double precision floating point ( Double) value. For such a comparison both values have to be of the same type. This would be Double in this case. Now we know that Double has more precise and the information theorem tells us that information cannot be restored. Hence we see know that the lost precision cannot be regained. In this unlucky case we have hit a sweep spot and this will actually result in a problem. So far, so good. If we want to debug this we will actually face another problem. In the debugger both values appear to be equal (to be precise: at 1.22). How can that be? The answer is quite simple: In the output everything is displayed as a string (we do not have a bytes view, unfortunately). The string representation is .NET specific (while the number format is not!). This will cause some confusion. Let's write a simple C program to see what is exactly (on the machine) going on: #include <stdio.h> int main() { float s = 0.0; unsigned char *p; while(s < 1.0) { s += 0.01f; p = (unsigned char*)&s; printf("%f (%d%d%d%d)\n", s, p[0], p[1], p[2], p[3]); } return 0; } Great! Now let's let it run ... 0.010000 (102153560) 0.020000 (1021516360) 0.030000 (14319424560) 0.040000 (102153561) 0.050000 (2042047661) 0.060000 (14219411761) 0.070000 (409214361) 0.080000 (921516361) 0.090000 (2348118461) 0.100000 (20320420461) [...] Well, so far no rounding errors (at least not visible with the C representation of numbers). Smart people would now go for more digits (and we could then most probably already see some rounding error), but here we do not care about this. We will now write a similar program in C#: void Main() { Num num = new Num(); float s = 0f; while(s < 1f) { s += 0.01f; num.Number = s; String.Format("{0} ({1})", s, num).Dump(); } } [StructLayout(LayoutKind.Explicit, Pack = 1)] struct Num { [FieldOffset(0)] public Single Number; [FieldOffset(0)] public Byte A; [FieldOffset(1)] public Byte B; [FieldOffset(2)] public Byte C; [FieldOffset(3)] public Byte D; public override String ToString() { return A.ToString() + B.ToString() + C.ToString() + D.ToString(); } } We could have also used an unsafe context, but on the other side we could have also used an union in C. Nevertheless the code does pretty much exactly the same. What is the outcome here? 0,01 (102153560) 0,02 (1021516360) 0,03 (14319424560) 0,04 (102153561) 0,05 (2042047661) 0,05999999 (14219411761) 0,06999999 (409214361) 0,07999999 (921516361) 0,08999999 (2348118461) 0,09999999 (20320420461) Aha! The digit representation is different. However, (and this is really important!) we have the same checksum (which is the concatenation of the integer values of the bytes). So what did we learn? Casting a double to a single precision value will result in truncation, which will eventually be some eps different than the original single precision value. So one should make sure to never use equality in cases where values might differ by some eps - always include some tolerance is such cases. If we require fixed precision then we might want to think about using Decimal. This is a fixed precision type and it could store 1.22 precisely. The number of digits (here we had 2 digits) does not say anything about the possible accuracy. Floating point numbers do not represents true arithmetic operations - since they cannot store all numbers (like 1.22).
https://florian-rappl.de/Articles/Page/201
CC-MAIN-2021-43
refinedweb
692
76.82
Bokeh is a Python package that helps in data visualization. It is an open source project. Bokeh renders its plot using HTML and JavaScript. This indicates that it is useful while working with web-based dashboards. It helps in communicating the quantitative insights to the audience effectively. The ‘figure’ function contains multiple functions, and using this, vectorised glyphs of different shapes (circle, square, rectangle) can be drawn. from bokeh.plotting import figure, output_file, show plot = figure(plot_width = 300, plot_height = 300) plot.circle(x = [1, 4, 6], y = [3,7,8], size = 20, fill_color = 'red') plot.circle_cross(x = [2,4,5], y = [3,8,11], size = 20, fill_color = 'black',fill_alpha = 0.2, line_width = 2) plot.circle_x(x = [5,3,2], y = [2,1,7], size = 20, fill_color = 'green',fill_alpha = 0.6, line_width = 2) show(plot) The required packages are imported, and aliased. The figure function is called along with plot width and height. The ‘output_file’ function is called to mention the name of the html file that will be generated. The ‘circle’, ‘circle_cross’, and ‘circle_x’ functions present in Bokeh are called, along with data. The ‘show’ function is used to display the plot.
https://www.tutorialspoint.com/how-can-bokeh-be-used-to-visualize-different-shapes-of-data-points-in-python
CC-MAIN-2021-49
refinedweb
192
69.28
I suffered to get this to work, you shouldn't have to. There is a patch belowthat you need to apply, I'll ship it to Linus too.[Wed May 1 00:11:41 PDT 1996 - lm@sgi.com - version 0.9]This is a mini HOWTO on setting up your system to have a serial "console".It's mostly aimed at kernel hackers who are used to Silicon Valley callsthe kernel hacker setup: two machines, one without a graphics head thatis used for debugging, and the other a complete machine that is used fordevelopment.If you are a kernel hack, you'll be disappointed to learn that this HOWTOdoes not describe how you could do remote debugging via gdb/ptrace. Inother words, you don't have anything listening on the serial "console"until a getty starts running.Finally, you'll probably need a graphics card and head to set this up(although it is possible to do it without one if you have a networkconnection, or you just know your setup well enough).Still here? OK, here's the scoop:Let's call the two machines DEV and DEBUG. DEBUG has no graphics sothat's the one we need a console for.You need a null modem cable. Connect that from a port in one box to theother. Let's assume that DEBUG's port is what prints as tty00 at 0x03f8 (irq = 4) is a 16550Aat boot time.My /etc/lilo.conf on DEBUG looks like prompt timeout=0 boot = /dev/sda vga = normal # force sane state install = /boot/boot.b message = /boot/message image = /vmlinuz root = /dev/sda1 label = cnd append = "console=0x3f8 ether=0,0,4,eth0 ether=0,0,eth1"The critical line is the append= line. That says to use the tty at 0x3f8for the serial console.At next boot, the first line you should see is: Serial console on ttyS1This is all you have to do if all you want is to see the kernel printkmessages. Other things you probably want are /dev/console messages anda getty on the serial port./dev/console messages: I link /dev/ttyS1 to /dev/console and under RedHat startup, this link is honored (in other words, they don't stomp onit as part of the rc scripts. Your mileage may vary).Login prompt (getty): you need to add one of the following to your /etc/inittab # Red Hat style S0:234:respawn:/sbin/getty ttyS0 DT9600 vt100 # Slackware style s1:45:respawn:/sbin/agetty 9600 ttyS1 # Rasta style s9:45:respawn:/usr/games/smoke big_spliff ja rastaJust kidding on that last one :-)To allow root logins (you want this) add "console" to the /etc/securettyfile if it isn't there. If you don't do the link (or you are justparanoid), add ttyS0 as well.That's it. As the serial HOWTO frequently says, rejoice!Problems you might have: I have an ASUS motherboard where tty01 would speak but not listen (typical human behavior, didn't expect it from acomputer). That motherboard has two ports (as do most) and the cableconnections on the motherboard are the same. I just flipped the cablesso that the 9 pin port was COM2 and the 25 pin was COM1 and that worked.I still have one bad port but I'm not using it so who cares. This wasfaster than waiting for the stores to open to buy a new card (and cheapertoo). Try this if things are not working for you.Handshaking on the modem: I think a full null modem will work. Read theserial HOWTO for more info. I know that if you do the hack that wiresRTS to CTS, etc., that works because that's what I'm using.Cool stuff for the future: wouldn't it be neat if we actually made serial consoles a fully support thing so you could do gdb -r? Yes, itwould and a volunteer needs to step forward :-)----------------------------------------------------------------------------Patch for the console= stuff. You will want to apply this by hand, I cut &pasted it on an xterm and the tabs will be all messed up. It's very simple.*** 3.91/init/main.c Tue Apr 16 00:27:09 1996--- linux/init/main.c Tue Apr 30 11:30:10 1996****************** 57,62 ****--- 57,63 ---- extern long pci_init(long, long); extern void sysctl_init(void); + extern void console_setup(char *str, int *ints); extern void no_scroll(char *str, int *ints); extern void swap_setup(char *str, int *ints); extern void buff_setup(char *str, int *ints);****************** 213,218 ****--- 221,227 ---- } bootsetups[] = { { "reserve=", reserve_setup }, { "profile=", profile_setup },+ { "console=", console_setup }, #ifdef CONFIG_BLK_DEV_RAM { "ramdisk_start=", ramdisk_start_setup }, { "load_ramdisk=", load_ramdisk }, *** old/drivers/char/console.c Wed Mar 20 01:39:51 1996--- linux/drivers/char/console.c Wed May 1 00:43:16 1996****************** 183,188 ****--- 183,189 ---- static long blank_origin, blank__origin, unblank_origin; + #define CONFIG_SERIAL_ECHO #ifdef CONFIG_SERIAL_ECHO #include <linux/serial_reg.h>****************** 190,201 **** extern int serial_echo_init (int base); extern int serial_echo_print (const char *s); - /*- * this defines the address for the port to which printk echoing is done- * when CONFIG_SERIAL_ECHO is defined- */- #define SERIAL_ECHO_PORT 0x3f8 /* COM1 */ static int serial_echo_port = 0; #define serial_echo_outb(v,a) outb((v),(a)+serial_echo_port)****************** 292,302 ****--- 287,309 ---- comstat = serial_echo_inb(UART_RX); /* COM? RBR */ serial_echo_outb(0x00, UART_IER); /* Disable all interrupts */ + printk("Serial console on ttyS%d\n", base == 0x2f8 ? 0 : 1);+ return(0); } #endif /* CONFIG_SERIAL_ECHO */ + void console_setup(char *str, int *ints)+ {+ #ifdef CONFIG_SERIAL_ECHO+ if (ints[0] == 1) {+ serial_echo_port = ints[1];+ }+ #endif+ }+ + int vc_cons_allocated(unsigned int i) {****************** 2065,2085 **** set_origin(currcons); csi_J(currcons, 0); /* Figure out the size of the screen and screen font so we can figure out the appropriate screen size should we load a different font */ - printable = 1;;- #ifdef CONFIG_SERIAL_ECHO- serial_echo_init(SERIAL_ECHO_PORT);- #endif /* CONFIG_SERIAL_ECHO */ printk("Console: %ld point font, %ld scans\n", video_font_height, video_scan_lines);--- 2072,2092 ---- set_origin(currcons); csi_J(currcons, 0); + printable = 1;+ #ifdef CONFIG_SERIAL_ECHO+ serial_echo_init(serial_echo_port);+ #endif /* CONFIG_SERIAL_ECHO */+ /* Figure out the size of the screen and screen font so we can figure out the appropriate screen size should we load a different font */; printk("Console: %ld point font, %ld scans\n", video_font_height, video_scan_lines);----.
https://lkml.org/lkml/1996/5/2/22
CC-MAIN-2021-39
refinedweb
1,007
60.55
import java.util.*; public class Payroll { // main method begins execution of Java application public static void main( String args[] ) { // create Scanner to obtain input from command window Scanner input = new Scanner( System.in ); String name = ""; // employee's name int number1; // hourly rate int number2; // number of hours worked for the week int product; // product of number1 and number2 while(name!=null && !name.equalsIgnoreCase("stop")) { number1 =-1; number2 = -1; System.out.print( "Enter employee's name: "); //prompt user to input name name = input.nextLine(); //read employee's name from user's input while(number1<0) { System.out.print( "Enter hourly rate: " ); // prompt user for employee's hourly rate number1 = input.nextInt(); // read hourly rate from user's input } while(number2<0) { System.out.print( "Enter hours worked for the week: " ); // prompt user to enter number of hours worked for the week number2 = input.nextInt(); // read number of weeks from user's input } product = number1 * number2; // multiply numbers System.out.print( "The Employee " + name ); // displays employee's name System.out.println( " weekly pay is $%d\n" + product ); // displays weekly pay } } // end method main } // end class Payroll String name; private int hourlyRate; private int hoursWorked; private int weeklyPay; // need something better than "number1" and "number2" then you create a constructor, getters, and setters for all of the fields. The input from the user can stay in the Payroll class and once you have all of the fields information, you call the constructor. Or can you create an empty Employee object, and call the setter methods as you get the input. When user types STOP, just do a System.exit(0); What do you mean // need something better than number1 and number2? it's not very oriented object programming. Give them a name in the context Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more. Open in new window Your constructor should initialize all of the necessary fields. Open in new window Experts Exchange Solution brought to you by Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.Start your 7-day free trial should be: public Employee( String name, int hourlyRate, int hoursWorked) { employeeName = name; // initializes employeeName this.hourlyRate = hourlyRate; this.hoursWorked = hoursWorked; } // end constructor and I correct setHoursWorked from my snippet: public void setHoursWorked (int hoursWorked ) { this.hoursWorked = hoursWorked ; }
https://www.experts-exchange.com/questions/23114570/Need-help-modifying-a-code.html
CC-MAIN-2018-34
refinedweb
403
56.15
Excel. Excel add-ins run across multiple versions of Office, including Office 2016 for Windows, Office for iPad, Office for Mac, and Office Online. The following table lists the Excel requirement sets, the Office host applications that support that requirement set, and the build versions or number for those applications. Note: Any API that is listed as beta is not ready for production usage. They are made available so that developers can try them out in test and development environments. They are not meant to be used against production/business critical documents. Excel Runtime requirement support check During the runtime, add-ins can check if a particular host supports an API requirement set by doing the following-check: if (Office.context.requirements.isSetSupported('Excel ExcelApi requirement set, version 1.3. <Requirements> <Sets DefaultMinVersion="1.3"> <Set Name="ExcelApi" MinVersion="1.3"/> </Sets> </Requirements> Office common API requirement sets For information about common API requirement sets, see Office common API requirement sets. Upcoming Excel 1.6 release features Conditional formatting Introduces Conditional formating of a range. Allows follwoing types of conditional formatting: - Color scale - Data bar - Icon set - Custom In addiiton: * Returns the range the conditonal format is applied to. * Removal of conditional formatting. * Provides priority and stopifTrue capability * Get collection of all conditional formatting on a given range. * Clears all conditional formats active on the current specified range. For API details, please refer to the Excel API open specification. Upcoming Excel 1.5 release features Custom XML part - Addition of custom XML parts collection to workbook object. - Get custom XML part using ID - Get a new scoped collection of custom XML parts whose namespaces match the given namespace. - Get XML string associated with a part. - Provide id and namespace of a part. - Adds a new custom XML part to the workbook. - Set entire XML part. - Delete a custom XML part. - Delete an attribute with the given name from the element identified by xpath. - Query the XML content by xpath. - Insert, update and delete attribute. Reference implementation: Please refer here for a reference implementation that shows how custom XML parts can be used in an add-in. Others range.getSurroundingRegion()Returns a Range object that represents the surrounding region for this range. A surrounding region is a range bounded by any combination of blank rows and blank columns relative to this range. getNextColumn()and getPreviousColumn(), `getLast() on table column. getActiveWorksheet()on the workbook. getRange(address: string)off of workbook. getBoundingRange(ranges: [])Gets the smallest range object that encompasses the provided ranges. For example, the bounding range between "B2:C5" and "D10:E15" is "B2:E15". getCount()on various collections such as named item, worksheet, table, etc. to get number of items in a collection. workbook.worksheets.getCount() getFirst()and getLast()and get last on various collection such as tworksheet, able column, chart points, range view collection. getNext()and getPrevious()on worksheet, table column collection. getRangeR1C1()Gets the range object beginning at a particular row index and column index, and spanning a certain number of rows and columns. For API details, please refer to the Excel API open specification. What's new in Excel JavaScript API 1.4 The following are the new additions to the Excel JavaScript APIs in requirement set 1.3. Named item add and new properties New properties: comment scopeworksheet or workbook scoped items worksheetreturns the worksheet on which the named item is scoped to. New methods: add(name: string, reference: Range or string, comment: string)Adds a new name to the collection of the given scope. addFormulaLocal(name: string, formula: string, comment: string)Adds a new name to the collection of the given scope using the user's locale for the formula. Settings API in in Excel namespace Setting object represents a key-value pair of a setting persisted to the document. Now, we've added settings related APIs under Excel namespace. This doesn't offer net new functionality - however this make easy to remain in the promise based batched API syntax reduce the dependency on common API for Excel related tasks. APIs include getItem() to get setting entry via the key, add() to add the specified key:value setting pair to the workbook. Others - Set table column name (prior version only allows reading). - Add table column to the end of the table (prior version only allows anywhere but last). - Add multiple rows to a table at a time (prior version only allows 1 row at a time). range.getColumnsAfter(count: number)and range.getColumnsBefore(count: number)to get a certain number of columns to the right/left of the current Range object. - Get item or null object function: This functionality allows getting object using a key. If the object does not exist, the returned object's isNullObject property will be true. This alows developers to check if an object exists or not without having to handle it thorugh exception handling. Available on worksheet, named-item, binding, chart series, etc. worksheet.GetItemOrNullObject() What's new in Excel JavaScript API 1.3 The following are the new additions to the Excel JavaScript APIs in requirement set 1.3. What's new in Excel JavaScript API 1.2 The following are the new additions to the Excel JavaScript APIs in requirement set 1.2. Excel JavaScript API 1.1 Excel JavaScript API 1.1 is the first version of the API. For details about the API, see the Excel JavaScript API reference topics.
https://dev.office.com/reference/add-ins/requirement-sets/excel-api-requirement-sets
CC-MAIN-2017-34
refinedweb
904
50.53
Scala - Files I/O Scala is open to utilize any Java objects and java.io.File is one of the articles which can be utilized in Scala programming to read and write files. import java.io._ object Demo { def main(args: Array[String]) { val writer = new PrintWriter(new File("test.txt" )) writer.write("Hello Scala") writer.close() } } Save the above program in Demo.scala. The commands are used to compile and execute this program. Command \>scalac Demo.scala \>scala DemoIt will make a document named Demo.txt in the present index, where the program is set. Coming up next is the substance of that document. Output Hello Scala Reading a Line from Command LineAt some point you have to read client input from the screen and afterward continue for some further processing. Sometime model program tells you the best way to read input from the command line. Reading File Content Reading from files is extremely basic. You can utilize Scala's Source class and its buddy item to read files. Following is the precedent which tells you the best way to peruse from "Demo.txt" document which we made earlier. Command \>scalac Demo.scala \>scala Demo Output Following is the content read: Hello Scala
https://www.welookups.com/scala/scala_file_io.htm
CC-MAIN-2020-29
refinedweb
205
77.94
Override get method of HashMap works in Java for full story, equals method is also used to avoid duplicates on HashSet and other Set implementation and every other place where you need to compare Objects. Default implementation of equals() class provided by java.lang.Object compares memory location and only return true if two reference variable are pointing to same memory location i.e. essentially they are same object. Java recommends to override equals and hashCode method on equals() and hashCode() method for comparing keys and values, Java provides following rules to override equals method Java. As per following rule equals method in Java should be: 1) Reflexive : Object must be equal to itself. 2) Symmetric : if a.equals(b) is true then b.equals(a) must be true. 3) Transitive : if a.equals(b) is true and b.equals(c) is true then c.equals(a) must be true. 4) Consistent : multiple invocation of equals() method must result same value until any of properties are modified. So if two objects are equals in Java they will remain equals until any of there property is modified. 5) Null comparison : comparing any object to null must be false and should not result in NullPointerException. For example a.equals(null) must be false, passing unknown object, which could be null, to equals in Java is is actually a Java coding best practice to avoid NullPointerException in Java. Equals and hashCode contract in Java And equals method in Java must follow its contract with hashcode method in Java as stated below. 1) If two objects are equal by equals() method then there hashcode must be same. 2) If two objects are not equal by equals() method then there hashcode could be same or different. So this was the basic theory about equals method in Java now we are going to discuss the approach on how to override equals() method, yes I know you all know this stuff :) but I have seen some of equals() code which can be improved by following correct approach. For illustration purpose we will see an example of Person class and discuss How to write equals() method in Java for that class. Steps to Override equals method in Java Here is my approach for overriding equals method in Java. This is based on standard approach most of Java programmer follows while writing equals method in Java. 2) Do null check -- if yes then return false. 3) Do the instanceof check, if instanceof return false than return false from equals in Java , after some research I found that instead of instanceof we can use getClass() method for type identification because instanceof check returns true for subclass also, so its not strictly equals comparison until required by business logic. But instanceof check is fine if your class is immutable and no one is going to sub class it. For example we can replace instanceof check by below code if((obj == null) || (obj.getClass() != this.getClass())) { return false; } 4) Type cast the object; note the sequence instanceof check must be prior to casting object. 5) Compare individual attribute starting with numeric attribute because comparing numeric attribute is fast and use short circuit operator for combining checks. If first field does not match, don't try to match rest of attribute and return false. It’s also worth to remember doing null check on individual attribute before calling equals() method on them recursively to avoid NullPointerException during equals check in Java. Code Example of overriding equals method in Java /** * Person class with equals and hashcode implementation in Java * @author Javin Paul */ public class Person { private int id; private String first; } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj == null || obj.getClass() != this.getClass()) { return false; } Person guest = (Person) obj; return id == guest.id && (firstName == guest.firstName || (firstName != null && firstName.equals(guest.getFirstName()))) && (lastName == guest.lastName || (lastName != null && lastName .equals(guest.getLastName()))); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((firstName == null) ? 0 : firstName.hashCode()); result = prime * result + id; result = prime * result + ((lastName == null) ? 0 : lastName.hashCode()); return result; } } If you look above method we are first checking for "this" check which is fastest available check for equals method then we are verifying whether object is null or not and object is of same type or not. only after verifying type of object we are casting it into desired object to avoid any ClassCastException in Java. Also while comparing individual attribute we are comparing numeric attribute first using short circuit operator to avoid further calculation if its already unequal and doing null check on member attribute to avoid NullPointerException. Common Errors while overriding equals in Java Though equals() and hashcode() method are defined in Object class along with wait, notify and notifyAll, and one of fundamental part of Java programming I have seen many programmers making mistake while writing equals() method in Java. I recommend all Java programmer who has just started programming to write couple of equals and hashcode method for there domain or value object to get feel of it. Here I am listing some of common mistakes I have observed on various equals method in Java, if you like to learn more about common mistakes in Java programming then see my post Don’t use float and double for monetary calculation and Mixing static and non static synchronized method. Now let’s see common mistakes by Java programmers while overriding equals in Java : 1) Instead of overriding equals() method programmer overloaded it. This is the most common error I have seen while overriding equals method in Java. Syntax of equals method defined in Object class is public boolean equals(Object obj) but many people unintentionally overloads equals method in Java by writing public boolean equals(Person obj), instead of using Object as argument they use there class name. This error is very hard to detect because of static binding. So if you call this method in your class object it will not only compile but also execute correctly but if you try to put your object in collection e.g. ArrayList and call contains() method which is based on equals() method in Java it will not able to detect your object. So beware of it. This question is also a frequently asked question in Java interviews as part of Overloading vs Overriding in Java as how do you prevent this from happening ? Thankfully along-with Generics, Enum, autoboxing and varargs Java 5 also introduces @Override annotation which can be used to tell compiler that you are overriding a method and than compiler will be able to detect this error during compile time. Consistently using @Override annotation is also a best practice in Java. 2) Second mistake I have seen while overriding equals() method is not doing null check for member variables which ultimately results in NullPointerException in Java during equals() invocation. For example in above code correct way of calling equals() method of member variable is after doing null check as shown below: firstname == guest.firstname || (firstname != null && firstname.equals(guest.firstname))); 3) Third common mistake is not overriding hashCode method in Java and only overriding equals() method. You must have to override both equals() and hashCode() method in Java , otherwise your value object will not be able to use as key object in HashMap because working of HashMap is based on equals() and hashCode to read more see , How HashMap works in Java. 4) Last common mistake programmer make while overriding equals() in Java is not keeping equals() and compareTo() method consistent which is a non formal requirement in order to obey contract of Set to avoid duplicates. SortedSet implementation like TreeSet uses compareTo to compare two objects like String and if compareTo() and equals() will not be consistent than TreeSet will allow duplicates which will break Set contract of not having duplicates. To learn more about this issue see my post Things to remember while overriding compareTo in Java Writing JUnit tests for equals method in Java Its good coding practice to write JUnit test cases to test your equals and hashCode method. Here is my approach for writing JUnit test case for equals method in Java. I will write test cases to check equals behaviour, contract of equals and hasCode method and properties of equals method in Java on different circumstances. You can also JUnit4 annotation to write JUnit test cases, than you don’t need to use test prefix on test method, just use @Test annotations. testReflexive() this method will test reflexive nature of equals() method in Java. testSymmeteric() this method will verify symmetric nature of equals() in Java. testNull() this method will verify null comparison and will pass if equals method returns false. testConsistent() should verify consistent nature of equals method in Java. testNotEquals() should verify if two object which are not supposed to equals is actually not equal, having negative test cases in test suite is mandatory. testHashCode() will verify that if two objects are equal by equals() method in Java then there hashcode must be same. This is an important test if you are thinking to use this object as key in HashMap or Hashtable 5 Tips on writing equals method in Java Here are some tips to implement equals and hashCode method in Java, this will help you to do it correctly and with ease: 1) Most of the IDE like NetBeans, Eclipse and IntelliJ IDEA provides support to generate equals() and hashcode() method. In Eclipse do the right click-> source -> generate hashCode() and equals(). 2) If your domain class has any unique business key then just comparing that field in equals method would be enough instead of comparing all the fields e.g. in case of our example if "id" is unique for every Person and by just comparing id we can identify whether two Person are equal or not. 3) While overriding hashCode in Java makes sure you use all fields which have been used in equals method in Java. 4) String and Wrapper classes like Integer, Float and Double override equals method but StringBuffer doesn’t override it. 5) Whenever possible try to make your fields immutable by using final variables in Java, equals method based on immutable fields are much secure than on mutable fields. 6) Don't use instanceof check in equals method, as it could break contract of equals() method in sub-class, results in non-symmetric equals, because instanceof return true for child class as well. For example, if you compare two objects Parent and Child from same type-hierarchy; Parent.equals(child) will return true, because child instanceof Parent is true, but Child.equals(parent) will return false, because Parent instanceof Child is false. This means equals() is not following symmetric contract, which states if a.equals(b) == true than b.equals(a) == true, as shown below : public class Parent { } public class Child extends Parent { } public class InstanceOfCheck { public static void main(String args[]) { Parent p = new Parent(); Child c = new Child(); System.out.println("child instanceof Parent " + (c instanceof Parent)); System.out.println("parent instanceof Child " + (p instanceof Child)); } } Output : child instanceof Parent true parent instanceof Child false Alternatively, you can mark equals as final method to prevent it from being overridden. 7) While comparing String object in Java, prefer equals() than == operator. 8) Use IDE or Apache commons EqualsBuilder and HashCodeBuilder utility classes to automatically implement equals() and hashcode() method in Java. 9) Two object which is logically equal but loaded from different ClassLoader cannot be equals. Remember that getClass() check, it will return false if class loader is different. 10) Use @Override annotation on hashcode() as well, as it also prevents subtle mistakes over return type. e.g. return type of hashcode() method is int, but many times programmers mistakenly put long. 11) One. 12) From Java 7 you can also use a new utility class called java.util.Objects for null safe equality check and calculating hash code. You can replace our null-safe code for check equality : (name == guest.name || (name != null && name.equals(guest.getName()))) to much concise Objects.equals(name, guest.getName()); Use of Equals and Hashcode Method in Hibernate Hibernate is a popular, open source Java persistent framework, which provides Object Relational Mapping, also known as ORM framework. It uses equals and hashcode method to provide object's equality in Java side. You should override equals() and hashcode() if : 1) You are storing instance of persistent class in a Set for representing many-valued associations. 2) You are using reattachment of detached persistent instances. Another worth noting point is that Hibernate only guarantees equivalence of database row (persistent identity) and Java object inside a particular Session. Which means if you store instances retrieved in different Sessions in a Set, you will be having duplicates. Now the most important aspect of overriding equals and hashcode() for hibernate entity classes, you should never decide equality just based upon identifier. Though it’s convenient to compare identifier to see if the belong to same database row, Unfortunately, we can't use this approach with generated identifiers. Since Hibernate only assign identifier values to the object that are persistent, a newly created instance will not have any identifier value. Similarly, if an instance is not persisted, and currently in a Set, saving it to database will assigned an identifier value, which will further change the value of hashcode() method, finally results in breaking the contract of the Set. That's why it's best to implement equals and hashcode in Hibernate using business key equality e.g. an Employee is same if it's name, surname, father's name, department, date of birth is same. Properties which are not prone to change e.g. date of birth are better candidate of business equality than those which is easier to change e.g. address and contact number. In short, remember these best practices while overriding equals() and hashcode() for Hibernate entity class : 1) Don't let your equals() method only uses identifier values for equivalence check. 2) Implement equals() and hashCode() using real word key that would identify instance in real world. 3) Use Immutable and unique properties of objects for equality.. That’s all about overriding equals() and hashcode() methods in Java, I am reiterating this but its imperative for a Java programmer to be able to write equals , hashcode(), compareTo() method by hand. It is not just useful for learning purpose but to clear any coding exercise during Java interviews. Writing code for equals and hashcode is very popular programming interview questions now days. For Hibernate persistent class its rather tricky to override equals() and hashCode() because otherwise bad practices turns into best practices because of extensive of proxy. You should not use Eclipse IDE code generator for equals() and hashCode() for hibernate entity class, as they use getClass() to check type equality. 38 comments : Nice Info Just to add, There are utilities available to write efficient and time saving equals method. One can use ToEqualsBuilder in Apache commons-lang package. It is very easy to implement and does lot of calculation automatically. Since firstName and lastName are String objects, == operator might not always return true, you should use equals() method to compare them. You'll want to be careful using == on Strings like you're doing, they may not always be the same object. Thanks Kevin and Anonymous for pointing that out , it was typo I was meant to call equals() method of String but some how writing "==" which is absolutely not recommended. Thanks for pointing that out, also it does highlight another important consideration of leveraging "equals()" method of standard JDK classes e.g. String equals has interesting interactions with inheritance. If you use an instanceof test, you will want to declare equals as final. Otherwise, subclasses might override it and you would get non-symmetric equals, which is a no-no. See Core Java or Effective Java for guidance--it's a tricky subject. Or, if you want subclasses to have their own notion of equality, use getClass() == obj.getClass() instead of instanceof. what I like most in your equals method tutorial is your unit test for testing equals method in java. those are simply great man and I can reuse it to test my equals() method. many thanks to you. fantastic tutorial about equals method in java, but why not you have mentioned about hashcode in java or how to override hashcode method in java ? Since equals and hashcode has to be overridden together to not explaining about hashcode method surprised me. Hi, Javin Paul, While overriding hashcode method in Java makes sure you use all fields which have been used while writing equals method in Java. I believe it is the other way, While overriding equals method in Java makes sure you use all fields which have been used while writing hashCode method in Java. This is to ensure that when two objects are equal there hashcode must be equal. it is really help full for any java programer. please help for this question what is the need of jUnit test in equals() method Hi Sraban, Thanks for you comment and good to fin d that you like this java equals tutorial. questions is just opposite mate, why not ? I prefer to write for my own because I myself have written equals method , you can avoid if you are using IDE to generate equals method or Apache commons EqualsBuilder and hashCodeBuilder because those are already tested. you may also like my article on how to override hashcode in Java Hi Javin, very nice blog. Congratulations. About the item "1) Instead of overriding equals() method programmer overloaded it.", a trick to avoid this issue is always to use the "@Override" annotation. Your IDE will complain that the new method does not exist in the parent class. @Enio Pereira, Thanks for your comment but IDE will not complain sometime and may treat it as different method because of different signature.@Override will ensure this check by IDE and compiler.You may also like How to override hashCode in Java I like how to override equals and hashCode in Java but do you really need to write unit test cases covering equals and hashcode in Java. I see value of having unit testing on equals and hashcode but does it worth ? This is a poorly proofed article whose English is almost so atrocious as to be unreadable. It was difficult to decipher for that reason. I had a question regarding instanceof check : if((obj == null) || (obj.getClass() != this.getClass())) { return false; } ---- Well, this means if the contended object ie. this is to be added to the collection say HashMap will be added even if there is a type mismatch. According to me , we must return true because when equals method returns true, we mean to skip that object of different class type from being added to the collection. Dev J Some people recommend using Equals and HashCodeBuilder from apache commons but that is likely to create ThreadLocal variable and memory leak. Thanks to Tomcat that it points that out as shown in below message: "SEVERE: The web application [/Helloworld] created a ThreadLocal with key of type [org.apache.commons.lang.builder.HashCodeBuilder$1] (value [org.apache.commons.lang.builder.HashCodeBuilder$1@132b67c]) and a value of type [java.util.HashSet] (value [[]]) but failed to remove it when the web application was stopped. This is very likely to create a memory leak." . Very useful! Thanks a lot! Under Common Errors while overriding equals in Java in Point 2 ; the code should make use of '&&' instead of '&'.So it should read : firstname == guest.firstname || (firstname != null && firstname.equals(guest.firstname))); instead of firstname == guest.firstname || (firstname != null & firstname.equals(guest.firstname))); Hi Saurabh, thanks for pointing that, Its indeed short circuit AND operator && so that if first condition is not true don't all equals() method to avoid NullPointerException Java 7 users can use java.util.Objects.equals(firstName, guest.firstName) and Objects.hashCode(firstName) (nulls are handled automatically :) Useful 4 test helper classes for equals hashcode are here For junit3 can use the junit-Addons project on sourceforge Best tutorial on equals and hashCode I have read so far. equals() and hashCode() example are very clear to me. Just to add : 1) Two object which is logically equal but loaded from different ClassLoader can not be equals. 2) Use EqulasBuilder and HashCodeBuilder from Apache commons for overriding equals and hashCode. Thank you, thank you, THANK YOU for this informative tutorial! I am taking a programming languages class and am pretty much expected to already know Java, which I don't. This is incredibly helpful! In one of Interview, one questions appeared How equals method works in Java and explains this with example of String class's equals() method. I explained them that equals() is like any other method but called by many Java builtin classes e.g. Collections and you need to override hashcode when you implement equals method, is that correct ? @Override annotation on hashCode() method also prevents subtle mistakes over return type. e.g. return type of hashCode method is int, but many times I tried to put long. If you are using IDE like netbeans, it will highlight that this is not overriding actual hashCode method. Hello, why didn't you take care of this object? If it is null, a NullPointerException will be thrown. if (this == null || obj == null || obj.getClass() != this.getClass()) { return false; } Hi @Maxim, this can not be null mate, because if this would have been null your call to equals method has thrown NullPointerException already, since you are able to reach inside equals() means this is not null. Let me know if you disagree, and see any edge case, which is worth considering Hi, @Javin, I completely understood you. Of course, I forgot that if a variable references to null, none of its methods can be called. Thank you! Can any one tel me y prime 31 used above... @Krishna, prime 31 is used to create hashCode which is uniformly distributed to avoid collisions in hash based collection classes. Inclusion of prime e.g. 31, 37 or 17 results in more uniformly distributed hashcode. One of the better. This is why Java is 100 time more difficult than any other language. In COBOL, you say IF FIELDA = FIELDB. Done. A word count on this subject: Java - 3900 words COBOL - six words. The winner? COBOL of course. At least, when you consider that progress means making things simpler, not more complex. I always initialize objects. That way there are no nulls. public class Person { private int id = 0; private String firstName = ""; private String lastName = ""; I consider that the NullPointerException is a FLAW in the Java design. For example, 0 != "" != null - zero is not equal to empty string is not equal to null. But it shouldn't raise an error. Can you please add info about use of equals and hashcode in Hibernate. I mean why it's important to override equals and hashcode for Hiberante entity class, what happens if we don't? and how we can automate this process. Sorry to say, but you are presenting a too complex set of ad-hoc rules, that inevitable will be forgotten, misunderstood, violated and/or abused by different developers in your team, and result in occasional bugs -- I promise you :) The first principle when defining equals/hashCode for ORM-entities, is to NEVER consider any other attributes than the ID (or UUIDs; see below) keys. Think about it... why would you want to involve any other attributes? If the IDs are equals but the entities differ in some OTHER attribute, it apparently means you are comparing an entity BEFORE some update, to the SAME entity AFTER the update. That should simply never be done. If you accidentally do that, debug your code or rethink your design. So, if we ONLY consider the IDs (or UUIDs), the only tricky case occurs if you compare two entities where BOTH IDs are null. That means you compare two entities that have just been created, and not yet persisted. Are such entities equal or not? Well, to make a long story short: In this case, you should EITHER use == on the entities themselves (i.e this==other) to determine equality OR go for the UUID solution. See, for example: Also, a beautiful thing, if you ONLY consider attributes ID (or UUID) is that you can use an abstract super-class for all other entities, that only define setter and getter for the key(s), and put the hashCode and equals methods in this super-class, and then you can just forget about this whole headache in all other entity entity-classes. Hooray! :) To let you know there’s a handy utility class called EqualsTester available as part of the GSBase JUnit extensions (), which helps enormously in verifying that a given class has implemented the delicate contract for equals and hashCode properly, or not. For example, it can verify the contract as specified by java.lang.Object which states that if A.equals(B) is true then B.equals(A) is also true. It can also check that if A.equals(B) is true then A.hashCode() will equals B.hashCode(). .
http://javarevisited.blogspot.com/2011/02/how-to-write-equals-method-in-java.html?showComment=1343387653384
CC-MAIN-2015-40
refinedweb
4,224
61.97
What's TOTP and How to generate It to Login into Zerodha Kite API using Python? 6 min read Zerodha recently announced a significant change in its login flow via APIs where they made it mandatory to login via 2FA to place any orders via the KiteConnect APIs. This change is applicable from 3rd October 2021. While this was optional between a PIN and a 2FA before, I am pretty sure 99% of the users used the PIN option just because it's hassle-free, and you can hard code it. But now, they have made it mandatory based on this SEBI Cyber Security Circular. Naturally, the KiteConnect Forum did not take this very well. It is an inconvenience to non-coders who now have to go back to their developers and get their code changed to include TOTP verification or just move to another broker. If you are a non-coder and know at least a little bit of Python, this article will help you change your code to factor in TOTP verification instead of a PIN. Quick Disclaimer: This article is only for educational purposes, and there is no intention to mislead readers to bypass the law via a quick hack. This is to show you how TOTP works. You can use it at your discretion. What is TOTP? TOTP (Time Based One Time Passwords) are unique numeric passwords that get generated with a standardized algorithm that uses the current time as an input. The time-based passwords are available offline and provide user-friendly, increased account security when used as a second factor. TOTP codes are generally only valid for 30 seconds. TOTPs are generally more secure than SMS OTPs because SMS OTPs are static numbers that are only valid to be used once and are usually valid for more extended time periods like 5-10 mins. If someone clones your SIM CARD and gets access to the SMS OTP before you even enter it into the system, they can get into your account and do bad things. Whereas TOTPs are generated on apps like Google Authenticator, and they are linked to specific Google Accounts, so it's a tad bit difficult to get into those and get access to TOTPs. Why Zerodha is suddenly making it Mandatory? Well, according to their forum, they have been questioned by the regulators several times on what steps they are taking to secure user funds, and accounts and TOTPs are the way forward. SEBI already recommended this in December 2018, but it is unclear why they waited until now to make it mandatory. It is also quite baffling that no other broker has made it mandatory. Some other Broker APIs don't even require generating an accesstoken, their access is as simple as just providing the API KEY, USER ID, and USER PASSWORD. All in all, I think each and everyone in the industry should welcome this move; after all, it is just more security to our accounts. Introduction to PyOTP So, how are we going to fix our TOTP problem in KiteConnect APIs? We will use this open-source library pyotp, long live Open Source Contributors. You can install this library using pip install pyotp Next, open up a Jupyter Notebook and try it out using the below code. import pyotp totp = pyotp.TOTP('ABCD') totp.now() What is happening under the hood is that we are giving the TOTP function in the pyotp module a secret key called ABCD and using the .now() function to generate the TOTP valid right now. If you try this 30 seconds later, the TOTP will automatically change; give it a try. Zerodha 2FA registration will give you this secret key which you can provide to the function and use the .now() function to get the TOTP for that time. Confused? Move on to the next section. Registering for 2FA TOTP on Zerodha If you are already registered for 2FA, please unregister by going to the Password & Security Section on Kite and follow the below steps. Once done, click again on Enable 2Factor TOTP, which will shoot out an OTP (How ironic?) on your registered email; verify that. Now, before you move on to scanning the QR code generated, click on Can't scan? Copy the key. This is the key we give to the pyotp module. This will generate a key like below. Please do not try and copy my key; I will have changed it by then :) Now, go ahead and scan this QR code using the Google Authenticator App, and once then, let's try and put this key into the code we wrote above. Yay! It Matches. Unfortunately, Google Authenticator doesn't allow you to take screenshots of its app, so I had to take pictures from another phone. So, we now have a solution; we just need to integrate it in our regular Selenium Workflow, which I guess everyone uses to get requestToken Amending the Zerodha Login Script Before all of this, please ensure you have all the required libraries to run the code; otherwise, it will not work correctly for you. pip install undetected_chromedriver pip install selenium pip install kiteconnect undetected_chromedriver is a selenium alternative where you don't have to worry about the Chromedriver version. You can use selenium as well if you prefer. from kiteconnect import KiteConnect from kiteconnect import KiteTicker import undetected_chromedriver as uc from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By import time, pyotp def login_in_zerodha(api_key, api_secret, user_id, user_pwd, totp_key): driver = uc.Chrome() driver.get(f' login_id = WebDriverWait(driver, 10).until(lambda x: x.find_element_by_xpath('//*[@id="userid"]')) login_id.send_keys(user_id) pwd = WebDriverWait(driver, 10).until(lambda x: x.find_element_by_xpath('//*[@id="password"]')) pwd.send_keys(user_pwd) submit = WebDriverWait(driver, 10).until(lambda x: x.find_element_by_xpath('//*[@id="container"]/div/div/div[2]/form/div[4]/button')) submit.click() time.sleep(1) #adjustment to code to include totp totp = WebDriverWait(driver, 10).until(lambda x: x.find_element_by_xpath('//*[@id="totp"]')) authkey = pyotp.TOTP(totp_key) totp.send_keys(authkey.now()) #adjustment complete continue_btn = WebDriverWait(driver, 10).until(lambda x: x.find_element_by_xpath('//*[@id="container"]/div/div/div[2]/form/div[3]/button')) continue_btn.click() time.sleep(5) url = driver.current_url initial_token = url.split('request_token=')[1] request_token = initial_token.split('&')[0] driver.close() kite = KiteConnect(api_key = api_key) #print(request_token) data = kite.generate_session(request_token, api_secret=api_secret) kite.set_access_token(data['access_token']) return kite Please note, the assumption is that you already have a Zerodha login script that you want to amend; if you are unsure how I constructed the above code, you will be better off looking at my Youtube Channel with a detailed video soon. Please check the above code where I have mentioned the adjustment starting line and ending. The function should accept the TOTP Key as a parameter we got from Zerodha, and it will return a KiteObj, which you can use to place orders, fetch holdings, and all the regular stuff. You can use the below code to test if the function works or not. kiteobj = login_in_zerodha('ZERODHA_API_KEY', 'ZERODHA_API_SECRET', 'ZERODHA_USER_ID', 'ZERODHA_USER_PWD', 'ZERODHA_TOTP_KEY') print(kiteobj.profile()) Would you please Zoom In to see the below image properly to see the example? Conclusion That's pretty much it, guys! Change is hard, and Zerodha has always been the pioneer in bringing change and making the trading experience secure and user-friendly. TOTP is undoubtedly moving in that direction, it indeed temporarily causes a little bit of inconvenience, but it's worth it, and look how easy it is to fix it anyway! I hope this article does help you. I have uploaded this code on Github here. If you are still unsure how to fix your script, please fill in the Contact Us Form on the top with your details, and I will try and help you. Feel free to reach out to me on Linkedin or Twitter. If you have any suggestions about the blog, you can use the Feedback widget on the right hand of your screen, and if you wish to Contact Us, you can fill in the form here. If you like the content on Trade With Python, please do consider subscribing to our newsletter (you will find an option at the top of the page). Lastly, if you want to keep our spirits high and produce more content like this, you can BuyMeACoffee by clicking here or on the button below. Did you find this article valuable? Support Trade With Python by becoming a sponsor. Any amount is appreciated!
https://tradewithpython.com/totp-login-zerodha-kiteconnect
CC-MAIN-2022-21
refinedweb
1,418
55.64
Backwards compatablility If you remove those methods you will break backwards compatablility. Also.. the conversion from the old style speed control and the velocity control is not linear! So.. I don't like this idea. Please do not do this. It is not correct. Please review the existing mapping function in the Java code. Might be a misunderstanding - Might be a misunderstanding - e.g. the "setHandSpeed(...)" function is marked deprecated. But in the standard gestures we have over 100 lines calling setHandSpeed(...)! So your opinion is to step through all the files and replace them with correct "setHandVelocity()" entries? A huge task. I will stick to my method until we can have a replacement for the setSpeed that allows to specify a percentage of the max velocity for a servo. To me its much easier to say "move it half of max speed" than finding an apropriate absolute velocity-value for each servo in every gesture. setSpeed There was a long discussion about this subject. The setSpeed has two problems. 1. The "max speed" is undefined. so per say, half max speed is also undefined. SetSpeed(0.99) should result in almost the same speed as setSpeed(1), but it doesn't. 2. setSpeed(0.75) should result in 3/4 of 1 or .99, but it doesn't. It's not linear. So what speed you get is totally depending on what servo you use, So you can never know what speed you will get for any gesture. What works for you will only work for people using the same servo. That's the reason for the change from setSpeed to setVelocity. When setVelocity is used you get the same speed, independant of what servo you use, as long as the servo can keep up with the speed. as kwatters and Mats explain, as kwatters and Mats explain, setSpeed have many problems that are hard to understand for the common user and that's why it have been deprecated in favor of setVelocity. That said, setSpeed is still too widely used to be totally removed anytime soon. So I still have many gestures using the setSpeed, but I do new one with setVelocity or change it when I modify a gesture. So I don't think it worth changing all your gesture right now, but you should start to use the setVelocity as you do new stuff. I consist on being I insist on being misunderstood! what I did is creating a python function for the main robot parts (arm, hand, head, eye, torso) def setArmSpeed(side, b, r, s, o): i01.setArmVelocity(side, b*15, r*15, s*15, o*15) I agree it could be improved by using the maxVelocity values of the servos, e.g. b*i01.leftArm.bicep.maxVelocity instead of my constant 15. I then did a "replace in files" of all i01.setArmSpeed( with setArmSpeed( in the gestures folder. This results in calling my setArmSpeed python function with e.g. the factors all set to 0.8. My gestures are now calling the new setArmVelocity java routine through my python function with the factors 0.8. As this might still not be 100% perfect it is a significant improvement for getting a relatively exact velocity and it avoids using the depricated java setArmSpeed routine? And in addition - I do not understand why the setArmSpeed routine got depricated instead of making maxVelocity values mandatory and use the same logic of applying partial speeds as partial maxVelocity values. speed vs velocity Ok.. let me start by saying, you are correct that the speed/velocity thing is a mess and it's confusing to people. I think everyone here agrees with that. Next, The switch between speed & velocity a few months back really confused a lot of people and made them very frustrated with MyRobotLab for a number of reasons, but mostly because servos moved "slowly" and that the old style setSpeed didn't work anymore. Adding , yet another method for speed / velocity control isn't the answer. The proper answer is to do it in a consistent and documented way that is unit tested and consistent in how it works. Additional methods for doing this is only making things more complex, not less. The goal here should be simple, well documented, and stable. When I say stable, I mean th e interfaces will NOT change going forward unless there is a seriously good reason to change them. Having stable interfaces is really important if anyone is going to develop software against them. Next, I want to remind you that the relationship between the old style speed and the new style velocity control is not linear. And as a matter of fact, the old style speed and the new style velocity control is aready being mapped programmaticly. Please review this peice of code :... You will see that it's actually an exponential relationship between speed and velocity, and if you trace through the InMoovArm service code, you'll see it actually maps down to the method that I listed above. Next, I'm not sure that the current velocity control is actually 100% mathematically correct, as it's implemented at the arduino level, and I am a little concerned that the math didn't look framiliar to me. (but it might be 100% correct, but generally, when it comes to servos, you control position , not velocity.. so we need to compute the angular velcoity for the servo and resolve that back to an angular position. This should be done using standard questions such as x(t) = 1/2 a * t^2 + v * t + x(0) ... In general, we're not supporting acceleration, so that term is zero. leaving x(t) to be v * t + x(0) ... If we stretch our imagination, we can consider the angular position to conform to this equation assuming a constant velocity (as acceleration is 0.) This means, that in order to compute the position that the servo should be at, you need to know how much time has passed since the last time you set the position and also what position it was at when you last told the servo to move. I think the current arduino code does this, but I'm not so certain that the change in time is actually what's expected... (I'm pretty sure I left a comment in the code about this at one point.) There's a lot of history around this topic, and I don't want us to change any of this prior to Manticore release. Lastly, Stuff like this should be implemented in the Java layer, as that's official... if you want to update python scripts locally to do anything you like you should definitely feel free to do that... As for contributing it back to the InMoov repo, I think that Moz4r should be involved in that conversation also. Sorry if I am being stubborn on this.. but I think that the whole servo speed/velocity stuff has hurt the reputation of MRL and I believe , if we're going to change it again, we really should think it though much more completely and holistically , rather than just giving people yet another option for it. -Kevin Hi KevinThanks for your Hi Kevin Thanks for your lengthy and great explanation. I do agree with all your statements however struggle a bit with the change from the old to the new way of controlling the speed/velocity mostly because its a change from a relative setting to an absolute setting. To use deg/sec as fundament is unquestioned a great improvement and also allows to take individual modifications of the robot into account (e.g. using a more expensive and faster servos for the omoplate). However, in order e.g. to slow down movements for the arm, we will need to memorize or lookup the maxVelocity values of each of the 4 servos. In case of the current java defaults it is 20 for all 4 servos but using the values of ".../InMoov/config/skeleton_leftArm.config" it is bicep=26 rotate=18 shoulder=14 omoplate=15 To a gesture creator / adaptor to run a movement at half speed he will have to use: i01.setArmVelocity("left", 13, 9, 7, 7.5) So what I wanted to have back is a relative setting versus the absolute setting. Something like setRelativeArmVelocity("left", 0.5, 0.5, 0.5, 0.8) I am not requesting a change of the java code. I simply wanted to show a way how I - replaced all depricated set<xx>Speed lines in the gestures with set<xx>Velocity entries - maintain a relative setting against an absolut setting (beeing aware that it might not be the exact speed I was used to and might need adjustions in the gesture file anyway sooner or later)
http://myrobotlab.org/content/deprecated-speed-settings
CC-MAIN-2021-10
refinedweb
1,476
62.88
Suppose, you are given an encoded string. A string is encoded in some kind of pattern, your task is to decode the string. Let us say, < no of times string occurs > [string ] Example Input 3[b]2[bc] Output bbbcaca Explanation Here “b” occurs 3times and “ca” occur 2 times. Input 2[b2[d]] Output bddbdd Explanation Here it will work in two parts first it will expand “d” 2 times so it will become 2[bdd] then if we repeat this twice it will be bddbdd. Algorithm for Decode String - Set temp and output to an empty string, we will use it later temporarily storing the strings. - Starting from 0, while i less than string length: check if str[i] is equal to the digit, push it to integer stack. - Else if str [i] is equal to any character except ‘] ’, push it to character stack. - If ‘]’ is found then pop the number from integer stack and pop all the characters from character stack and store it to the temporary string until ‘[ ’is found and pop ‘[’. - Store and add the value of temp to output until the number pop from integer stack. - From the output string, push all the characters into a character stack and set the output to an empty string. - Repeat this process until all the characters from the character stack and integers from the integer stack are popped(). - Pop all the characters from the character stack and store it into output. - Return output Explanation for Decode String We are given a string which is decoded in some pattern, we have to encode it and return a suitable string which verifies the decoded string, for this, we are going to use two different stacks. In one we are going to store integers and in other stack, characters. Suppose we are given a string, 3[b2[ca]], it means it should output 2 times ac that means “caca” and now it concat with b so inside it will become “bcaca” and this string it occurs 3 times, so it will become bcacabcacabcaca. Let us take an example Example of Decode String Input: 3[b2[ca]] i=0; str[i] =3 it will push into integer stack i=1; str[i] = ‘[’ it will push into character stack. i=2; str[i] =b, it will push into character stack i=3; str[i] = ‘2’ it will push into integer stack. i=4; str[i] =‘[’ , it will push into character stack i=5; str[i] = ‘c’ it will push into character stack. i=6; str[i] = ‘a’ it will push into character stack. i=7; str[i] = ‘ ] ’ according to the algorithm, if we find this ‘]’, we need to pop integer from integer stack that is 2 now and we need to pop the character one by one and store it to temporary string from the character stack until we found ‘[ ’ this character and at last pop this character. So now temp will be “ca”. We will multiply that temp string as no of times as the number we popped from the integer stack and that is noOfInteger = 2 and store it to output. So the output of Decode String will become “caca” after taking it in we need to push it again into character stack. i=8; str[i]= “] ”, again we found this, we need to pop integer from integer stack that is 3 now, and we need to pop the character one by one and store it to temporary string from the character stack until we found ‘[ ’ this character and at last pop this character. So now temp will be “bcaca”. We will multiply that temp string as no of times as the number we popped from the integer stack and that is noOfInteger = 3 and store it to output. So the output will become “bcacabcacabcaca”. And after this, the length of the string is reached we return output. Our output will be: “bcacabcacabcaca”. Implementation for Decode String C++ Program #include <iostream> #include <bits/stdc++.h> using namespace std; string getDecodeString(string str) { stack<int> pushInt ; stack<char> charStack ; string temp = ""; string output = ""; for (int i = 0; i < str.length(); i++) { int noOfInteger = 0; if (isdigit(str[i])) { while (isdigit(str[i])) { noOfInteger = noOfInteger * 10 + str[i] - '0'; i++; } i--; pushInt.push(noOfInteger); } else if (str[i] == ']') { temp = ""; noOfInteger = 0; if (!pushInt.empty()) { noOfInteger = pushInt.top(); pushInt.pop(); } while (!charStack.empty() && charStack.top()!='[' ) { temp = charStack.top() + temp; charStack.pop(); } if (!charStack.empty() && charStack.top() == '[') { charStack.pop(); } for (int j = 0; j < noOfInteger; j++) { output = output + temp; } for (int j = 0; j < output.length(); j++) { charStack.push(output[j]); } output = ""; } else if (str[i] == '[') { if (isdigit(str[i-1])) { charStack.push(str[i]); } else { charStack.push(str[i]); pushInt.push(1); } } else { charStack.push(str[i]); } } while (!charStack.empty()) { output = charStack.top() + output; charStack.pop(); } return output; } int main() { string str = "3[b2[ca]]"; cout<<getDecodeString(str); return 0; } bcacabcacabcaca Java Program import java.util.Stack; class stringDecoding { static String getDecodeString(String str) { Stack<Integer> pushInt = new Stack<>(); Stack<Character> charStack = new Stack<>(); String temp = ""; String output = ""; for (int i = 0; i < str.length(); i++) { int noOfInteger = 0; if (Character.isDigit(str.charAt(i))) { while (Character.isDigit(str.charAt(i))) { noOfInteger = noOfInteger * 10 + str.charAt(i) - '0'; i++; } i--; pushInt.push(noOfInteger); } else if (str.charAt(i) == ']') { temp = ""; noOfInteger = 0; if (!pushInt.isEmpty()) { noOfInteger = pushInt.peek(); pushInt.pop(); } while (!charStack.isEmpty() && charStack.peek()!='[' ) { temp = charStack.peek() + temp; charStack.pop(); } if (!charStack.empty() && charStack.peek() == '[') { charStack.pop(); } for (int j = 0; j < noOfInteger; j++) { output = output + temp; } for (int j = 0; j < output.length(); j++) { charStack.push(output.charAt(j)); } output = ""; } else if (str.charAt(i) == '[') { if (Character.isDigit(str.charAt(i-1))) { charStack.push(str.charAt(i)); } else { charStack.push(str.charAt(i)); pushInt.push(1); } } else { charStack.push(str.charAt(i)); } } while (!charStack.isEmpty()) { output = charStack.peek() + output; charStack.pop(); } return output; } public static void main(String args[]) { String str = "3[b2[ca]]"; System.out.println(getDecodeString(str)); } } bcacabcacabcaca Illustration of above code Complexity Analysis Time Complexity Here time complexity is not fixed because it depends upon the input string because each time we repeat some step and concatenate a string Space Complexity O(n) where n is the length of the string. We use a stack for implement and the maximum possible size of the stack is n.
https://www.tutorialcup.com/interview/stack/decode-string.htm
CC-MAIN-2021-25
refinedweb
1,058
65.22
ULIMIT(3P) POSIX Programmer's Manual ULIMIT(3P) This manual page is part of the POSIX Programmer's Manual. The Linux implementation of this interface may differ (consult the corresponding Linux manual page for details of Linux behavior), or the interface may not be implemented on Linux. ulimit — get and set process limits #include <ulimit.h> long ulimit(int cmd, ...); −1, check to see if errno is non-zero. Upon successful completion, ulimit() shall return the value of the requested limit. Otherwise, −1 shall be returned and errno set to indicate the error. The ulimit() function shall fail and the limit shall be unchanged if: EINVAL The cmd argument is not valid. EPERM A process not having appropriate privileges attempts to increase its file size limit. The following sections are informative. None. Since the ulimit() function uses type long rather than rlim_t, this function is not sufficient for file sizes on many current systems. Applications should use the getrlimit() or setrlimit() functions instead of the obsolescent ulimit() function. None. The ulimit() function may be removed in a future version. exec(1p), getrlimit(3p), write(3p) The Base Definitions volume of POSIX.1‐2008, ulimitLIMIT(3P) Pages that refer to this page: ulimit.h(0p), sh(1p), ulimit(1p), exec(3p), fclose(3p), fflush(3p), fputc(3p), fputwc(3p), fseek(3p), getrlimit(3p), write(3p)
http://man7.org/linux/man-pages/man3/ulimit.3p.html
CC-MAIN-2017-51
refinedweb
224
58.89
When Python runs a script and an uncatched exception is raised, a traceback is printed and the script is terminated. Python2.1 has introduced sys.excepthook, which can be used to override the handling of uncaught exceptions. This allows to automatically start the debugger on an unexpected exception, even if python is not running in interactive mode. Discussion The above code should be included in 'sitecustomize.py', which is automatically imported by python. The debugger is only started when python is run in non-interactive mode. If you have not yet a 'sizecustomize.py' file, create one and place it somewhere on your pythonpath. Gui debugger? This is a great idea; I'd love to use it under the PythonWin gui debugger. Any way to make that happen? I'm using Python as the Active Script language for IIS/ASP, and would love to throw the errors into the PythonWin debugger. Thanks! using pywin debugger. instead of: import pdb pdb.pm() use: import pywin.debugger pywin.debugger.pm() Some small improvements. It is nice to check if the exception is a syntax error because SyntaxError's can't be debugged. Also nice is just assigning the debug exception hook when the program is run is debug mode. Should check if stdin.isatty also. If stdin isn't a tty (e.g. a pipe) and this gets called the pdb code will just start printing it's prompt continually instead of giving a useful traceback. Changing the test to "not (sys.stderr.isatty() and sys.stdin.isatty())" fixes it. -Adam Addidtional check: sys.stdout.isatty(). If the standart output is redirected to a file, then you might not want to start the debugger, because you do not see the debugger's output. Under consideration of the previous comments the condition has to be changed to: if hasattr(sys, 'ps1') or not sys.stderr.isatty() or not sys.stdin.isatty() or not sys.stdout.isatty() or type==SyntaxError: Note, sometimes sys.excepthook gets redefined by other modules, for instance if you are using IPython embedded shell. In this case, insert following after all the imports in your script from sitecustomize import info sys.excepthook=info
http://code.activestate.com/recipes/65287/
crawl-002
refinedweb
363
61.12
I ran into what I think is a bug in storeAtts. While looping over appAtts there's a small optimization to bail out early when nPrefixes is 0. The code then loops over the remaining attributes and does |((XML_Char *)(appAtts[i]))[-1] = 0;|. The problem is that because of the early bail out i didn't get incremented, and just before bailing out the code sets |appAtts[i] = s;| with s coming out of the tempPool, so in the second loop we end up nulling some memory inside the tempPool. One solution consists in incrementing i just before bailing out (I'm attaching a patch that does this). Another solution would be to make the first loop be |for (; nPrefixes && i < attIndex; i += 2) {| and drop the early bail-out. Peter Van der Beken 2005-06-15 Proposed fix Karl Waclawek 2005-06-15 Logged In: YES user_id=290026 I believe you are correct. Fixed in xmlparse.cs rev. 1.148. Need to run a few tests with namespaces on. Karl Waclawek 2005-06-15 Karl Waclawek 2006-01-13 Karl Waclawek 2006-01-13 Logged In: YES user_id=290026 Since Fred is not active anymore, there is no-one to write a test case. Closing the issue.
http://sourceforge.net/p/expat/bugs/381/
CC-MAIN-2015-06
refinedweb
208
71.24
[ ] Doug Cutting commented on AVRO-656: ----------------------------------- > this patch would be a major backwards-incompatible change to the spec. In our code, we we're using the ["null", "fixed4", "fixed16"] case all the time to represent IPv4 or IPv6 addresses That would nix the patch, then, since we don't want to introduce such an incompatibility. If C does correctly implement unions as specified then I was mistaken to assert above that no language did. So instead perhaps I should fix Java to correctly implement unions as currently specified: - fixing union dispatch among records to consider the namespace (easy, should be compatible, already in this patch) - adding a getSchema() method to GenericEnumSymbol and GenericFixed so that we can check the name (incompatible API change, adding a Schema method to the constructors for these) Unless there are objections, I'll try this approach. > writing unions with multiple records, fixed or enums can choose wrong branch > ----------------------------------------------------------------------------- > > Key: AVRO-656 > URL: > Project: Avro > Issue Type: Bug > Components: java > Affects Versions: 1.4.0 > Reporter: Doug Cutting > Assignee: Doug Cutting > Fix For: 1.5.0 > > Attachments: AVRO-656.patch, AVRO-656.patch > > > According to the specification, a union may contain multiple instances of a named type, provided they have different names. There are several bugs in the Java implementation of this when writing data: > - for record, only the short-name of the record is checked, so the branch for a record of the same name in a different namespace may be used by mistake > - for enum and fixed, the name of the record is not checked, so the first enum or fixed in the union will always be assumed when writing. in many cases this may cause the wrong data to be written, potentially corrupting output. > This is not a regression. This has never been implemented correctly by Java. Python and Ruby never check names, but rather perform a full, recursive validation of content. -- This message is automatically generated by JIRA. - You can reply to this email to add a comment to the issue online.
http://mail-archives.apache.org/mod_mbox/avro-dev/201101.mbox/%3C25916864.164371294248287010.JavaMail.jira@thor%3E
CC-MAIN-2017-51
refinedweb
340
57.91
August 3, 2007 By Peter W. Schramm On October 23, 2006--the 50th anniversary of the beginning of the Hungarian Revolution--an article by the Hungarian émigré Peter Nadas appeared in The Wall Street Journal. Mr. Nadas was a young participant in the revolution, so his article said many interesting and insightful things, but perhaps the most revealing is this: To this day I can recite the chronology of those 13 days. Even today I cannot quite contain my romantic frenzy felt over the sensation that everybody is with us, the whole world is with us. You couldn't be everywhere at the same time, but all the news, the stories and the legends of glory reached you. Upon hearing them you experienced them vicariously, relying on your reserves of empathy and you embellished them, hence the greater number of variations. The Revolution recognizes a first person plural which, instead of excluding the first person singular, accommodates and even absorbs the latter with all of its characteristics. [Emphasis added.] As I said, it is a very revealing quote--one with which I happen to disagree. When I say that I disagree, let me be clear: It may very well be that Mr. Nadas and his cohorts shared these feelings during the revolution. I certainly do not dispute his memories or his feelings about them. What I do question is his understanding and explanation of the pull and appeal of the revolution. It may have been what moved Mr. Nadas, but if that is so, it is too bad. It is the wrong way to approach a revolution--or, at least, it is a highly imperfect way. I understand the pith and eloquence of his explanation. I understand and sympathize with part of its meaning. But the part about the first person plural absorbing--that is to say, "swallowing up"--the first person singular is a dangerous temptation in all revolutions, and it is one, I am happy to say, you Americans have been fortunate and wise enough, by and large, to resist. It was, I think, precisely this sentiment--so poetically described by Mr. Nadas--that helped doom the Hungarian Revolution to failure. Ironically, some 33 years later, this same tendency toward absorbing the first person singular would be one of the things cited as a justification for the destruction of the Communists whom the revolutionaries of '56, in their fervor, had meant to expel. The irony is that the revolutionaries of Mr. Nadas's memory had so much of an elemental nature in common with their enemies. Or perhaps it is not ironic, just sadly predictable, in a land without the blessings and habits of liberty. The individual can never really--and should never really--simply be absorbed into the political. No legitimate political cause would ask such a thing of a man. It is a kind of madness and barbarism. But this lesson, though sometimes deeply felt in the heart, is difficult to internalize in the mind and externalize in action, particularly in the face of the kind of "romantic frenzy" described by Mr. Nadas. In America, each generation has to be educated in our principles of right, the natural rights that stem from those principles, and about our constitutional soul, which gives these rights their functional order. As Madison put it, "liberty and learning always have to be attached." In this unique country--this novus ordo seclorum--citizens have to be made because it is not enough that they be born. Unfortunately, it took me a very long time to come to that realization. Born, as I was, in post-war Hungary, becoming American was not just an obstacle of birth; for I came to America in late 1956, just as the revolution failed. I was only 10 years old, so my education about America came mainly in America. But it did not come to me in any organized or systematic way. Much of it--too much of it--came to me by way of happy accidents. Though I fumbled about looking for it on my own--in your public schools and in your state universities--it was not until I reached graduate school that I really began the study of American liberty. Only there did I have the opportunity and the guidance to introduce myself to men like Jefferson, Madison, and Washington on their own terms. That is, I was able to read them without being distracted by Marxist or Freudian interpretations. But even then, I was lucky. I happened to have a few good professors, and they happened to have the good sense to let these men speak for themselves. These "old time men," as Lincoln called our founders, persuaded me that we Americans--that is to say, ordinary human beings--are capable of something quite extraordinary: self government. But their wisdom and my experience with tyranny also persuaded me that self-government is a fragile commodity. The project of self-government is not well served by "romantic frenzy" and absorbing the "I" into the "we." It is much too serious a business for that kind of mindless sentiment and drive. In Madison's words, "The people must arm themselves of the power which knowledge gives." So I set my mind to learning from these "old time men." Now I am honored to be one of those professors who lets these men speak for themselves and to work at a place that Benjamin Rush might have called a "republican seminary"--the John M. Ashbrook Center for Public Affairs at Ashland University. Here, I teach mainly native Americans--that is, the sons and daughters of you who were born in this great country. What I do with these American natives is to remind them of the axioms of a free society. I start with a simple thing about their country and themselves. I tell them that they are among the fortunate of the earth, among the blessed of all times and places. I tell them not only that their country is the most powerful and the most prosperous nation on earth, but also that it is the freest and the most just. Then I tell them how and why this is so. I teach the principles from which these blessings of liberty flow. I invite them to consider whether they can have any greater honor than to pass this great inheritance of freedom undiminished to their children and their grandchildren. Then we talk for a few years about how they might accomplish this. But the irony of my situation is not lost on me. How did this Hungarian immigrant become a teacher of American things to native-born Americans? Revolution and Escape I came to this country on Christmas Eve, 1956--one day after my tenth birthday. The revolution had begun exactly two months prior to our arrival. The Soviets moved in and crushed the Hungarian revolutionaries on November 4. My father told my mother that he had had enough. He had wanted to leave the country for years, but because of all the ties to kith and kin, he was persuaded to resist the temptation. But the coming of the revolution had stirred up new hope in my father--who had suffered first under Nazi and then under Communist oppression. He had witnessed the brutalization and near starvation of his own father in a Communist gulag for the high crime of having had a small American flag in his possession. The doom of this revolution was too much to bear. He told my mother it was time to get serious about leaving. Hesitant at first, for all the usual and expected reasons, she knew in her heart that he was right. But she needed support in this decision, and perhaps because she could not discuss it with the elder members of our family for fear of putting them in danger, she told my father that she would go only if the children agreed. So my mother approached me and told me that my father was thinking of leaving the country. She asked if I would be willing to go with him. My mother claims--though I don't remember saying this--that I responded to her question by saying, "With my father I am willing to go to hell." Like the statement from Mr. Nadas above, there is something that appeals to one's emotions in that response. I am tempted, still, to like it. But upon reflection, one sees in my response an imperfection very similar to the imperfection of Mr. Nadas's formulation. But I was young. I had not quite developed a sense of right and of wrong that went much beyond familial piety. Perhaps I was ready to be swept up by a "romantic frenzy," and I might have been, had it not been for the natural courage and good sense of my father. For my father informed me that our destination was not "hell"--we were already there--but someplace rather its opposite: America. I do remember asking him this next question because his answer, in reflecting something greater than familial piety, turned out to be one of those pithy and moving moments that stays in your mind, not only because it is a good memory, but also because it shapes you and moves you through life in a certain direction as opposed to another one. I asked him, "Why are we going to America?" Dad answered, "Because, son, we were born Americans, but in the wrong place." Born Americans but in the wrong place? When my father said these words, they settled our minds and calmed our hearts. I don't claim that we understood the full import of his words--indeed, I've spent the better part of the last 50 years working to more fully understand them. But the good sense of his pronouncement had a jolting effect, and if we didn't grasp all the implications and permutations of this very American concept, we certainly knew that it wasn't completely insane. We sensed that he was on to something. Of course, we knew something about America in that vague way that Europeans then did--and probably still do. Although today there is much more distraction with the attention given to mass media and popular culture, in those days it was not uncommon for schoolchildren of my age to have read, as I recently had done, The Last of the Mohicans, Uncle Tom's Cabin, Tom Sawyer, and Huckleberry Finn. Everybody read those books, and they probably still do read them in many places around the world--except, of course, in American high schools and colleges. My father was on to something deeper than these vague and imprecise notions we all had about America. Everyone understood America to be a free and a good place where one might prosper unmolested. But in saying that we were "born Americans but in the wrong place," Dad, in his way, was saying that he understood America to be both a place and an idea at the same time. It was a place that would embrace us if we could prove that we shared in the idea. We meant to prove it. We could not so express it at the time, but we meant to show that we were, in Lincoln's words, "blood of the blood, and flesh of the flesh" of all true Americans because "the father of all moral principle" in us was the same as that of those "old time men" who brought forth this fine nation dedicated to the proposition that "all men are created equal." We had never heard these ideas so expressed, but that did not matter. We knew that our dignity as human beings demanded that our government respect us accordingly. We knew that a government that failed to do this was no government at all, but tyranny. And so, we left Hungary. Our escape was not without its drama. Such escapes were rarely simple matters--else they would not be called "escapes." But my father was an enterprising and a clever man. He plotted a way for us to go that would attract the least amount of suspicion, and he knew the countryside along the Austrian border. We could not tell anyone--least of all our remaining family--that we were leaving. Though this was certainly the best policy for their safety and ours, it caused us some anguish, for we knew not whether we would survive our attempt at escape, let alone whether we would ever see them again. We had to hope that we would survive and to assume that we would not see the rest of our family again. We took almost nothing with us. My mother had a little satchel with some jewelry and mementos. My sister, who was then four, and I each carried a little doll. My father had some U.S. currency that took him a lifetime to squirrel away. It was about $17 in single dollar bills. We boarded a train headed for a town on the Austrian border. No one spoke on the train, for we all knew that most of the people aboard were engaged in the same endeavor. My father shook his head as he saw a large number of these folks exit the train at a particular stop. He knew that they would not succeed if they took that route. He was right. When we exited the train and began walking, it became clear after a while that although this was the road less traveled, it was still pretty seriously traveled. Before long, we had amassed a group of some 50 people as we picked up stragglers along the way. My father became a kind of de facto leader of this group, as he had grown up around here and played in these fields as a child. I remember picking up small children crying over the dead bodies of their parents, shot by Soviets. But we had to be very careful in doing this. It was a well-known Soviet trick to use a crying child as a trap. It was nearly daylight when, after crossing a little bridge, we heard people speaking German. We had done it. We were in Austria. I remember being amazed, as a typical little boy, by watching the Austrian guards approach our group, saying something I couldn't understand, and then seeing the members of our group unload an arsenal of every imaginable kind of weapon. That was, to my young mind, one of the most fascinating things about our journey. I could not fathom the fear that had caused these men to come so prepared. Some 200,000 Hungarians left Hungary in the aftermath of 1956. Nearly a quarter of these would also decide to come, if not immediately, then eventually, to the United States. Who knows how many more wished to come but could not find a sponsor? The story of our amazing good luck in finding our sponsor involves a bit of serendipity that sounds almost contrived as a bit of bad fiction writing. As we recuperated from our journey in a camp outside of Nickelsdorf, Austria, representatives from different embassies would meet with the refugees and try to persuade us to come to their country, depending upon the refugee's occupation, their needs, and so on. Since "Schramm" is a German name, the man from the German embassy informed my father, we would be considered Volksdeutschen in Germany, and so we should consider moving there. He told my father all about the great generosity of their welfare system: We would have an apartment, a car, and a guaranteed monthly income. We had virtually nothing, mind you, but my father responded with, "No, thank you, I'm not a German." He waited for the man from the American embassy to speak with us. Of course, we had to speak to him through an interpreter, but we finally came to understand that getting to America was not as simple as stating a desire to come. There was a limit on how many people they could take, and there was a very large number of people vying for those spots. It would be very good, the man informed us, if we had a relative in the United States. That would help us get to America faster. Of course, we had none. "Well, even a friend might be helpful if he would sponsor you. Do you know anyone in America?" My father started to say "no," but my mother stopped him. She ran back to her satchel and pulled out a rumpled business card. She put it in front of my father. "Oh!" said my father--surprised not only by the memory that it inspired but by my mother's keen foresight in both saving the card and bringing it with her on this journey. The card, barely legible after all these years, said "Dr. Joseph Moser, DDS, Hermosa Beach, California." The man from the embassy is waiting patiently, but he does not understand. "What does this mean?" he asked my father. "I do know someone in America," my father explained. "I know this man." Then he explained the following story to the American ambassador. In 1946, before I was born but while I was on the way, my father was newly married and post-war Europe was economically devastated. Hungary was no exception to this rule, but my father was an entrepreneurial character, and so he was able to fashion a rude sort of vehicle out of four wheels, an engine, and a flat bed--in other words, random parts cast off from military vehicles. He would use this vehicle to scavenge the countryside for things to sell or trade. This is one way we existed for a few years after the war. Actual cars were almost never seen on the roads in those days, so when Dad came across a broken-down Volkswagen off to the side of one road--good will and neighborliness were only two reasons to stop; curiosity compelled it--it turned out that the man with the vehicle was an American G.I., now on leave and touring Europe. He had been born in Hungary and was taking advantage of an opportunity to see it again, but the car had broken down, and he could not fix it. Dad could, and so he did. Naturally, the man wanted to give Dad some money. Dad refused the offer and said it had been his pleasure to help. Of course, in reality, the money would have been a huge help to him, but something made him refuse it. So the man instead handed him his business card and said to my father, "Well, you've been very kind with your time and effort, so here's my business card. If you ever need anything," he said with real meaning, "give me a call." Of course, that was Dr. Moser. Ten years later, Dad needed something. The man from the embassy took the card and looked skeptically at my father. "Have you had any contact with this man in the intervening years?" he asked. My father reported that there had been no contact between them. Still, he took the card and went away. Three or four days later, he returned with good news. Dr. Moser remembered the encounter with my father; he said he would be happy to sponsor us. Americans Come Thus it was that my family and I arrived in New York on Christmas Eve, 1956. We moved to Camp Kilmer, New Jersey, on Christmas morning to be processed, and by January 5, 1957, which happened to be my father's birthday, we arrived in Hermosa Beach, California, to meet with Dr. Joseph Moser, DDS. Christmas and birthdays were all overshadowed by this tremendous gift: the chance to start our new life in freedom. We started out in a small beach house the Mosers helped to secure for us. The shock of our new environs was jolting at first. In our typical Hungarian arrogance, we had scoffed at cornflakes in Camp Kilmer--Hungarians feed such things to pigs--and we assumed that this house we were now inhabiting was some kind of vacation beach shack. It was, in fact, a perfectly nice home, but my point is that in all the ordinary ways, we were entirely out of our element. We had much to learn about this country. Dad, of course, went to work immediately. We had to make certain promises upon entering the country and had to prove that we would not become a burden on the American taxpayers. So Dad began moving and lifting heavy things for the Hermosa Beach Daily Breeze newspaper. My mother worked cleaning houses. Within a couple of years, they had saved enough money to go into business for themselves. Of course, none of us spoke any English right away. In addition, my parents had no formal higher education or specific job training upon which they could draw in America. But Mom could certainly cook, and so, together, Mom and Dad looked around and said, "These Americans are nice enough people, but they can't cook. Why don't we cook for them?" And so it was that Schramm's Hungarian Restaurant was born with $1,500 of hard-earned savings and another $1,500 loaned by some trusting American banker. It was a small place on Pico Boulevard in Los Angeles. I was about 12 and my sister was six when we opened it. I say "we" because, as is typical in such situations, we all worked there. My English and writing were the best among us, so I was assigned to type the menus as well as wash dishes, wait tables, and so on. We prospered, and in a few short years, we were able to move into a larger location in Studio City. I mentioned that it was my responsibility to type the menus. We would change them every week or so, depending upon which foods and dishes were available. From the beginning, the first and most popular dish was stuffed cabbage. It was very good, very easy to make, and people loved it, so it was a regular item on the menu. Something like three or four years after we opened the first restaurant, one of our regular customers approached me and said, "Peter, I've been meaning to tell you this for a while because I know you're typing the menus." "Vat eez eet?" I demanded, sensing that I was about to be corrected and, possibly, deeply embarrassed about something I had done. "Well, Peter, you've been spelling 'stuffed cabbage' wrong." "Vat do szyoo mean?" I asked in heavily accented English. "Peter, you've been typing 'stuffed garbage' all these years. I think it's time you knew it." Of course, I was just as embarrassed as could be. My mother was mortified. But this is how we learned: in bits and pieces, by trial and error. There was no "bilingual" education in the schools, so it was up to me to learn English as I could. There was a very kind little red-headed boy named Jeffrey in my first American classroom, who would take me to the back of the room and read with me. He would point to the words, and I would read them. He would correct me. I would repeat it again until I got it right. Eventually, after nine months of this painful exercise, I began to understand. Another boy in that first fifth grade class--and I swear it is true that his name was "Butch"--used to beat me up every day. This was probably because I was wearing lederhosen until a kind woman from our neighborhood explained to my skeptical--and somewhat appalled--mother that it was more customary for American children to wear blue jeans and such to school. Butch beat me up every day until the last day of school that year, when I was finally able to pin him down and make him say "Uncle." I suppose today some well-meaning administrator might enroll Butch and my classmates in a sensitivity training class, but I think this baptism by fire, painful as it was, was more effective and did me and my classmates more good. After I won that final fight, my classmates all cheered and rewarded me with a baseball book that everyone, including Butch, proudly and generously signed. Mishaps and memorable misadventures were my primary way of learning about America. One amusing example happened on the third or fourth day after we arrived in Hermosa Beach, when I stole a Bible. I still have it. I was walking down a street, and there was some kind of a garage sale in progress. I didn't know about such things in Hungary, so I assumed that the people were throwing the things away. I saw the Bible lying there, immediately recognized what it was, and--though I couldn't read it yet--I thought it a shame to see it thrown out, and so I took it. So off I went with my new Bible, and later that evening there was a knock at the door. Mrs. Moser had to be summoned to interpret for us. This little boy and his parents were there to inform my parents that I had stolen the Bible. They were not worried about the Bible so much as indignant about my apparent ignorance of the commandment against stealing. When finally it was all explained, I was told to keep the Bible, and their son became my first American friend and soon taught me to swim in the Pacific Ocean. In short, there was no systematic plan for our assimilation as Americans, but in these many small and innumerable ways, we did assimilate. As an immigrant to your country, I must say that I find the concern that some people have for these trivial kinds of assimilation to be very odd. These small things that, upon our first meeting, make us uncomfortable in one another's presence for one reason or another have a way of working themselves out--or at least they used to--without much interference. On the whole, Americans tend to be among the most kind and generous people on earth. For every Butch there are a thousand Jeffreys. But when it comes to the important and necessary kind of assimilation--that is, teaching immigrants about the history and greatness of your country--there the public schools, the universities, the government fall flat. There is very little concern, unfortunately, for that kind of lack of assimilation. Becoming American After fifth grade, I attended American schools and a four-year university. I was never required to read any kind of founding document in any of them. I probably read some kind of textbook account of American history, but nothing worthy of the subject. Though I was always an avid reader and had a general interest in history, nothing I learned about American history in school had any effect on me; there was no poetry in it, nothing to inspire appropriate awe or respect. The closest thing I got by way of an education in high school was in an English class where a harsh spinster of a teacher insisted that we memorize 40 lines from Shakespeare. She was a serious person, and though we made fun of her behind her back, I actually liked her and wanted to please her. Unimaginatively, perhaps, I chose Hamlet's famous "To be or not to be" soliloquy. In order to master it, I would pace up and down in my bedroom reading aloud. At first I only had a sense of the rhythm and the music of the language. I liked it, but I really had no idea what it meant. At some point, however, after repeatedly reading it aloud, it hit me. I realized that I finally understood what Shakespeare was saying, and, more than that, I realized that I finally had some real grasp of the English language. Until that moment, I was living in English but dreaming in Hungarian. After that moment, I never had a dream in anything other than This modest beginning of an education, though certainly very good for me, still left me without much curiosity about the nature of the regime to which I had emigrated. I still had no concept of the greatness of America or why, beyond what my Dad told me and the contrast with tyranny that I had witnessed, I should love it. I knew we were free here, but I had no idea about how rare, how difficult, and how remarkable that freedom was. My experience at a California state university did not do much to enlighten me. I started to ask questions and to inquire about American history, but the professors would denigrate it as a study in hypocrisy. Lincoln, of course, was dismissed as a racist. I thought that was somehow odd. I didn't know much about American history, but I knew that Lincoln was certainly, in all the ordinary ways, known to be a very important person in American and, indeed, in world history. Everybody has always known this, including Leo Tolstoy, and here's my professor, at an American state university in California, dismissing all of this out of hand. It was immediately after that class that I went down and changed my major from history to political science. I later had to change it back to history because another professor--this time in political science--told the class that anyone who believed in God should immediately leave his class. I and another woman were the only ones who did this, but we got up and left. So I graduated with a degree in history but focused on European history in order to avoid studying this so-called American hypocrisy. I didn't want to study these Americans who talked big about rights and justice and duty and obligation and constitutional government but who were in fact hypocrites who established slavery and then couldn't end it. So I studied tyranny. I studied Louis XIV and Stalin and Hitler. I figured it just made sense to take things in their pure form without the hypocrisy, and it was rather fun if one likes counting bodies and wars. So that's what I did: I counted the bodies of the people that tyrants from Genghis Khan to Stalin killed. I talked about why they were killed, and then I counted more bodies. I was a typical history student, and all because of that one professor who misled me. Fortunately, I was still interested in politics. It was the '60s, so I guess everyone was interested in politics. I walked precincts for Goldwater in '64 and started reading National Review. There was this organization called the Intercollegiate Society of Individualists, now the Intercollegiate Studies Institute, or ISI, that sponsored week-long summer institutes. This group was appealing to me because I certainly was not a Communist. I would go to these seminars, and I would meet 40 or 50 really bright students from around the country, and we would talk about things in a way that seemed more intelligent and more intellectually and morally enlivened than the conversations of most of my colleagues at the state college. And they went deeper and further than my conservative friends in the political world, looking back and beyond the immediate battles at hand. As a result of these seminars, I came upon some very interesting people--Harry Jaffa, Martin Diamond, Bill Allen--all associated with Claremont Men's College, now Claremont McKenna College. I really had no idea of what I was doing at this point in my life. I only knew that I had stumbled upon something very interesting and that I wanted to know everything I could about it. I had so many credits at the state school that I was more or less forced into graduation. I panicked because I thought this meant that I had to stop studying and learning. I had no idea about graduate school, so being forced into graduation nearly devastated me. Then Bill Allen suggested I enroll at Claremont Graduate School, and I did. I was already spending all my time over there, so it was a natural fit. And so I began, in earnest, the study I continue with my own students today: the study of the nature and purpose of American constitutional government and the story of its creation and birth. Put another way, as my Dad once put it, I study what it means to be born American. Teaching Americans I know this is a wonderful country for all kinds of reasons, not the least of which is that I now get paid to think and talk and write and teach about these deeply interesting things. The students I teach are usually native people: Americans who happen to have been born in the right place, probably the greatest country ever--meaning the biggest, the strongest, and the most significant country, but even more interestingly, the freest. This is the country that is the most self-consciously free, the one that really talks about itself in wonderful philosophical terms of justice, of rights, of individual liberty and dignity and equality, and limited self-government. I teach my students that this is a unique thing. If you as an American, regardless of your political opinions, left or right, don't understand that uniqueness or are, perhaps, even offended or embarrassed by it, as some on both the left and--I regret to say--the right are, then I think you're making a very bad mistake, very much like the one I made in college when I gave up studying American history. Take it up again or discover it for the first time--but do it on its own terms. This is a novus ordo seclorum--a new order for the ages, and because everyone has always understood that, it has also offended nearly everyone. When you stand up and you say that an ordinary John Smith--a farmer or a mechanic or a man his "betters" might have called a peasant dog--can govern himself with as much ease as a George III and with as much right, that offends the George IIIs and the would-be George IIIs of this world. It offends all the self-appointed aristocrats who think something flowing in their veins or beating about in their brains gives them the right to govern themselves and everybody else--without, of course, the consent of the governed. This country isn't really just a regime. It's the still-burning spark of a new world. Our fathers then, and all of us now, have stood up in a manly way and said to all the world that we can govern ourselves, and we are doing it, despite the chaos around us; despite the fury of elections, the horrors of war, and the grind of sometimes apparent stupidity. The fact of the matter is that we've done it all and done it in an extraordinarily good way. We have to remind ourselves of what we are at our best. More important, we have to remind our children of that, because Hungarians and Germans may be born, but Americans are not. Nobody is really born an American. You have to be made into an American. In a certain way, you're born by nature to be an American--in a kind of teleological way, if you like, as an end or purpose. But for this purpose to be fulfilled, human interference has to be involved. You have to teach a young person, this would-be American citizen, what are the things worth fighting for? What are things that might be worth dying for? And why? This is a country worth loving not only because it is your own country, but because it is good. Lincoln might be right. America might be "the last best hope" for freedom on this earth. To neglect her is to allow the spark of this new order of the ages to be extinguished. And that, I submit, we have no right to do. Peter W. Schramm, Ph.D., is Executive Director of the John M. Ashbrook Center for Public Affairs and a Professor of Political Science at Ashland University. Previously, he served as Director of the Center for International Education in the United States Department of Education during the Reagan Administration and as President of the Claremont Institute for the Study of Statesmanship and Political Philosophy in Claremont, California. Dr. Schramm earned his Ph.D. in government from the Claremont Graduate School in 1981 and in 2006 was awarded the Salvatori Prize in American Citizenship by The Heritage Foundation for his work in teaching the principles of the American Founding. This essay was published August 3, 2007. Each generation has to be educated in our principles of right, thenatural rights that stem from those principles, and ourconstitutional soul, which gives these rights their functionalorder. As Madison put it, "liberty and learning always have to beattached." In this unique country, citizens have to be made becauseit is not enough that they be born. Peter W. Schram
http://www.heritage.org/Research/Reports/2007/08/Born-American-Reflections-of-an-Immigrant-Patriot
CC-MAIN-2015-11
refinedweb
6,246
69.82
A gotostatement, you give it a labeled position to jump to. This predefined position must be within the same function. You cannot implement gotos between functions. Here is an example of a goto statement: void bad_programmers_function(void) { int x; printf(“Excuse me while I count to 5000...\n”); x = 1; while (1) { printf(“%d\n”, x); if (x == 5000) goto all_done; else x = x + 1; } all_done: printf(“Whew! That wasn’t so bad, was it?\n”); } This example could have been written much better, avoiding the use of a goto statement. Here is an example of an improved implementation: void better_function(void) { int x; printf(“Excuse me while I count to 5000...\n”); for (x=1; x<=5000; x++) printf(“%d\n”, x); printf(“Whew! That wasn’t so bad, was it?\n”); } As previously mentioned, the longjmp() and setjmp() functions implement a nonlocal goto.. Here is an example of the longjmp() and setjmp() functions: #include <stdio.h> #include <setjmp.h> jmp_buf saved_state; void main(void); void call_longjmp(void); void main(void) { int ret_code; printf(“The current state of the program is being saved...\n”); ret_code = setjmp(saved_state); if (ret_code == 1) { printf(“The longjmp function has been called.\n”); printf(“The program’s previous state has been restored.\n”); exit(0); } printf(“I am about to call longjmp and\n”); printf(“return to the previous program state...\n”); call_longjmp(); } void call_longjmp(void) { longjmp(saved_state, 1); a > b > goto label; label; ………….. …………. …………. …………. …………. …………. Label; goto label; Statement;. / * // program to find the sum /*A program to find the sum of n natural numbers using goto statement */ #include < stdio.h > //include stdio.h header file to your program main ( ) //start of main { int n, sum = 0, I = 0, // variable declaration printf (“Enter a number”); // message to the user scanf (“t.d”, &n); //Read and store the number Loop: I ++; //Label of goto statement Sum + = I; //the sum value in stored and I is added to sum If (i < n) goto Loop; //If value of I is less than n pass control to loop Printf (“\n sum of y.d natural numbers = y.d”, n, sum); //print the sum of the numbers & value of n } In this tutorial you will learn about C Programming - Decision Making - Looping, The While Statement, The Do while statement, The Break Statement, Continue statement and For Loop. simplest of all looping structure in C is the while statement. The general format of the while statement is: while (test condition) { body of the loop } Here the given test condition is evaluated and if the condition is true then the body of the loop is executed. After the statements immediately after the body of the loop. The body of the loop may have one or more statements. The braces are needed only if the body contained two are more statements Example program for generating ‘N’. The do while loop is also a kind of loop, which is similar to the while loop in contrast to while loop, the do while loop tests at the bottom of the loop after executing the body of the loop. Since the body of the loop is executed first and then the loop condition is checked we can be assured that the body of the loop is executed at least once. The syntax of the do while loop is: Do { statement; } != ‘n’); //while loop ends if(inchar==’y’) // checks whther entered character is y printf(“you pressed u\n”); // message for the user else printf(“You pressed n\n”); } //end of for loop Sometimes while executing a loop it becomes desirable to skip a part of the loop or quit the loop as soon as certain condition occurs, for example consider searching a particular number in a set of 100 numbers as soon as the search number is found it is desirable to terminate the loop. C language permits a jump from one statement to another within a loop as well as to jump out of the loop. The break statement allows us to accomplish this task. A break statement provides an early exit from for, while, do and switch constructs. A break causes the innermost enclosing loop or switch to be exited immediately. Example program to illustrate the use of break statement. /* A program to find the average of the marks*/ #include < stdio.h > //include the stdio.h file to your program void main() // Start of the program {); // print thte sum. } // end of the program. }
https://ecomputernotes.com/what-is-c/function-a-pointer/what-is-the-difference-between-goto-and-longjmp-and-setjmp
CC-MAIN-2020-29
refinedweb
738
72.16
The QListWidget class provides an item-based list widget. More... #include <QListWidget> Inherits QListView. The QListWidget class provides an item-based list widget. Q: QListWidget *listWidget = new QListWidget(this);(tr("Oak"), listWidget); new QListWidgetItem(tr("Fir"), listWidget); new QListWidgetItem(tr("Pine"), listWidget); QListWidgetItem; newItem->setText(itemText); listWidget->insertItem(row, new.. Note: All items will be permanently deleted. Closes the persistent editor for the given item. See also openPersistentEditor(). Returns the current item. See also setCurrentItem(). This signal is emitted whenever the current item changes. The previous item is the item that previously had the focus, current is the new current item. This signal is emitted whenever the current item changes. The currentRow is the row of the current item. If there is no current item, the currentRow is -1. This signal is emitted whenever the current item changes. The currentText is the text data in the current item. If there is no current item, the currentText is invalid. Handles the data supplied by an external drag and drop operation that ended with the given action in the given index. Returns true if the data and action can be handled by the model; otherwise returns false. See also supportedDropActions(). Starts editing the item if it is editable.(), isItem. The hint parameter specifies more precisely where the item should be located after the operation. Returns a list of all selected items in the list widget. Sets the current item to item. Depending on the current selection mode, the item may.
http://doc.trolltech.com/4.5-snapshot/qlistwidget.html
crawl-003
refinedweb
248
53.47
Overview Atlassian SourceTree is a free Git and Mercurial client for Windows. Atlassian SourceTree is a free Git and Mercurial client for Mac. Overview This is a Python package for developing applications that can run code in the cloud using the API of sourceLair. Reading the Docs Don't forget to read the docs before using the SDK! Using the SDK The Python SDK of sourceLair is fast and intuitive, but it needs a couple of steps to be done, before it is used. Creating a sourceLair App The first thing to be done is creating an account at and then create an App. By creating an App you can will get the API key that you will use. sl.py The next thing to be done is put the file sl.py into the directory of your project. Now you are ready to go. Example import sl MyApp = sl.App( "MyAPIKey" ) result = MyApp.run( "puts 'Hello'" , "ruby" )
https://bitbucket.org/skuda/sourcelair-python-sdk
CC-MAIN-2017-09
refinedweb
158
76.42
Understanding the Business Object Model (or BOM as it is affectionately known) is one of the keys to using JRules effectively. In this entry I hope to lay some groundwork for subsequent more in-depth entries on the Vocabulary, Executable Object Models and B2X mapping. The BOM defines the "entities", "classes", "types", or "concepts" ("things") that you want to write rules about. It is a powerful and expressive object model in its own right, heavily influenced by the capabilities of the Java object model, but also with features from XML Schema and with annotations to describe domains. The BOM is serialized into a .bom file using a plain text serialization that looks very similar to Java-style class definitions. For example, if you create a "Hello World" rule project using the Rule Project Wizard and then open the generated BOM in a text editor you will see: property uuid "_L9byoE4CEd2KE6Zi_qxKvw" package helloworld; public class Clock { public static readonly ilog.rules.brl.Time currentTime; } The syntax should be pretty familiar to most developers. Note that ilog.rules.brl.Time is another BOM class, defined in the JRules System BOM. The System BOM defines the base classes and primitives that are automatically imported into a user application BOM. ilog.rules.brl.Time BOM classes are namespaced using package declarations, and aggregated within a BOM Entry. BOM Entries are referenced from a Rule Project's BOM Path. All the BOM classes from all the BOM Entries on the BOM Path are available to a Rule Project. The analogy with Java classes, packages, JARs and the classpath should be obvious. Before the BOM can be used to author Business Action Language if-then-else rules or decision tables/trees it must be verbalized. The process of verbalization generates human-readable phrases for the classes, attributes and methods in the BOM. The verbalized BOM is expressed as a Vocabulary which is serialized into a .voc file. For the Hello World project the .voc file looks like this: # Vocabulary Properties uuid = _L9akgE4CEd2KE6Zi_qxKvw helloworld.Clock.currentTime#phrase.navigation = the current time I.e. the phrase "the current time" has been associated with the static attribute helloworld.Clock.currentTime. BOM classes create vocabulary Terms while BOM attributes/methods create vocabulary Phrases. The diagram below shows how the text within a Business Rule is first related to the vocabulary, which is mapped onto a BOM. One key point to keep in mind is that the BOM is locale independent -- it is an object model created for rule authoring purposes. The vocabulary on the other-hand is locale specific as it contains human-readable text. You can create different vocabularies for the same BOM, allowing you to define how rules should look in English, French or Chinese for example. A BOM is typically created though a "bottom-up" design process: Java classes or XML Schemas are created by the development team defining the Executable Object Model (XOM). A BOM Entry is then generated from the classes or complex types in the XOM. It is then a simple matter to verbalize the BOM to create a Vocabulary and start writing rules. Because the BOM was generated from a XOM, the rules will be directly executable, using instances of the types defined within the XOM as the source of data for the rule engine. An alternative use case is to define the BOM using a "top-down" design process - creating the classes within the BOM independent of the XOM. Additional work is then typically required to map the BOM to a XOM for use during execution. This mapping declaration is defined in a B2X file which I will return to in a later post. The BOM is represented and manipulated using the classes in the ilog.rules.bom package. For example, using the API it is possible to create a BOM from an external data source, such as database tables, UML diagram or even a structured requirements document. The BOM serves several important purposes: This post has only scraped the surface of the capabilities of the BOM, XOM, Vocabulary and B2X. I aim to drill down into some of the details in subsequent posts. Stay tuned! Microsoft has made some WCF performance data available on MSDN for a while now. The data shows the performance advantages of WCF over ASMX and other SOA frameworks on the platform. In general, WCF is the stronger performer--good news to all the folks who are currently implementing ILOG Rule Execution Server for .NET. If you are deploying RES.NET using IIS 7.0 with Windows Server 2008, then you are no longer limited to the bassicHttpBinding. Moreover, the new architecture allows one to trim down the modules used by IIS--allowing for minimal features for your deployment. You can read about the new architecture here. If you want to read about the top 10 reasons why you should like IIS 7.0, then here is a link to a blog entry from Microsoft.com operations, "The Tasty Morsels Found in Dogfood..." CCB. Since the release of ILOG Rules for .NET 3.0 in February of this year I have seen a good number of questions now regarding best practices with RES.NET integration and deployment. In many cases, the question is around what provider to use--Local or Remote. Given the WCF underpinnings, is there anything one should think about that would affect performance? The short answer is yes. Below are some general facts and guidelines that should be understood and followed: 1. The RES.NET execution API wraps WCF by dynamically generating the proxy client (ChannelFactory) and exposes a limited set of options that we must do in our client code. This pattern is used regardless of how you are invoking the API--local or remote. 2. In the case of the local invocation, the execution API spawns a ServiceHost object programmatically in the background. This is a lightweight service running within managed code and shares the same process that launched it. When this is done, the ServiceHost spawns its own thread pool using the .NET library and is built into WCF. 3. If your project is a thick client (.NET managed code) you should cache the session object for reuse—make it a high-level member of the EXE. All threads in the application will in turn point to the ServiceHost that was created. 4. For a managed application or fat client, the most efficient configuration is the local provider. Do not attempt to add your own thread pool or create multiple instances of the session you created on the first invocation of the RES.NET client. 5. If you have an ASP.NET application, you should always deploy RES.NET to IIS and ASP.NET. This is because WCF will share the thread pool with IIS and WCF will reuse the thread for processing the WCF request. This is only the case where both the application and RES.NET share an IIS instance on the same machine. If they are on separate machines, again, you should use the ASP.NET deployment option for RES.NET (this requires the use of the remote provider when using the execution API). 6. Do not use the local provider for ASP.NET applications. This will spawn the ServiceHost and will create an additional thread pool. 7. If you have a class library that is uses RES.NET but need to run in both a fat client and ASP.NET, then you should write a little factory and load the correct provider for the deployment model. If you would like to start a thread on this topic, post your question or comment to the RES.NET forum (click here for the forum) . Hope this helps many of you and have fun. Two books I have read recently made a surprising connection. The first was the 1972 science fiction novel entitled “Hellstrom’s Hive” by Frank Herbert—the author of the well know Dune series. The premise of the book was that human communities, though extreme in the story, may act collectively in ways that one might call intelligent. Almost a year later, I found myself reading a book by Steven Johnson titled “Emergence: The connected lives of ants, brains, cities, and software.” I find these two books interesting because they consider human behavior on a macro scale and they address the key point that the collective has its own behavior, tastes, and values. With the introduction of media, starting with the first news papers, the notion of a feedback loop was introduced to human experience. This established a sort of dialectic between a community as it is and what it might become. Feedback loops also exist in with software. The requirements process needs the feedback loop to ensure features match the market its intended for. Software that fails to have the feedback loop tends to have a short life. From a Web 2.0 perspective, feedback loops can be used as a tool to solve a larger set of problems that scale beyond the capacity of traditional human organization. Johnson gives several great examples of well-known web sites using feedback to manage everything from fraud to the promotion of solid content. However, all of these examples from the Internet have something in common—they most certainly are using some form of rules technology behind the scenes. Imagine the decentralized behavior of millions of web users on a single site providing, in aggregate, perspective on content, tastes, and enforcement of terms of service. Rules technology provides the right kind of tooling that correlate user behavioral data with policies. In aggregate, it takes the work of the collective and directs it toward something that’s manageable. There are still companies today that must be organized by traditional means; however, even they can take advantage of emergent behavior. Random remains the most efficient way to load an airplane and so long as the data represents human activity (a loan, a purchase, a claim) rules technology can scale enforcement of policy beyond the performance of most teams. There is still room to mature how best to achieve 100% straight-through-processing in many industries but harnessing the power of the collective remains the only way to solve some business problems at Internet scale.. You may have noticed that the BRMS Resource has had a makeover recently, expanding it to cover JRules, Rules for .NET and Rules for COBOL. 6 month trial versions of both JRules and Rules for .NET are now available and the content available to help you evaluate Rules for .NET has been expanded. Don't hesitate to send your feedback to the BRMS product managers! Recently I have seen some project requirements where customers have requested the use of working memory with ILOG Rule Execution Server for .NET (RES.NET). Even though RES.NET requires the use of parameters for passing in the XOM (see my white paper on parameters vs working memory in the X-Ray Series) you may still want to use Rete and working memory in a stateless manner. This can be accomplished by creating a virtual method for each object you intend to assert. In the sample below, I have used the business method wizard on a customer object. You can start the wizard from the BOM view of an object and right click on it: I created a method named “Assert” that took no parameters and used the rule context. You need to check “Use rule context” if you want the wizard to pass in the engine reference to the method: Next, I added code to the method that calls the assert method on the engine instance: namespace BusinessObjectModel { [ILOG.Rules.BusinessObjectModel.ExtendType(typeof(BusinessObjectModel.Customer))] public class CustomerExtender { [ILOG.Rules.BusinessObjectModel.Method(UseRuleContext = true)] public static void Assert(ILOG.Rules.RuleEngine engine, ILOG.Rules.RuleInstance instance, BusinessObjectModel.Customer customer) { // TODO: Add Assert implementation engine.Assert(customer); } } } The final step requires a new rule that does the assertion: if 'param customer instance' is not null then Assert 'param customer instance' ; When using RES.NET, all working memory object instances will be internal to the engine; however, you can still pass out data by assigning instances to your out parameter list. Here is an example: if the age of the working memory customer instance is more than 21 then add the status key "APPROVED" to 'param customer instance' ; else add the status key "DECLINED" to 'param customer instance' ; Have fun.
https://www.ibm.com/developerworks/community/blogs/brms/date/200807?sortby=2&maxresults=10&lang=en
CC-MAIN-2019-43
refinedweb
2,077
63.8
Are you sure? This action might not be possible to undo. Are you sure you want to continue?. It is available to classes that are within the same assembly and derived from the specified base class. 4. Describe the accessibility modifier “protected internal”.. System.Text.StringBuilder classes? System.String is immutable. System.StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed. System.String? StringBuilder is more efficient in cases where there is a large amount of string manipulation. Strings are immutable, so each time a string is changed, a new instance in memory is created. 7. What’s the difference between System.String and 8. What’s the advantage of using System.Text.StringBuilder over Can multiple catch blocks be executed for a single try 17. What’s the . What class is underneath the SortedList class? 14. control is transferred to the finally block (if there are any). Example: class MyNewClass : MyBaseClass 2. from being over-ridden? Yes.NET collection class that allows an element to be 13. Business (logic and underlying code) and Data (from storage or other sources). application.new instance of each element's object. Once the proper catch block processed. 15. Presentation (UI). Can you allow a class to be inherited. You can also omit the parameter data type in this case and just write catch {}. 11. Just leave the class public and make the method sealed. 3. Will the finally block get executed if an exception has not occurred? Yes. 12.Exception. Can you prevent your class from being inherited by another class? Yes. 16. but prevent the method . yet identacle object. accessed using a unique key? HashTable. How can you sort the elements of the array in descending order? By calling Sort() and then Reverse() methods. statement? No. resulting in a different. A sorted HashTable. The keyword “sealed” will prevent the class from being inherited. Explain the three services model commonly know as a three-tier Class Questions 1. What is the syntax to inherit from a class in C#? Place a colon and then the name of the base class. What’s the C# syntax to catch any possible exception? A catch block that catches the exception of type System. 2. no accessibility modifiers are allowed. To Do: Investigate In an interface class. What is the difference between a Struct and a Class? Structs are value-type variables and are thus saved on the stack. What’s an abstract class? A class that cannot be instantiated. In an abstract class some methods can be concrete. all methods are abstract . conflicting method names? It’s up to you to implement the method inside your own class. The data type of the value parameter is defined by whatever . and defined as separate entities from classes. methods. 5. but as far as compiler cares you’re okay. 9. This might cause a problem on a higher-level scale if similarly named methods from different interfaces expect different data. and are therefore public by default.NET does support multiple interfaces. When do you absolutely have to declare a class as abstract? 1. An abstract class may have accessibility modifiers. An abstract class is a class that must be inherited and have the methods overridden. In an interface class. But unlike classes. What happens if you inherit multiple interfaces and they have 10. so implementation is left entirely up to you. 8. When at least one of the methods in the class is abstract. like classes. additional overhead but faster retrieval. An abstract class is essentially a blueprint for a class without any implementation. . What’s the implicit name of the parameter that gets passed into the set method/property of a class? Value. Why can’t you specify the accessibility modifier for methods inside the interface? They all must be public. What is an interface class? Interfaces. What’s the difference between an interface and abstract class? 11. 7. Method and Property Questions 1. Can you inherit multiple interfaces? Yes. Another difference is that structs cannot inherit. 6.there is no implementation. They are implemented by classes. When the class itself is inherited from an abstract class. define a set of properties.4. but not all base abstract methods have been overridden. interfaces do not provide implementation. and events. 3.data type the property is declared as. XML Documentation Questions 1. (Note: Only the keyword virtual is changed to keyword override) Different parameter data types. 2. method is not static? No. and XML documentation . What’s a multicast delegate? A delegate that has multiple handlers assigned to it. What does the keyword “virtual” declare for a method or property? The method or property can be overridden. different order of parameters. Overloading a method simply involves having another method with the same name within the class. and then keyword base (parameter list to invoke the appropriate constructor) in the overloaded constructor definition inside the inherited class. How is method overriding different from method overloading? When overriding a method. The signature of the virtual method must remain the same. different number of parameters. If a base class has a number of overloaded constructors. /* */ comments and /// comments? Single-line comments. 2. What are the different ways a method can be overloaded? 6. can you enforce a call from an inherited constructor to a specific base constructor? Yes. Events and Delegates 1. you change the behavior of the method for the derived class. multi-line comments. What’s a delegate? A delegate object encapsulates a reference to a method. and an inheriting class has a number of overloaded constructors. just place a colon. 4. Is XML case-sensitive? Yes. 2. Each assigned handler (method) is called. Can you declare an override method to be static if the original 5. What’s the difference between // comments. What’s the difference between the Debug class and Trace class? Documentation looks the same. allowing you to fine-tune the tracing activities.comments. To the Console or a text file depending on the parameter passed to the constructor. 2. How do you debug an ASP. proper handling). 3. 5. Five levels range from None to Verbose. assert takes in a Boolean condition as a parameter. 2. 3. Can you change the value of a variable while debugging a C# application? Yes. If you are debugging via Visual Studio. 4. For applications that are constantly running you run the risk of overloading the machine and the hard drive.NET SDK? 1. use Trace class for both debug and release builds. To use CorDbg. DbgCLR – graphic debugger. Use Debug class for debug builds. and shows the error dialog if the condition is false. you must compile the original C# file using the /debug switch.NET uses the DbgCLR. What debugging tools come with the . Debugging and Testing Questions 1. Attach the aspnet_wp. How do you generate documentation from the C# file commented properly with a command-line compiler? Compile it with the /doc switch.NET. 3.exe process to the DbgClr debugger. Negative test cases (broken or missing data. Where is the output of TextWriterTraceListener redirected? 6. Visual Studio . 8. What does assert() method do? In debug compilation. Why are there five tracing levels in System. Positive test cases (correct data. correct output). just go to Immediate . 2. The program proceeds without any interruption if the condition is true.TraceSwitcher? The tracing dumps can be quite verbose. CorDBG – command-line debugger. Exception test cases (exceptions are thrown and caught properly).Diagnostics.NET Web application? 7. What are three test cases you should go through in unit testing? 1. NET data provider is high-speed and robust. OLE-DB. ADO.window. Explain ACID rule of thumb for transactions. which one is trusted and which one is untrusted? Windows Authentication is trusted because the username and password are checked with the Active Directory. Windows Authentication (via Active Directory) and SQL Server authentication (via Microsoft SQL Server username and password). no “inbetween” case where something has been updated and something hasn’t. A DataReader provides fast access when a forward-only sequential read is needed. so it’s not as fastest and efficient as SqlServer. but requires SQL Server license purchased from Microsoft. 4. OLE-DB.NET and Database Questions 1. data provider classes in ADO. The wildcard character is %. forward-only rowset from the data source.NET connections? It returns a read-only.NET is universal for accessing other sources. DB2. Between Windows Authentication and SQL Server Authentication. since SQL Server is the only verifier participating in the . 4.it is one unit of work and does not dependent on previous and following transactions. Durable . 3.NET? SQLServer.NET. Microsoft Access and Informix. What is the role of the DataReader class in ADO. What are advantages and disadvantages of Microsoft-provided 3. Consistent . Isolated . Atomic .NET is a . like Oracle. the proper query with LIKE would involve ‘La%’. What connections does Microsoft SQL Server support? 6. 2.data is either committed or roll back. 5.the values persist if the data had been committed even if the system crashes right after.no transaction sees the intermediate results of the current transaction). the SQL Server authentication is untrusted.NET layer on top of the OLE layer. A transaction must be: 1. 2. What is the wildcard character in SQL? Let’s say you want to query database with LIKE for all employees whose name starts with La. where every parameter is the same. you could call the garbage collector when you are done using a large object (or set of objects) to force the garbage collector to dispose of those very large objects from memory. 8.Resources. and XCOPY command. you should not call the garbage collector.NET? an Assembly. What are the ways to deploy an assembly? 3. 7. When you write a multilingual or multi-cultural application in .transaction. What is a satellite assembly? 4. However. and want to distribute the core application separately from the localized modules. To Do: answer better. this is usually not a good practice. . What does the Initial Catalog parameter define in the connection string? The database name to connect to. The connection string must be identical.NET. What is the smallest unit of execution in . 6.NET? Assembly versioning allows the application to specify not only the library it needs to run (which was available under Win32). However. a CAB archive. How is the DLL Hell problem solved in .NET? As a good rule. application? System. 2. but also the version of the assembly. 9. What namespaces are necessary to create a localized 5. the localized assemblies that modify the core application are called satellite assemblies. including the security settings. An MSI installer. When should you call the garbage collector in . Assembly Questions 1. What is a pre-requisite for connection pooling? Multiple processes must agree that they will share the same connection. The current answer is not entirely correct. What does the Dispose method do with the connection object? Deletes it from the memory.Globalization and System. 1. What happens in memory when you Box and Unbox a valuetype? Boxing converts a value-type to a reference-type. 8. thus storing the value on the stack. 3. If it relates to data base validation we need to validate at server side. Should validation (did the user enter a real date) occur server-side or client-side? Why? ANS : client side . 5. Unboxing converts a reference-type to a valuetype. it will redirect pages which or in the same directory. Thru http context we can able to get the previous page control values. What does the "EnableViewState" property do? Why would I want it on or off? ANS: IT keeps the data of the control during post backs.NET component . Response.7. We can pass the query string thru which we can manage sessions. there is no need to go to validate user input.Trnasfer will prevent round trip.Redirect : There is a round trip to process the request. We can redirect to any page external / internal other than aspx. thus storing the object on the heap. 4. if we turn off the values should not populate during server round trip. How do you convert a value-type to a reference-type? Use Boxing. What type of code (server or client) is found in a Code-Behind class? ANS : Server side. Can you give an example of when it would be appropriate to use a web service as opposed to a non-serviced . What is the difference between Server. NO way to pass the query strings .Transfer and Response. Explain the differences between Server-side and Client-side code? ANS: Server side code will execute at server end all the business logic will execute at server end where as client side code will execute at client side at browser end. 6. 2.Redirect? Why would I choose one over the other? ANS: Server. NET Web Forms? How is this technology different than what is available though ASP (1.ANS : Web services are best suite for Hetrogenious environment. 11.NET We need to have Wrapper to communicate COM components in .NET Dataset and anADO Recordset?\ ANS : DIsconnected architechure . Can you explain the difference between an ADO. RCW : RUN time callable wrapper. Remoting is best suite for Homogenious environment. Maintainace relation schemas. InterDev 6) and this application utilizes Windows 2000 COM+ transaction services. Connected one . ASP. MUtilple table grouping.0)? ANS : ASP . 8. Can you explain what inheritance is and an example of when you might use it? .Net Compiled. What are ASP. 11. 7. Interprepter. Can you give an example of what might be best suited to place in the Application_Start and Session_Start subroutines? ANS: APplication_start need for global variable which are available over the application.NET web appplication is spanned across three web-servers (using round-robbin load balancing) what would be the best approach to maintain login-in state for the users? ANS : Database Support. 9..net. Operator overloading. use the script engine. Sesssion_Start : login dependent ( user dependent) 10. 12. How would you approach migrating this application to .NET/C# achieve polymorphism? ANS : Function overloading. or Thru state service. and vis versa CCW : Com Callable wrapper. How does VB.0-3. If I'm developing an application that must accomodate multiple security levels though secure login and my ASP. Let's say I have an existing application written using Visual Studio 6 (VB 6. The systems that under CLR. and what are the limitations of any approach you might take in implementing one ANS: Preprocessing before going to IIS. IL.INLINE ANS: inline function bind at compile time can write in aspx page with in <% %> . page is size is heavy.Meta data versioning .conf the following lines 23. Use the existing functionality along with its own properities. and a good use for one ANS : is an xml grammer. Calture .NET/C#? ANS: Derived Class : Basecalss VB.mode State sever OUtprocess sql 22. Whats an assembly ANS : A Basic unit of executable code > Which contains : Manifest .NET running in Apache web servers . How would you get ASP.NEt : Derived Class Inherits Baseclass 14. How would you implement inheritance using VB. Explain what a diffgram is. Where would you use an iHTTPModule.Install Mod_AspDotNet Add at the end of C:\Program Files\Apache Group\Apache2\conf\httpd.which is best in a loosely coupled solution Tightly coupled . 17. how does it work and what are the limits ANS: Session . 13. 21 Describe session handling in a webfarm. 20. 18. and why should my developers need an appreciation of it .ANS : Heridity. it talk about state of node in xml file. Whats MSIL.why would you even do this? ANS: ---. What are the disadvantages of viewstate/what are the benefits ANS : IT can be hacked . Describe the difference between inline and code behind . Reference 15. net supported languages after comiplation will produce.Web. What tags do you need to add within the asp:datagrid tags to bind . 33. 24. Appreciation for cross language support. error message 34. As a developer is it important to undertsand these events? ANS : INIT. What base class do all Web Forms inherit from? System.if at all? ANS : Microsoft Intermeidate lanaguage. What property must you set. Prerender . in order to bind the data from some data source to the Repeatercontrol? Datasource. UNload. How can you provide an alternating color scheme in a Repeatercontrol? AlternateItemTemplate 29. 25. and what method must you call in your code. Which method do you invoke on the DataAdapter control to load your generated dataset with data? Fill() 26. What method do you use to explicitly kill a user s session? abondon() 32 How do you turn off cookies for one page in your site? disablecookies.Page 31.UI. PageLoad. Which two properties are on every validation control? control to validate. in order to display data in a Repeater control? ITemtemplate 28. In what order do the events of an ASPX page execute. Which template must you provide. DataBind 30. Can you edit data in the Repeater control? NO 27. which is the out put for all the . How do you create a permanent cookie? Cooke = ne cookee(). True or False: To test a Web service you must create a windows application or Web application to consume this service? no 49.NET DLL contain? . Which method do you use to redirect the user to another page without performing a round trip to the client? server.NET false 41. Where on the Internet would you look for Web services? UDDI 44. What is the transport protocol you use to call a Web service SOAP http 40. Autogenerate columns 45.columns manually? autogenerated columns is set to false 35. 36. How is a property designated as read-only? get 47. to display data in the combo box? datatext datavalue 46. Which property on a Combo Box do you set with a column name.adddate. What is the standard you use to wrap up a call to a Web service -----------38. prior to setting the DataSource. What tag do you use to add a hyperlink column to the DataGrid? hyper link column 37. it is used to generate for proxy( server object) 42. Which control would you use if you needed to make sure the values in two different controls matched? compare filed validator 48. True or False: A Web service can only be written in .transfer 39. cooke. What does WSDL stand for? webservice discription language. What tags do you need to add within the asp:datagrid tags to bind columns manually. 43. How many classes can a single . What property do you have to set to tell the grid which page to go to when using the Pager object? Page Index. NET. ASP. ? How do we use different versions of private assemblies in same application without re-build? [Rama Naresh Talluri] In Asseblyinfo file need specify assembly version. XML: ? How many types of JIT compilers are available? [Rama Naresh Talluri] There are Two types of JIT compilers. ? standard JIT compiler. Add the publisher policy assembly to the GAC using GACutil tool Gacutil /i 3.NET Editor ? How do you implement SSL? . During runtime CLR is looking into the publisher policy file and redirect the application to bind with new version assembly as specified inside the publisher policy. assembly: AssemblyVersion ? Different methods of using a legacy COM component in . Reference a COM component directly from . ? EconoJIT compiler.as many as u want.NET.NET framework? [Rama Naresh Talluri] 1. ADO.. TLBIMP to create an Assembly from a COM component 2. ? . publisher policy file is the configuration file to redirect to different version 1. C#. Create the publisher Policy assembly using the assembly linker 2.NET assemblies to be shared by several applications on that computer. create certificate request [ =>Right click on the website (VD) =>Click Directory Security Tab and click Server Certificate => Type name of certificate . ] 2.NET IDE? If yes.[Rama Naresh Talluri] 1. and then click Submit ] ? Is it possible to debug java-script in . ?. view state. hidden variables. Write debugger statement to stop the cursor for debugging .Client Side [ Query string. => Type the path need to save certificate information Submit certificate request. [ => Browse =>.Submit Certificate request. how? [Rama Naresh Talluri] Yes.cookies] . server name location info. select Web Server or User. Organization name . AsyncState. service).2.Compiler and Microsoft. session.Service1 service = (MyWebServiceApp.localhost.Server side [application .callService(“add”. } .EndHelloWorld(oRes)). Var iCallID. iCallID = service. In these namespaces we can find the tools that allow us to compile an assembly either to disk or into memory.asmx?WSDL”.BeginHelloWorld(new System.MyTest.AsyncCallback (WriteHello).CodeDom.IAsyncResult oRes) { //End the call localhost. //Write the call result to a MessageBox MessageBox.Service1 service = new MyWebServiceApp.Show(service. We can also need the Reflection namespace as it contains the tools to invoke an object and its methods once we have compiled the object.localhost.2).Net provides powerful access to the IL code generation process through the System. private void WriteHello(System. } ? How to invoke a webservice using javascript? [Rama Naresh Talluri] <script language =”javascript”> Function init() { Service.useservice(“/services/test. ? How to pass server control values from one form to another using in-line code? [Rama Naresh Talluri] Server. “MyTest”).1. database] ? How do we Generate and compile source code dynamically? [Rama Naresh Talluri] .Service1().Transfer ? How to make a webservice call asynchronous? [Rama Naresh Talluri] //Create a new instance of the Web Service Class localhost.CSharp and Microsoft. //Make the asynchronous Web Service call and call WriteHello service.VisualBasic namespaces.Service1) oRes. we release all of our resources and call GC. ? What is the purpose of Singleton pattern? [Rama Naresh Talluri] Singleton pattern is used to make sure that only one instance of a given class exists.htc)”></div> </body> ? List out all the possible ways of maintaining the state of a session. and which objects it will Finalize. and the state of manage objects cannot be guaranteed. [Rama Naresh Talluri] InProc OutProc [State server. Structures use stack allocation. [Rama Naresh Talluri] Finalize is called by the Garbage Collector. Also. [Rama Naresh Talluri] Structures are value types. . classes are reference types. sql] ? What is the use of multicast delegate? [Rama Naresh Talluri] A multicast delegate can call more than one method. Within we dispose method. ? What is the purpose of a private constructor? [Rama Naresh Talluri] Prevent the creation of instance for a class ? Differentiate Dispose and Finalize.SuppressFinalize as we have done the work of the GC. we cannot determine when the GC will run. so we can not reference them. and is used to dispose of managed and unmanaged objects. ? Difference between structure and class. Dispose is called by the programmer.</script> <body onload =”init()”> <div id =”test” style =”behaviour:url(webservice. ValueType. class variables and constants are Private by default. Structures are never terminated. so the common language runtime (CLR) never calls the Finalize method on any structure. Structure variable declarations cannot specify initializers or initial sizes for arrays. Structures are not inheritable. the SAX API allows us to process the data as it is parsed . classes can inherit from any class or classes other than System. so there are potentially less memory allocation. the SAX API may help to remove the intermediate step If we do not need all the XML data in memory. which calls Finalize on a class when it detects there are no active references remaining. ? Difference between DOM and SAX parser. classes are terminated by the garbage collector (GC). SAX approach is useful for large documents in which the program only needs to process a small portion of the document SAX parsers generally requires more code than the DOM interface. Structures implicitly inherit from the System. The DOM tree is not constructed. we can't as easily write the XML file back to disk. If we convert the data in the DOM tree to another format. Structure elements cannot be declared as Protected. classes are. [Rama Naresh Talluri] DOM Approach is useful for small documents in which the program needs to process a large portion of the document. class variable declarations can. All structure elements are Public by default.ValueType class and cannot inherit from any other type. Unless we build a DOM style tree from our application's internal representation for the data.classes use heap allocation. while other class members are Public by default. class members can. Dataset is a data structure which represents the complete table data at same time. 2. It contains the tags that specify the original and new state of data ? Differentiate between legacy ADO recordset and . What are typed datasets. SAX approach is useful for large documents in which the program only needs to process a small portion of the document If we do not need all the XML data in memory.NET Typed DataSets generate classes that expose each object the in the DataSet in Type-safe manner. . Connection is open . It meets all the well-formedness constraints given in this specification. the SAX API allows us to process the data as it is parsed ? What is a well-formed XML and is the purpose of Diffgram? [Rama Naresh Talluri] A textual object is a well-formed XML document if it satisfies all the following points 1. Each of the parsed entities which is referenced directly or indirectly within the document is well-formed. Taken as a whole.NET dataset. The purpose of Diffgram is the Ability to pass parameters. Dataset is just a data store and manipulation is done through DataAdapters in . It will raise error at compile time if any mismatch of column data type. [Rama Naresh Talluri] Recordset provides data one row at a time. 3. it matches the production labeled document.? Under what circumstances do you use DOM parser and SAX parser [Rama Naresh Talluri] DOM Approach is useful for small documents in which the program needs to process a large portion of the document.
https://www.scribd.com/doc/57294029/510555-C-Interview-Questions
CC-MAIN-2018-22
refinedweb
4,340
62.24
Different ways to delete elements from Stack container in C++ STL Get FREE domain for 1st year and build your brand new site A Stack is a container in C++ STL that is based on the concept of Last In First Out (LIFO) context,i.e.the element which has been inserted recently will be on the top of stack and will be the first to get out. Stack container in C++ STL uses Deque container internally. So, the pop() operation in stack actually calls pop_back() function in the internal deque container. We will explore ways to delete elements from a stack. Now, here we are going to discuss methods to remove elements from stack: 1. stack::pop() stack::pop() is a public member function that is used to remove the top-most element of the stack. Since,there is only one end for insertion and deletion in stack,therefore the element added recently would be on the top of satck,and would be the first to get out of the stack. Everytime,the size is decreased by one on performing pop operation on stack,until the stack is completely empty. Few important points: - pop() function does not require any parameter. - On calling pop() function,it does not return any value. - Time Complexity of performing pop is Constant time Do you know that behind the stack,in the background another container is used that is hidden from outside world.This is deque container which supports stack. The operations which happen behind the scene are: - stack::push() --> deque::push_back() - stack::pop() --> deque::pop_back() - stack::top() --> deque::back() Both implementation are bgiven below.First one is the simple implementation of stack::pop(),but in second one it has been done with deque::pop_back() Implementation 1 In this implementation, we have created a stack with some initial elements (10, 20, 30, 40) and printed the top element by deleting the top element each time. This demonstrates the use of pop() function in stack container in C++ STL. // Part of OpenGenus //Implementation of stack::pop() (); //Removing top element every time } return 0; } Output 1 The front element is:40 Input Stack is: 40 30 20 10 Implementation 2 Following code example demonstrates deque which can behave as a stack where pop_back() functions acts same as pop() function in Stack container. Internally, deque is used within a stack. //Implementing stack with deque #include<iostream> #include<deque> using namespace std; int main() { deque <int> st; //Pushing into stack st.push_back(10); st.push_back(20); st.push_back(30); st.push_back(40); cout<<"The front element is:"<<st.back()<<"\n"; //pop from stack cout<<"Input stack is:\n"; while(!st.empty()) { cout<<st.back()<<"\n"; st.pop_back(); } return 0; } Output 2 The front element is:40 Input stack is: 40 30 20 10 See,in both cases the output are same. Note that we cannot use pop_back() function directly on a Stack container. It will raise a compilation error. Following will be the error: opengenus.cpp: In function ‘int main()’: opengenus.cpp:25:12: error: ‘class std::stack<int>’ has no member named ‘pop_back’ st.pop_back(); //Removing top element every time ^ To check the above error, consider the following code example: // Part of OpenGenus // Demonstrates we cannot use pop_back with stack _back(); //Removing top element every time } return 0; } Hence, pop() is the only approach to delete an element from a stack container in C++ STL. With this article at OpenGenus, you must have the complete idea of removing elements from stack in C++ STL. Enjoy.
https://iq.opengenus.org/delete-element-from-stack-cpp/
CC-MAIN-2021-43
refinedweb
588
61.36
See also: IRC log <PaulVincent> scribenick PaulVincent <PaulVincent> Christian: will decide today on breakout topics eg implementation... <PaulVincent> Chris: session on Extensibility <PaulVincent> scribenick: PaulVincent Reviewing Sandro's Extensibility_Design_Choices doc (all definitions quoted in the minutes below are from this document) Definitions: what is a RIF Document? "A RIF Document is an XML document with a root element called "Document" in the RIF namespace (). In general, RIF documents are expected to convey machine-processible rules, data for use with rules, and metadata about rules." Paul: does this imply all data in a RIF doc? Sandro: no Jos: RIF doc may not be XML? Sandro: that is the current intent: RIF is an XML doc Christian: RIF may not contain data for use in rules ... withdraws comment <sandro> PROPOSED: accept definition of RIF Document as in Chris: proposes RIF Document definition is set once here as normative Christian: if this is a final definition then need more defining eg on data containment Axel: object to definition on root element as RIF:Document <Harold> What about: In general, RIF documents are expected to convey machine-processible rules, facts for use with rules, and metadata about rules. <sandro> PROPOSAL WITHDRAWN <sandro> Chris: defn okay -- nothing but nit picking complaints Chris: retracts enforcement of never-adjust-this definition <sandro> Sandro: I do intend "RIF Document" to imply they are all XML documents <sandro> Chris: The other issue was data, facts, and making it lower priority (ie at end of list with weasel words) Harold: would prefer facts rather than data (in RIF doc definition) as knowledge = rules + facts ." <sandro> Sandro: Are "RIF Consumer" and "RIF Producer" good? <sandro> everyone happy <sandro> re RIF Dialect -- Axel -- Dialect may have more than XML. . " Axel: objects to RIF Dialect being an XML language <AxelPolleres> On I proposed the following notion... <AxelPolleres> (which is probably also not the last word, but some things might be worthwhile): <AxelPolleres> # a dialect MUST restricts/define which parts of the abstract model you are allowed to use in its instance rulesets and how. <AxelPolleres> # a dialect MUST assign a semantics to this restricted part (model-theoretic, proof-theoretic, operational in that order of preference) ). <sandro> Bob: usually assumes you can write syntactically valid programs without them being meaningful. <sandro> Sandro: I specifically mean to rule that out. <Harold> What about: A RIF Dialect is a specification of a (usually infinite) set of RIF Documents. <AxelPolleres> what is missing is probably: # MUST defne an XML Language for RIF Documents <sandro> Bob: Then syntax must be clear as going MORE DETAILED than in Schema. <sandro> Gary: cf Signatures.... Christian: dialect is more than a schema ... dialect has a normative specification outside of the schema <sandro> Axel reads what he put on IRC. Axel: suggests bullet list for definition <sandro> Sandro: Let' leave dialect not well defined and move on. Chris: move onto definition of Language Conflict . " Harold: can only have inclusion hierarchy: multiple semantics is an issue Christian: need to define language conflict to know what we need to avoid <sandro> MK: the def of Lang Conflct doesn't need to go into Spec -- that's for us. Sandro: this may be a concept for dialect designers Michael: we should design to avoid this <sandro> csma: We seem to agree what is a language conflict, and that we don't want them. Chris: RIF Extension "A RIF Extension is a set of changes to one dialect (the "base" dialect) which produce another dialect (the "extended" dialect), where the extended dialect is a superset of the base dialect. " <sandro> Axel: Superset in the sense that every document in the extended dialect is a document in the base dialect. <sandro> Jos: superset is too restrictive. <sandro> csma: but that's what extension means. Jos: removing from "where" to avoid "superset" will be more general Chris: RIF Profile is the complement of RIF Extension "A RIF Profile is the complement of a RIF Extension; it is a set of changes to one dialect (the "base" dialect) which produce another dialect (the "profile" dialect), where the profile dialect is a subset of the base dialect." Sandro: Profile is a general term for a standard subset Jos: this is already a design choice (Extension and Profile) <sandro> Jos: These definitions reflect reflect some design choices -- they preclude naming dialects <sandro> Sandro: true Jos: removing subset/superset makes extension=profile Christian: can extend definition to be extension = dialect that covers more rule types than the parent (etc) <sandro> Sandro: rif change, modification, delta, ..... Chris: ... but extension could also modify definition of ruleset etc Christian: RIF extension can also process the parent's rules <sandro> csma: we need to keep in mind that "RIF Extension" as written here is a specifc kind of thing, and there is a more general notion. Chris: need another term for a delta / derivative that is not an extension / profile <sandro> "RIF Functionality Extension" vs "RIF Pure Syntactic Superset Extension" Sandro: RIF syntactic extension and functional extension? Michael: Also consider an "invisible extension" ... so we need to define the extensions more specifically Jos: invisible extensions that are just syntactic then this is not a RIF extension <sandro> Jos: this definition means "invisible extension" is not an extension. <sandro> Sandro: true. <sandro> Chris: Maybe metadata doesn't count as part of the syntax....? Chris: need to define a more general notion of RIF extension ... Backward and Forward Compatibility ." <sandro> Chris: I understand BC, but it sounds like there is wiggle room around metadata, eg language identifier.... Sandro: example: IE identifies itself as Mozilla as this was meant to be metadata but is now used as an executable interpretation... <AxelPolleres> I personally don't really like dialect identifiers... so far, any convincing argument for them? Sandro: Metadata compatibility is important (Chris: some noncompatible metadata changes may not prevent executable backward compatibility) Christian: "future or unknown languages" term means? Sandro: this is simply a problem definition, not a solution <AxelPolleres> What I wanted to say is that Fwd-compatibility, if desired, already *fixes* the fallback mechanism in some sense. Chris: Fallback )." Sandro: allows for graceful behavior - predictable degradation Jos: why should fallback imply convergence eg rather than ignore some aspect <AxelPolleres> examples for Fallback: <AxelPolleres> - refuse ruleset <AxelPolleres> - ignore rules <AxelPolleres> - ignore rule parts Michael: this is an issue, not a solution Axel: is "ignore" a transformation? <AxelPolleres> note there is also "semantic fallbacks" probably. (think of strict vs. loose language layering (in Jos' sense)) Chris: impact <sandro> Jos: switching from "transformation" to "mapping" helps. <Harold> Issue: If the receiver just omits what they can't understand, the sender won't know how much was understood. So, the receiver need to inform the sender about what they omitted. <AdrianP> Define default semantics as a fallback mechanism Sandro: a single dialect extension may have multiple fallbacks with multiple impacts "Impact is information about the type and degree of change performed by a fallback transformation. For instance, a fallback transformation which affects performance might be handled differently from one which will cause different results to be produced. This difference is considered impact information. " <AxelPolleres> Examples of impact might be: <AxelPolleres> - soundness lost <AxelPolleres> - completeness lost <AxelPolleres> ... Gary: Example - bad element tree being pruned: ie could remove part or all of a rule <AxelPolleres> sounds kind of like "cautious" and "brave" fallbacks. <sandro> Gary: prune at AND and you get false negatives; prune at RULE and you get fewer results --- user needs to choose. Chris: highlights of extensions ... user extensions vs official extensions ." Christian: user extensions for own fancy features via an extension framework - this is a strong motivation for adoption of extensibility <sandro> csma: Big Goal: to allow users to deploy extensiion which eventually turn into official extensions. Christian: examples may be vendor extensions, which can then be brought into an official extension <AxelPolleres> Do we want to go down to how a certificate for endorsement of a dialect needs to look like? <Harold> How to avoid that a vendor comes up with their fancy 'user' extension to differentiate themselves from other vendors. Christian: will say 2nd example after the break... BREAK to 10.35 <Harold> ... We could encourage vendors to collaborate on joint 'usergroup' extensions, so chances would go up for their extensions to become official. <ChrisW> Scribe: MichaelKifer discussion of invisible extensions ." csma: clarify the diff betw invisible extensions and language conflicts sandro: invisible extension is a "harmless" language conflict <sandro> *might* sometimes be harmless. <sandro> Jos: better example of invisible extension is RDF and OWL-Full. Same syntax, very very different semantics. <sandro> Sandro: Yes, but.... some caveats maybe. mk: dont want language conflicts, but the notion of invisible extension is useful for specifying fallbacks and impact factors. sandro,csma: want to avoid invisible extensions scribe: as well as language conflicts <sandro> Chris: There is an intuitive notion of Invisible Extension that makes it different from Language Conflicts in general.... <sandro> Sandro: Yes <AxelPolleres> How about, "Strictly semantically layered extension" and "loosely layered semantically layered" semantics. examples of invisible extensions: OWL-DL->OWL-Full, Well-formed, stable negation vs stratified negation <ChrisW> seemed like general agreement that invisible extensions and language conflicts are the same and undesirable <Harold> Since XML can express things with elements or attributes, we should use one element, e.g. Naf, with an attribute, e.g. flavor, which could distinguish stable, well-founded, etc. <sandro> Sandro: An "invisible extension" would be "naf" and you have to say out of band which kind of NAF it is. <Harold> So, <Naf flavor="stable"> vs. <Naf flavor="well-founded"> <AxelPolleres> ChrisW, they are NOT the same: invisible extensions are a special case of conflict! <Harold> where one could be picked as the default. <josb> "An invisible extension defines a dialect which is a superset of the base dialect, but which defines a different semantics for documents in the base dialect." sandro: motivating example for user-defined extension ... what's the mechanism for granting permissions to define a dialect? what namespace? Harold: namespace change is not a problem <Harold> because it also occurs for RIF's own versions. csma: if u want to become a standard, use RIF namespace. sandro: may not know if something will become a standard at the beginning ... another way is to rewrite vendor NS into a RIF NS automatically <Harold> Developers of user dialects should be strongly encouraged to reuse as many as possible of existing (official) standards when they look for a basis to define their own extension dialects. sandro: how can we ensure that different groups developing different dialects don't step on each other <AxelPolleres> +1 we need some "principle of maximum reuse" csma: pro for having a central authority: there is some quality control <Harold> Re 2.1.2: What about a much less expensive light-weight control. sandro: W3C doesn't want to be a central authority for every possible extension. This position has led OASIS to take over some of the extensions. ... of XML csma: create a RIF Consortium sandro: central repository of namespaces has a problem in case of IP and patent enforcement attempts <Harold> Maybe, by analogy to Incubator Groups, W3C needs a notion of 'Outcubator Groups' which maintain further development of specs after a WG ended. <sandro> csma: we'll have to decide soon whether BLD and PRD use the same namespace <AxelPolleres> solution: common abstract model, common namespaces for overlapping constructs :-) csma: how do we manage overlap between dialects? for ex: BLD and PRD are not extensions of each other, but they share the condition sublanguage. What namespace for that sublanguage? <sandro> sandro: if we think of BLD lists as an extension, is there some reason to put them in a different namespace. gary: maybe just use the same namespace for everything? sandro: +1 csma: but how do we achieve this at the technical level? axel: another way is to split off abstract model and dialects, e.g. CONDITION is an abstract model construct, it is not specific to a dialect <Harold> The namespace should contain at least. A new namespace could be created for. BLD would then become an extension of Conditions by Horn rules. <sandro> PROPOSED: RIF-WG will only use its one namespace, but to allow user extension to use other namespaces. csma: what if the same document is in both dialects (eg, a subset of PRD and BLD)? Then u don't want the same constructs (eg negation) to be in different namespaces. <sandro> PROPOSED: All official extensions will use the main RIF namespace, but we will support user extensions using other namespaces. <AxelPolleres> Well, we would be getting close to a Core here again, harold, don' we? <sandro> PROPOSED: All official extensions will use the main RIF namespace, but we will support user extensions using other namespaces. <sandro> PROPOSED: All official extensions will use the main RIF namespace, and we will support user extensions using other namespaces. <sandro> PROPOSED: All official (ie standard) dialects will use the main RIF namespace. We will support user extensions using other namespaces. <sandro> Harold: what about subspaces? <sandro> Sandro: No, really the same namespace string. <AxelPolleres> This fits very well with the common abstract model idea... btw., I like it. <sandro> RESOLVED: All official (ie standard) dialects will use the main RIF namespace. We will support user extensions using other namespaces. <sandro> csma: if this leads to serious design difficulties, we may to re-open this, of course. csma: this resolution may cause design difficulties. if this occurs then we'll dissolve or modify the resolution <sandro> Do we ever allow invisible extensions? => not really resolved yet csma/sandro: issue: do we allow invisible extensions? mk: unclear what "allow" means <sandro> How do you know when extensions are compatible? => no idea yet. issue: how do we know if extensions are compatible? csma: probably we don't care <sandro> "Do people ever need" .... component library, mk: difficult for 6months times. => No criticial impact here now. <Harold> An extension should always start from the largest base dialect(s) that will be semantically contained in the newly defined dialect. issue: should we allow flags at the document root to modify the meaning of syntactic constructs (eg, to say whether negation is a WFS-NAF or ASP-NAF or ...) sandro: table this for the moment <AxelPolleres> I think further, we could probably not get anything more than a "principle of maximum reuse" and something like defining BLD and PRD as core in the following sense. Proposal: <AxelPolleres> Other dialects should reuse BLD and PRD wherever possible. Other dialects MUST agree with the semantics of BLD and PRD on the parts (of the abstract model) they share with BLD and PRD. <Harold> Starting from the 'largest' base dialect(s) will exclude starting from the 'null' dialect except when defining a totally different language (unrelated to the rest of RIF). csma: is it possible to tell when ASP and WFS agree? <sandro> Merging: wfnaf in one file and smnaf in the other, and you merge them..... document-level flags wont allow that. mk: no. it's undecidable, but some sufficient conditions (stratification at the predicate level) exsist <AxelPolleres> -1 to document level flg for the moment, not convinced yet. the smsnaf vs wfsnaf issue could be solved with different identifiers for the different nafs. <Harold> 'Document-level flags' correspond to the XML attributes I mentioned earlier: Eg. a 'flavor' attribute for Naf, which distinguishes well-founded, ... semantics. <sandroPost> scribeNick: AdrianP csma: document publication plan ... how many documents; which ones; why, what dependencies, etc <sandro> mk: 1. arch with fallback + extesnibility stuff 2. two for logic michael: ideally architecture document (fallback, extensibility), logical framework, production rule framework ... Framework for BLD and PRD <Harold> <Harold> shuffled material from BLD. michael: seperate documents, e.g. ARCH document, CORE framework, BLD <sandro> csma: rule of thumb -- different audiences == different documents. Michael: we would have very large documents otherwise ... signature, semantics etc are currently in BLD and should be moved csma: compatibility of dialects with OWL, RDF, compatibility of PRD to XML schema ... shall this be described in an extra document? chris: + different framework for PRD? chrisw: Arch could be split into different documents? michael: CORE is postponed after PRD csma: do we need a core for different dialects chris: interchange and overlap covered by Extensibility document? axel: principle of extensibility needs to be written in Extensibility document <AxelPolleres> As proposed earlier: <AxelPolleres> " Other dialects should reuse BLD and PRD wherever possible. Other dialects MUST agree with the semantics of BLD and PRD on the parts (of the abstract model) they share with BLD and PRD." sandro: as a user you are interested in the core (overlap) ... this overlap should be extracted and written down chris: Is Core is an instantiation of guidance how to interchange two dialects csma: Instead of having a Core could it be a profile of PRD and BLD? <Harold> The 'Core' overlap (based on the Condition Language) of BLD and PRD consists of the Pure Production Rules we had discussed early on and its extensions (e.g., by Naf, Bagof, ...). Sandro: intersections of dialects should be documented <AxelPolleres> chrisW said: Extensibility should define how to specify interchange between two non-subsuming dialects. (Q: Do you mean by defining fallbacks? in that case agreed.) <sandro> If there is a useful overlap, then it should be documented. Jos: Extensibility talks about extension of XML syntax ... Framework talks about semantic extensions Axel: Framework currently defines general notions of semantics, signatures Jos: purpose of framework? csma: example: PRD reused conditions of BLD, i.e. PRD points to BLD ... so it might make sense to take it out of BLD jos: e.g. signature are not used michael: signatures set the framework for extensions ... Framework creates the general framework how to create dialects by specialising ... Framework can evolve ... Framework is about logical extensibility <AxelPolleres> Suggestion for what the "Framework" is: <AxelPolleres> 1. Each RIF dialect MUST define a semantics (model-theoretic, proof-theoretic, operational in that order of preference). <AxelPolleres> 2. Principle of maximum reuse: Other dialects should reuse RIF endorsed dialects (currently BLD and PRD) wherever possible. <AxelPolleres> 3. Other dialects MUST agree with the semantics of RIF endorsed dialects (currently BLD and PRD) on the parts (of the abstract model) they share with BLD and PRD. sandro: fallback mechanism is standard for RIF chris: Extensibility and Framework need to be understand by dialect designer <sandro> every fallback "programming language" has to be implement in every RIF consumer. ." <GaryHallmark> Scribe: GaryHallmark <scribe> ScribeNick: GaryHallmark not sure about the agenda item, but we are discussing public comments dicussing comments from Peter Patel-Schneider why 3 different kinds of atomic formulae? this will be addressed in the semantic web compatibility doc why is new treatment of data values needed? josb: why different from rdf and owl ... difference is rdf/owl use data maps, but rif has fixed list ... rif does not use data mapping michael: leaving data types open could be dangerous for rif only 1 or 2 attendees claim to understand this distinction chrisw: should this be an issue - fixed v. open data types michael: how can RIF semantics handle open data types negotiated out of band? josb: entailment checking would use out of band info, too chrisw: need an action to determine difference in type handling and justify if there is a difference <sandro> ACTION: jdebruij to explain in writing the difference in 'treatment of data types' mentioned in PFPS's comment [recorded in] <rifbot> Created ACTION-362 - Explain in writing the difference in \'treatment of data types\' mentioned in PFPS\'s comment [on Jos de Bruijn - due 2007-11-12]. why is there a symbol space for IRI identifiers? <sandro> MK; to increase uniformity. <sandro> ACTION: kifer to make a wiki page for replying to PFPS and start drafting reply, including explain why the symbol space for IRIs. [recorded in] <rifbot> Created ACTION-363 - Make a wiki page for replying to PFPS and start drafting reply, including explain why the symbol space for IRIs. [on Michael Kifer - due 2007-11-12]. treatment of slotted formulae is "unusual" chrisw: ask Peter if it is a problem condition language is very complex josb: 3 frame formulas, slotted predicates, etc. harold: it's not "complex", it's "rich"! sandro: could be simpler chrisw: some of these comments don't need a response why worry about interpretations where IP is not a subset of IR? <sandro> ACTION: jdebruij to respond to '"Why worry about interpretations where IP is not a subset of IR", explaing how keeping the option of RDF Entailment open. [recorded in] <rifbot> Created ACTION-364 - Respond to \'\"Why worry about interpretations where IP is not a subset of IR\", explaing how keeping the option of RDF Entailment open. [on Jos de Bruijn - due 2007-11-12]. <sandro> Jos: you can no longer have ill-types literals in RIF. <sandro> ACTION: jdebruij to draft reply to PFPS about il-typed-literals and make sure Chris likes it [recorded in] <rifbot> Created ACTION-365 - Draft reply to PFPS about il-typed-literals and make sure Chris likes it [on Jos de Bruijn - due 2007-11-12]. josb: latest draft ties rdf:type and rdfs:subClassOf to # and ## no actions on RIF-OWL compatibility why are xsd:date, boolean, float excluded but xsd:int are required? Why is xsd:integer the only derived datatype? csma: not really done on purpose what is the arity of #Imadethisup discuss implementation plans who plans to implement bld? axel: will not implement function symbols <sandro> Kifer, Adrian, Harold, Igor, Axel--partial, Sandro <sandro> kifer: in and out translators for XML, ... I don't know, toward end of 2008. If only presentation syntax then flora-2 already implements all of this. <sandro> sandro: i certainly plan to implement translators between XML and presentation syntax, .... but PS isn't real. <sandro> kifer: I doubt anyone can really implement equality. <sandro> csma: implementation means that you can produce and consume RIF BLD documents. <sandro> kifer: some substitutions are very expensive to do. sandro: python translator for N3 and prolog <AxelPolleres> axel: I would implement what can be handled by our engine, ie. datalog, w/o equality, but I could use RDF as data and would try to look into NAF extensions based on that. adrian: translate to/from prova (an iso prolog language) <sandro> ? <sandro> 2-3 months <sandro> prova == prolog + java <sandro> adirian: I'd use XSLT <sandro> Harold: OO-jDREW <sandro> Harold: I'd also use XSLT <sandro> Harold: estimate completeion end of 1Q08 adrian: would wait for stable bld spec <sandro> Mike: Did SWRL to BLD, XSLT. <mdean> <mdean> next step: validate output against just-published XSD <sandro> Igor: we're mostly interested in producing RIF rules, from our machine learning systems. we need builtins, lists, NAF, ... first. igor: leverage another rif consumer to execute what we produce <sandro> Igor: we'd want to use consumer, based on Flora or Prolog. It should take a couple months, after BLD is really fixed -- not at this stage. <sandro> Axel: I want a hook in the language for referring to RDF data sets.... I want something quick based on the presentation syntax. <sandro> Axel: ~2 months, when we have RDF reference mechanism. <sandro> Chris: implementor's breakout tomorrow.... <sandro> PaulVincent, Gary, Stella, Bob === waiting for PRD <sandro> Jos - academic, at the moment. <sandro> ilog == prd as well. <sandroPost> scribeNick: Harold csma: ... walk-thru explaining assumptions etc. ... Formal description based on Claude Kirchner et al.'s rewriting approach. (from project MANIFICIO) MichaelK: You have semantics in two places, one not used. csma: maybe one to be removed. Gary: Hard to discuss semantics before having any syntax. csma: Occasionally useful. Gary: OK, on the level of deciding model-theory, operational, etc. semantics. csma: Removed pattern language section. ... Reuses condition language. Jos: Thought you dont support function symbols? ... Actions in the 'head' (then-part) of rules. But action lang. extends condition language. csma: Two actions: Add/Remove a fact. ... Not an extension of Condition language, but new lang. on top of it. ... OK, but only first draft. ... Copied from BLD: 1.3.2 (Why is it a Web lang., ...) ... Diff from BLD: Structural diagrams and XML for syntax. No presentation syntax. Gary: Why none? csma: Not needed. MichaelK: But it's on the first page. Gary: PR vendors will want to see a presentation syntax. To discuss what a given snippet means. csma: Starting from the botton. Jos: Another use of pres. syn.: didactic, introductory reasons. csma: Audience for PRD more developers than academics, so more interested in XML. ... E.g. Mark Proctor said: "... just give me the XML syntax involved..." ... Took BNF syntax principles from WSDL. ... E.g. defined_element contains BNF (comment?) ... Condition lang. with a few modifications: simplifications such as removing some things. ... Classification only uses Membership. Frame only with one object, one slot (deal with the rest in the XML syntax as syntactic sugar). Gary: ALso see it as too general in BLD? csma: Yes. Gary: Let's resist temptation to try in PRD to fix issues of BLD. csma: TERM Gary: If you get rid of Uniterm then you dont have nested functions, which are not present in production rule systems. Sandro: For calls you dont want to distinguish if they are builtins or user-defined. <AxelPolleres> If we don't syntactically distinguish built-ins, I am a bit worried about extensibility, honestly. MichaelK: builtins in both head and body? <AxelPolleres> Why should a thing in one dialect be a logical function and in the other a builtin??? THat would be the result of not syntactivally distinguishing them, or no? csma: Yes, but no problem since there are no function symbols. <sandro> Not in one dialect vs another --- one *implementation* vs another. <AxelPolleres> same with interpreted functions. csma: Tried to be compliant with PRR. <sandro> Like, append/3 can be a built in or a library function. <AxelPolleres> or a logical function :-) <sandro> library function == logical function, as I meant it. csma: This community is more development oriented. That's why added more than absolutely necessary. <AxelPolleres> ok, so, how to distinguish? each dialect needs to specify which are built-in (ie. fixed interpretation) and which are logical (ie. variable interpretation) functions/predicates? csma: NonMonNot is neutral with respect to earlier discussion about negation. <AxelPolleres> and obviously the symbol spaces need to be disjoint for those. csma: TERM like in BLD -- could become a substitution group. ... Const copied BLD part about symb. spaces. .] csma: Keep 'type=" ... IRI ..." <AxelPolleres> "NonMonNot is neutral with respect to earlier discussion about negation." ... If we would have had (general) NAF in the condition language, would you have reused it? <sandro> actually, this probably violates No-Language-Conflicts.... <sandro> this == my side conversation here about append/3. <AxelPolleres> yes, that is what worries me, sandro. csma: Even inlined examples need no pres. syntax: <Const type="SYMSPACE">LITERAL</Const>. <sandro> Yeah, I think you're right, Axel. csma: Different communities -- different ways to write rules. Gary: Dont think this at all. Only want to see 'deltas' w.r.t. BLD, not need to learn pres. syn. from scratch. csma: I thought people from ILOG, ORACLE, etc. will directly start to read PRD (dont need to read BLD documents). <AxelPolleres> As for the nonmonnegation... I, from an abstractModel point of view, ask myself is NAF a subclass of NonMonNegation or the other way around, or are they completely unrelated? <AxelPolleres> (conceptually, they are obviously related...) Paul: Potential use case: could use logic or production rule approach. Gary: Perahps it was a historical accident that business users chose prod. rules, not logic rules. csma: Gary, I agree that BLD and PRD docs should LOOK the same. ... Would argue BLD should be restructured like this, by components (not as a whole), would make it easier for developers. Gary: Better to be common than to be slightly better: Lets not try to do BLD changes in PRD. csma: If it makes sense as now in PRD, then the BLD team will take it over, otherwise not. ... Point is NOT to compete between BLD and PRD. ... Only the presentation/structure of the PRD document seems to be useful. Jos: Concern that a lot of material of this PRD draft is a repetition of what's already in BLD. But it should only be in ONE place. csma: Yes. Jos: I thought we dont want to have negation in Phase 1. Now it's in PRD. Sandro: OK for exploratory purposes. Gary: Until we dont have such extensions of the Condition lang. we should ask them to add them, not invent them in PRD. Rather PRD should move on to formalizing Actions. Sandro/Axel: Which kind of negation is appropriate for production rules. <AxelPolleres> sandro, we don't have subclassing in XML, but we do have it in RDFS :-) Harold: Granularity of reuse better when there are sublanguages of the Condition lang. <sandro> csma: I really want a common component library, and maybe a common core. BLD and PRD should draw from those, but not have to be exactly the same. csma: Library of constructs may be advantageous. <AxelPolleres> I think, which I said already some times admittedly: s/ common Core <AxelPolleres> /common abstract model/ AdrianP: Many Reactive lang. have such a library. <AxelPolleres> that would keep the "component library" somewhat "dialect independent" csma: Uniterm: We cannot say informally only in the spec that the arg order matters. .... <AxelPolleres> At least by subclassing , you can define some trivial fallbacks. csma: That this is not (only) a model-theoretic semantics is even clearer for the And: works also for operat. semantics. <sandro> Attendance note -- observing for the afternoon has been Carine Bournez, (The RIF meeting is listed on the conference schedule as being open to observers, by accident.) <AxelPolleres> i.e. if a dialect supports the conceptual superclass semantically, the default fallback would be replacing the special with the more general one. MichaelK: You have to be careful where you are talking formally and where informally. ... We prioritized model-theor., then fall back to operational, then to procedural. ... But this is none of these, it's mixed. csma: It's formal (although written in English). ... Define when a condition is true. ... then execute the actions. MichaelK: OK, but it's kind of confusing. Suppose I read this, but wont understand. <sandro> AxelPolleres, so the subclass relationships in the abstract model automatically generate some fallback substitutions? My guess is that's reasonable and somewhat helpful, but I'm not sure. csma: This is why put sem on top. ... Dont see why this is not formal. MichaelK: First do syntax, then semantics. <AxelPolleres> that would be the idea... also not 100% sure, needs some dialect examples, which I still owe, admitedly. MichaelK: E.g. it's not interpreted as a function from to, everything is regarded as matching. <AxelPolleres> ... but it sounds appealing to try to me csma: The pattern matching mechanism gives me the function. Chris: What do you regard as the interpretation function? csma: A mapping to a domain element. ... What does pattern matching do? Tells you what's the interpretation! ... Tells you what's and what's not in the interpretation. ... But what I get from discussion: This is confusing. Not the right way to put it in a spec. ... However, the earlier approach also seemed confusing. ... Wanted to keep it as close to BLD as possible. Harold: Much better than earlier version. MichaelK: What's wrong: You say here's a program, I determine from a procedure what the meaning is. The wrong way round. csma: Perhaps misunderstanding. ... Removed pattern section. ... Actions have to be worked on. ... Gary's point is valid that top-level of Rule syntax is different unnecessarily from BLD. ... But this is because BLD is not frozen yet. ... Could perhaps just one CONDITION rather than two. Historical from earlier patterns and the 'else' parts. But it may be good to keept both. Restart at 4PM. <StellaMitchell> ScribeNick: StellaMitchell csma: we didn't consider carefully which xsd datatypes to pick Chris: Yes, we settled on a set during one of our meetings ... (projecting list of xpath functions and operators) jos: will these be predicates or functions in BLD? Chris: do we have notion of builtin as external call? are all predicates, all functions ? Harold: telecon with DARPA demo group - we chose a fixed interpretation for builtins ... the point is - we have equality in RIF mk: if we assume URI's identify functions, we can Harold: mode declaration of functions ... for now, it would be very nice to have builtins as functions axel: for predicates, it is not so clear what is input and output <sandro> binding patterns == modes <sandro> Harold: non-deterministic builtins Harold: (something is) then you would have non-deterministic functions Sandro: trying to clarify between functions and predicates ... you might have extension that has more builtins (that the dialect it extends) <Harold> Because in RIF we have Equal, we can finally come back to builtins being functions, not (artificially) relations. Advantage: uniform mode declarations. Sandro: can lead to a language conflict (syntax has different meaning) Chris: Also, datatype extensibility is an open issue <sandro> Sandro: It should be a syntax error to use a builtin that's not in some dialect. Chris: I don't think it makes sense to assume the list of builtins is fixed Jos: xpath uses namespaces, but we use curies... csma: functions as relations, means uniterms of the atomic kind? ... so the only uniterm of the term kind are logical functions mk: asking about xpath urls, namespaces, what is behind it? axel: reads definition from xpath spec Sandro: they are available to users as other symbols <Harold> For example, NumericAdd has uniform mode In x In -> Out as used in ?Result = 23 + 17 or <Equal> <Var>Result</Var> <NumericAdd><Const>23</Const><Const>17</Const></NumericAdd> </Equal>. <AxelPolleres> Chris: back to questions - builtins as relations or external calls? csma: what is the difference? sandro: diff between interpreted and logical functions - for interpreted, you have to call some other piece of code to evaluate it csma: Allowing user-defined interpreted functions? sandro: that wouldn't allow for extensibility csma: producer and consumer have out of band agreement on what it is ... function names are iris, so if you can't recognize it, you don't handle that external functions sandro: no, in that case it could be a logic function csma: I can't think of any concrete case where it would be a problem sandro: append - would be reasonable as either Chris: what is the status of functions in BLD ... how does a user define a logic function? Gary, MK: they just use it <sandro> "logic functions that are term constructors" vs "evaluable" or "interpretable" functions, ....? <Harold> In my example, NumericAdd as a relation would have hetereogeneous mode Out x In x In. sandro: an "eval" function <sandro> "external call", "procedural attachment", ... sandro: it's a little confusing that an external call is a builtin ... issue is, if you can tell from the syntax whether it is a builtin or a logical function Chris: is anyone opposed to having a special syntax to distinguish? <Harold> We already can define functions using ATOMIC Equality facts based on ATOMIC ::= Uniterm | Equal. csma: if we want fully stripped xml syntax, we need elment mk: builtins are supposed to have a uri, and in semantic web uri already has a meaning, so from that point of view we don't have to say anything sandro: gives example showing it is more complicated mk: uris are supposed to be self-denoting sandro: op:numeric-add is self denoting Chris: is it possible to define syntax and that would indicate which it is? <Harold> We can user-define as an equational fact fatherOf(Mary) = John or <Equal> <Uniterm><Const>fatherOf</Const><Const>Mary</Const></Uniterm> <Const>John</Const> </Equal>. mk: no, I don't think so sandro: dereference argument and get documentation and links to downloads ... but from point of view of semantics, it is just an opaque string that denotes a function Chris: syntax that denotes builtins, and spec says which ones have to be supported ... and people would be able to add more mk: we can't control what is at the URL of fn:compare sandro: uri goes to the text description <AxelPolleres> <Uniterm> vs <Builtinterm> Chris: advantage of having an explicity syntax is that it is open - people can add more ... who thinks we should special syntax to identify builtins? (people on both sides, there is disagreement) Harold: in lisp there is a uniform way to call user defined and builtin functions Chris: but in lisp, it is not open BobM: ?? axel: you are saying builtin terms must always have fixed interpretations <sandro> "ExternalUniterm" mk: I think we can make it extensible Chris: but you are signalling it syntactically, like with defun mk: I would use "require" (the list of bld functions) sandro: that is not extensible mk: we only care that a symbol is used consistently ... if not, things are broken anyway sandro: "append" example, where it could be either builtin or logical function mk: but it would have different uris for different uses axel: what if the builtin is in the head (conclusion)? Chris: we can discuss that later, after we resolve this questions ... if we syntactically mark builtins, it is very clear how it would work ... but some people here think it's cleaner to not have to syntactically indicate it ... proponents of not syntactially marking can try to come up with a suggestion, maybe in a break out tomorrow <sandro> Chris: Result --- default is External Calls In Syntax; people who want something else (including him) need to come up with a proposal. Chris: that group will come up with a proposal or agree to the other method <Harold> Looking at <Harold> <Uniterm> <Harold> <op><Const type="rif:local">fn:subtract-dateTimes-yielding-dayTimeDuration</Const></op> <Harold> <arg><Var>deliverydate</Var></arg> <Harold> <arg><Var>scheduledate</Var></arg> <Harold> <arg><Var>diffduration</Var></arg> <Harold> </Uniterm> Chris: metadata ... meta means "after" ... what metadata do we need? <Harold> the "fn:" in fn:subtract-dateTimes-yielding-dayTimeDuration shows that we have an external call here. Chris: which syntactic terms can have metadata? <Harold> However there are some ways to mark this more explicitly as a builtin call: Sandro: and other questions about metadata: is the metadata fixed for a given dialect? Chris: you mean is there a finite set of preset tags? sandro: yes PaulV: is it extensible? <Harold> * Use <Const type="rif:builtin"> Sandro: or rather, if you want a new metadata item, do you need to make an extension? Gary: can you always ignore the metadata and get the same result? <Harold> * Use <Const type="rif:local" builtin="yes"> PaulV: what is an example of metadata that cannot be ignored? <sandro> csma: is rule priority metadata? <sandro> csma: it affects semantics. jos: if you refer to a datamodel using metadata, and that datamodel affects the semantics Sandro: this is why I advocate having no metadata Adrian: example of using RIF document as data <sandro> no metadata mechanism --- just more extensions. Chris: do we want to talk about a class of metadata that cannot be ignored? csma: I think Sandro had a good point. We don't call it metadata, just data <Harold> * Both of the above are much better than using a totally different calling method such as <ExternalUniterm>, because the transition from user-defined to builtin should be kept as simple as possible (see above discussion about lisp and prolog). Sandro: I suggested pushing this off until we understand extensibility better Chris: It should not be that you need an extension to add author metadata csma: isn't metadata the things that don't have to do with semantics mk: dublin core PaulV: and that (dublin core) would be a good starting point for RIF jos: we shouldn't have a fixed set of metadata - it's just a set of attribute value pairs sandro: so properties are iris and values are strings? mk: sandro, what did you want? sandro: import dublin core wholesale <Harold> I think metadata should be non-prescriptive annotations, i.e. not change the normative semantics of a ruleset. <PaulVincent> mk: how does owl do it? jos: they say you can use any metadata you want, as long as it is an annotation property Chris: I think that agreeing on specific metadata tags should not be part of dialect defintion - just say how to include metadata ... who thinks the set of metadata for a dialect is fixed? ... strawpoll csma: can we have both? a required set and a way to add more? Chris: 3 proposals: ... 1 fixed ... 2 open <Harold> Metadata thus act just like comments from the perspective of the normative semantics, although non-semantics-preserving processing such as in AdrianP's author-filtering example will be possible. Chris: 3 required, plus a way to add more sandro: I object to passing a resolution now because we hav not settled on our extensibility mechanism official count: fixed: 1, open:4, mixed: 6 Chris: We will put on hold the question of where we can put metadata (which elements to attach it to) <sandro> Chris: Non-ignorable metadata is part of a dialect. I think we have consensus. Chris: non-ignorable metadata is part of a dialect definition bobm: i'd say non-ignorable metadata is not metadata <sandro> Sandro: So the question is whether to have an annotation mechanism for ignorable content. <sandro> Gary: 'this rule is effective during the month of november' --- is that metadata? Chris: the mechanism we are talking about is the annotations that don't affect the semantics ... ( the ignorable metadata) <Harold> +1 to bobm <sandro> The issue here is whether to provide a syntactic mechanism for including structured annotations which have no effect on the semantics. And if so, how? <sandro> (Avoids the term metadata) <sandro> general consensus on that issue statement. <PaulVincent> Paul: proposes some use cases for metadata eg RIF for execution won't need metadata eg RIF for rules mgmt will find metadata significant <sandro> Sandro: I'm not convinced we need this, yet. I think light-weight extensions might cover these use cases. <mdean> scribe: Mike Dean Chris: we will discuss it more after we settle on the extensibility mechanism <mdean> scribenick: mdean ChrisW: overview of test cases in WebOnt WG entailments for each operator resolution of issues often documented as test case <Harold> ChrisW: RIF could adopt this methodology Sandro: consistency tests too? <sandro> Agreement -- we need Inconsistency and Consistency tests too. csma: have people submit cases where they think there is ambiguity ... what is the form of these tests? example test case in Stella's email above structured annotations wrapping OWL documents premise in one file, conclusions in another <josb> owl example: message uses example URIs - OWL tests were real Sandro: likes .hrif for presentation syntax ... Jeremy Carroll wrote nice software to manage test cases for WebOnt ... recently asked to resurrect this for OWL WG ... Jeremy and Jos deRoo just did it Adrian: need separate query language? ChrisW: not needed - just specify in manifest ... can we leverage JUnit? Sandro: let's wait for a few weeks on OWL WG ChrisW: need time limit Sandro: ... unless someone else volunteers ... could still submit a test in natural language in email or Wiki page josb: good to link to examples in document csma: some tests should also be linked to use cases Sandro: group seems to be comfortable mirroring what OWL did csma: what about testing implementations? Sandro: WebOnt generated table of tests by implementation, showing each was handled by at least 2 csma: could be a way to test that specification meets requirement, i.e. was implementable Sandro: doesn't ring any bells Sandro: prefer conformance csma: yes/no test or degrees of conformance? ... define profiles/levels ChrisW: based on test cases that implementation passed, not a formal thing josb: normative OWL test cases section on conformance ... syntax and consistency checkers parking passes distributed <Harold> We need to make entailment ( |- ) relative to the logic we are in. Eg in FOL p(a) :- q(a) |- ~q(a) :- ~p(a), but not so in Horn logic. Sandro: strawman conformance test: phrase as some sort of ACTION: this software does this ... csma: prefer one level of compliance - must implement everything ... then could have compliance for specific extensions Michael: most implementations probably won't implement full equality ... OWL has not been fully implemented either josb: Pellet isn't complete with nominals Sandro: unfortunate that we don't have complete OWL implementations yet Michael: same with SQL, thousands of pages of spec ... don't exclude something just because it's hard to implement csma: compliance is like conformance but not quite :-) ... want to promote adoption, motivate comfortant implementations Michael: could be conformance level that doesn't include equality csma: could end up with so many dialects and levels that OWL looks simple <Harold> The paramodulation calculus is a refutational theorem proving method for <Harold> first-order logic with equality, originally presented in Robinson &Wos (1969) <sandro> Chris: Issues 1 - whether to have levels of conformance (vs just boolean) per dialect <sandro> Chris: Issues 2 - whether to have lowest conformance level match implementations (eg full equality). bob: many features aren't implemented or implementable with reasonable time ... interoperability is most important ... don't define logic that can't be implemented <sandro> Chris: 4 square, levels vs expected. csma: boolean might not require equality profiles not the same as levels Chris: boolean per dialect Michael: profiles are kinds of dialects straw poll <sandro> Chris: Levels + Expected: 0 <sandro> Chris: Booleans + Expected: looks like everyone <sandro> Chris: Boolean + Not-Expected -- Michael <sandro> Michael: There will be useful implementations which don't conform. <Harold> The axioms for the equality relation need not be built into RIF (without it's easy to implement), because they can be 'loaded' as another ruleset: Chris: does everyone assume profiles? 6 of N-1 thought they were voting for profiles <sandro> Voting for profiles: 6, Sandro: voting for compliance being something that's implementable Chris: BLD - equality not a profile? Sandro: change BLD to not include equality csma: current BLD becomes an extension <sandro> Sandro,Bob: define BLD as something that's implementable. +5 for Sandro <sandro> 5 people agreeing with that view. csma: same for PRD ... extensions could be harder to implement Sandro: profile vs. extension is marketing difference csma: important for adoption Sandro: same for equality and negation Chris: plenty of SQL operators are partially implemented ... nobody needs the full implementation csma: must jump start implementations Chris: not ready for resolution, but consensus that we want boolean tests for conformance with some disagreement over what to test Michael: could also use test cases Chris: industry likely to do this, publish their test case results Sandro: BLD querying system vs implementation Chris: do we need issue regarding equality? ... always boils down to test cases <sandro> group of five who wants BLD changed to remove quality, so that it's practical to implement it fully <sandro> ACTION: Christian to open issue about removing equality from BLD because it's not so practical to implement. [recorded in] <rifbot> Created ACTION-366 - Open issue about removing equality from BLD because it\'s not so practical to implement. [on Christian de Sainte Marie - due 2007-11-12]. adjourned
https://www.w3.org/2005/rules/wg/wiki/F2F8/RIFMinutes5Nov07.html
CC-MAIN-2017-04
refinedweb
7,906
55.64
Opened 2 years ago Last modified 1 year ago Using mysql5.0 and python2.4, the maxlength of a CharField is three times as big as the varchar column's definition says in the table. Huh. Confirmed on Python 2.4, Mysql 5.0.45, @6851 Models.py says this: from django.db import models # Create your models here. class Fudge(models.Model): snork = models.CharField(max_length=10, blank=True) The table is created in MySQL like so: mysql> describe t5725_Fudge; +-------+-------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------+-------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | snork | varchar(10) | NO | | | | +-------+-------------+------+-----+---------+----------------+ 2 rows in set (0.03 sec) & inspectdb gives this - class T5725Fudge(models.Model): id = models.IntegerField(primary_key=True) snork = models.CharField(max_length=30) class Meta: db_table = u't5725_fudge': Sorry, I meant charset above where I said collation. My bad.. By Edgewall Software.
http://code.djangoproject.com/ticket/5725
crawl-002
refinedweb
141
72.12
It is possible to have the "optimize usings" feature of code cleanups just remove unused using statements? It seems to also shorten existing using statements, which I don't want. Thanks! It is possible to have the "optimize usings" feature of code cleanups just remove unused using statements? It seems to also shorten existing using statements, which I don't want. I would really like this feature. Optimize usings can be too aggressive in the steps it takes, which tends to upset my co-workers. I suggest that imports optimization should have additional options: checkbox: remove unused using statements checkbox: sort using statements alphabetically checkbox: group using statements by root namespace (this would interact with the setting for how many lines between using groups, so may not be necessary) Radio buttons: Leave using directives in existing scope Move using directives to outtermost scope Move using directives to deepest scope Move using directives matching namespace inside namespace I admit that the last item is a bit weird -- this is a pattern my co-worker uses: using System.A; using System.B; using ThirdParty.A; using ThirdParty.B; namespace MyCompany.Foo { using Bar; ... (Where Bar is a shortening of MyCompany.Bar) Even if the last option was not implemented, simply having the ability to "Leave using directives in existing scope" would allow me to run optimize usings across our entire codebase. If the last option were implemented I would want any using directives that were moved to a deeper scope to be shortened (or not) according to the "Prefer fully qualified using name at nested scope" setting. Thanks, Dave +1 You should open a feature request. :)
https://resharper-support.jetbrains.com/hc/en-us/community/posts/206678335-Configuring-optimize-usings-
CC-MAIN-2020-24
refinedweb
274
54.73
Team B - OOP344 201: Benson Wong - Task: Create prototypes and empty definitions for all classes - To be completed by: - Status: Complete - CButton - Member: Arlene Lee - Task: Code cbutton.h and cbutton.cpp - To be completed by: - Status: In Progress - CValEdit - Member: - Task: Code cvaledit.h and cvaledit.cpp - To be completed by: - Status: In Progress - CCheckMark - Member: Benson Wong - - Complete - The comment should include your github id, date, and time in the cframe.h file - Push the final changes to github Meetings November 13, 2013 - Media Pod 4 - Went over release 0.4 as a team over Skype and in the study room, will decide specific member roles and deadlines to finish each task on Monday, November 18, 2013 October. -. - Avoid placing using directives and declarations in header files, as this might lead to namespace conflicts since we do not know in which order a header file will be included within any other file (source: Chris Szalwinski, BTP300 readings on namespace design considerations) Project Marking Percentage Group work: 40% Individual work: 60% + ----------------------- Total: 100% { // Else statement will be on a newline after the If control structure cout << "Get out." << endl; } return 0; }
https://wiki.cdot.senecacollege.ca/w/index.php?title=Team_B_-_OOP344_20133&oldid=102127
CC-MAIN-2020-34
refinedweb
192
58.92
The Builder Pattern is a creational Gang of Four (GoF) design pattern, defined in their seminal book Design Patterns: Elements of Reusable Object-Oriented Software, in which they presented a catalogue of simple and succinct solutions to commonly occurring design problems. The pattern is useful for encapsulating and abstracting the creation of objects. It is distinct from the more common Factory Pattern because the Builder Pattern contains methods of customising the creation of an object. Whenever an object can be configured in multiple ways across multiple dimensions, the Builder Pattern can simplify the creation of objects and clarify the intent. Let's explore the Builder Pattern and how developers can use it to construct objects from components. You may have already seen that the Factory Pattern returns one of several different subclasses, depending on the data passed in arguments to creation methods. We'll now learn that the Builder Pattern assembles a number of objects in various ways depending on the data. Advantages of the Builder Pattern - The builder pattern enables developers to hide details of how an object is created - The builder pattern enables developers to vary the internal representation of an object it builds. - Each specific builder is independent of others and the rest of the application, improving Modularity and simplifies and enables the addition of other Builders. - Provides greater control over the creation of objects. The builder pattern is similar to the Abstract Factory Pattern in that both return classes made up of a number of other methods and objects. The main difference between the Builder Pattern and the Abstract Factory Pattern, is that the Abstract Factory Pattern returns a family of related classes and the Builder Pattern constructs a complex object step by step, depending on the data presented to it. Builder Pattern in Unit tests The builder pattern is a popular pattern to use in Unit tests, in fact one of my favourite tools to use in Unit Tests is Nbuilder - A rapid test object generator, which if you read the source code also provides a great example of how to implement the builder pattern. In his book Adaptive Code Gary Maclean Hall states the builder pattern is useful for encapsulating and abstracting the creation of objects, and provides an example of using the builder pattern to help clarify the intent of unit tests, by assisting to eliminate any unnecessary arrange code. Example Builder Pattern. Contents Software Design patterns are typically categorised into three… In this example, we are going to implement a very simple Builder Pattern and use it to create a Person class to contain some attributes to describe a person public class Person { public int Id { get; set; } public string Firstname { get; set; } public string Lastname { get; set; } public DateTime DateOfBirth { get; set; } public Gender Gender { get; set; } } You may notice that we make use of an Enum to contain the value of the gender. public enum Gender { Male, Female } There is nothing all that complicated about the class, it's a simple POCO class. We can now develop our Builder class, which again we will keep simple to help illustrate the point. The builder class will basically return the object in a string format. public class Person { public int Id { get; set; } public string Firstname { get; set; } public string Lastname { get; set; } public DateTime DateOfBirth { get; set; } public string Occupation { get; set; } public Gender Gender { get; set; } public override string ToString() { return $"Person with id: {Id} with date of birth {DateOfBirth.ToLongDateString()} and name {string.Concat(Firstname, " ",Lastname)} is a {Occupation}"; } } The builder class in its simplest guise just a series of name constructor methods with arguments, you'll notice that they always return an instance of the class. The final method on the builder class is Build method will return the completed object. By convention this method is typically named Build or Create or something similar. public class PersonBuilder { private readonly Person _person; public PersonBuilder() { _person = new Person(); } public PersonBuilder Id(int id) { _person.Id = id; return this; } public PersonBuilder Firstname(string firstName) { _person.Firstname = firstName; return this; } public PersonBuilder Lastname(string lastname) { _person.Lastname = lastname; return this; } public PersonBuilder DateOfBirth( DateTime dob) { _person.DateOfBirth = dob; return this; } public PersonBuilder Gender(Gender gender) { _person.Gender = gender; return this; } public PersonBuilder Occupation(string occupation) { _person.Occupation = occupation; return this; } public Person Build() { return _person; } } We can now make use of our Builder to create a person as follows. class Program { static void Main(string[] args) { var person = new PersonBuilder() .Id(10) .Firstname("Gary") .Lastname("Woodfine") .Gender(Gender.Male) .DateOfBirth(DateTime.Now) .Occupation("Freelance Full-Stack Developer") .Build(); Console.WriteLine(person.ToString()); Console.ReadLine(); } } We build the object by instantiation the PersonBuilder then adding the properties, then the final method we call is the Build method. We then simply call the ToString() method to write out our values. Using the Builder Pattern, we can avoid using large constructor methods to provide all the required parameters for constructing our object. Large constructor methods lead to unreadable and difficult to maintain code. It is possible that there may not always be the need to supply all arguments in constructor methods because in all probability they won't always be needed. In the above code, I intentionally introduced a code smell, in the ToString(), you'll notice there is a lot of string interpolation and even additional concatenation. I primarily because I wanted to highlight how the .net core makes use of the builder pattern. We can make use of the StringBuilder class, StringBuilder prevents having to recreate a string each time you are adding to it. Using the String class in C# means you are using an immutable object, but StringBuilder is much faster in most cases since it's not having to create a new String each time you append to it. We can now refactor our ToString() method as follows. public override string ToString()=> new StringBuilder() .Append("Person with id: ") .Append(Id.ToString()) .Append("with date of birth ") .Append(DateOfBirth.ToLongDateString()) .Append(" and name ") .Append(Firstname) .Append(" ") .Append(Lastname) .Append(" is a ") .Append(Occupation) .ToString(); We use the StringBuilder to create the string. You'll notice, that even though I said by convention you could use the Build or Create to define the method that will return your object, but you don't really need to rather you could opt for another name, in the case of StringBuilder it is ToString() In the above example, we have implemented a simple builder pattern, however, it probably isn't easy to determine why this actually provides any benefit to developers. After all, from this simple implementation, you might be thinking but surely we could just simply use C# object initialisation and get exactly the result. var person2 = new Person { Id = 10, Firstname = "Gary", Lastname = "Woodfine", DateOfBirth = DateTime.Now, Occupation = "Freelance Full Stack Developer", Gender = Gender.Male }; The problem with this approach is that it is vry similar to passing arguments to a function, which inadvertently adds complexity to understanding the code. The ideal number of arguments for a function is zero (niladic). Next comes one (monadic), followed closely by two (dyadic). Three arguments (triadic) should be avoided when possible. More than three (polyadic) requires very special justification – and then shouldn’t be used anyway. There will invariably be situations when instantiating objects that you will need to call a function to do something to provide a value to that object. i.e. Generate a new ID which may need calling out to function to get a newly created Id value etc. It is in situations like this that make the Builder pattern a much more viable option, and as defined in Philosophy of Software Design we are able to pull complexity downwards. When developing a module, look for opportunities to take a little bit of extra suffering upon yourself in order to reduce the suffering of your users. John Ousterhout - Philosophy of Software Design Fluent Builder Pattern implementation The standard definition the Builder pattern separates the construction of a complex object from its representation so that the same construction process can create different representations. The Builder pattern provides step-by-step creation of a complex object so that the same construction process can create different representations to the Builder class. It's a subtle difference. The Builder pattern is applicable when the algorithm for creating a complex object should be independent of the parts that make up the object and how they are assembled and the construction process must allow different representations for the object constructed. If we consider a person object and think of all the different variations we could expect to create a person object. For instance, how do we deal with married woman? Considering in some cases we may need to take into consideration her maiden name. It soon becomes clear that there are all manner of rules and variations we need to consider when building a person object. All manner of varying combinations and additional properties we will need to include. Rules that may not be easy or convenient to incorporate in object initialization. We will also need to have the flexibility and adaptability to change or add additional methods in future developments. In our first implementation of builder for a fluent interface of the Person class, we implemented the builder with no strings attached. We have not enforced rules for the order of assignment. The code is simple and easy to understand but it does leave the builder class open to misuse. We can implement the basic expression builder with method chaining in C# .NET. We're going to refactor our builder slightly to incorporate a new method Create which will accept Firstname and Lastname argument but more importantly we are going to remove the creation of the Person class from the constructor and into Create method. It also doesn't make much sense providing and Id to an object on creation, it is highly likely that a new Id should be created when the object is created. So we'll also remove the Id parameter from the Builder. Implementing a fluent interface is a relatively straight-forward task that can be done through the use of method chaining. Method chaining is simply a set of assignment methods that return itself.. public class PersonBuilder { private Person _person; public PersonBuilder Create(string firstName, string lastName) { _person = new Person(); _person.Firstname = firstName; _person.Lastname = lastName; _person.Id = Guid.NewGuid(); return this; } public PersonBuilder DateOfBirth( DateTime dob) { _person.DateOfBirth = dob; return this; } public PersonBuilder Gender(Gender gender) { _person.Gender = gender; return this; } public PersonBuilder Occupation(string occupation) { _person.Occupation = occupation; return this; } public Person Build() { return _person; } } We’ve implemented the Expression Builder pattern using method chaining. The class itself constructs a Person Build() method to obtain the completed Person class. Summary We examined the Builder Pattern and seen how useful it is too create complex objects. We also looked at an example of how the .net core framework itself makes use of the builder pattern to provide common functionality string building functionality. Discussion (6) Great article, thanks! I think that this example with 'Person' should be more complex, Currently PersonBuilder.cs methods just assign properties, and method build just returns Person entity, so in this example, more relevant (I guess) is to create person entity and assign properties, see dotnetfiddle.net/Hu5nNb. I understand that the idea of example if to show how to use 'Builder' pattern, but also I think it makes sense to show how pattern helps developers to design their code better, so I think it's better to show more complex example Anyway, Thank You! No worries. I understand where you're coming from, but also bear in mind that Complexity is a subjective and relative term. What, may be simple to you may be complex to others. So when devising a sample one has to err on the side of simplicity. In the article, I have provided links to more complex implementations of the Builder pattern implementations. I will be updating the article later with some examples of how to implement a Fluent implementations which may include further implementations. Hi Gray Thank you for the article. I have a small remark for the last example. If we want to 'lock' the builder in order to force using the 'Create' method, I think we should implement a private constructor, for the builder, and make 'Create' method static. In this way, we will be sure that we will have at any moment an instance of Person. Because right now, if I will call 'new PersonBuilder().Occupation(_something).Build()' it will fail because there's no instance for the '_person' yet created. Thanks Good luck. Thanks for the feedback. I will attempt to update the article to incorporate your input. Thanks I'd be interested in seeing how you implented the fluent aspe TS of the builder. I like the approach but not sure how to implement it, unless I'm missing something. Great article btw I'll try to update the article to include fluent aspects. Good idea!
https://dev.to/gary_woodfine/the-builder-pattern-net-core-49gj
CC-MAIN-2021-10
refinedweb
2,180
53
See also: IRC log ChrisWilson: The goal this morning is to go through the spec with an eye towards building a test suite MikeSmith: We talked about when the TAG was here, having a rational discussion about what parts of the spec can be split out ... Assess work effort for possible sections Hixie: I can take a action item to do that MikeSmith: We should focus now on the status part ... I can take on updating the annotations Hixie: What info do we want for a section? <DanC_lap> ah... found the annotations hacking I did; it's in MikeSmith: There is one section we should talk about right now <pimpbot> Title: html5/spec/ (at dev.w3.org) MikeSmith: 1.4.3 Relationship to XHTML 1.x Hixie: We are waiting from feedback from the XHTML2 WG Lachy: What were their complaints? Hixie: They didn't like it DanC_lap: We should find the email addressing their complaints <DanC> this one from Roland? <pimpbot> Title: Re: changes in HTML5 draft regarding XHTML1 from Roland Merrick on 2008-06-20 (public-html@w3.org from June 2008) (at lists.w3.org) MikeSmith: The initial objections were communicated privately to me <DanC_lap> in that 20 jun msg, he accepts the ball "I will put the subject on the agenda for our WG telecon. <DanC_lap> " MikeSmith: Originally they objected to language that has since been changed <Hixie> is the latest i could find <pimpbot> Title: Re: changes in HTML5 draft regarding XHTML1 from Roland Merrick on 2008-07-31 (public-xhtml2@w3.org from July 2008) (at lists.w3.org) <DanC_lap> "we will get back to you" -- Merrick 31 July <pimpbot> Title: Re: changes in HTML5 draft regarding XHTML1 from Roland Merrick on 2008-07-31 (public-html@w3.org from July 2008) (at lists.w3.org) <Lachy> The other messages from the XHTML2 WG: <Lachy> <Lachy> <Lachy> <pimpbot> Title: Re: changes in HTML5 draft regarding XHTML1 from Roland Merrick on 2008-06-19 (public-html@w3.org from June 2008) (at lists.w3.org) <pimpbot> Title: Re: changes in HTML5 draft regarding XHTML1 from Roland Merrick on 2008-06-19 (public-html@w3.org from June 2008) (at lists.w3.org) <pimpbot> Title: XHTML2 WG Virtual FtF Day 3 -- 19 Jun 2008 (at) MikeSmith: Hixie, we need another status category in your annotation tool for sections. <scribe> .... "pending feedback" Hixie: I would like to add something like "controversial feedback" <DanC_lap> issue-52: "we will get back to you" -- Merrick 31 July <trackbot> ISSUE-52 Resolve XHTML2 WG objections to language in HTML5 draft regarding XHTML1 notes added <pimpbot> Title: Re: changes in HTML5 draft regarding XHTML1 from Roland Merrick on 2008-07-31 (public-html@w3.org from July 2008) (at lists.w3.org) <DanC_lap> html5 is listed in too <pimpbot> Title: XHTML namespace (at) DanC: ISSUE-52 contains pointers XHMTL 2 WG's concern with the spec language <CWilso> ACTION: ChrisWilson to suggestion text for 1.4.4 [recorded in] <trackbot> Created ACTION-78 - Suggestion text for 1.4.4 [on Chris Wilson - due 2008-10-31]. MikeSmith: Everytime I go somewhere to speak I am asked "how does XHTML 5 relate to XHTML 1 or 2"? <DanC_lap> action-62? <trackbot> ACTION-62 -- Michael(tm) Smith to ensure HTML WG response to XHTML 2 WG re name of XML serialization -- due 2008-10-02 -- OPEN <trackbot> <pimpbot> Title: Re: The only name for the xml serialisation of html5 from Dan Connolly on 2007-10-31 (public-html@w3.org from October 2007) (at lists.w3.org) <pimpbot> Title: ACTION-62 - HTML Issue Tracking Tracker (at) MikeSmith: I can talk to Roland this week and see where we are at CW: 1.5 is controversial because of the name "XHTML5" rsagent, make minutes public Lachy: I'm trying to find an older email where concerns were expressed about the namespace Murray_Maloney: I object to the namespace CW: Explain why we can't use something else Hixie: The browsers already use this namespace (in section 2.1.1) <Lachy> <pimpbot> Title: Test (at html5.lachy.id.au) MM: I understand that may be your goal, the namespace belongs to the W3C and XHTML ... You're applying a different meaning <CWilso> issue: Reuse of 1998 XHTML namespace is potentially misleading/wrong <trackbot> Created ISSUE-60 - Reuse of 1999 XHTML namespace is potentially misleading/wrong ; please complete additional details at . Lachy: In Firefox you get a DOM tree MM: Yesterday we had a talk with TAG about having a contract. There is an expectation with other user-agents and you're violating that contract. <CWilso> ACTION: ChrisWilson - send email to spark issue-60 [recorded in] <trackbot> Created ACTION-79 - - send email to spark issue-60 [on Chris Wilson - due 2008-10-31]. CW: We have evidence then that this section (2.1.1) is controversial MikeSmith: It might be nice to have a freeform comment field in your annotation tool Hixie: We do, it is the mailing list CW: It might be nice though to have these comments inline with the spec <DanC_lap> Lachy, is the namespace name observable from tests without using the application/xhtml-xml mime type? <Lachy> yes <zcorpan> alert(document.body.namespaceURI) <DanC_lap> ok. whew. thought I was confused. <Lachy> if we were to use a different namespace for the HTML serialisation from the XHTML serialisation, then that would create problems <Lachy> and we cannot get away with using a different namespace for XHTML <DanC_lap> seems worthwhile, to me, to capture that constraint in a test case. here's hoping. <zcorpan> switching namespace is as much of a non-starter as switching all the tag names. in fact it's basically the same thing MikeSmith: Moving on to review section 2.2 Hixie: Conformance requirements is pretty stable DanC: I'm very much unhappy about the conformance section ... It is not objective, the conformance requirements depend on the mood of the author CW: I understand what you are saying, I might put it a different way <zcorpan> at least if you switch all the tag names you still keep the HTMLElement interface (so class and style etc still work). if you switch the namespace it's just Element (only xml:lang etc works) CW: you should raise the issue if you like DanC: I've raised it in an email before CW: You should make a recommendation with alternative language <DanC_lap> <pimpbot> Title: keep conformance objective (detailed review of section 1. Introduction) from Dan Connolly on 2007-08-30 (public-html@w3.org from August 2007) (at lists.w3.org) <DanC_lap> issue: conformance depends on author's intent <trackbot> Created ISSUE-61 - Conformance depends on author's intent ; please complete additional details at . <DanC_lap> issue-61: originates in <trackbot> ISSUE-61 Conformance depends on author's intent notes added <pimpbot> Title: keep conformance objective (detailed review of section 1. Introduction) from Dan Connolly on 2007-08-30 (public-html@w3.org from August 2007) (at lists.w3.org) MikeSmith: What about section 2.2.2? "this section will be removed at some point" Hixie: I want to replace it with a pointer to DOM3CORE MikeSmith: What is are the asterisks on the spec? Hixie: Whenever you see those there is a red box in that section CW: In section 2.3 is that really what IE does for string comparison? Hixie: Yes CW: We'll need to go through and double-check Hixie: Feedback on this section would be very welcome <DanC_lap> (this string compare stuff seems straightforward to test too. but ok... I guess I'm OK to focus more on status/requirements than test-suite-building) DanC: The annotation system allows for links to test, right? Hixie: Yes MikeSmith: Who has tests for section 2.4.1? <CWilso> [in section 2.3 - the issue is that IE does caseless string compares in some situations where other browsers might do ASCII case-insensitive compares. we will need to review each compare to ensure we're making the right decision.] Geoffery Sneddon: I had test for section 2.4.3 and I've just updated the annotation scribe: I think my tests may be out of date DanC: Someone can try to reproduce your results though MM: Can we have pointers in the spec to open issues? Hixie: It would be hard to keep them up-to-date <DanC_lap> (thousands of issues? I count 59. ) <pimpbot> Title: Issues - HTML Issue Tracking Tracker (at) GS: Could we have something like when a section was last edited? MM: What mechanism do we have to know there are no complaints? MikeSmith: We use the w3c tracker system and the w3c bugzilla system for different groups MM: I'm not interested in the systems, what is the process used within the working group to determine stability of the spec <DanC_lap> hmm... my annotations-munging code seems horked. MM: how can different groups tracking the stability of individual sections? the descriptions of the editing states aren't all that helpful ... I'm used to working with a little more clarity with status levels on a document going through an editorial process. it should be more visible to members of other working groups and the public. BM: What is the process you are used to? MM: That there is a metric to measure stability or clear definition of what the process is CW: I share your concerns but we need something flexible MikeSmith: Having some kinda of mechanism for when the status changes, would be great ... maybe we can have something like an RSS feed or something automated CW: We need some way to define what a controversial section means <DanC_lap> aha... I was matching on match="h:ul[@class='toc']" and it's now an <ol> Hixie: The issues that have been marked controversial so far, have all been marked just today so I don't have anything other than what is in the minutes for today. <CWilso> we are now using the queue Karl Dubost: My impression of the process was that everything is a working draft until there are enough implementations to make a section stable Cynthia: I want to describe some of the process we had on WCAG. ... we would send out surveys to our members ... and we would discuss the survey feedback on telecons ... once consensus was reached we didn't reopen sections Julian: I am confused about the term "last call" on a section ... I'm not sure if it means I only have a certain time left to respond CW: It is not like "Last Call", in the capital L and C sense Hixie: Right now there are 2500 outstanding emails ... we are not reopening a section when the feedback has been processed ... but often feedback comes in afterward that necessitates reopening a section (for example, security issues) ... once something is implemented interoperably we don't have much room to change ... once you have implementations and people are using them we can't change them MM: There are places for the status of implementations for browsers. Shouldn't one of the status be "not applicable"? ... the technical part might be stable but the text part might need work still ... it seems to me it would be useful to distinguish between the editor's view and the working group's view ... we should leverage the semantic web resources at the w3c because it seems like this spec is a good example of an awesome semantic web application <DanC_lap> (our system admin channel bot quips "sounds like a semantic web project" when asked to do something unfamiliar) <DanC_lap> [10:32] <DanC_lap> infobot, what about a better tracking system? <DanC_lap> [10:32] <infobot> danc_lap: sounds like a good semantic web project Cynthia: How do you know when something is done and how do you decide when to reopen? CW: We do have a process for that. The decision making process is that editor makes a recommendation in text and we use a number of mechanisms to review that. ... we try to have significant discussion about an issue to gauge consensus before we go to polling the working group. <DanC_lap> fixed my code... Hixie: I want to clarify a comment that Murray made between the difference on my opinion of a section and the working group's opinion. ... my opinion is based on whether or not there is outstanding feedback MM: There doesn't seem to be an audit trail for feedback. CW: We do have that, there is the mailing list and issue tracking. <CWilso> issue tracking in particular is the answer to the "audit trail" question Hixie: The reason that implementations are already an issue is because the implementors are writing code quickly ... when there is one implementation we can talk to implementor and make changes but once there are two or three implementations it becomes much harder <DanC_lap> there... <DanC_lap> (which also serves as a copy of (some of the) annotation data on w3.org) <CWilso> s/wants/needs <Lachy> <pimpbot> Title: WHATWG Issues List (at) <pimpbot> Title: HTML WG -- 24 Oct 2008 (at) <anne> did he go out with chaals? <anne> ;) anyone else want to scribe? because uh, while this last session went on i've got some issue tracking work I need to catch up <gsnedders> +present Michael Smith <gsnedders> RRSAgent: draft minutes <pimpbot> Title: HTML WG -- 24 Oct 2008 (at) <gsnedders> someone needs to do that <gsnedders> I can't recall everyone's name offhand <gsnedders> bonjour, mes amis <gsnedders> hsivonen: ping <gsnedders> Are at 2.5? scribe volunteers? <MikeSmith> scribenick: cshelly <MikeSmith> scribe: CynthiaShelley <CWilso> scribe: CynthiaShelly <DanC_lap> i.e. URL sections <DanC_lap> would be great for somebody to pick up testing and report interop results for base uris content type is controversial, but what parts are stable? <CWilso> chair: ChrisWilson <smedero> hsivonen, I believe it is going to be in exec4, which is "upstairs" <smedero> (you have to go up a another flight of stairs from the lobby...) hsivonen, we'll meet in the WG room, and then go up to exec 4 together <hsivonen> smedero, cshelly, thanks <DanC_lap> issue-28? <trackbot> ISSUE-28 -- Content type rules in HTML 5 overlaps with the HTTP specification? -- CLOSED <trackbot> <pimpbot> Title: ISSUE-28 - HTML Issue Tracking Tracker (at) which types need to be sniffed? What are never encountered <gsnedders> <pimpbot> Title: Content Sniffing Data (as of September 26, 2008) (at crypto.stanford.edu) <gsnedders> <pimpbot> Title: [whatwg] Mime sniffing data (at lists.whatwg.org) <DanC_lap> GS: a problem with writing tests on this is that it doesn't define [missed] <DanC_lap> ... I sent mail... <Lachy> implementation of that content sniffing algorithm in javascript <pimpbot> Title: text/html Content Sniffing (at html5.lachy.id.au) <scribe> ACTION: Hixie to look for other editor for sniffing section [recorded in] <trackbot> Sorry, couldn't find user - Hixie <gsnedders> <pimpbot> Title: Step 10 of Feed/HTML sniffing (part of detailed review of "Determining the type of a new resource in a browsing context") from Geoffrey Sneddon on 2007-08-17 (public-html@w3.org from August 2007) (at lists.w3.org) <gsnedders> That's the email I sent <scribe> ACTION: hixie to look for other editor for sniffing section [recorded in] <trackbot> Sorry, couldn't find user - hixie <CWilso> ACTION: Hixie to put content-type sniffing section on list of sections to find an editor for [recorded in] <trackbot> Sorry, couldn't find user - Hixie <CWilso> ACTION: ChrisWilson: Hixie to put content-type sniffing section on list of sections to find an editor for [recorded in] <trackbot> Created ACTION-81 - Hixie to put content-type sniffing section on list of sections to find an editor for [on Chris Wilson - due 2008-10-31]. hixie: methods starting with xxx are temporary <Hixie> DanC_lap: section 3 (of 11) <gsnedders> — out of date version of the content-type sniffing algorithm, but shipping <pimpbot> Title: SimplePie 1.x - /releases/1.1.1/simplepie.inc - SimplePie (at bugs.simplepie.org) <DanC_lap> (what happened with 2.8?) Mike: do we actually need section 3.1, intro to semantic structure? ... sections 3 and 4 are core definitions of markup language. <DanC_lap> (I'd like to see the security stuff written up in "extended abstract" form or something.) <DanC_lap> Hixie: a lot of this stuff [3.2.3 Resource metadata management] is DOM level 0. [ i.e. unstandardized ] <DanC_lap> Hixie: there's feedback pending on this... e.g. cookies Mike: web apps dependencies on HTML 5 Marcos: none on resource metadata management Dan: work the interface name into the section title, might make it clearer ... are global attributes interoperably implemented? Hixie: no <DanC_lap> Hixie: e.g. draggable has maybe 1 implementation Julian: data attributes are sometimes used for extensibility, but not designed to do that <DanC_lap> looking at 3.7 Dynamic markup insertion <pimpbot> planet: Ben on contributing to the W3C HTML WG <11> Dan: why is innerHTML bad? Hixie: it's not typed. not checking <DanC_lap> (innerHTML sounds a little like eval. pointy instrument, but sometimes useful.) Timbl: perhaps put in the spec that you should only use innerHTML for balanced stuff and compile time check it? <DanC_lap> +timbl Hixie: agree in principal, may be hard in javascript <DanC_lap> (noodling on a QA/TAG/HTML blog item on innerHTML and document.write() ... ) timbl: document.write is much worse, not adding to the DOM ... spec that whatever you put in there should correspond to a piece of DOM hixie: timbl means something that is well formed and wouldn't throw a parse error <pimpbot> Title: ISSUE-1 - XHTML2 Working Group Tracker (at) Murray: preamble: 2 years ago I was here and the problem was social: tension between XML and HTML communities. GRDDL bridges the gap. ... in this meeting I see that there is a big social problem between HTML WG and the rest of the world here is an opportunity for Semantic Web community to help HTML WG. problem is visibility to what is happening, how to track, etc. other big problem is lack of resources for editing, providing technical assistance, etc. Semantic Web part of w3c all about how to relate data and such other social problem is that w3c has spent lots of resources on semantic web but there aren't real world uses that have been implemented can't wrap my brain around why Tim is having problems with HTML, and why HTML 5 is having problems with XML quite a few members of HTML 5 WG have deep knowledge of XML and understand problems it has for the things people and browsers want to do with HTML quite a few XML people willing to accept that feedback technologies should work together want to put out there the idea of having the rest of w3c community help the HTML WG work in a way that helps the process and visibility work without interfering with how HTML WG does its job tim you have all these resources on Semantic Web, can we improve the status annotation on the HTML 5 draft? Hixie has defined some things, but could be expanded. Would be really useful in all w3c specs we're having process problems in this group, and in all groups. Marcos: its not the tools, its the people ... could be doing it on paper Murray: lots of resources applied to semantic web, seems that w3c applying semantic web resources to creating some tools... Timbl: in semantic web area, people are developing specs. don't have grad students looking for work. ... I can understand an argument for moving resources from Semantic Web to HTML. ... another adjustment you could talk about is to have a concerted tools effort instead of human cycles ... expanding this tool might be useful ... neither semantic web nor tools is magic. people still need to do the work. ... allowing people to extend this so people can mark what's implementation, what's authoring, allowing crowdsourcing Dan: I asked for these tools when the WG was set up chris wilson suggests hosting a table at lunch to discuss time to break <karl> reconvening at 12:45 <pimpbot> Title: HTML WG -- 24 Oct 2008 (at) <karl> Meeting: HTML WG - 24 October 2008 - Technical Plenary <pimpbot> Title: HTML WG -- 24 Oct 2008 (at) <smedero> Chair: ChrisWilson <pimpbot> Title: HTML WG -- 24 Oct 2008 (at) Ian Hickson Ben Millard, Anne van Kesteren, Cynthia Shelly, Michael Cooper, Henri Sivonen, and Marcos Caceres met for a separate “breakout session” to discuss ARIA implicit roles. See the separate minutes for that discussion. <CWilso> MS: Summary of where we are with Authoring Guide. <gsnedders> Can we have a link in IRC? <smedero> <pimpbot> Title: The Web Developer’s Guide to HTML 5 (at dev.w3.org) <CWilso> thanks smedero. <MikeSmith> scribenick: MikeSmith <gsnedders> The document doesn't comply with ISO 2145 — Numbering of divisions and subdivisions in written documents. Lachy is giving and overview of the Editor's Draft of an authoring guide that he has been working on. <Hixie> (subgroup is meeting in #role) <karl> I have a better CSS. Lachy: text/html examples are shown in gray, XML examples in yellow ... <Zakim> karl, you wanted to talk about resources constraints on this document and deadlines Lachy: recently been working on the attributes section ... purpose, syntax, quoted/unquoted, examples ... types of content (e.g., phrasing, etc.) ... elements section is still sketchy karl: I asked Lachy what the resource constraints would be ... I'm willing to spend time after the end of November on helping with this. Lachy: yeah, I've asked for people to help me with this, but so far nobody did karl: what about a deadline? Lachy: after I get CSS Selectors API to LC, then I have more time karl: I can't start working on it before the end of November ... could work full time on it for December Lachy: I want to get a lot of the common elements documented MikeSmith: maybe a first step would be for you guys to get together and talk about high-level organization of the spec <Zakim> gsnedders, you wanted to ask some questions about problems I see with it <smedero> (apparently) gsnedders: [pointing out concerns about the Introduction] ... the current draft seems to require too much background knowledge on the part of readers ... it needs to make clear what's expected of the person reading it Lachy: it does provide that information karl: so who do you think should read the document? gsnedders: I think it should be something you could learn HTML from, without having [too much] prior knowledge. karl: I think we should not focus too much on the Introduction.. I think we share the same goals, but we need to get to the meat first. Lachy: gsnedders, how about you take a shot at rewriting the Introduction? gsnedders: yes CWilso: so it seems like we don't have anything blocking this.. just that it's clear more work needs to be done [lunch break] <pimpbot> planet: Ben Millard on contributing to the W3C HTML WG <11> <pimpbot> Title: HTML WG -- 24 Oct 2008 (at) <smedero> In case anyone didn't catch it yet, <pimpbot> Title: notes from "implicit role" breakout session from Anne van Kesteren on 2008-10-24 (public-html@w3.org from October 2008) (at lists.w3.org) [Going through sections of the HTML5 specification marking up stability of sections. Currently at section 4.] Jonas: section 4 does not define parsing right? Hixie: yes Jonas: (<title> section) does it say that it is live? Hixie: yes, different section though; should say that, if it doesn't, e-mail ... <base> section has issues Jonas: specification doesn't define what we do? Hixie: it says what IE7 changed to do ... I did a study on this; didn't matter much; vast majority of the pages were spam pages or autogenerated index pages Jonas: I'd love to remove the code [<link> section marked as "last call"] [<style> section] Henri_Sivonen: I thought scoped was controversial, dhyatt commented on it ... I think if dhyatt is not ok with it it counts as controversial David_Baron: there was discussion in the CSSWG whether it should be matched against the root of the whole tree or the subtree Lachlan: I think it should be the whole tree, like in Selectors API Jonas: perf implications? [silence] [some stuff about the CSSOM and its editor] Hixie: <eventsource> is probably "last call" because we get implementations ... <script> probably not because <script async> is new Jonas: we're implementing <eventsource>, not sure what the status is Henri_Sivonen: are we considering header level implementation part of the <section> section? IH, MS: different section, so no AnneVK: headings and sections is not really desirable to implement because styling is not addressed David_Baron: CSS also needs changes for CSS counters and user agent style sheets will need changes for sizes Henri_Sivonen: has the CSS WG looked into that? David_Baron: no, but I have sort of a mental action item to look into that Lachlan: it would be nice if the CSS WG defined selectors for this so you can easily select all second level headings Hixie: for the <q> section we need to figure out quoting, so "working draft" Jonas: so is that a break from HTML4? Hixie: yes ... we're screwed either way David_Baron: Firefox does it but gets complaints from different locales because people do not agree on quotation rules CW: sigh, we did it the HTML4 way in IE8 <gsnedders> q:lang(en)::before { content: '"'; } — anyone agree with that? :P <myakura> Lachy, ::before is css3, so probably not [missed bits] David_Baron: so maybe we should drop support for it before IE8 does <karl> gsnedders, you meant q:lang(en)::before { content: '“'; } Henri_Sivonen: one option would be to obsolete quote and require ugly quotation marks in the rendering section David_Baron: people don't agree what the quotation rules for English are at the third nested level <gsnedders> karl, I did deliberately do " :) David_Baron: the Bible has five levels deep and is widely translated, and different locales disagree on the quotation rules Henri_Sivonen: I would like to add that the Bible is a bad use case for tree based markup as it has overlapping ranges <gsnedders> karl, doesn't it make no difference for non-scribes? <hsivonen> gsnedders, a verse can span a paragraph break, IIRC <gsnedders> hsivonen, Yeah. Often does. <dbaron> for 5-nesting of quotes <pimpbot> Title: Re: Deep nesting of quotes from Simon Montagu on 2006-05-16 (www-style@w3.org from May 2006) (at lists.w3.org) [text-level semantics] Hixie: outstanding feedback on all of them MS: what about footnotes Hixie: they are conventions that people should use for footnotes <gsnedders> Example of overlapping range: <> <pimpbot> Title: Mark 14:64 :: Bible Search (at) <gsnedders> Lachy: The verse cannot be marked up as a single element because it continues beyond the paragraph break Hixie: the <legend> element is reused and it's not clear whether that is actually possible due to legacy <hsivonen> Lachy, consider both paras and verses as containers Jonas: was this fixed in Firefox 3? Hixie: I think it was one of the things it wasn't ... in Mozilla <legend> implies a <fieldset> ... other browsers just drop it on the ground ... nobody relies on this one way or another <Lachy> hsivonen, ok, it makes sense if I look at it in context, and see how the passage numbers are used Hixie: I would like not to add yet another way to mark up a heading Henri_Sivonen: I think the legacy parsing will scare away authors so I would prefer a new name Hixie: it will hamper transition, but delaying it another couple of years is fine with me given the cost it would add to the language [<img> section] Hixie: the red box regarding longdesc is a lie, I have considered that feedback David_Baron: what about image maps? Hixie: separate section [sandboxing] Henri_Sivonen: does it work for e.g. chrome to have a separate process for the nested browsing context Hixie: that has been taken into consideration [object and embed] [how classid maps to a plugin per platform etc.] <pimpbot> Title: Bluish Coder: HTML 5 Video Element Examples (at) <hsivonen> <pimpbot> Title: Index of /test/moz/video-selection (at hsivonen.iki.fi) [going through the media element section] Jonas: smaug was saying loadend was not relevant Hixie: we have load, error and abort, so loadend does make sense CW: what "Implemented and widely deployed" mean beyond "last call" Hixie: yeah [discussion whether there should be annotations for sections that could be moved out of the spec] Hixie: it's typically not a concrete section, but rather several sections that have to be taken out together Henri_Sivonen: for the <map> element, should we annotate it with browser support regarding HTML and XML MS: we can't do that level of detail <Lachy> scribenick: Lachy <scribe> scribe: Lachlan Hunt MS: We could probably skip the forms section today ... also Tables Hixie: Forms has a lot of feedback pending. ... Most feedback on tables is about headers [added a few annotations to the forms and table sections] Hixie: I'm hoping we'll get at least one implemented working on the datagrid section and provide feedback. ... No-one has said it's bad MS: Is the name of the <bb> element stable? Hixie: No <anne> heh, the interface name is actually BrowserButton Hixie: It was added in response to Apple's feedback, wanting to provide an in page way of triggering application functionality Jonas: Why not use a JS API? Hixie: It's to prevent annoying abuses that are possible with JS CW: I'm not sure this is better than an API though Henri_Sivonen: How much of the rendering section will be different from the CSS appendix? Hixie: Rendering is a misnomer. It contains more than just basic styles ... There's 2 big issues: The obsolete APIs and elements, and how to map that to CSS Henri_Sivonen: My spec scraper works better when each element is defined in only one place Hixie: [points out other problems that still don't solve Henri's issues] <Hixie> dbaron, wfm in ff trunk <smedero> Philip, did you ever file this bug properly with the IE folks? <pimpbot> Title: IRC logs: freenode / #whatwg / 20081008 (at krijnhoetmer.nl) <Philip> smedero, no - I started trying to write some proper tests for all the localStorage stuff rather than reporting bugs randomly, but then I kind of got bored/lazy/distracted/busy and didn't get anywhere <Philip> (Firefox had strange bugs with funny characters in globalStorage too) <smedero> ahh, ok. I can help out a bit if you want to (and it makes sense to) split up that work. <CWilso> ACTION: ChrisWilson to come up with a 16x16 image icon for IE for implementation chart [recorded in] <trackbot> Created ACTION-83 - Come up with a 16x16 image icon for IE for implementation chart [on Chris Wilson - due 2008-10-31]. <Philip> smedero, I started doing something based on my canvas test framework with all the canvas-specific bits ripped out, with the intention of adding storage-specific bits (like the ability to run each test on a separate domain to get independent storage areas), so I probably should try to finish that stuff, and then the actual tests should be fairly straightforward to write :-) <pimpbot> Title: HTML WG -- 24 Oct 2008 (at) <MikeSmith> [afternoon break until 4pm CET] <Philip> CWilso, you could print out some SVG people from <pimpbot> Title: Image:Human.svg - Wikimedia Commons (at commons.wikimedia.org) <hsivonen> <pimpbot> Title: Re: SVG in HTML proposal from Henri Sivonen on 2008-07-21 (public-html@w3.org from July 2008) (at lists.w3.org) <MikeSmith> scribenick: MikeSmith CWilso: so... SVG in text/html <Hixie> -_- <shepazu> <pimpbot> Title: SVG and HTML (at dev.w3.org) <shepazu> <pimpbot> Title: Feedback on SVGWG's SVG-in-text/html proposal from Ian Hickson on 2008-08-28 (www-svg@w3.org from August 2008) (at lists.w3.org) shepazu: we did incorporate some feedback we got on our proposal ... nothing is set in stone, we can make further refinements to the proposal ChrisL: I assume it's a goal that developers should not have to rewrite scripts and such Robin_Berjon: yeah, issue is just about the syntax Shepazu: all comes down to the syntax ... we have disagreements about the syntax, but is there anything else? <hsivonen> <pimpbot> Title: Re: SVG in HTML proposal from Henri Sivonen on 2008-07-21 (public-html@w3.org from July 2008) (at lists.w3.org) hsivonen: in July, I sent a message about the proposal but did not get a reply... shepazu: we made some changes because of comments you, hsivonen, made hsivonen: I was objecting to the whole premise of how the integration would be done [in your proposal] ... about which tokenizer is used ... I've implemented the proposal that was commented out ... I estimated what work it would take to implement it in Gecko and in Java SE ... and my assessment is that it's much easier in both cases to implement the commented-out proposal [from Hixie] ... I sent comments about why the SVG WG is not implementable ... I fundamentally disagree with having an XML parser inside the HTML parser ChrisL: I disagree. You've not shown that it's massively inefficient. hsivonen: I don't think I need to implement it [in order to prove it] Hixie: a question that came out is a question of goals <Hixie> Is it a goal that anything that is functional in text/html be functional when copied and pasted into image/svg+xml shepazu: Hixie, do you mean anything? Hixie: anything *SVG* ChrisL: to the extent possible ... hsivonen makes a good point... e.g., Illustrator puts entities in <Zakim> chaals, you wanted to talk about implementation and propose an answer to hixie ChrisL: so losing that would be fine chaals: we have not thoroughly implemented either system ... <ChrisL> but i want most SVG to be usable. Some bits with entities may need modification, thats fine chaals: but., and editor ... we don't want to break the use case of cut-and-paste in that scenario ed: to me it's not a goal to allow something to be very different from the syntax we have now ... important to stay as close as possible to what is out there already hsivonen: I agree about the importance of the copy-and-paste from browser into editor ... but following the line of thought, it leads to breaking the fundamental permissive nature of text/html (the "host" format) ... you can get around this without making fundamental changes to HTML parsing ... ... some browsers allows you to [output a well-formed serialized output of the DOM] shepazu: we can't count on that functionality being available always, and don't want to spec it as a requirement ... problem case is of some of this funky [not-well-formed] SVG getting propagated <karl> There is a *virtuous* circle to keep good markup or even improve it in an ecosystem. shepazu: somebody thinks it should work, but it won't ... so your scenario [serialized DOM output] does not solve the problem Hixie: so we need to look as [what the problem is that we want to solve] ... if we think that it's a goal that anything that is functional in HTML should always be functional when pasted into XML, then the SVGWG does not satisfy that requirement shepazu: I think you do not require attribute quoting? Hixie: correct ... another example is omitting the SVG end tag sicking: I think we [may have] incompatible goals ChrisL: being able to draw something in a drawing tool and paste it into an HTML document, yeah, of course that should work sicking: other goals are that the way that HTML authoring is done should also be OK for SVG ... but that is an incompatible goal ... string concatenation... people generating invalid markup ... writing HTML docs in Notepad, et.c ChrisL: people do already generate SVG in those ways [using PHP, etc.] sicking: we need goals ... if we talk about requirements first, then we can work together toward a solution <Zakim> Robin_Berjon, you wanted to reflect on tools Robin_Berjon: about the goals thing ... ... everyone agrees that we want to have SVG in HTML ... the editor vendors will make it happen ... ... it will be cheap to add an HTML5 parser to an editing application ... currently, SVG is being produced by [people who are more XML-aware] ... but once SVG gets very widely used, [the "funky" instances of it] will increase, and we will have to deal with them hsivonen: I think our goal should be that browsers will have the UI [for outputting a serialized DOM] ... browsers already have a different parser for text/html and XML, so... <anne> hsivonen, I think the point from Chris Lilley is that nobody has implemented the proposal from the SVG WG yet so in theory it is unclear which one is simpler; though you did point out you thought it was sort of "doomed" the way it is currently written hsivonen: suggesting that they wouldn't do so seems weird because they are already doing it Hixie: I think it is possible to avoid allowing "tag soup" parsing support for SVG ... ... but we don't have agreement about that being a reasonable goal <Zakim> chaals, you wanted to suggest that we drop the hand-raising protocol and force people to simply remember their rebuttals and wait their turn and to suggest that we drop the <Lachy> Just in regards to the UI suggestion from Henri, I just want to point out that there are several alternatives besides providing a way to get the DOM source, such as simply using "Save Image As..." to export a well-formed, re-serialised copy of the image to an SVG file. chaals: our experience is that by-and-large, the quality of SVG has improved over time ... ... due to it being a goal that we enforce quality requirements ... majority case is drawing tools, yeah ... ... but they are also generating using PHP, whatever ... ... and they do go back and fix their code [if it turns out it's not producing well-formed SVG] ... we do see it as a goal to keep SVG parsing strict ... ... tools for SVG have remained high-quality ... ... we don't see it as a goal to make the [SVG content] crappier than it already is ... ... an area where that's important is mobile ... whilst that world is also changing ... ... proper browsers being deployed ... ... but to blow that off -- to allow [become more tolerant of] crappy SVG code <Zakim> CWilso, you wanted to suggest that we walk through the goals and straw-poll each chaals: [we don't want to do that] CWilso: so can we look at the set of goals? [we have only 10 minutes left] <Hixie> goals: <pimpbot> Title: Feedback on SVGWG's SVG-in-text/html proposal from Ian Hickson on 2008-08-28 (www-svg@w3.org from August 2008) (at lists.w3.org) sicking: concerned about having a requirement about strict parsing ... <Hixie> Robin_Berjon: eh, i start all mine by saying "i, er, i think, there is, hm, if we, hm, ..." ;-) <shepazu> me that's because I usually go on for half an hour :) sicking: is [the problem of unstable equilibrium which we have learned] that there is a risk it will just not happen that way in the long run ChrisL: is it a goal to stop people from putting in well-formed content? <CWilso> * It should be possible to drop an SVG file from a graphic editor into an <CWilso> HTML5 document sent as text/html and usually have it validate and work. <CWilso> * The DOM aspect of this should be very similar to using SVG in XHTML, so <CWilso> that there is no work required beyond parser changes for text/html. [agreement within rough consensus?] <ChrisL> (whether it validates or not is irrelevant to me, but it should render as expected) <CWilso> * The DOM aspect of this should be very similar to using SVG in XHTML, so <ChrisL> I'm glad that penalising WF is not a goal <CWilso> that there is no work required beyond parser changes for text/html. [agreement from all] <CWilso> * Changes to the parser should be relatively small and localised. For <CWilso> example, it should not double the number of states in the tokeniser, or add <CWilso> half a dozen tree construction insertion modes. <CWilso> * The parsing model should be very light-weight. It shouldn't require, <CWilso> for example, extra buffering, or parsing text twice. shepazu: I don't strongly oppose this goal. chaals: the underlying goal is that the processing is reasonably efficient ... the stated goal has more implementation detail in it than needed [no broad consensus on this goal] <CWilso> * The markup should be as easy to edit by hand as regular HTML, modulo <CWilso> complications due to the vocabulary itself. ChrisL: it over-constrains implementations CWilso: "as small as an elephant" <hsivonen> I agree with the goal [broad consensus] <CWilso> * The syntax shouldn't introduce two different syntaxes for HTML <CWilso> elements in text/html. For example, it should be possible to take a big <CWilso> blob of existing HTML, and wrap it in a <foreignObject> and have it <CWilso> just work, without having to fix up missing end tags or namespace <CWilso> declarations or whatever. [agreement] <CWilso> * If possible, the same mechanism should work for both MathML and SVG, <CWilso> and it should make it relatively easy to introduce other vocabularies <CWilso> in future, at least for vocabularies designed with this mechanism in <CWilso> mind. ChrisL: problematic <CWilso> * Markup seen on real pages today, and errors of a similar vein, <CWilso> shouldn't result in dramatically different renderings in browsers that <CWilso> support this feature. Hixie: this is the "don't break legacy pages" requirement ed: the question is "At what cost?" <ChrisL> depends on which broken pages you want to preserve. shepazu: some of your pages that you [Hixie] gave as examples are [totally broken] [discussion about whether it's feasible to do educate/evangelize to get people to fix their broken content Hixie: this a the single most important requirement from the POV of the Chrome team ChrisL: SVG pages which currently work -- which produce some useful output -- should continue working <Hixie> <pimpbot> Title: New Page 1 (at puysl.com) <Hixie> ^ that one hsivonen: [describes a cargo-cult copy-and-paste scenario <CWilso> We must not require users to declare namespace prefixes correctly. sicking: I want to find out how common [the case is that we currently are discussing] ChrisL: I would like this clarified. CWilso: so you can have an svg element and all its children without the namespace <CWilso> * If possible, we shouldn't expose users to namespace syntax at all, <CWilso> though the DOM still needs to expose the namespaces. CWilso: that should be allowed ... ChrisL: but it should not disallow the namespaces hsivonen: one issue is, should it render as SVG if you have a namespace, but it's the wrong namespace? <CWilso> Hixie: we should definitely allow the xmlns case. sicking: seems like the third issue [wrong namespace] is the only one we don't have agreement on ... do we want it to be possible to use an off-the-shelf XML parser? ... are we OK to restricting ourselves to non-off-the-shelf XML parsers? hsivonen: the problem is, that presupposes part of the solution? sicking: if I as an implementor am not OK with writing my own XML parser, than that excludes [some implementors] Hixie: writing your own XML parser is not a small and localized change CWilso: I think we are narrowing down to get an idea of where the disagreements about goals are. <shepazu> * It is not a goal that any valid SVG file must be embeddable in <shepazu> text/html. (Only the syntax that is actually widely used need be <shepazu> supported.) shepazu: this is not talking about whitelisting? Hixie: this is about SVG that uses namespace prefixes or that use an DTD internal subset ChrisL: only place I see people using prefixes in SVG is in compound documents shepazu: OK, I don't think this is controversial [strong consensus that this is a non-goal] <shepazu> * It is not a goal that anything that is valid text/html be valid <shepazu> image/svg+xml. In particular, whether to use case-sensitive or case- <shepazu> insensitive tag and attribute names at the syntax level should be <shepazu> driven from implementation performance choices, not conformance. shepazu: case sensitivity... ... related to error-correction ChrisL: if you're allowed to doing the stuff that the SVG spec says, or corrects it to conform to the SVG spec, then fine <Zakim> hsivonen, you wanted to talk about mobile hsivonen: the performance issue here is very important anne: we've had no implementations of the SVGWG proposal, [so we don't have any data] <karl> the debate on performance should be really put aside before having real data on the table for the two options shepazu: how about if the spec says it's strongly recommended or "SHOULD" that authors should try to [follow XML well-formedness constraints] sicking: requiring the SVG parts to be totally XML-compliant is fine... but authors are going to do whatever ends up working in browsers [discussion about the fact that quotes are in fact needed even in some cases in text/html] ChrisL: "quotes are not required except when they are" hsivonen: I'm not fine with requiring that a parser used for a validator be different from the parser used by browsers. Murray: are there levels of conformance? karl: people will always choose the more liberal choice CWilso: they will choose random levels sicking: majority of people test it in a browser, if it works, OK <pimpbot> Title: HTML WG -- 24 Oct 2008 (at) <sicking> last post! <gsnedders> last + 1 post! <anne> o_O [adjourned in the company of members of the SVG WG]
http://www.w3.org/2008/10/24-html-wg-minutes.html
CC-MAIN-2016-26
refinedweb
7,681
58.01
Databases are an integral part of many C# applications. They are used to store data that can be used in any desktop or web based program. For example the database may contain: Customer details such as name, email and postal address Product details such as price, postage and quantity in stock Order details such as customer and product ids and dispatch dates Of course, these are only useful if the C# application can access the data. Fortunately that’s not a problem if the information is stored in a MySQL database, and that’s because MySQL provide a .NET connector. If a programmer uses the MySQL .NET connector then any of their C# applications (or, in fact, any of their .NET based applications) can connect to a MySQL database with very little effort. Downloading and Installing the MySQL .NET Connector The MySQL .NET connector installer can be downloaded from the MySQL Connector/Net web page. Once that’s been done then the installer can be run (by double clicking on it in Windows Explorer). When the installer has finished its task then the connector will be ready for use. Adding the MySQL .NET Connector as a Project Reference The programmer must next add the MySQL .NET Connector as a project reference before they can use it in an IDE (Integrated Design Environment), such as SharpDevelop, where they do can this by: Opening a new or existing C# project Clicking on Project and then “Add References” Selecting the MySQL.Data reference (as shown in figure 1 and the bottom of this article) They will now be able to use the connector in their application. With MySQL.Data set up as a reference the correct library will need to be loaded. In this case that is the MySqlClient library: using MySql.Data.MySqlClient; The MySQL connector can now be used in the application. Creating the MySQL Database Connection Object with C# Now the programmer can create the connection object itself: MySqlConnection connection = new MySqlConnection (); This new connection cannot be used yet. For that to happen the connection must be given a connection string. Setting the Connection String The connection string needs to contain all of the information required to connect to a database. These are: the server – by default this is always “localhost” the database the user’s id the user’s password Each of the elements must have a semicolon between them. For example: connection.ConnectionString = “server=localhost;” + “database=aec;” + “uid=aec_user;” + “password=aec;”; Here the connection will be made on the localhost to the aec database via the aec_user account. Opening the MySQL Database Connection The connection has not actually been made yet, but that is a very simple step: connection.Open (); And now the connection is ready to receive SQL (Structured Query Language) statements such as: Insert Update This enables the programmer to carry out all of the database operations that they need. Closing the MySQL Database Connection The database connection should close when the user exits from the application. However, it is always good practice to close the connection neatly in the code: connection.Close(); This will ensure that any memory uses by the connection will be freed up, and will stop the application from hogging too many of the computer’s resources. Summary Any C# programmer wishing to connect to a MySQL database simply has to: Download and install the MySQL .NET Connector Add the MySQL.Data reference to a C# project Load the MySQLClient library Create the connection object Set the database connection string Open the connection And they can then produce an application that connects seamlessly with any MySQL database.
https://www.techora.net/tips-connect-mysql-database-c.html
CC-MAIN-2018-34
refinedweb
605
61.87
This is your resource to discuss support topics with your peers, and learn from each other. 10-03-2012 12:32 PM hi, is it possible to use the holo theme in a android app? if yes how? or is it even possible to use a navite looking theme in a android app, so that the user think that this is the navite ui? Solved! Go to Solution. 10-16-2012 08:07 AM 10-20-2012 12:45 PM Evozi wrote: Yes, use HoloEverywhere library to get your app to have Holo theme do you have an idea why i have so many errors when i import holoEverywhere? 10-20-2012 01:34 PM Import HoloEverywhere from root folder and ActionBarSherlock from contrib folder into Eclipse Add HoloEverywhere project as library into your project (Properties/Android/Library/Add) Add next theme declaration: android:theme="@style/Holo.Theme.Sherlock" in your application manifest Example: <application android: Also you can use Holo.Theme.Sherlock.Light for light theme and Holo.Theme.Sherlock.Light.DarkActionBar for light theme with dark action bar. Example: public class MainActivity extends com.WazaBe.HoloEverywhere.sherlock.SListActivity { ... Also you should cast view to with the same name from package com.WazaBe.HoloEverywhere.widget, if possible. This, for example, ProgressBar and Spinner. Read this too 10-21-2012 05:14 AM I made all of this steps, but now i just have one error left which i cant solve: R cannot be resolved to a variable this is everywhere where i make the: (Button)findViewById(R.id.button1); 10-21-2012 07:06 AM 10-21-2012 11:05 AM Evozi wrote: Try Project->Clean in Eclipse. unfortunately it did not solve the issue
https://supportforums.blackberry.com/t5/Android-Development/using-holo-theme-in-android-app/m-p/1932419/highlight/true
CC-MAIN-2017-04
refinedweb
286
65.73
Today days back I provided a list of online tools to reduce image size. But when you have hundreds of images, it’s better to invest some time and write a program that does this work for you. So let’s see how we can resize an image in java. Table of Contents. Java Image Resize Program package com.journaldev.util; import java.awt.AlphaComposite; import java.awt.Graphics2D; import java.awt.Image; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; /** * This class will resize all the images in a given folder * @author pankaj * */ public class JavaImageResizer { public static void main(String[] args) throws IOException { File folder = new File("/Users/pankaj/Desktop/images"); File[] listOfFiles = folder.listFiles(); System.out.println("Total No of Files:"+listOfFiles.length); Image img = null; BufferedImage tempPNG = null; BufferedImage tempJPG = null; File newFilePNG = null; File newFileJPG = null; for (int i = 0; i < listOfFiles.length; i++) { if (listOfFiles[i].isFile()) { System.out.println("File " + listOfFiles[i].getName()); img = ImageIO.read(new File("/Users/pankaj/Desktop/images/"+listOfFiles[i].getName())); tempPNG = resizeImage(img, 100, 100); tempJPG = resizeImage(img, 100, 100); newFilePNG = new File("/Users/pankaj/Desktop/images/resize/"+listOfFiles[i].getName()+"_New.png"); newFileJPG = new File("/Users/pankaj/Desktop/images/resize/"+listOfFiles[i].getName()+"_New.jpg"); ImageIO.write(tempPNG, "png", newFilePNG); ImageIO.write(tempJPG, "jpg", newFileJPG); } } System.out.println("DONE"); } /** * This function resize the image file and returns the BufferedImage object that can be saved to file system. */ public static BufferedImage resizeImage(final Image image, int width, int height) { final BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); final Graphics2D graphics2D = bufferedImage.createGraphics(); graphics2D.setComposite(AlphaComposite.Src); //below three lines are for RenderingHints for better image quality at cost of higher processing time graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR); graphics2D.setRenderingHint(RenderingHints.KEY_RENDERING,RenderingHints.VALUE_RENDER_QUALITY); graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON); graphics2D.drawImage(image, 0, 0, width, height, null); graphics2D.dispose(); return bufferedImage; } } - First few lines uses Java IO to retrieve the list of files from the directory and then in the for loop, each file is processed. resizeImageis the method where Graphics2Dis used to resize image and return it as BufferedImageobject. - Again we use ImageIOto write it into the file system in both PNG and JPG format. Java Resize Image Important Points - You can use RenderingHintsto get high quality image at the cost of processing time. If you are not reducing images to a very small size, you might want to avoid them for faster processing. It depends on your situation that you need fast processing or better quality. - The method doesn’t throw any Exception even if there are any files that are not image file like text, doc or pdf files. In that case, it will resize it and you will get a black colored image. You can easily extend the code to skip these files by filtering through their name. - PNG image size is more than JPG image size for same resolution and it’s significant. So if you want to resize the image for web pages, you might want to use JPG format to save page loading time. Java Image Resizer Program Results I placed one PNG and one PDF file in the image directory and executed the program. Input image is Eclipse Juno image of size 168KB: Here are the output images with size: PNG image without Hints 23KB JPG image without Hints 4KB PNG image with Hints 24KB JPG image with Hints 4KB Non image file output in PNG and JPG I hope the given program help you in resizing images quickly. Java Resize Image with Aspect Ratio In a normal scenario, you want to keep the image aspect ratio else it will look stretched from one side. Here is the code snippet that will help you in maintaining the aspect ratio. double aspectRatio = (double) img.getWidth(null)/(double) img.getHeight(null); tempPNG = resizeImage(img, 100, (int) (100/aspectRatio)); Note that in this case, you would have to make sure that there are only images in the directory else it will throw exception. Further Reading: Here is another program to upload files on server using Apache Commons Net FTP API. Reference: Graphics2D API Doc Hey, thanks a lot. Very helpful intro to creating resized images! 🙂 hi im getting java.lang.UnsupportedOperationException: Not supported yet. on resizeImage. please get me a solution please where can i download or find your code about it? i need for JPG image resizing, please help me. if you do not see the code above, try a different browser. For me, the code was invisible only when using IE. Hi, Thank you. It is working for JPEG. But for PNG image, resized image quality is very poor. Please help Can Please Provide me the Complete Code for PDF To tiff using “pdfbox-0.7.3.jar”
https://www.journaldev.com/615/java-resize-image
CC-MAIN-2021-17
refinedweb
812
50.63
Java Task on Algorithms - 9th Jun, 2022 - 15:41 PM 1.a. Scope of the variable is the part of the program in which it can be accessed. In Java, variables can have Class level, Method level and Block level scope. In class level, its variables should be declared inside class and not inside any function of the class, so they can be used anywhere inside class. public class Class_level {// member variables int a; char b; } In Method level, variables are defined inside a method and can’t be accessed outside that method. public class Method_level { void test() { // local variable int x; } } In block level, variables are defined inside a pair of flower brackets “{” and “}” in any method and the variables have scope inside those the brackets. public class Block_level { for (int i = 0; i < 10; i++) // i is loop variable and has scope inside for loop { System.out.println(i); } // cant access i here, shows error System.out.println(i); } 1.b. Creating a variable is called a variable declaration. To declare a variable, you must specify the data type and a unique name for it. When you declare a variable, a memory location is set aside for a variable of that type and the name is associated with that location.For an integer variable 32 bits, for double 64 bits and for boolean 1 bit of space in memory is allocated. So, declaration gives the type and name of the variable. Initialization means assigning the value while declaration.
https://www.theprogrammingassignmenthelp.com/blog-details/java-task-on-algorithms
CC-MAIN-2022-33
refinedweb
250
62.58
Finite automata or finite state machine can be thought of as a severely restricted model of a computer. Finite state machine that are acceptable only input alphabet‘0’ and ‘1’. - Determine the initial state. - The transition occurs on every input alphabet. - Determine whether the self-loop should apply or not. - Mark’s final state. Designing DFA step by step: Step -1: Make initial state “q0” then it is the possibility that there would not be any ‘1’ but have only ‘0’ in the string which is acceptable because 1 is multiple by 3. So, in this case, any number of 0’s can be present here and for this self-loop of ‘0’ on initial state “q0“. In above table -> represents initial state and * represents final state. In this post, initial and final state is same which is final state. Code: Main.java import java.util.Scanner; public class main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String str = sc.nextLine(); checkStateA(str); } private static void checkStateA(String str) { if (str.length() == 0){ System.out.println("String Accepted"); } else { if(str.charAt(0)=='0') checkStateA(str.substring(1)); else stateB(str.substring(1)); } } private static void stateB(String str) { if(str.length() == 0){ System.out.println("string not accepted"); } else { if(str.charAt(0)=='0') stateB(str.substring(1)); else stateC(str.substring(1)); } } private static void stateC(String str) { if(str.length() == 0){ System.out.println("string not accepted"); } else { if(str.charAt(0)=='0') stateC(str.substring(1)); else checkStateA(str.substring(1)); } } } Output: Enter the String 10101 String Accepted Recommended: - Introduction to Finite Automata - Deterministic Finite Automata (DFA) - Number of 1’s is not multiple of 3 on {0,1} using DFA - Automata Theory and Formal Languages - Kleene Closure - Recursive Definition of a Language - Finite Representation of language 1 thought on “Number of 1’s is a multiple of 3 on {0,1} using DFA”
https://quizforexam.com/number-of-1s-is-a-multiple-of-3-on-01-using-dfa/
CC-MAIN-2021-21
refinedweb
323
52.87
It’s on v1 Hmm… I am not sure how a Siamese network would work in @sbrunk’s example of TD+NLP data? I thought Siamese network uses the same layers/models for the two input, but the TD and NLP data should need different layers/models/archi’s to process? Curious to hear more about what you think is possible to do though, with Siamese on TD+NLP : ) Thanks. Yijin Ah you may be correct, sorry for misusing the terminology! What I meant was to use two networks (one for tabular, one for text) and then concatenate them at the head in order to produce a single output. Zach wrote a nice notebook demonstrating classification using multiple images. Back in Fastai v1, I made a model for multivariate regression using image and tabular data, and other Fastai users came up with great implementations for classification using image, text, and tabular data and classification using text and tabular data. Really enjoyed this lesson recreating AWD_LSTM. Thank you for all your efforts. Thank you so much for the awesome series of lessons! Going through the concepts and code examples of fastbook and attempting to answer questions at the end based on my understanding has been a real constructive exercise - good chance to find out what I thought I understood but didn’t. Fast.ai Part 1 Round 2 support group anyone? I plan on going through the chapters again, starting with Ch1 after a week off. Timing wise currently thinking Mondays or Tuesdays 6-9pm PST or Sunday afternoon. If this is of interest to you, heart this post and I’ll set up a google form to manually organize people into post-class support groups. Format will be silently re-reading the chapters or implementing notebooks, followed by 30 mins of discussion. I’d love a Tuesdays 6-9PM PST schedule myself, if at all possible. What do you all think? This is awesome! I’ve continued the discussion here for anyone that might be interested in joining the reading groups Thank you Jeremy, Sylvain and Rachel for your efforts to create and deliver this fantastic 4th incarnation of course1. I can’t echo the feelings of those who are sad that it’s over – because it’s not over unless you want it to be. We have our work cut out for us – to review and get at the marrow of each of the 8 lessons. And I’m looking forward to it! Thank you Jeremy, Sylvain and Rachel for the fantastic course! Looking forward to part 2! Chapter 10 and the ULMFiT paper indicates that training a bidirectional model reduces the error rate on IMDB by almost 1%. Does this mean that the base LM trainer on wikitext is trained backward and then then we further fine tune this LM with the IMDB dataset in the sale backward direction? By backward does it mean that every sequence of words in text and text_ are just flipped around and the LM’s task is to predict the first word in the sentence in this case rather than the next? The reason why tokenization techniques like stemming or lemmatization are not recommended when training neural networks, they essentially throw away certain useful pieces of information about the vocabulary and about the language. I have seen people still use these techniques in Information Retrieval domain to improve the recall. So it depends on the context and knowing when to use & when not to use them. More or less actually! You can see my example notebook I experimented with this (and sentence piece too on) back in v1, but it’s still the same thing in terms of concepts (it just shows sentence piece in terms of show_batch but you can see the backwards sentences) Also Rachel discusses this too in her NLP course as well Hi everyone! I have been trying to get started with NLP but I struggle to get a very simple example to work and I do no longer know what to try out. I have a dataframe with several columns most of which I do not need. Among them, the useful ones are my x (‘Answered Questions’) and my y (‘Classification’). I manage to successfully build a language model with it and I am only missing the classifier. I am struggling a lot to pass the y as a label… what am I missing here? def get_y(r): return r['Classification'] dls_clas = DataBlock( blocks=(TextBlock.from_df('Answered Questions', vocab=dls_lm.vocab, seq_len=dls_lm.seq_len), CategoryBlock), get_x=ColReader('text'), get_y=get_y, splitter=RandomSplitter(0.1)).dataloaders(data, bs=128) I have the feeling I am almost there but I get `TypeError: ‘str’ object cannot be interpreted as an integer -> KeyError: ‘Classification’ Setting up Pipeline: get_y -> Categorize (error happens here!) This was my best attempt in adapting the fastai text tutorial. Thanks a lot @muellerzr! I’ll try re-implementing that! Have you by any chance worked on visualising the trained embeddings using PCA? I have been Trying to do this but without much luck. Also have you looked into the slanted triangular learning rates introduced in ULMFiT or do you have any resources for that? I’m trying to work on the IMDB_SAMPLE dataset to try out various quick experimentations as mentioned in the paper on it while not overfitting that model as it’s a tiny dataset! Is ‘data’ in this case, which is passed to your dataloaders your pandas dataframe? I haven’t. I can provide a resource someone did for the tabular models if you think that would help Nope! I just followed the pattern instead. Hard not to, but good idea Perhaps play with a ton of dropout to see if it helps Yeah, would love to try that out myself! Haha, yeah noticed that! There’s a wonderful notebook by @Pak here: Jeremy covered this as well in the tabular lecture a bit: Thanks!! I finally found the mistake (which I would suggest to clarify in the documentation). So basically, the dataframe that is passed (data in my case) must have only two columns. The x can be called whatever but the y must be called label! db_clas = DataBlock( blocks=(TextBlock.from_df('Answered Questions', vocab=dls_lm.vocab, seq_len=dls_lm.seq_len), CategoryBlock), get_x=ColReader('text'), get_y=ColReader("label"), splitter=RandomSplitter(0.1)) This last bit was not clear to me by reading the documentation.
https://forums.fast.ai/t/lesson-8-official-topic/70494/230
CC-MAIN-2022-27
refinedweb
1,070
63.39
VARIANT Truth be told, I think the VARIANT concept is actually pretty cool. Wrap your data up in a nice little package with a type descriptor or two, throw it across a function call boundary and let the other side figure it out. If done right it can solve a lot of otherwise nasty problems. I just wish they were easier to work with! So that's the apology out of the way. Let's look at what a VARIANT is. Weakly typed languages allow you to pass arguments that don't match the types expected. So the question should arise - if you can pass the wrong argument type to a function how does the language respond? Most weakly typed languages 'coerce' the value that was passed into the expected type. What does this mean? It means that the language runtime will try and convert the data that was passed into the correct data type. For example, if you were to pass an integer to a function that expected to see a string the most natural 'coercion' is to convert the integer into a string representation. Pass a date where a string is expected and the natural 'coercion' is to convert it to a string representation. As C++ programmers we're already used to coercion on a small scale - we're used to the idea that the compiler can do promotions from short to int and so on. Weakly typed languages just take it a step or two further. short int So what has this to do with VARIANTs? Imagine you're designing your own programming language. You know the kinds of datatypes you want to support. You know the kinds of intrinsic operators you want. You can design your compiler to keep track of the datatype of everything in your program, so that when the programmer passes the wrong datatype to a function your compiler knows it and can insert the necessary code to convert the data. Now imagine you're required to not only support your language but another language (say C++). You have complete control over your own language but no control whatsoever over the second language. Yet you want to be able to interoperate with that language. Since it's you who wants to interoperate with something you cannot change it's up to you to adapt to the 'something you cannot change'. So you design your datatypes in such a way that they contain sufficient information over and above the data they encapsulate to allow anyone else to decipher their contents. oaidl.h wReserved What we're interested in are the vt values and the union. vt is the valuetype and the union is the value. You'll see that the union encompasses LONG, BYTE, SHORT, FLOAT and so on (there are a bucketload of em). vt tells us how to interpret the value, using the member names. In C++, you might do it like this <pre lang=c++> void SomeFunc(VARIANT& v) { USES_CONVERSION; if (v.vt == VT_I4) printf(_T("variant value is %d\n"), v.lVal); else if (v.vt == VT_BSTR) printf(_T("variant value is %s\n"), W2A(v.bstrVal)); } This checks the vt member of the VARIANT. If it's a VT_I4 then the data we want is contained in the lVal member of the union. Since the lVal member is a LONG we can use %d as the format spec in the printf call. If it's a VT_BSTR then the data is a BSTR contained in the bstrVal member of the union. vt LONG BYTE SHORT FLOAT VT_I4 lVal %d printf VT_BSTR BSTR bstrVal Notice how VARIANTs use the BSTR datatype to pass string data. This is done so that a VARIANT can be passed across a process boundary without incurring marshaling overhead. There are many other datatypes (not discussed in this article) which do require marshaling to cross a process boundary but the passing of strings is so common that using a BSTR to sidestep marshaling is a nice optimisation. CVariant(int iValue) ToString() SAFEARRAY The SAFEARRAY definition looks like this (this is the Win32 definition - it's a trifle different for WinCE). <pre lang=c++> typedef struct tagSAFEARRAY { USHORT cDims; // How many dimensions in this array USHORT fFeatures; // Allocation control flags ULONG cbElements; // The size of each array element ULONG cLocks; // Array lock count. PVOID pvData; // Points at the data in the array SAFEARRAYBOUND rgsabound[1]; } SAFEARRAY; You're going to love the purpose of the SAFEARRAYBOUND member. It's a structure that specifies the number of elements in this dimension and the lower bound. This allows an index into a particular dimension of the SAFEARRAY to start at any arbitrary number rather than the 0 that we C/C++ programmers know and love. There's an array of these structures, one for each cDim. SAFEARRAYBOUND cDim So accessing a VARIANT array in C++ involves interpreting the contents of the VARIANT as a pointer to a SAFEARRAY, validating the first array index against cDims to be sure it's in range, then indexing into pvData by the size of cbElements, accounting for the contents of this indices entry in the rgsabound array. Phew, what a mouthful! cDims pvData cbElements rgsabound Suddenly it's starting to look like maybe a class to encapsulate this stuff might be useful. This class can handle simple VARIANTS with signed integer datatypes or strings. It can also handle 1 dimensional arrays where each element of the array is a VARIANT which can be any of the simple types handled by the class. If you want more you can follow the code to see how to handle extra types. I've not needed types beyond those supported so I haven't written support for those types. VARIANTS Ok so that's the caveat out of the way. Here's the class header. <pre lang=c++> class CVariant : public VARIANT { public: CVariant(); CVariant(bool bValue); CVariant(int nValue); CVariant(LPCTSTR szValue); CVariant(VARIANT *pV); CVariant(int lBound, int iElementCount); ~CVariant(void); // Attributes BOOL IsArray(int iElement = 0); BOOL IsString(int iElement = 0); BOOL IsInt(int iElement = 0); BOOL IsBool(int iElement = 0); // Conversions VARIANT *operator&() { return this; } // Get operations VARIANT *ElementAt(int iElement = 0); CString ToString(int iElement = 0); int ToInt(int iElement = 0); BOOL ToBool(int iElement = 0); // Set operations void Set(LPCTSTR szString, int iElement = 0); void Set(int iValue, int iElement = 0); void Set(bool bValue, int iElement = 0); }; You've already seen the simple constructors. There are two other constructors. The first constructor lets you define an array. It takes the lower bound for an index, and a count of how many elements. The code looks like this. <pre lang=c++> CVariant::CVariant(int lBound, int iElementCount) { // Set the type to an array of variants... vt = VT_ARRAY | VT_VARIANT; parray = new SAFEARRAY; // We only support 1 dimensional arrays.. parray->cDims = 1; parray->fFeatures = FADF_VARIANT | FADF_HAVEVARTYPE | FADF_FIXEDSIZE | FADF_STATIC; parray->cbElements = sizeof(VARIANT); parray->cLocks = 0; // Allocate the array of variants we point to... parray->pvData = new VARIANT[iElementCount]; memset(parray->pvData, 0, sizeof(VARIANT) * iElementCount); parray->rgsabound[0].lLbound = lBound; parray->rgsabound[0].cElements = iElementCount; } From my description of the SAFEARRAY structure earlier this should all be pretty clear. We only support 1 dimensional arrays so we set the various members of the newly created SAFEARRAY instance to reflect that fact. The new SAFEARRAYs rgsabound[0] structure is set with our lower bound and count variables. It's important to remember that the VARIANT we're creating may be used to interoperate with a module created in another language and we can't assume that indexes start at 0. Where you start your indexes depends on what you're interoperating with. rgsabound[0] The fFeatures member needs some explanation. The flag values I used specify that the array contains VARIANTs of a fixed size and static (not created on the stack). I specify that it's static because if I need to allocate memory I do it from the heap. fFeatures The other constructor lets you take an existing VARIANT (passed perhaps to an event handler for some foreign object you're hosting) and attach it to a CVariant. The code looks like this. <pre lang=c++> CVariant::CVariant(VARIANT *pV) { // Validate the input (and make sure it's writeable) ASSERT(pV); ASSERT(AfxIsValidAddress(pV, sizeof(VARIANT), TRUE)); vt = VT_VARIANT; pvarVal = pV; } If it's a debug build we do some asserts to be sure that it's a pointer to a block of valid memory at least large enough to actually contain a VARIANT. There's not much more runtime validation we can do. Once we're sure it's something that could be a VARIANT we assign the pointer to the pvarVal member and set the type to VT_VARIANT. Once that's done we can use any of the other member functions on the VARIANT as though we'd created it ourselves. CVariant pvarVal VT_VARIANT CVariant::CVariant(VARIANT *pV) Attach Note well that there is no attempt at a copy constructor. Life is way too short to try and write such a beast. Think about it. Your code would have to cope with every possible variation and do deep copies of arrays within arrays within arrays. IsAsomething() Why don't I encourage access to the vt member via an explicit member function? Glad you asked. Access to that member would return the exact type. Why is that bad? It's bad because you then have to allow for all the myriad options. It could be VT_USERDEFINED or VT_BLOB_OBJECT or VT_DISPATCH. Since the class doesn't handle those types you can do nothing useful with the information. Much better, in my opinion, to ask the class, are you a string? Or are you an integer? If the answer is yes then you can proceed to perform meaningful operations. If not, you do whatever error handling is appropriate. VT_USERDEFINED VT_BLOB_OBJECT VT_DISPATCH Of course there's nothing stopping you accessing the vt member explicitly but if you do you're on your own. OPTION BASE 0 OPTION BASE 1 OPTION BASE The accessors use the ElementAt() helper function to access the data requested and then apply the appropriate data conversion based on the datatype. The ElementAt() function looks like this. <pre lang=c++> VARIANT *CVariant::ElementAt(int iElement) { if (vt == VT_VARIANT) // It's a pointer to an external VARIANT // so return that variant return pvarVal; if (!(vt & VT_ARRAY)) // It's not an array so return ourselves return this; // Calculate our element offset int offset = iElement - pvarVal->parray->rgsabound[0].lLbound; // Offset must be zero or greater and less than the bounds if (offset >= 0 && offset <= int(pvarVal->parray->rgsabound[0].cElements)) return &((VARIANT *) pvarVal->parray->pvData)[offset]; else return (VARIANT *) NULL; } You can see what I was talking about earlier. If the VARIANT is wrapping a VARIANT obtained from somewhere else we return that VARIANT. If the VARIANT isn't an array we return a pointer to ourselves (remember the class is derived from the VARIANT structure and has no vtable so this is equivalent to a pointer to the base VARIANT structure). ElementAt() vtable this Otherwise we have an array so we calculate an offset into the SAFEARRAY taking into account the lower bound stored in the rgsabound structure. Then we check that the offset is greater than or equal to 0 and less than the number of elements in the array and if it is we return a pointer to the SAFEARRAY element. If you've specified an index that's invalid you get back a NULL pointer. NULL The actual accessor looks like this. <pre lang=c++> CString CVariant::ToString(int iElement) { USES_CONVERSION; // Get the VARIANT at the iElement offset VARIANT *v = ElementAt(iElement); // Must be a valid pointer and must be valid readable memory if (v != (VARIANT *) NULL && AfxIsValidAddress(v, sizeof(VARIANT), FALSE) && v->vt == VT_BSTR) return W2A(v->bstrVal); return _T(""); } Pretty simple. The other accessors work in much the same way. Notice that the bool overloads use the lowercase bool datatype, not the typedef'd BOOL. This is necessary to distinguish between the int and bool overloads. We need the different overloads so we can in fact create a VARIANT with the VT_BOOL type. bool typedef BOOL VT_BOOL switch 20 March 2004 - Added bool overloads. 28 March 2004 - Fixed a bug in the ElementAt().
https://www.codeproject.com/articles/6462/a-simple-class-to-encapsulate-variants/?fid=35985&df=90&mpp=10&sort=position&tid=1128257
CC-MAIN-2017-09
refinedweb
2,066
62.88
Use PowerShell and WMI or CIM to View and to Set Power Plans Summary: Microsoft Scripting Guy, Ed Wilson, shows how to use Windows PowerShell and WMI or CIM cmdlets to view and to set power plans on his laptop. Microsoft Scripting Guy, Ed Wilson, is here. Tomorrow, the Scripting Wife and I are at the Microsoft Technology User Group in Oslo, Norway. I will be talking about using Windows PowerShell 3.0 to manage a remote Windows 8 workstation. Last night we were in Stockholm with the Stockholm PowerShell User Group, and today is a travel day. We are taking the beautiful train from Stockholm to Oslo. In addition to being a great way to travel, it provides stunning views, and a comfortable compartment within which to write Hey, Scripting Guy! Blog posts. All these trains, user group presentations, and more trains, got me to thinking: I like to have my laptop running full power when making a user group presentation—of course, I am always plugged in to power while doing so. When I am on a train, or in a plane, I generally am running on battery (although most of the trains we have been riding on also have power at the seat). So, when plugged into electricity, I want to run the laptop on full power; when running on battery, I want to run the laptop on maximum conserve power. I think this calls for a quick Windows PowerShell script. But first, I need to spend a bit of time talking about WMI, CIM, and the Win32_PowerPlan WMI class. Detecting laptop power plans Windows 7 introduced the Win32_PowerPlan WMI class. This WMI class resides in the Root\Cimv2\Power WMI namespace. Because this is not the default Root\Cimv2 namespace, this means that any script or code to query from this class must include the Root\Cimv2\Power namespace in the code. To enumerate the available power plans on the laptop, I can use either Get-WmiObject, or, in Windows PowerShell 3.0, I can use the Get-CIMInstance class. Either one works and using one as opposed to the other, in this case, is a simple matter of substituting one name for the other. The Get-WmiObject command is shown here, where gwmi is an alias for the Get-WmiObject cmdlet, -NS is a parameter alias for –NameSpace, select is an alias for the Select-Object cmdlet, ft is an alias for the Format-Table cmdlet, and –a is a partial parameter for –autosize. gwmi -NS root\cimv2\power -Class win32_PowerPlan | select ElementName, IsActive | ft -a ElementName IsActive ———– ——– Balanced False High performance True Power saver False An expanded version of the command is show here. This is still a single-line command with complete cmdlet names and parameter names. I have broken it at the pipe character for readability: Get-WmiObject -Namespace root\cimv2\power -Class win32_PowerPlan | Select-Object -Property ElementName, IsActive | Format-Table -Property * -AutoSize If I do a direct substitution, from the short form of the command to Get-CimInstance, an error arises when I run the code. This is because Get-CimInstance does not have a parameter alias NS for the NameSpace parameter (by the way, Get-CimInstance uses –classname instead of –class for the complete parameter name as well). The error is shown here. The easy solution: Just use –N instead of the parameter alias –NS. This technique is shown here. PS C:\> Get-CimInstance -N root\cimv2\power -Class win32_PowerPlan | select ElementNa me, IsActive | ft -a ElementName IsActive ———– ——– Balanced False High performance True Power saver False Making a particular power plan active To make a particular power plan active, I only need to call the Activate method from a specific instance on a Win32_PowerPlan WMI class. What this means is that I return a specific power plan via the Win32_PowerPlan WMI class, and then call the Activate method. This is really easy by using the Get-WmiObject cmdlet—it is a bit more difficult by using the CIM classes. Note The new way to work with WMI classes is to use the new CIM interface. The OLD WMI COM interface is now legacy. This means that you should begin learning the new CIM cmdlets, and, as far as possible, use them instead of the legacy methods. The CIM cmdlets are much more powerful, and once mastered, they are actually easier to use and to understand. For a good overview of the CIM cmdlets see this article. I will illustrate each technique in the following sections. Using Get-WmiObject First, by using the Get-WmiObject cmdlet, I add a filter that returns only one power plan. In this case, I want to return only the Power Saver power plan. I store the returned object in a $p variable. Once I have done this, I call the Activate method, as shown here. $p = gwmi -NS root\cimv2\power -Class win32_PowerPlan -Filter “ElementName =’Power Saver'” $p.Activate() I can certainly use the following query to confirm that the change worked, but it is obvious when the laptop screen dramatically dims. J gwmi -NS root\cimv2\power -Class win32_PowerPlan -Filter “IsActive = ‘true'” If I am in doubt, I can also verify in the Power Options dialog box, as shown here. Using the CIM cmdlets to set the power plan on my laptop The procedure to set the power plan on my laptop is exactly the same whether I use the CIM cmdlets or whether I use the Get-WmiObject cmdlet—I must return an instance of the power plan, and I must make it active. However, the CIM cmdlets do not permit calling methods from “de-serialized” or “non-live” objects. It is not a good idea and can actually lead to potential instability. The old WMI COM interface does permit this calling of methods from the non-live objects. When I use Get-WMiObject and return a list of processes (via Win32_Process), the process objects are no longer live. In fact, I could stop processes, or start new processes, and the changes are not represented in the variable containing the returned process objects. This is something people often forget. If I then take one of these offline processes and attempt to terminate the process, and the process no longer exists, then an error arises. By using CIM, this problem never happens because I cannot call methods on the returned objects. Instead, I must use the Invoke-CimMethod cmdlet. The cmdlet is easy to use, and I will follow the same procedure I used with Get-WmiObject. $p = Get-CimInstance -Name root\cimv2\power -Class win32_PowerPlan -Filter “ElementName = ‘High Performance'” Invoke-CimMethod -InputObject $p -MethodName Activate Note One thing I should mention is that the new CIM interface is AMAZINGLY FAST! Whereas the call using Get-WmiObject took nearly 10 seconds to return, the Invoke-CimMethod call returned immediately. Join me tomorrow when I will write the actual script that will set the appropriate power plan for my laptop.
https://devblogs.microsoft.com/scripting/use-powershell-and-wmi-or-cim-to-view-and-to-set-power-plans/
CC-MAIN-2022-40
refinedweb
1,165
60.14
In today’s Programming Praxis exercise, our task is to calculate all the narcissistic numbers, also known als the Armstrong numbers or the pluperfect digital invariants, i.e. the sequence of numbers for which the sum of the cubes of the digits is equal to the number itself. Supposedly, a mathematician by the name of Dik Winters developed an algorithm in 1985 that could generate all 88 numbers in about half an hour, which should theoretically run in seconds on modern day hardware. Unfortunately, neither Phil (the author of the Programming Praxis blog) nor I were able to find the original algorithm. The exercise provides a brute-force solution, which of course will not terminate in anything close to an acceptable time since the highest number in the sequence has 39 digits. The solution I came up with in the end (after lots of different approaches to speed things up) is significantly faster than the naive brute-force solution, yet still nowhere close to the theoretical solution. Some imports: import Data.List import qualified Data.Vector as V Since calculating the full sequence takes too long, I added an argument to specify the maximum amount of desired digits for timing purposes. narcissistic :: Integer -> [Integer] narcissistic upto = narcs =<< [1..min 39 upto] \\ [2,12,13,15,18,22,26,28,30,36] When generating the narcissistic numbers, we make a number of improvements to the brute-force algorithm: - Since the order of the digits doesn’t matter for the sum of cubes, we only look increasing series of digits, ruling out all permutations - Since the power function is relatively expensive, we precalculate all 10 possibilities into a lookup table - All digits sequences with a sum that is too low or high for an n-digit number are ignored narcs :: Integer -> [Integer] narcs n = sort $ f [] 0 9 n where powers = V.fromList $ map (^n) [0..9] pow i = powers V.! fromIntegral i (lo, hi) = (10^(n-1), 10^n) f ds s x 1 = [ s' | i <- [0..x], let s' = s + pow i, s' >= lo , s' < hi, sort (show s') == (show =<< (i:ds))] f ds s x d = [0..x] >>= \i -> f (i:ds) (s + pow i) i (d-1) With this approach, calculating the numbers of 1 through 16 digits takes about 3.4 seconds. 1 through 25 digits takes just over 4 minutes. I have no idea how long the full sequence would take. I’m sure there’s some way to eliminate more options using some mathematical proof, but I haven’t been able to find or come up with one. main :: IO () main = mapM_ print $ narcissistic 16 Tags: armstrong, bonsai, code, digital, Haskell, invariants, kata, narcissistic, numbers, pluperfect, praxis, programming, winters December 16, 2012 at 1:07 am | N=20 ___ 1,91 secs N=25 ___ 13,12 secs N=39 ___ 13,06 minutes
https://bonsaicode.wordpress.com/2012/12/14/programming-praxis-115132219018763992565095597973971522401/
CC-MAIN-2016-50
refinedweb
479
57.61