text
stringlengths
454
608k
url
stringlengths
17
896
dump
stringlengths
9
15
source
stringclasses
1 value
word_count
int64
101
114k
flesch_reading_ease
float64
50
104
Discussion Board for collaboration related to Creating Analytics for QlikView. I have a script but i dont want to write where condition in this script i have dimensions like these ID Name Type there is 3 types of people now i want only 3 type in table but i dont want to put where condition in script because this table is associated with other tables so i am trying to filter it out on TYPE dimension how i done this any help ? ?? Assuming you want a,b,c you can do the following. inner join (Your_source_table) load * inline [ Type a b c ]; no i dont want like that i want to filter it our on dimension not on script .. i have data like this type 1 2 3 i add dimension TYPE then from that i only want 3 i dont want to where condition in script try this in filter if(type=3,type,null()) if(type=1 or type=2 or type= 3 ,type) this is not working if type field is in Text format put it in ' '(Single quote) i did that but not working if(type='3',type) type is TYPE is same .. look there is the data in TYPE column I.E. 1,2,3 now i want 3 type in my data like with this i have a separate columns from different tables i,e, name country address type abc US none 1 xyz UAE abc_address 3 def MAL gh_Address 2 and so on data type typename 1 low 2 high 3 medium now i add script like this load name , country , address type from abc_file and on the other tab load type,typename from type_file now if i only want data type 3 is supposed to write script like this load name , country , address type from abc_file where type=3 but i dont want like this i add table then i add dimensions i.e. name and type so now on that type dimension how i add where condition ?
https://community.qlik.com/t5/QlikView-Creating-Analytics/where-condition-in-dimension/m-p/1542839
CC-MAIN-2019-09
refinedweb
336
56.66
import bb.cascades 1.0 TabbedPane { id: tabbedPane showTabsOnActionBar: true Tab { title: "Tab 1" content: Page { content: Label { text: "This is tab 1." } } } // end of first Tab Tab { title: "Tab 2" content: Page { content: Label { text: "This is tab 2." } } } // end of second Tab } // end of TabbedPane Tabs You can use a TabbedPane to manage multiple screens in your app and let users navigate between the screens. A TabbedPane stores screens as a set of tabs that are located at the bottom of the screen, in the same area where actions are displayed. Users can tap a tab to display the associated screen. Only the screen that's associated with the currently selected tab is displayed, and the others are hidden. A Tab represents an individual screen in a TabbedPane. A Tab can include a Page or NavigationPane as its content, each of which can have their own content and actions associated with them. A TabbedPane includes properties that specify the set of tabs in the TabbedPane (the tabs property) and the tab that's currently displayed (the activeTab property). A TabbedPane also includes signals that are emitted when tabs are added or removed, and when the active tab changes. To specify how a tab appears at the bottom of the TabbedPane, you can use various properties of Tab and its superclass, AbstractActionItem. For example, you can use the title property to set the name of the tab, or the image property to specify an image to display with the name of the tab. You can also use the showTabsOnActionBar property of Tab to determine whether tabs appear in the action bar at the bottom of the screen or in the tab menu on the left side of the action bar. If showTabsOnActionBar is true, tabs are displayed directly on the action bar. If showTabsOnActionBar is false, tabs appear in the tab menu and users can tap the tab menu button to access all of the available tabs. When tabs are placed in the tab menu, the name and icon of the current tab are displayed on the tab menu button. Note that even if the showTabsOnActionBar property is true, if you add more tabs than can fit on the action bar (more than four tabs), the tab menu is created automatically. In this case, the tab menu contains all of the tabs in the TabbedPane, even the ones that fit on the action bar. When the tab menu is added, the left-most tab on the action bar becomes a button that opens the tab menu, leaving three other tabs displayed on the action bar. To add tabs to a TabbedPane, you can call TabbedPane::add(). This function appends the specified tab to the list of existing tabs at the bottom of the screen. You can also call TabbedPane::insert() to add a tab to a specified location in the list of existing tabs. The tabs that you add to a TabbedPane appear at the bottom of the screen. This area also contains actions that are associated with the screen that's currently displayed. When you use a TabbedPane and one of the screens includes actions, these actions are displayed to the right of the tabs at the bottom of the screen. If the screen includes a single action on the action bar, that action is displayed to the right of the tabs. If the screen includes more than one action, the actions appear in the action menu to the right of the tabs. Users can tap the action menu button to display the action menu for that screen. You can create a TabbedPane object, define Tab objects, and add the Tab objects to the TabbedPane. // Create the root TabbedPane, and specify that tabs should appear on // the action bar TabbedPane *root = new TabbedPane; root->setShowTabsOnActionBar(true); // Create the first tab and its content Tab *firstTab = Tab::create() .title("Tab 1"); Page *firstTabContent = new Page; firstTabContent->setContent(Label::create("This is tab 1.")); firstTab->setContent(firstTabContent); // Create the second tab and its content Tab *secondTab = Tab::create() .title("Tab 2"); Page *secondTabContent = new Page; secondTabContent->setContent(Label::create("This is tab 2.")); secondTab->setContent(secondTabContent); // Add the tabs to the TabbedPane root->add(firstTab); root->add(secondTab); // Display the TabbedPane Application::instance()->setScene(root); Not applicable Dynamic loading of tabs To reduce the start times of your app, you can delay the loading of content until it's absolutely necessary. For content in tabs, you do this by using the Delegate and the TabDelegateActivationPolicy classes. The Delegate class provides a generic delegate that instantiates an object when it's active, and deletes it when it's not active. The delegateActivationPolicy property specifies when a Tab sets the active property of its delegate. Using these classes, you can define a delegated tab and control its loading and deletion. In this code sample, the Page to be dynamically loaded is included as the source of the Delegate: TabbedPane { Tab { id: tab1 delegate: Delegate { id: tabDelegate source: "page1.qml" } delegateActivationPolicy: TabDelegateActivationPolicy.Default } } Not applicable Not applicable Here, delegateActivationPolicy is set to TabDelegateActivationPolicy.Default, which sets the active property of the delegate to true, meaning the content is loaded on tab selection. The available activation policies are: - Default: The system chooses the activation policy, typically the object activates with selection. - None: The tab never sets the active property, you decide when to load or delete the object. - ActivatedWhileSelected: The tab content is loaded (active set to true) when the tab is selected and deleted (active set to false) when it's no longer selected. This improves start time but switching between tabs may be slow. - ActivateWhenSelected: The tab content is loaded (active set to true) when the tab is selected and never deleted during the lifetime of the object. Since the content is never deleted, performance is impacted only the first time the tab is selected. - ActivateImmediately: The active property is immediately set to true and the tab content is created when the delegate's source property is set. Clearing source deletes the content. In the following code sample, using a delegateActivationPolicy of TabDelegateActivationPolicy.None, you must include code that sets the active property explicitly: TabbedPane { Tab { id: tab1 delegate: Delegate { id: tabDelegate1 source: "page1.qml" } delegateActivationPolicy: TabDelegateActivationPolicy.None } Tab { id: tab2 delegate: Delegate { id: tabDelegate2 source: "page2.qml" } delegateActivationPolicy: TabDelegateActivationPolicy.None } onActiveTabChanged: { if (activeTab == tab1) { tabDelegate1.active = true; tabDelegate2.active = false; } if (activeTab == tab2) { tabDelegate1.active = false; tabDelegate2.active = true; } } onCreationCompleted: { tabDelegate1.active = true; } } Not applicable Not applicable In this way, you are controlling the loading and unloading of content explicitly. Last modified: 2015-07-24 Got questions about leaving a comment? Get answers from our Disqus FAQ.comments powered by Disqus
https://developer.blackberry.com/native/documentation/ui/navigation/multiple_screens_tabs.html
CC-MAIN-2020-34
refinedweb
1,120
54.52
Preincrement vs. postincrement I was looking through the Guru of the Week archives ( ) and came across this item in the issue on temporary objects ( ): "Preincrement is more efficient than postincrement, because for postincrement the object must increment itself and then return a temporary containing its old value. Note that this is true even for builtins like int!" For objects this makes sense, but I haven't found it to be true for int's. An instructor told me years ago that all my loop indexes should be preincremented because it's more efficient. So, I tested this by compiling a small C program with two for loops, something like: for ( ; ; i++ ) { ... } -- and -- for ( ; ; ++i) { ... } I found no difference between the two in the resulting assembly file. My assumption is that compilers have just optimized it, so is this really an issue anymore? Yet another anon Friday, August 06, 2004 Turn off optimisation and find out (yes, there are some places where compiler optimised output is not allowed). Friday, August 06, 2004 I had this worry myself :) For native types like int the compiler indeed optimizes it away (I checked), but with more complex objects it might choke (I didn't check). I usually post-increment native types (can't break the habit) and pre-increment only iterators etc. Alex Friday, August 06, 2004 Also from that article: [Rule] Follow the single-entry/single-exit rule. Never write multiple return statements in the same function. I speak from very limited experience, but it doesn't seem tremendously difficult to implement return-value optimization. From what I've peeked at, the caller itself preallocates N bytes on the stack and THEN makes the call. The called function forms the object directly in the space reserved, and returns. The callee now has a valid object right on top of the stack. It depends on the processor and what is being done with he result whether or not preincrement or postincrement is faster, or even the same. For example, postincrement is faster than preincrement on the motorola 68000 series because postincrementing can be done in a single operation. Tony Chang Friday, August 06, 2004 Yes, the compiler will optimise it out for int, now try it with an iterator over a std::map. More to the point, however, you should use preincrement because it expresses what you actually mean. Preincrement means 'incrememnt this', postincrement means 'increment this and then give me it's original value' - use whichever fits your intended meaning better. Mr Jack Friday, August 06, 2004 Tony - I think the point is to avoid (possibly unnecesary) object creation caused by the "give me its previous value" indicated in Mr Jack's post. I doubt that the 68000 can do that in one operation :-) Uh? That sounds wrong. Certainly the "C" specification says that the post increment happens at the end of the statement so simple code that trys to convert two ascii digits into decimal like this: x=(*(c++) -'0')*10+(*(c++) -'0'); can be legitimately compiled (and has been by at least one compiler I know) into: x=(*c -'0')*10+(*c -'0'); c+=2; The increments happen at the end of the statement. No extra copy required. I don't know what the C++ spec says about this but I'd guess it was the same. Peter Ibbotson Friday, August 06, 2004 Are you sure about that Peter? Have you actually checked the specs? In C++ the bit of code you just described has undefined behaviour, and I'd be very, very surprised in the C++ version was more loosely defined than the C one (unless they introduced the change in C99, that is). I refer you to - note 5. I can't quite see it in there the only relevant bit I can see is: -4- Except where noted, the order of evaluation of operands of individual operators and subexpressions of individual expressions, and the order in which side effects take place, is unspecified. My brief test with MS VC6.0 with this code (I've made x a global to stop the compiler optimising the second increment away). char *x; int ParseIt() { return (*(x++)-'0')*10+(*(x++)-'O'); } Compiling with CL /Ox /Fa /c test.cpp Produces this assembler output: ?ParseIt@@YAHXZ PROC NEAR mov ecx, DWORD PTR ?x@@3PADA movsx eax, BYTE PTR [ecx] sub eax, 48 add ecx, 2 mov DWORD PTR ?x@@3PADA, ecx lea edx, DWORD PTR [eax+eax*4] lea eax, DWORD PTR [eax+edx*2] ret 0 ?ParseIt@@YAHXZ ENDP Better yet the current VS.NET 2005 compiler produces this output: ?ParseIt@@YAHXZ PROC ; ParseIt mov ecx, DWORD PTR ?x@@3PADA movsx eax, BYTE PTR [ecx] imul eax, 11 add ecx, 2 sub eax, 545 mov DWORD PTR ?x@@3PADA, ecx ret 0 ?ParseIt@@YAHXZ ENDP An interesting question at this point is what does gcc do? I don't have a copy handy any more, so I can't say. Bugger, somehow the formatting got screwed up! Anyway try it and see. ." ... says the comp.lang.C FAQ Using a variable the state of which changes during the same expression is not illegal, but the results are either implementation defined or altogether undefined. (If it's implementation defined it means that in theory your compiler vendor should have a section in their manual which explains what will happen for that case on that version of that compiler with that OS, architecture and libraries, whereas if it's undefined it means the compiler may legitimately do anything that it pleases with no further warning. Classically the GNU compiler has threatened to replace undefined programs with "nethack" or to provide a result binary that when run destroys the undefined source code...) Nick Lamb Friday, August 06, 2004 "Except where noted, the order of evaluation of operands of individual operators and subexpressions of individual expressions, and the order in which side effects take place, is unspecified." That's it exactly. As with many things in C/C++ it may work just fine on your compiler, but it may not on others. Incidently, the reason it is not defined is apparently because it's possible for a compiler to optimise better by not worrying about it, so it's even possible that the same compiler could do it differently with different expressions. Re-reading my original what I meant to say instead of: "happens at the end" was "happens by the end" And I thought you were arguing the other end. Particularly with your statement "postincrement means 'increment this and then give me it's original value'" which it clearly doesn't. What postincrement means is: "Use the current value and increment at some point between here and the end of this expressions evaluation" I don't play[1] C language lawyer anymore I've used "end of this expressions evaluation" 'cos I've forgotten what the exact term ANSI use is. [1] Once upon a time many years ago (1987?) when TurboC was version 1.0 I did the support in the UK and could quote bits of the proposed ANSI spec. Good point. My phrasing was sloppy - in my defense I was refering to the original posters usage where the entire expression is 'i++' vs. '++i'. Phew... at least we agree. In fact the real problem is in the original article and it's mention of integers. Also it does depend on architecture, on many processor families there is a post increment / pre decrement addressing mode available to allow stacks to be easily built. > An instructor told me years ago that all my loop indexes should be preincremented because it's more efficient. Does your instructor also cut their lawn with nail scissors? That's terrible advice. Micro-optimizations do not make programs more efficient. On modern architecture, that change will save you what, two billionths of a second? That'll really please the users and sell more copies... Don't worry a whit about these kinds of optimizations unless you're building a compiler. Worry about the big stuff that takes milliseconds, not the stuff that takes nanoseconds. Eric Lippert Friday, August 06, 2004 comparing: for ( ; ; i++ ) { ... } -- and -- for ( ; ; ++i) { ... } These will likely will generate identical instructions. The reason is that the only semantic difference is the value of the expression (++i vs i++), and your program doesn't use the value. If you change it to something like: int foo; for ( ; ; foo=i++ ) { ... } You'll see the difference in the generated code, but they will probably compile to the same number of instructions. As others have said, the real difference comes when i is not a built-in type, but is an instance of a class that defines the ++ operators. Then, assuming you are sane and they are semantically identical except for the return value, the postfix operator ++ can't be faster than the prefix operator ++. EL> That's terrible advice. Micro-optimizations do not make programs more efficient True, it will almost never make a measurable difference. But given that one is necessarily no faster than the other, and they are otherwise equivalent, why would you choose the slow one? I wouldn't go back through existing code just to change this, but for new code why not write ++i? Brian Monday, August 09, 2004 Recent Topics Fog Creek Home
http://discuss.fogcreek.com/joelonsoftware/default.asp?cmd=show&ixPost=171881
CC-MAIN-2014-41
refinedweb
1,560
62.88
21 October 2008 15:15 [Source: ICIS news] By Will Beacham LONDON (ICIS news)--The chemicals business of UK oil major BP is in the midst of a global collapse in demand for its products which is expected to last at least until the end of the year, a company executive said on Tuesday. ?xml:namespace> Demand was falling across the portfolio and in all the company’s key geographical regions, said Steven Welch, chief operating officer, international business refining and marketing segment. The fall-off, which became more noticeable around six weeks ago, had led to zero or even negative demand growth for some products, he said at a press meeting. The company was still analysing how much of the downturn was due to the global economic slowdown and how much was down to de-stocking by its customers, Welch added. “In Europe and the ?xml:namespace> In In The news was also bleak for acetic acid, another important product area where the company controlled about 25% of the global market, he said. “The slowdown in building, construction and home improvement use means that year on year we expect [acetic acid] demand to be somewhat negative in Europe and
http://www.icis.com/Articles/2008/10/21/9165283/bp-suffers-global-collapse-in-demand-for-chems.html
CC-MAIN-2014-41
refinedweb
200
51.92
Let's say I have two classes. One class, "parent", has many of another class "child". This is not inheritance, I don't want parent methods to act on child objects. What I want is the child object to be able to reference the parent object, get variables from it (child.parent.var) and call parent methods that modify the parent ( child.parent.update class Parent attr_accessor :var def initialize(num) @var = num end def increase @var += 1 end end class Child attr_accessor :var, :parent def initialize(parent, num) @parent = parent @var = num end def sum @parent.increase @parent.var + var end end parent1 = Parent.new(1) child1 = Child.new(parent1, 2) child2 = Child.new(parent1, 3) child1.parent.increase # update the parent variable child2.parent.var # get the parent variable This is basically how it's supposed to be done :) There are a couple of possible improvements though, depending on what you actually want to achieve. Right now, your Child instances expose access to the parent on their external interface (via the public parent accessor). This is often a violation of the Law of Demeter which states that objects should only talk to their direct neighbors. In this sense, the parent is a stranger when accessed though the child object. You could improve your design by hiding the parent object: class Child extend Forwardable def_delegator :@parent, :var, :parent_var def_delegator :@parent, :increase attr_accessor :var def initialize(parent, num) @parent = parent @var = num end def sum @parent.increase @parent.var + var end end Here, we use Ruby's Forwardable module to provide access to some methods of the parent from the client. This makes these methods part of the single public interface of your Child class. parent = Parent.new(1) child = Child.new(parent, 2) child.var # => 2 child.parent_var # => 1 child.increase # => 2 parent.var # => 2 # ^^^^ the increase method was called on the parent object From the outside, it doesn't matter that the methods are forwarded and you can later change this without affecting your external interface at all. A second improvement could be to extend your Parent class to generate children directly: class Parent # ... def child(num) Child.new(self, num) end end This is usually called a Factory Method, i.e. a method which builds other objects. With this, you can hide the complexity of building your Child objects and attaching them to your parent. You can call it like parent = Parent.new(1) child = parent.child(2)
https://codedump.io/share/O3c7apZUSXXG/1/quotparentquot-quotchildquot-classes-in-ruby-not-inheritance
CC-MAIN-2018-22
refinedweb
411
59.4
Russell Cattelan <cattelan@xxxxxxxxxxx> writes: > Christoph Hellwig wrote: > >> Now that the xfs-dev branch was updated after a while I tried a git pull >> an get a useless error message: >> >> > I agree that is a worthless error message and does nothing to really > tell you what the problem is. > >. > >>. Please read git documentation. You don't want to be pulling xfs-dev into a xfs/master tree, you should setup a remote properly and have local branch tracking them. > of course this would be so damn confusing if somebody would document > the procedures someplace?! > Hmm I wonder where we could do that.... ohh wait maybe the WIKI! --> out of captcha images; this shouldn't happen you can read this: ----------------------------------------------------------- * Where is it? * Checking out a tree * Tree Status * Modifying files before checkins * Commiting/checking in * Going back in history - changing one's mind * Tracking remote trees * Publishing one's tree * Reviews and requesting them * Importing changes to our development tree * Lost your quilt ? ----------------------------------------------------------- * Where is it? A git server is setup on git.melbourne.sgi.com which is serving out of /git. A user, git, has been setup with the home directory of /git. The xfs trees are located under /git. The main development tree is a bare repository under /git/xfs.git. (So it has no checked out files just the .git database files at the top level) So far, it has a master, a mainline and an xfs-dev branch. The master branch is used for the checking in of development, it is mainline+latest XFS. xfs-dev will be set up to track ptools, checkins are currently closed to that branch. Additionally the config of the git setup (gitconfig, gitdescription, and git-hooks) as well as some home scripts (git-finalize and git-ptools) can be found in git+ssh://git.melbourne.sgi.com/git/git-ptools) * Checking out a tree: o Ptools: $ mkdir isms/2.6.x-xfs; vi isms/2.6.x-xfs/.workarea; cd fs/xfs; p_tupdate o Git: $ git clone git+ssh://git.melbourne.sgi.com/git/xfs/ ( for local trees you can use the path directly, if the machine is running a git-daemon you can use git://, but that will not auto-setup push syntax ) this will clone the tree (all the commit objects), and checkout the HEAD branch (master for our case, other branches can be seen with git branch -a, to checkout a branch (local or remote) just use: $ git checkout $branch * Tree Status: o Ptools: $ p_list -c # shows file you've informed ptools about o Git: $ git status # lists modified, unmerged and untracked files. $ git log # shows all commited modifications ( you can use git log $remote/branch to see the log of a remote ) * Modifying files before checkins: o Ptools: $ p_modify file # modify $ p_fetal file # add $ p_delete file # remove o Git: # no need to mark files for modification, git will find out about them automagically, just edit them. $ git add file # add $ git rm file # remove Note: that if one uses "git-commit -a" or "git-finalize -a" then you don't have to add files which have been modified or deleted as git will detect them, you only have to add new files. * Commiting/checking in: o Ptools: $ p_finalize file o Git: $ git commit From man page - useful options: -------------------------------- -a|--all:: Tell the command to automatically stage files that have been modified and deleted, but new files you have not told git about are not affected. -. -s|--signoff:: Add Signed-off-by line at the end of the commit message. I do like to git commit -asm "Commit message" -------------------------------- remember that a git commit, only commits to YOUR local tree, you then need to push things over: General form is: $ git push git://uri/of/the/other/rep +refspec ---------------- For XFS project: ---------------- Using the wrapper script, git-finalize, this would become: $ git-finalize -a # it asks questions to set up commit description git-finalize: [-d] [-a] [-p pv] [-u author] [-r reviewer] [-s summary] [-F desc_file] [files] noting: -d: debug option - doesn't run the commit command -a: the all option passed thru to git-commit pv: bugworks pv number which will be looked up using bwx author: author in format: Andrew Morton <akpm@xxxxxxxxxxxxxxxxxxxx> reviewer: in author format and can have multiple -r options summary: summary 1 line description of the commit desc_file: a file containing body of the commit description [files]: explicit files for commit (can't use with -a option) $ git push melbourne Where in workarea/.git/config it has the few lines: [remote "melbourne"] url = ssh://git.melbourne.sgi.com/git/xfs.git push = master (Or modify the config file using "git remote add" mentioned below) * Going back in history - changing one's mind o Ptools: $ p_unmodify file o Git: [the STUPID (ptools) way] $ git revert $mod will introduce a new commit reverting $mod. [ the OH GOD WE ARE DISTRIBUTED way (for mods not pushed anyway)] if the mods to revert are the last n one: $ git reset HEAD^n if not (dangerous) $ git rebase -i $mod^1 # considered harmfull read documentation ! Other related commands: $ git reset # see doc for --hard * Tracking remote trees: o Ptools: remote what ? there shall be only one tree, MY TREE o Git: $ git remote add $name $uri # adds a remote tracking $ git remote update # updates all remotes $ git branch -a # shows all accessible branches ( including remotes in the $remote_name/ namespace ) $ git checkout -b $local_branch_name --track $remote_name/$remote_branch # creates a tracked local branch, git will warn whenever the remote adds commits. * Publishing one's tree: o Ptools: Be Andy. o Git: give shell access to your tree, use git+ssh://machine/path or direct path or $ sudo git-daemon --export-all --base-path=/srv/git --base-path-relaxed --reuseaddr --user-path=public_git # exports all git trees found under ~/public_git and /srv/git Or set up indetd etc. * Reviews and requesting them o Git: [ Developer ] (A) From a git tree: É publishes a git tree at git://dev/tree, containing his feature1 branch É Requests a pull from the reviewer. or (B) publishes a series of patches: $ git format-patch $since_head # create ordered patches since head $since_head, i.e. on branch linus-create-ea, I'd $since_head would be linus/master $ git send-email --compose *.patch * Importing changes to our development tree o Git: [ Reviewer - typically us at SGI ] (A) From a git tree: É Adds a remote locally called "dev": $ git remote add dev git://dev/tree É Looks at the differences between his tree (dev) and feature1: $ git log HEAD...dev/feature1 # differences in both ways, read man for more detailâ List patches of commits from HEAD or dev/feature1 but not in both (A...B in one branch but not both) (A..B in branch B but not in A) É Reviews the diffs: (-p adds commit change in patch form) $ git log -p dev/feature1..HEAD É For each commit he accepts, imports it to his tree, adding a Signed-off-by: automatically: Whilst in our own development tree, cherry-pick from the remote $ git cherry-pick -s -e $commit # easily scriptable with git cherry É The only trick there is putting the description into our preferred format, with summary line with [XFS] prefix, body, and SGI-PV. I guess we'll need to do that manually. É Pushes it to tree git+ssh://git.melbourne.sgi.com/git/xfs.git $ git push melbourne # if you've set up tracking remotes correctly if not $ git push git://chook/xfs/xfs-dev <refspec> # read manâ of form: git push repository <refspec> where <refspec> of form: The canonical format of a <refspec> parameter is `+?<src>:<dst>`; that is, an optional plus `+`, followed by the source ref, followed by a colon `:`, followed by the destination ref. The local ref that matches <src> is used to fast forward the remote ref that matches <dst>. If the optional plus `+` is used, the remote ref is updated even if it does not result in a fast forward update. or (B) From emailed patches:  From a plain patch: $ git apply $patch # evil  From a mailbox: $ git am -s $mailbox # the way to go, adds Signed-off-by In order to modify the commit description, it may work to apply the committed patches in another branch and then "cherry-pick -e" them into the development branch. * Lost your quilt ? Hope you use underwear. if not, you can look at many projects made of awesome: guilt (written by Jeffpc, an XFS hacker): quilt for git; similar to Mercurial queues Guilt (Git Quilt). stgit: manage stacks of patches in a git repository. topgit (house favourite, we may want to impose this one, but needs a bit of git knowledge to fully understand):. if you s/git.melbourne.sgi.com/oss.sgi.com/ Cheers, -- Niv Sardi
http://oss.sgi.com/archives/xfs/2008-12/msg00275.html
CC-MAIN-2013-48
refinedweb
1,472
56.29
Tailing in Pythonpython (59) Writing complicated systems is a fantastic feeling. You know, ideas so vast that you have to sit down with pen and paper just to think for a bit. You might even talk with a coworker instead of just imagining your solution is perfect right off the bat and implementing code_that_wont_get_used_for_various_reasons/misguided_solution.py.r9999. Then there are other days. When you have lost the ability to function in any meaningful way and you end up putting a disproportionate amount of mental energy into crafting a Python version of.. I don't know.. tail. If you too are staring at a blank wall in confusion on this fine Sunday, perhaps you can write your own Python implementation of tail which meets these requirements: - supports following newly appended lines to a file (without showing the existing lines of the file), - supports iterating through all the existing lines and then following new lines as they appear. Judging criteria are: - correctness (working is better than not working) - simplicity (simple is better than complex) - conciseness (short is better than long) - performance (fast is better than slow) - style (mine is better than yours) Well, get coding! My Implementation For your consideration, here is my solution. import time from optparse import OptionParser SLEEP_INTERVAL = 1.0 def readlines_then_tail(fin): "Iterate through lines and then tail for further lines." while True: line = fin.readline() if line: yield line else: tail(fin) def tail(fin): "Listen for new lines added to file." while True: where = fin.tell() line = fin.readline() if not line: time.sleep(SLEEP_INTERVAL) fin.seek(where) else: yield line def main(): p = OptionParser("usage: tail.py file") (options, args) = p.parse_args() if len(args) < 1: p.error("must specify a file to watch") with open(args[0], 'r') as fin: for line in readlines_then_tail(fin): print line.strip() if name == 'main': main() Now, where's yours?
https://lethain.com/tailing-in-python/
CC-MAIN-2021-39
refinedweb
312
66.13
Add a Paypal button on the Shopify cart page I want to move the Paypal button from the Shopify Checkout to the Cart page. The problem I have is that the Paypal button on the Checkout has a token that's only available on the Checkout page. I've also checked the Shopify documentation and there is no mention on how to retrieve this token. Answer Solution: If you have the paypal express enabled in payment gateway. This code should let you display the Paypal button in cart page. {% if additional_checkout_buttons %} <div class="additional_checkout_buttons">{{ content_for_additional_checkout_buttons }}</div> {% endif %} Answer Solution: Login to your Shopify admin Go to Themes page Click Template Editor Click cart.liquid and open it in online code editor Please include the following code. {% if additional_checkout_buttons %}Or Checkout using: {{ content_for_additional_checkout_buttons }} {% endif %} Save your.
https://e1commerce.com/items/add-a-paypal-button-on-the-shopify-cart-page
CC-MAIN-2022-40
refinedweb
135
54.83
Heres the code, extremely basic Cpp #include <iostream> using namespace std; int main(){ cout << "C++ is FUN!\n"; return 0; } The symbols that can not be found are "std" trying to use the name space, and "cout". the full error message is. make: *** [FirstProject] Error 1 FirstProject C/C++ Problem Symbol 'cout' could not be resolved FirstProgram.cpp /FirstProject line 5 Semantic Error Symbol 'std' could not be resolved FirstProgram.cpp /FirstProject line 2 Semantic Error symbol(s) not found for architecture x86_64 FirstProject C/C++ Problem EDIT: here is the whole linker line: make all Building target: FirstProject Invoking: Cross G++ Linker g++ -o "FirstProject" ./FirstProgram.o Undefined symbols for architecture x86_64: "_main", referenced from: implicit entry/start for main executable ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation) make: *** [FirstProject] Error 1 Does anyone know what could potentially be the problem? You are not compiling using a C++ compiler. If you are using the GNU toolchain then use g++ and not gcc.
https://www.codesd.com/item/c-will-not-work-on-my-mac-symbol-s-not-found-for-x86-64-architecture.html
CC-MAIN-2019-13
refinedweb
178
52.39
- Articles - Documentation - Distributions - Forums - Sponsor Solutions. Types of mappings Vim actually recognizes different types of mappings, depending on what mode the editor is in. For example, you might have a mapping for F2 in insert mode that enters an HTML tag or a line of C code, and a different mapping for F2 that toggles the syntax mode on when you're in normal mode. Vim provides several different types of map commands, including: c keys in visual mode only. So, use imap if you want to set a mapping that works in Vim's insert mode, cmap for mappings to work in command (last line) mode, omap to map keys to function after an operator has been used in normal mode, and so on. Setting a mapping Let's start with something simple. To set a mapping while in Vim, enter command mode and use the map command. Here's a quick example: :map <F10> <Esc>:tabnew<CR> The syntax is pretty simple. First you tell Vim that you're setting a mapping. Then, tell Vim the key that will be bound to the action -- in this case, F10. Finally, spell out the action that Vim will perform when you use F10. This is pretty easy, because you're basically just listing the same keystrokes that you'd use if you were doing it manually. In this example, we tell Vim to enter command mode ( Esc:) and run the tabnew command, followed by the carriage return to return us to normal mode. (<CR> is the same as <Enter>, just faster to type.) Now, when you type F10 in normal mode, visual mode, or operator-pending mode, Vim will open a new tab. Every now and again, it might be useful to set a mapping on the fly -- but the odds are, if it's worth doing once, it's worth setting the mapping permanently. To do this, just open your .vimrc and insert the mapping there, like so: map <F10> <Esc>:tabnew<CR> Want to see all of the mappings you have set? Type :map with no arguments, and Vim will list the defined mappings, like so: n ,S <Esc>:syn off<CR> n ,s <Esc>:syn on<CR> <F11> <Esc>:setlocal nospell<CR> <F10> <Esc>:setlocal spell spelllang=en_us<CR> The other mapping commands, :imap and :omap, can also be used without arguments to show what characters are mapped for those modes -- the :map command only shows keys mapped for modes set with :map. In this example, you can see that I have F10 set to turn on spellchecking, and F11 set to turn it off. This will work in normal and visual mode. In normal mode, using ,S will turn syntax highlighting off, and ,s will turn it on. I use the comma in that mapping for a couple of reasons. First, the comma has no special meaning in normal mode on its own. Second, it's within easy reach of the home keys. Since I spend a lot of time working with HTML, I've set a few mappings to work in insert mode to insert HTML tags that I use frequently: imap <F2> <p> imap <F3> <strong> imap <F4> <em> imap <F5> <code> imap <F6> <a href=" imap <S-F6> "> imap <F7> <blockquote> imap <S-F2> < imap <S-F3> > You can also set a mapping to call a function. For instance, I like Vim's highlight search, when I've just performed a search. But I like to get rid of the highlighting as soon as I am done with it. I found a useful tip on the Vim.org site with a function to toggle highlight search, so I could turn it off and on with a simple quick keystroke. Here's the function that I put in my .vimrc: function ToggleHLSearch() if &hls set nohls else set hls endif endfunction Then, I added this to the mapping section: nmap <silent> <C-n> <Esc>:call ToggleHLSearch()<CR>. In this example, <silent> isn't a key -- it's to tell Vim not to print a message when it runs the command. Then, the key shortcut that is mapped to the action, and the action that will be called. Mappings can be really useful once you start writing your own Vim functions -- or using Vim functions that other folks have written already. It's certainly easier to type Ctrl-n than type :call ToggleHLSearch() every time! Also, I don't know about other Vim users, but I've always found the F1 mapping for Vim's :help command to be a bit annoying. It's not unusual for me to accidentally tap the F1 key when I mean to hit Escape or F2. So I've taken to mapping F1 to Escape in my .vimrc: map <F1> <Esc> imap <F1> <Esc> Unsetting mappings From time to time, you might want to get rid of a mapping. You can do this in a couple of ways. The first is to change the mapping for a key -- if you want to set F10 to a new mapping, just run :map <F10> command , to replace it for that session. To unmap it completely, use :unmap <F10>. Each of the map commands has its own unmap command -- so, to unmap an insert map ( imap) command, use :iunmap; to unmap a normal mode command ( nmap), use :nunmap; and so forth. Unlike the :map commands, the :unmap commands require an argument -- so, running :unmap won't just unset all of the active mappings, it will simply return an error. You can also prevent a key from being remapped by using the :noremap command, or :inoremap, :onoremap, etc. This can be useful if you want to set a mapping using map, but want that key to be used for something else in operator-pending mode, or something like that. Despite the name, you can override a noremap command while in Vim. Mapping notation We've covered the notation for some of the special keys already, such as Escape (<Esc>), Enter (<CR>), and function key notation (<F1>, <F2>, etc.). For the most part, the notation is pretty intuitive, but not always. For example, if you want to set a mapping for Ctrl-Esc, you'd use <C-Esc>. If you want to use Shift-F1, you'd use <S-F1>. For Mac users, if you want to set a mapping for the Command key (the weird symbol-thingy that PC users scratch their heads over), you'd use <D>. Note that Alt and Meta are the same, and you can use <M-key> or <A-key>. You can also combine several keys if you want to emulate the Emacs hand-cramp style of key mappings. For example, if you want to run a command using Shift-Alt-F2, you could use map <S-A-F2> command . See the Vim online help for a full list of special keys and their notation. Abbreviations Abbreviations are much like mappings, but they're used primarily to insert plain strings of text. They're only triggered when you enter a character like a space, Escape, or Enter. If I set a mapping for F10, it takes effect as soon as I type F10. If I set an abbreviation for insert mode to replace "i" with "I," it won't take effect if I type "imagine" or "Delphi," but it will take effect if I type just "i" followed by a space. Another difference between mappings and abbreviations is that you can't use special keys, such as F10 or Shift-F10, to trigger an abbreviation. That's OK, because abbreviations tend to accumulate, and there are only so many ways you can combine the function, Control, Alt, and Shift keys anyway. (Especially since desktop environments like KDE also claim a number of them.) Abbreviations are useful for a number of situations. For example, if you are prone to certain typos -- like typing "helllo" instead of "hello" -- just set an abbreviation in your .vimrc like this: ab helllo hello If you'd like the abbreviation to work in insert mode only, use iab instead. Like mappings, abbreviations can be unset during your session. To remove a single abbreviation, use :una abbrv . To clear all abbreviations, use :abc. If you go at it a little at a time, eventually you'll have a set of mappings and abbreviations tuned for your work that help make Vim even more efficient than it is to begin with. Note: Comments are owned by the poster. We are not responsible for their content. Toggling highlightPosted by: Anonymous Coward on June 15, 2006 10:47 AM Similar thing i have to toggle expansion of tabs (expandtab). # Re:Toggling highlightPosted by: Anonymous Coward on June 15, 2006 10:50 AM # Re:Toggling highlightPosted by: Administrator on June 15, 2006 10:49 PM # Re:Toggling highlightPosted by: Anonymous Coward on June 16, 2006 02:23 PM # Re:One use for mappingsPosted by: Anonymous Coward on June 15, 2006 03:21 PM # Re:One use for mappingsPosted by: Administrator on June 15, 2006 08:14 PM A much better way to do pasting, is to use ":se paste", it disables a lot more than than just indenting. See ":help paste" Rock! Thanks so much, didn't know about that. Today seems to be the day of learning new things for old problems. I just learned about the -r option to sed today too, which makes expressions not require so many damn backslashes. # Fun articles.Posted by: Anonymous Coward on August 24, 2006 06:52 PM I think we all know the help files/documentation exists, but it's rather dry reading and sometimes its so terse you really have no idea *why* you'd want to do something. Further, the comments from other readers have been equally interesting. Anyway, keep up the good work. # emacs keystrokes in vim, yum yumPosted by: Anonymous Coward on September 22, 2006 05:37 PM imap <C-a> <Esc>0i imap <C-e> <Esc>$a map <C-a> <Esc>0i map <C-e> <Esc>$a </tt> # One use for mappingsPosted by: Administrator on June 15, 2006 12:00 AM Mappings are great. To give you another idea for their use, here is one thing that I use vim mappings for, changing the email signature I use: map ns<nobr> <wbr></nobr>/^-- ^Md}:read ~/.signature^M map suso<nobr> <wbr></nobr>/^-- ^Md}:read ~/.signature^M map blug<nobr> <wbr></nobr>/^-- ^Md}:read ~/.signature-blug^M map bloomingpedia<nobr> <wbr></nobr>/^-- ^Md}:read<nobr> <wbr></nobr>/.signature-bloomingpedia^M map personal<nobr> <wbr></nobr>/^-- ^Md}:read ~/.signature-personal^M Those ^M are actually the newline control character so you'll need to type Ctrl-V + Ctrl-M to get them. I have to use them in place of <CR> for it to actually work on older versions of vim like 6.3. So all you have to do to switch signatures is just type in the mapped word. Makes it handy to change your identity for the email that you are writing. The first one, 'ns' can be useful if you're using a random signature generating program and you want to cycle through the signatures (like my <a href="" title="suso.org">randomsig </a suso.org> program) Another useful thing is to map noi to turn off all the indenting options when you need to paste something into a file. map noi<nobr> <wbr></nobr>:set noautoindent<CR>:set nosmartindent<CR> # This story has been archived. Comments can no longer be posted.
http://www.linux.com/archive/articles/54936
crawl-002
refinedweb
1,928
69.62
14 February 2012 07:06 [Source: ICIS news] SINGAPORE (ICIS)--BASF will build a 300,000 tonne/year toluene di-isocyanate (TDI) plant and expand additional units at its ?xml:namespace> BASF plans to start up the TDI plant at the end of 2014. Its existing 80,000 tonne/year TDI plant in The company plans to develop its Schwarzheide site to focus on more specialty products, it said. BASF will also build a hydrogen chloride recycling plant in Its nitric acid, chlorine and synthesis gas facilities at “This project will position us as the low-cost TDI producer in “Building our new TDI plant at our largest Verbund site in With the investment, BASF will have two sites in Europe for polyurethane basic products: TDI is a key component mainly used for flexible polyurethane foams. BASF is a leading supplier of basic products for polyurethanes and is currently operating TDI.
http://www.icis.com/Articles/2012/02/14/9531842/basf+to+build+new+tdi+plant+other+units+in+ludwigshafen.html
CC-MAIN-2013-20
refinedweb
151
51.11
Spring MVC provides powerful way to manage form inputs. It also provides form validation functionality which is easy to integrate in any application. But other than the normal form bean mapping, recently I had a requirement to map dynamic values like key-value pairs in an HTML form and retrieve the same in Spring Controller. So basically HashMap came to rescue. Let us see how to map a key-value pair based HashMap in a Spring command object using Spring MVC. The example will show a simple form which renders a Map. Related: Spring 3 MVC Tutorial Series (Must Read) Tools and Technologies used: - Java 5 or above - Eclipse 3.3 or above - Spring MVC 3.0 Step 1: Create Project Structure Open Eclipse and create a Dynamic Web Project. Enter project name as SpringMVC_Hashmap and press Finish. Step 2: Copy Required JAR files Once the Dynamic Web Project is created in Eclipse, copy the required JAR files under WEB-INF/lib folder. Following are the list of JAR files: Don’t worry if you dont have these JARs. You can download all the JAR files with complete source code at the end of this tutorial. Step 3: Adding Spring MVC support Once the basic project setup is done, we will add Spring 3 MVC support. For that first modify default web.xml and add springs DispatcherServlet. File: /WebContent/WEB-INF/web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns: <display-name>Spring3MVC-Hashmap</display-name> > </web-app> Related: Tutorial: Learn Spring MVC Lifecycle Now add spring-servlet.xml file under WEB-INF folder. File: /WebContent/WEB-INF/spring-servlet.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="" xmlns: <context:annotation-config /> <context:component-scan > Note that in above spring-servlet file, line 10, 11 defines context:annotation-config and component-scan tags. These tags let Spring MVC knows that the spring mvc annotations are used to map controllers and also the path from where the controller files needs to be loaded. All the files below package net.viralpatel.spring3.controller will be picked up and loaded by spring mvc. Step 4: Add Spring Controller and Form classes File: /src/net/viralpatel/spring3/form/ContactForm.java package net.viralpatel.spring3.form; import java.util.HashMap; import java.util.Map; public class ContactForm { private Map<String, String> contactMap = new HashMap<String, String>(); public Map<String, String> getContactMap() { return contactMap; } public void setContactMap(Map<String, String> contactMap) { this.contactMap = contactMap; } } Note line 8 in above code how we have defined a HashMap which will hold the key-value pair data. File: /src/net/viralpatel/spring3/controller/ContactController.java package net.viralpatel.spring3.controller; import java.util.HashMap; import java.util.Map; import net.viralpatel.spring3.form.ContactForm; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; @Controller public class ContactController { private static Map<String, String> contactMap = new HashMap<String, String>(); static { contactMap.put("name", "John"); contactMap.put("lastname", "Lennon"); contactMap.put("genres", "Rock, Pop"); } @RequestMapping(value = "/show", method = RequestMethod.GET) public ModelAndView get() { ContactForm contactForm = new ContactForm(); contactForm.setContactMap(contactMap); return new ModelAndView("add_contact" , "contactForm", contactForm); } @RequestMapping(value = "/add", method = RequestMethod.POST) public ModelAndView save(@ModelAttribute("contactForm") ContactForm contactForm) { return new ModelAndView("show_contact", "contactForm", contactForm); } } In above ContactController class, we have defile two methods: get() and save(). get() method: This method is used to display Contact form with pre-populated values. Note we added a map of contacts (Contacts map is initialized in static block) in ContactForm bean object and set this inside a ModelAndView object. The add_contact.jsp is displayed which in turns display all contacts in tabular form to edit. save() method: This method is used to fetch contact data from the form submitted and save it in the static map. Also it renders show_contact.jsp file to display contacts in tabular form. Step 5: Add JSP View files Add following files under WebContent/WEB-INF/jsp/ directory. File: /WebContent/WEB-INF/jsp/add_contact.jsp <%@taglib <table> <tr> <th>Key</th> <th>Value</th> </tr> <c:forEach <tr> <td>${contactMap.key}</td> <td><input name="contactMap['${contactMap.key}']" value="${contactMap.value}"/></td> </tr> </c:forEach> </table> <br/> <input type="submit" value="Save" /> </form:form> </body> </html> In above JSP file, we display contact details map in a table. Also each attribute is displayed in a textbox. Note that modelAttribute=”contactForm” is defined in tag. This tag defines the modelAttribute name for Spring mapping. On form submission, Spring will parse the values from request and fill the ContactForm bean and pass it to the controller. Also note how we defined textboxes name. It is in form contactMap[‘key’]. Thus Spring knows that we want to display the Map item with key key. contactMap['${contactMap.key}'] will generate each rows as follows: contactMap[‘name’] // mapped to key ‘name’ in hashmap contactMap contactMap[‘lastname’] // mapped to key ‘lastname’ in hashmap contactMap contactMap[‘genres’] // mapped to key ‘genres’ in hashmap contactMap Here we used JSTL to iterate through an HashMap. Spring 3 MVC and path attribute and square bracket One thing here is worth noting that we haven’t used Spring’s tag to render textboxes. This is because Spring MVC 3 has a unique way of handling path attribute for tag. If we define the textbox as follows: <form:input Then instead of converting it to following HTML code: <input name="contactMap['name']" /> <input name="contactMap['firstname']" /> <input name="contactMap['genres']" /> It converts it into following: <input name="contactMap'name'" /> <input name="contactMap'firstname'" /> <input name="contactMap'genres'" /> Note how it removed square brackets [ ] from name attribute. In previous versions of Spring (before 2.5) the square bracket were allowed in name attribute. It seems w3c has later changed the HTML specification and removed [ ] from html input name. Read the specification. It clearly says that: ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens (“-“), underscores (“_”), colons (“:”), and periods (“.”). Thus, square brackets aren’t allowed in name attribute! And thus Spring 3 onwards this was implemented. So far I haven’t got any workaround to use springs <form:input /> tag instead of plain html <input /> to render and fetch data from multiple rows. File: /WebContent/WEB-INF/jsp/show_contact.jsp <%@taglib <tr> <td>${contactMap.key}</td> <td>${contactMap.value}<MVC_Hashmap.zip (2.8 MB) very useful tutorial. thanks you. well, how do you handle the validation? Hi, I’ve followed every step, but once I ran the application it comes out with 404 errors. Any idea of why? Hi, Please check if you errors in server logs. Most of the time when application is not compiled and the classes folder is not updated in WEB-INF/ of your server root, this error comes. It is better to keep the jar files in WEB-IF/lib folder or -Right click –> web project –> PROPERTIES – Choose the J2EE Module Dependencies – Click on the Add External JARs… and then point on your library file (ZIP or JAR) which is recommended method? Hi, its nice example, You have explained in very good manner and can be understand easily. I tried to change the this example by using ArrayList and having checkboxes instead of input texts. But my modelattribute is not populating my list at controller when I submits by clicking some checkboxes. What should be the value name attribute for list as in your example for map name=”contactMap[‘${contactMap.key}’]”? Thank you, Swapnil Hi Swapnil, May be you are looking for: Spring MVC ArrayList Form mapping. Basically you have to map the inputs by name arrayname[index]. Please go through that example. Iam new to Spring 3 , it is good tutorial to learn basics but for Data is not coming up in the jsp which is set in Controller.please tell me how can i get the data in jsp , i used the same code The coding was very helpful to me …. and thank u so much friend…… Any example of saving a foreign key value by using spring form ? e.g. let’s say you have one Category to many Products. After saving categories when you come to save a product you’ll have categories as a dropdown list, so you’ll be saving a product with category id as a foreign key. Iam using netbeans 7.0,created web project,1 dout..u r using spring-servlet.xml right..?what is the use of that file, where u including in the project?did u telling that file’s path in web.xml any? Hi Viral, very great tutorial. I have followed all the steps and was able to manipulate the code too. Right now I have to do something similar to this, however I have a config (XML) file that I am currently reading from. I need to have the same kind of a form and have someone add data and click the save button, then the data is written in XML to the config file(not removing the old data, but adding to it. The config file should change and remain what it has been changed to even if the browser was closed and opened again. Also if you could have the functionality to delete from the config file it would be great. Thanks in advance. Thanks a lot! Your tutorials are easy to understand, and are very useful! You saved a lot of my time! Thanks again! HTTP Status 404 – /SpringIntegration/show.html on running same example…. please help Please mention how to perform validation in this example. This issue has been troubling a lot. What is the path need to be mentioned for form:errors tag . And what is the key need to be used inside the Validator. Hi it is a good tutorial to learn spring annotations basics But . data is not coming in the jsp which is set in Controller Class.can you please tell me know how can i display the data in jsp , i used the same code,It is not workout.But I can able to get the data through request.setAttribute(). most people get error, could you correct it ? 404 error , can not find hello page , even i change the “hello.html” or patten to be / … hello all, Thanks in advance. i am new to roo and jspx . i have created the mvc based project with roo . but when i try to display foriegn key value in a table it dispays all the fields values of the primery key table. i only want to dispay only 1 field value. IF U show 404 errors. fix contactcontroller.java wrong -> @RequestMapping(value = “/show”, method = RequestMethod.GET) FIX -> @RequestMapping(value = “/”, method = RequestMethod.GET) Thanks lot of Hi Viral, I followed same approch but it didn’t work for me.I have following hashMap in form. private Map volumnGoalMap;. I can iterate and display content on jsp but when i update the same and submit to save changes, the form is not populated with HashMap.HashMap in form in for is empty. Your help will be appreciated. due to some reason my hashmap key and value is not displayed in comments.So i am explaining…i have hashMap with key as String and value as ManageGoalForm (object). It is very useful… thank you So much .. :) :) Thank you. Helpful! Why did you stop blogging? Your site is great. Hi, I tried your tutorial, my program was doing well at first i can show the data in the input fields but when i click on show to display/submit content my hashmap doesn’t have any value in it. Can you please help me with Maven in Java hi viralpatel your tutorial is good ,but if you known guidewire &gosu language sample project send me .plzzzz It is extremely useful example thanx for posting, good to see variety of concepts form you Nice Article awesome….. In ContactController.java class u puted Map value in contactMap and used into jsp file in el language but I want to use this map in scriplate in same jsp how i use this? The Source Code link is down
https://viralpatel.net/blogs/spring-mvc-hashmap-form-example/
CC-MAIN-2018-34
refinedweb
2,047
58.79
Perl has long been considered the benchmark for powerful regular expressions. PHP uses a C library called pcre to provide almost complete support for Perl’s arsenal of regular expression features. Perl regular expressions include the POSIX classes and anchors described earlier. A POSIX-style character class in a Perl regular expression works and understands non-English characters using the Unix locale system. Perl regular expressions act on arbitrary binary data, so you can safely match with patterns or strings that contain the NUL-byte ( \x00). Perl-style regular expressions emulate the Perl syntax for patterns, which means that each pattern must be enclosed in a pair of delimiters. Traditionally, the slash ( /) character is used; for example, / pattern /. However, any nonalphanumeric character other than the backslash character ( \) can be used to delimit a Perl-style pattern. This is useful when matching strings containing slashes, such as filenames. For example, the following are equivalent: preg_match('/\/usr\/local\//', '/usr/local/bin/perl'); // returns true preg_match('#/usr/local/#', '/usr/local/bin/perl'); // returns true Parentheses ( ( )), curly braces ( {}), square brackets ( []), and angle brackets ( <>) can be used as pattern delimiters: preg_match('{/usr/local/}', '/usr/local/bin/perl'); // returns true Section 4.10.8 discusses the single-character modifiers you can put after the closing delimiter to modify the behavior of the regular expression engine. A very useful one is x, which makes the regular expression engine strip whitespace and #-marked comments from the regular expression before matching. These two patterns are the same, but one is much easier to read: '/([[:alpha:]]+)\s+\1/' '/( # start capture [[:alpha:]]+ # a word \s+ # whitespace \1 # the same word again ) # end capture /x' While Perl’s regular expression syntax includes the POSIX constructs we talked about earlier, some pattern components have a different meaning in Perl. In particular, Perl’s regular expressions are optimized for matching against single lines of text (although there are options that change this behavior). The period ( .) matches any character except for a newline ( \n). The dollar sign ( $) matches at the end of the string or, if the string ends with a newline, just before that newline: preg_match('/is (.*)$/', "the key is in my pants", $captured); // $captured[1] is 'in my pants' Perl-style regular expressions support the POSIX character classes but also define some of their own, as shown in Table 4-9. Perl-style regular expressions also support additional anchors, as listed in Table 4-10. The POSIX quantifiers, which Perl also supports, are always greedy . That is, when faced with a quantifier, the engine matches as much as it can while still satisfying the rest of the pattern. For instance: preg_match('/(<.*>)/', 'do <b>not</b> press the button', $match); // $match[1] is '<b>not</b>' The regular expression matches from the first less-than sign to the last greater-than sign. In effect, the .* matches everything after the first less-than sign, and the engine backtracks to make it match less and less until finally there’s a greater-than sign to be matched. This greediness can be a problem. Sometimes you need minimal (non-greedy) matching —that is, quantifiers that match as few times as possible to satisfy the rest of the pattern. Perl provides a parallel set of quantifiers that match minimally. They’re easy to remember, because they’re the same as the greedy quantifiers, but with a question mark ( ?) appended. Table 4-11 shows the corresponding greedy and non-greedy quantifiers supported by Perl-style regular expressions. Here’s how to match a tag using a non-greedy quantifier: preg_match('/(<.*?>)/', 'do <b>not</b> press the button', $match); // $match[1] is '<b>' Another, faster way is to use a character class to match every non-greater-than character up to the next greater-than sign: preg_match('/(<[^>]*>)/', 'do <b>not</b> press the button', $match); // $match[1] is '<b>' If you enclose a part of a pattern in parentheses, the text that matches that subpattern is captured and can be accessed later. Sometimes, though, you want to create a subpattern without capturing the matching text. In Perl-compatible regular expressions, you can do this using the (?: subpattern ) construct: preg_match('/(?:ello)(.*)/', 'jello biafra', $match); // $match[1] is ' biafra' You can refer to text captured earlier in a pattern with a backreference: \1 refers to the contents of the first subpattern, \2 refers to the second, and so on. If you nest subpatterns, the first begins with the first opening parenthesis, the second begins with the second opening parenthesis, and so on. For instance, this identifies doubled words: preg_match('/([[:alpha:]]+)\s+\1/', 'Paris in the the spring', $m); // returns true and $m[1] is 'the' You can’t capture more than 99 subpatterns. Perl-style regular expressions let you put single-letter options (flags) after the regular expression pattern to modify the interpretation, or behavior, of the match. For instance, to match case-insensitively, simply use the i flag: preg_match('/cat/i', 'Stop, Catherine!'); // returns true Table 4-12 shows the modifiers from Perl that are supported in Perl-compatible regular expressions. PHP’s Perl-compatible regular expression functions also support other modifiers that aren’t supported by Perl, as listed in Table 4-13. It’s possible to use more than one option in a single pattern, as demonstrated in the following example: $message = <<< END To: you@youcorp From: me@mecorp Subject: pay up Pay me or else! END; preg_match('/^subject: (.*)/im', $message, $match); // $match[1] is 'pay up' In addition to specifying patternwide options after the closing pattern delimiter, you can specify options within a pattern to have them apply only to part of the pattern. The syntax for this is: (? flags: subpattern) For example, only the word “PHP” is case-insensitive in this example: preg_match('/I like (?i:PHP)/', 'I like pHp'); // returns true The i, m, s, U, x, and X options can be applied internally in this fashion. You can use multiple options at once: preg_match('/eat (?ix:fo o d)/', 'eat FoOD'); // returns true Prefix an option with a hyphen ( -) to turn it off: preg_match('/(?-i:I like) PHP/i', 'I like pHp'); // returns true An alternative form enables or disables the flags until the end of the enclosing subpattern or pattern: preg_match('/I like (?i)PHP/', 'I like pHp'); // returns true preg_match('/I (like (?i)PHP) a lot/', 'I like pHp a lot', $match); // $match[1] is 'like pHp' Inline flags do not enable capturing. You need an additional set of capturing parentheses do that. It’s sometimes useful in patterns to be able to say “match here if this is next.” This is particularly common when you are splitting a string. The regular expression describes the separator, which is not returned. You can use lookahead to make sure (without matching it, thus preventing it from being returned) that there’s more data after the separator. Similarly, lookbehind checks the preceding text. Lookahead and lookbehind come in two forms: positive and negative. A positive lookahead or lookbehind says “the next/preceding text must be like this.” A negative lookahead or lookbehind says “the next/preceding text must not be like this.” Table 4-14 shows the four constructs you can use in Perl-compatible patterns. None of the constructs captures text. (note that the regular expression is commented using the x modifier): $input = <<< END name = 'Tim O\'Reilly'; END; $pattern = <<< END ' # opening quote ( # begin capturing .*? # the string (?<! \\\\ ) # skip escaped quotes ) # end capturing ' # closing quote END; preg_match( "($pattern)x", $input, $match); echo $match[1]; Tim O\'Reilly. The rarely used once-only subpattern, or cut, prevents worst-case behavior by the regular expression engine on some kinds of patterns. Once matched, the subpattern is never backed out of. The common use for the once-only subpattern is when you have a repeated expression that may itself be repeated: /(a+|b+)*\.+/ This code snippet takes several seconds to report failure: $p = '/(a+|b+)*\.+$/'; $s = 'abababababbabbbabbaaaaaabbbbabbababababababbba..!'; if (preg_match($p, $s)) { echo "Y"; } else { echo "N"; } This is because the regular expression engine tries all the different places to start the match, but has to backtrack out of each one, which takes time. If you know that once something is matched it should never be backed out of, you should mark it with (?> subpattern ): $p = '/(?>a+|b+)*\.+$/'; The cut never changes the outcome of the match; it simply makes it fail faster. A conditional expression is like an if statement in a regular expression. The general form is: (?( condition) yespattern) (?( condition) yespattern| nopattern) If the assertion succeeds, the regular expression engine matches the yespattern. With the second form, if the assertion doesn’t succeed, the regular expression engine skips the yespattern and tries to match the nopattern. The assertion can be one of two types: either a backreference, or a lookahead or lookbehind match. To reference a previously matched substring, the assertion is a number from 1-99 (the most backreferences available). The condition uses the pattern in the assertion only if the backreference was matched. If the assertion is not a backreference, it must be a positive or negative lookahead or lookbehind assertion. There are five classes of functions that work with Perl-compatible regular expressions: matching, replacing, splitting, filtering, and a utility function for quoting text. The preg_match( ) function performs Perl-style pattern matching on a string. It’s the equivalent of the m// operator in Perl. The preg_match( ) function takes the same arguments and gives the same return value as the ereg( ) function, except that it takes a Perl-style pattern instead of a standard pattern: $found = preg_match( pattern, string[, captured]); For example: preg_match('/y.*e$/', 'Sylvie'); // returns true preg_match('/y(.*)e$/', 'Sylvie', $m); // $m is array('Sylvie', 'lvi') While there’s an eregi( ) function to match case-insensitively, there’s no preg_matchi( ) function. Instead, use the i flag on the pattern: preg_match('y.*e$/i', 'SyLvIe'); // returns true The preg_match_all( ) function repeatedly matches from where the last match ended, until no more matches can be made: $found = preg_match_all( pattern, string, matches[, order]); The order value, either PREG_PATTERN_ORDER or PREG_SET_ORDER, determines the layout of matches. We’ll look at both, using this code as a guide: $string = <<< END 13 dogs 12 rabbits 8 cows 1 goat END; preg_match_all('/(\d+) (\S+)/', $string, $m1, PREG_PATTERN_ORDER); preg_match_all('/(\d+) (\S+)/', $string, $m2, PREG_SET_ORDER); With PREG_PATTERN_ORDER (the default), each element of the array corresponds to a particular capturing subpattern. So $m1[0] is an array of all the substrings that matched the pattern, $m1[1] is an array of all the substrings that matched the first subpattern (the numbers), and $m1[2] is an array of all the substrings that matched the second subpattern (the words). The array $m1 has one more elements than subpatterns. With PREG_SET_ORDER, each element of the array corresponds to the next attempt to match the whole pattern. So $m2[0] is an array of the first set of matches ( '13 dogs', '13', 'dogs'), $m2[1] is an array of the second set of matches ( '12 rabbits', '12', 'rabbits'), and so on. The array $m2 has as many elements as there were successful matches of the entire pattern. Example 4-2 fetches the HTML at a particular web address into a string and extracts the URLs from that HTML. For each URL, it generates a link back to the program that will display the URLs at that address. Example 4-2. Extracting URLs from an HTML page <?php if (getenv('REQUEST_METHOD') == 'POST') { $url = $_POST[url]; } else { $url = $_GET[url]; } ?> <form action="<?php $PHP_SELF?>"method="POST"> URL: <input type="text" name="url" value="<?= $url ?>" /><br> <input type="submit"> </form> <?php if ($url) { $remote = fopen($url, 'r'); $html = fread($remote, 1048576); // read up to 1 MB of HTML fclose($remote); $$u</A><BR>\n"; } } ?> The preg_replace( ) function behaves like the search and replace operation in your text editor. It finds all occurrences of a pattern in a string and changes those occurrences to something else: $new = preg_replace( pattern, replacement, subject[, limit]); The most common usage has all the argument strings, except for the integer limit. The limit is the maximum number of occurrences of the pattern to replace (the default, and the behavior when a limit of -1 is passed, is all occurrences). $better = preg_replace('/<.*?>/', '!', 'do <b>not</b> press the button'); // $better is 'do !not! press the button' Pass an array of strings as subject to make the substitution on all of them. The new strings are returned from preg_replace( ): $names = array('Fred Flintstone', 'Barney Rubble', 'Wilma Flintstone', 'Betty Rubble'); $tidy = preg_replace('/(\w)\w* (\w+)/', '\1 \2', $names); // $tidy is array ('F Flintstone', 'B Rubble', 'W Flintstone', 'B Rubble') To perform multiple substitutions on the same string or array of strings with one call to preg_replace( ), pass arrays of patterns and replacements: $contractions = array("/don't/i", "/won't/i", "/can't/i"); $expansions = array('do not', 'will not', 'can not'); $string = "Please don't yell--I can't jump while you won't speak"; $longer = preg_replace($contractions, $expansions, $string); // $longer is 'Please do not yell--I can not jump while you will not speak'; If you give fewer replacements than patterns, text matching the extra patterns is deleted. This is a handy way to delete a lot of things at once: $html_gunk = array('/<.*?>/', '/&.*?;/'); $html = 'é : <b>very</b> cute'; $stripped = preg_replace($html_gunk, array( ), $html); // $stripped is ' : very cute' If you give an array of patterns but a single string replacement, the same replacement is used for every pattern: $stripped = preg_replace($html_gunk, '', $html); The replacement can use backreferences. Unlike backreferences in patterns, though, the preferred syntax for backreferences in replacements is $1, $2, $3, etc. For example: echo preg_replace('/(\w)\w+\s+(\w+)/', '$2, $1.', 'Fred Flintstone') Flintstone, F. The /e modifier makes preg_replace( ) treat the replacement string as PHP code that returns the actual string to use in the replacement. For example, this converts every Celsius temperature to Fahrenheit: $string = 'It was 5C outside, 20C inside'; echo preg_replace('/(\d+)C\b/e', '$1*9/5+32', $string); It was 41 outside, 68 inside This more complex example expands variables in a string: $name = 'Fred'; $age = 35; $string = '$name is $age'; preg_replace('/\$(\w+)/e', '$$1', $string); Each match isolates the name of a variable ( $name, $age). The $1 in the replacement refers to those names, so the PHP code actually executed is $name and $age. That code evaluates to the value of the variable, which is what’s used as the replacement. Whew! Whereas you use preg_match_all( ) to extract chunks of a string when you know what those chunks are, use preg_split( ) to extract chunks when you know what separates the chunks from each other: $chunks = preg_split( pattern, string[, limit[, flags]]); The pattern matches a separator between two chunks. By default, the separators are not returned. The optional limit specifies the maximum number of chunks to return ( -1 is the default, which means all chunks). The flags argument is a bitwise OR combination of the flags PREG_SPLIT_NO_EMPTY (empty chunks are not returned) and PREG_SPLIT_DELIM_CAPTURE (parts of the string captured in the pattern are returned). For example, to extract just the operands from a simple numeric expression, use: $ops = preg_split('{[+*/-]}', '3+5*9/2'); // $ops is array('3', '5', '9', '2') To extract the operands and the operators, use: $ops = preg_split('{([+*/-])}', '3+5*9/2', -1, PREG_SPLIT_DELIM_CAPTURE); // $ops is array('3', '+', '5', '*', '9', '/', '2') An empty pattern matches at every boundary between characters in the string. This lets you split a string into an array of characters: $array = preg_split('//', $string); A variation on preg_replace( ) is preg_replace_callback( ). This calls a function to get the replacement string. The function is passed an array of matches (the zeroth element is all the text that matched the pattern, the first is the contents of the first captured subpattern, and so on). For example: function titlecase ($s) { return ucfirst(strtolower($s[0])); } $string = 'goodbye cruel world'; $new = preg_replace_callback('/\w+/', 'titlecase', $string); echo $new; Goodbye Cruel World The preg_grep( ) function returns those elements of an array that match a given pattern: $matching = preg_grep( pattern, array); For instance, to get only the filenames that end in .txt, use: $textfiles = preg_grep('/\.txt$/', $filenames); The preg_quote( ) function creates a regular expression that matches only a given string: $re = preg_quote( string[, delimiter]); Every character in string that has special meaning inside a regular expression (e.g., * or $) is prefaced with a backslash: echo preg_quote('$5.00 (five bucks)'); \$5\.00 \(five bucks\) The optional second argument is an extra character to be quoted. Usually, you pass your regular expression delimiter here: $to_find = '/usr/local/etc/rsync.conf'; $re = preg_quote($filename, '/'); if (preg_match("/$re", $filename)) { // found it! } Although very similar, PHP’s implementation of Perl-style regular expressions has a few minor differences from actual Perl regular expressions: The null character (ASCII 0) is not allowed as a literal character within a pattern string. You can reference it in other ways, however ( \000, \x00, etc.). The \E, \G, \L, \l, \Q, \u, and \Uoptions are not supported. The (?{ some perl code })construct is not supported. The / D, / G, / U, / u, / A, and / Xmodifiers are supported. The vertical tab \vcounts as a whitespace character. Lookahead and lookbehind assertions cannot be repeated using *, +, or ?. Parenthesized submatches within negative assertions are not remembered. Alternation branches within a lookbehind assertion can be of different lengths. Get Programming PHP now with the O’Reilly learning platform. O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.
https://www.oreilly.com/library/view/programming-php/1565926102/ch04s10.html
CC-MAIN-2022-40
refinedweb
2,908
52.29
The JLayer class is a flexible and powerful decorator for Swing components. It enables you to draw on components and respond to component events without modifying the underlying component directly. The JLayer class in Java SE 7 is similar in spirit to the JxLayer project project at java.net. The JLayer class was initially based on the JXLayer project, but its API evolved separately. This document describes examples that show the power of the JLayer class. Full source code is available. JLayerClass LayerUIClass For a brief introduction to the material on this page, watch the following video. A JavaScript-enabled web browser and an Internet connection are required for the video. If you cannot see the video, try viewing it at YouTube. JLayerClass The javax.swing.JLayer class is half of a team. The other half is the javax.swing.plaf.LayerUI class. Suppose you want to do some custom drawing atop a JButton object (decorate the JButton object). The component you want to decorate is the target. LayerUIsubclass to do the drawing. JLayerobject that wraps the target and the LayerUIobject. JLayerobject in your user interface just as you would use the target component. For example, to add an instance of a JPanel subclass to a JFrame object, you would do something similar to this: JFrame f = new JFrame(); JPanel panel = createPanel(); f.add (panel); To decorate the JPanel object, do something similar to this instead: JFrame f = new JFrame(); JPanel panel = createPanel(); LayerUI<JPanel> layerUI = new MyLayerUISubclass(); JLayer<JPanel> jlayer = new JLayer<JPanel>(panel, layerUI); f.add (jlayer); Use generics to ensure that the JPanel object and the LayerUI object are for compatible types. In the previous example, both the JLayer object and the LayerUI object are used with the JPanel class. The JLayer class is usually generified with the exact type of its view component, while the LayerUI class is designed to be used with JLayer classes of its generic parameter or any of its ancestors. For example, a LayerUI<JComponent> object can be used with a JLayer<AbstractButton> object. A LayerUI object is responsible for custom decoration and event handling for a JLayer object. When you create an instance of a LayerUI subclass, your custom behavior can be applicable to every JLayer object with an appropriate generic type. That is why the JLayer class is final; all custom behavior is encapsulated in your LayerUI subclass, so there is no need to make a JLayer subclass. LayerUIClass The LayerUI class inherits most of its behavior from the ComponentUI class. Here are the most commonly overridden methods: paint(Graphics g, JComponent c)method is called when the target component needs to be drawn. To render the component in the same way that Swing renders it, call the super.paint(g, c)method. installUI(JComponent c)method is called when an instance of your LayerUIsubclass is associated with a component. Perform any necessary initializations here. The component that is passed in is the corresponding JLayerobject. Retrieve the target component with the JLayerclass' getView()method. uninstallUI(JComponent c)method is called when an instance of your LayerUIsubclass is no longer associated with the given component. Clean up here if necessary. To use the JLayer class, you need a good LayerUI subclass. The simplest kinds of LayerUI classes change how components are drawn. Here is one, for example, that paints a transparent color gradient on a component. class WallpaperLayerUI extends LayerUI<JComponent> { @Override public void paint(Graphics g, JComponent c) { super.paint(g, c); Graphics2D g2 = (Graphics2D) g.create(); int w = c.getWidth(); int h = c.getHeight(); g2.setComposite(AlphaComposite.getInstance( AlphaComposite.SRC_OVER, .5f)); g2.setPaint(new GradientPaint(0, 0, Color.yellow, 0, h, Color.red)); g2.fillRect(0, 0, w, h); g2.dispose(); } } The paint() method is where the custom drawing takes place. The call to the super.paint() method draws the contents of the JPanel object. After setting up a 50% transparent composite, the color gradient is drawn. After the LayerUI subclass is defined, using it is simple. Here is some source code that uses the WallpaperLayerUI class: import java.awt.*; import javax.swing.*; import javax.swing.plaf.LayerUI; public class Wallpaper { public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createUI(); } }); } public static void createUI() { JFrame f = new JFrame("Wallpaper"); JPanel panel = createPanel(); LayerUI<JComponent> layerUI = new WallpaperLayerUI(); JLayer<JComponent> jlayer = new JLayer<JComponent>(panel, layerUI); f.add (jlayer); f.setSize(300, 200); f.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); f.setLocationRelativeTo (null); f.setVisible (true); } private static JPanel createPanel() { JPanel p = new JPanel(); ButtonGroup entreeGroup = new ButtonGroup(); JRadioButton radioButton; p.add(radioButton = new JRadioButton("Beef", true)); entreeGroup.add(radioButton); p.add(radioButton = new JRadioButton("Chicken")); entreeGroup.add(radioButton); p.add(radioButton = new JRadioButton("Vegetable")); entreeGroup.add(radioButton); p.add(new JCheckBox("Ketchup")); p.add(new JCheckBox("Mustard")); p.add(new JCheckBox("Pickles")); p.add(new JLabel("Special requests:")); p.add(new JTextField(20)); JButton orderButton = new JButton("Place Order"); p.add(orderButton); return p; } } Here is the result: Source code: Wallpaper NetBeans Project Wallpaper.java Run with Java Web Start: The LayerUI class' paint() method gives you complete control over how a component is drawn. Here is another LayerUI subclass that shows how the entire contents of a panel can be modified using Java 2D image processing: class BlurLayerUI extends LayerUI<JComponent> { private BufferedImage mOffscreenImage; private BufferedImageOp mOperation; public BlurLayerUI() { float ninth = 1.0f / 9.0f; float[] blurKernel = { ninth, ninth, ninth, ninth, ninth, ninth, ninth, ninth, ninth }; mOperation = new ConvolveOp( new Kernel(3, 3, blurKernel), ConvolveOp.EDGE_NO_OP, null); } @Override public void paint (Graphics g, JComponent c) { int w = c.getWidth(); int h = c.getHeight(); if (w == 0 || h == 0) { return; } // Only create the offscreen image if the one we have // is the wrong size. if (mOffscreenImage == null || mOffscreenImage.getWidth() != w || mOffscreenImage.getHeight() != h) { mOffscreenImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); } Graphics2D ig2 = mOffscreenImage.createGraphics(); ig2.setClip(g.getClip()); super.paint(ig2, c); ig2.dispose(); Graphics2D g2 = (Graphics2D)g; g2.drawImage(mOffscreenImage, mOperation, 0, 0); } } In the paint() method, the panel is rendered into an offscreen image. The offscreen image is processed with a convolution operator, then drawn to the screen. The entire user interface is still live, just blurry: Source code: Myopia NetBeans Project Myopia.java Run with Java Web Start: Your LayerUI subclass can also receive all of the events of its corresponding component. However, the JLayer instance must register its interest in specific types of events. This happens with the JLayer class' setLayerEventMask() method. Typically, however, this call is made from initialization performed in the LayerUI class' installUI() method. For example, the following excerpt shows a portion of a LayerUI subclass that registers to receive mouse and mouse motion events. public void installUI(JComponent c) { super.installUI(c); JLayer jlayer = (JLayer)c; jlayer.setLayerEventMask( AWTEvent.MOUSE_EVENT_MASK | AWTEvent.MOUSE_MOTION_EVENT_MASK ); } All events going to your JLayer subclass get routed to an event handler method whose name matches the event type. For example, you can respond to mouse and mouse motion events by overriding corresponding methods: protected void processMouseEvent(MouseEvent e, JLayer l) { // ... } protected void processMouseMotionEvent(MouseEvent e, JLayer l) { // ... } The following is a LayerUI subclass that draws a translucent circle wherever the mouse moves inside a panel. class SpotlightLayerUI extends LayerUI<JPanel> { private boolean mActive; private int mX, mY; @Override public void installUI(JComponent c) { super.installUI(c); JLayer jlayer = (JLayer)c; jlayer.setLayerEventMask( AWTEvent.MOUSE_EVENT_MASK | AWTEvent.MOUSE_MOTION_EVENT_MASK ); } @Override public void uninstallUI(JComponent c) { JLayer jlayer = (JLayer)c; jlayer.setLayerEventMask(0); super.uninstallUI(c); } @Override public void paint (Graphics g, JComponent c) { Graphics2D g2 = (Graphics2D)g.create(); // Paint the view. super.paint (g2, c); if (mActive) { // Create a radial gradient, transparent in the middle. java.awt.geom.Point2D center = new java.awt.geom.Point2D.Float(mX, mY); float radius = 72; float[] dist = {0.0f, 1.0f}; Color[] colors = {new Color(0.0f, 0.0f, 0.0f, 0.0f), Color.BLACK}; RadialGradientPaint p = new RadialGradientPaint(center, radius, dist, colors); g2.setPaint(p); g2.setComposite(AlphaComposite.getInstance( AlphaComposite.SRC_OVER, .6f)); g2.fillRect(0, 0, c.getWidth(), c.getHeight()); } g2.dispose(); } @Override protected void processMouseEvent(MouseEvent e, JLayer l) { if (e.getID() == MouseEvent.MOUSE_ENTERED) mActive = true; if (e.getID() == MouseEvent.MOUSE_EXITED) mActive = false; l.repaint(); } @Override protected void processMouseMotionEvent(MouseEvent e, JLayer l) { Point p = SwingUtilities.convertPoint(e.getComponent(), e.getPoint(), l); mX = p.x; mY = p.y; l.repaint(); } } The mActive variable indicates whether or not the mouse is inside the coordinates of the panel. In the installUI() method, the setLayerEventMask() method is called to indicate the LayerUI subclass' interest in receiving mouse and mouse motion events. In the processMouseEvent() method, the mActive flag is set depending on the position of the mouse. In the processMouseMotionEvent() method, the coordinates of the mouse movement are stored in the mX and mY member variables so that they can be used later in the paint() method. The paint() method shows the default appearance of the panel, then overlays a radial gradient for a spotlight effect: Source code: Diva NetBeans Project Diva.java Run with Java Web Start: This example is an animated busy indicator. It demonstrates animation in a LayerUI subclass and features a fade-in and fade-out. It is more complicated that the previous examples, but it is based on the same principle of defining a paint() method for custom drawing. Click the Place Order button to see the busy indicator for 4 seconds. Notice how the panel is grayed out and the indicator spins. The elements of the indicator have varying levels of transparency. The LayerUI subclass, the WaitLayerUI class, shows how to fire property change events to update the component. The WaitLayerUI class uses a Timer object to update its state 24 times a second. This happens in the timer's target method, the actionPerformed() method. The actionPerformed() method uses the firePropertyChange() method to indicate that the internal state was updated. This triggers a call to the applyPropertyChange() method, which repaints the JLayer object: Source code: TapTapTap NetBeans Project TapTapTap.java Run with Java Web Start: The final example in this document shows how the JLayer class can be used to decorate text fields to show if they contain valid data. While the other examples use the JLayer class to wrap panels or general components, this example shows how to wrap a JFormattedTextField component specifically. It also demonstrates that a single LayerUI subclass implementation can be used for multiple JLayer instances. The JLayer class is used to provide a visual indication for fields that have invalid data. When the ValidationLayerUI class paints the text field, it draws a red X if the field contents cannot be parsed. Here is an example: Source code: FieldValidator NetBeans Project FieldValidator.java Run with Java Web Start:
http://docs.oracle.com/javase/tutorial/uiswing/misc/jlayer.html
CC-MAIN-2014-15
refinedweb
1,787
50.73
Finite automaton string search algorithm (Java). We will use generics so that we can operate on a list of any data type, not just strings of characters. [edit] Generating the state machine The first step, also the most complicated and expensive step, is generating the state machine we will use for matching. We will have a State class to represent states. <<State class>>= class State<E> { private static int nextStateNum = 0; private final int num = nextStateNum++; public final BitSet positions; additional State members public State(BitSet bs) { positions = bs; } public String toString() { return Integer.toString(num); } } <<imports>>= import java.util.BitSet; The State class contains a BitSet storing the positions in the string that the state includes. The initial position is always set. If the final position (after the last character) is set, that indicate a match. Each State also has a unique integer ID associated with it, in order of creation, starting from 0. The initial state should have ID 0. This ID is not important and is just printed for debugging purposes. We create a simple method that returns an instance of State with the specified position set or, if no such state exists, creates it. To do this we keep track of a mapping from sets of positions to states. We also keep track of a list of all the states in order of creation. <<DFAStringSearch fields>>= // maps the set of string positions a state represents to the state private final Map<BitSet, State<E>> stateMap = new HashMap<BitSet, State<E>>(); // list of states in order of creation private final List<State<E>> states = new ArrayList<State<E>>(); <<get state method>>= public State<E> getState(BitSet s) { if (stateMap.containsKey(s)) return stateMap.get(s); else { State<E> st = new State<E>(s); stateMap.put(s, st); states.add(st); return st; } } <<imports>>= import java.util.Map; import java.util.HashMap; import java.util.List; import java.util.ArrayList; Each state will have a transitions map which determines, given the current state and the next character in the input, which state we go to next. <<additional State members>>= public final Map<E,State<E>> transitions = new HashMap<E,State<E>>(); our case, the transition will not be defined for any character other than "O"; and if we encounter that we will simply go back to the initial state.). As transitions maps get filled in, more states may be added; we will also iterate through those new states as the states.size() increases. When the loop is done, all states will have their transition maps filled. We could not use an Iterator here because it would complain about concurrent modifications. For each state, we examine each position in that state and the next character at that position (if we have not already examined it at another position): <<DFAStringSearch constructor>>= public DFAStringSearch(E[] pattern) { create initial state for (int i = 0; i < states.size(); i++) { State<E> s = states.get(i); for (int j = s.positions.nextSetBit(0); j >= 0; j = s.positions.nextSetBit(j+1)) { deal with final position E cNext = pattern[j]; if (!s.transitions.containsKey(cNext)) fillTransitionTableEntry(pattern, s, cNext); } } } The initial state again contains only the initial position, which we create by calling getState(): <<DFAStringSearch fields>>= public State<E> initialState; <<create initial state>>= BitSet initialPos = new BitSet(); initialPos.set(0); initialState = getState(initialPos); The one tricky position to deal with is the final position, where there are no more characters. We mark these states as "final" (a term from automata theory meaning a match is complete when this is state is reached). (It cannot be named "final" because that is a keyword in Java.) <<additional State members>>= public boolean finale; <<deal with final position>>= if (j == pattern.length) { s.finale = true; break; } In fillTransitionTableEntry,>>= private void fillTransitionTableEntry(E[] pattern, State<E> s, E cNext) { BitSet newPositions = new BitSet(); newPositions.set(0); for (int i = s.positions.nextSetBit(0); i >= 0 && i < pattern.length; i = s.positions.nextSetBit(i+1)) { if (pattern[i].equals(cNext)) newPositions.set(i + 1); } s.transitions.put(cNext, getState(newPositions)); print trace message describing new entry } The trace message, which helps us to test our implementation, will be printed to standard err and gives the source state, character, and destination state: <<print trace message describing new entry>>= System.err.println("Adding edge " + s + " -" + cNext + "-> " + s.transitions.get(cNext)); [edit] Performing the search Once we have our machine built, the actual string matching step is very simple. We feed the string being searched into the machine, following the transition maps to move between states as instructed, until we reach a final state or use up the string: <<perform DFA-based search>>= public int search(E[] searchFor, E[] searchIn) { State<E> curState = initialState; int curPos; for (curPos = 0; curPos < searchIn.length && !curState.finale; curPos++) { curState = curState.transitions.get(searchIn[curPos]); if (curState == null) curState = initialState; } if (curState.finale) return curPos - searchFor.length; else return -1; } [edit] Files For now, we'll just create a single source module containing the above data and code. Ideally, each match would have an associated object to enable multiply concurrent uses of the search, and this interface would be described in a header file. <<DFAStringSearch.java>>= imports State class public class DFAStringSearch<E> { DFAStringSearch fields DFAStringSearch constructor get state method fill in transition table entry perform DFA-based search main method } [edit] Test driver By adding a small test driver to the file we can run it from the command line on test inputs: <<main method>>= private static Character[] str2charArray(String str) { Character[] result = new Character[str.length()]; for (int i = 0; i < str.length(); i++) result[i] = str.charAt(i); return result; } public static void main(String[] args) { Character[] a = str2charArray(args[0]), b = str2charArray(args[1]); DFAStringSearch<Character> foo = new DFAStringSearch<Character>(a); int result = foo.search(a, b); if (result == -1) System.out.println("No match found."); else { System.out.println("Matched at position " + result + ":"); System.out.println(args[1].substring(0, result) + "|" + args[1].substring(result)); } } If we compile and run the following command line: java DFAStringSearch
http://en.literateprograms.org/Finite_automaton_string_search_algorithm_(Java)
CC-MAIN-2015-14
refinedweb
1,013
57.16
This actually happens in a number of Adobe operations. Sometimes I can tab from one selection to the next and get by, but with this particular operation, I can only close the window with the mouse. I actually get past the first import as timeline window where I can select the premiere project file. I then get to select the sequence and that is when I have no mouse control within the window and thus can not select the sequence. Using the tab or enter keys also does not work. I can only close the window. Any suggestions? Details Operating System... brand/model mouse... exact mouse driver With more informatoin, someone may be able to help Right now, you've said you have a loaf of bread that doesn't taste good... but nobody knows if it is white bread, wheat bread, or bread made from seeds off a chicken coop floor >Using the tab or enter keys also does not work OK... you MAY have more than just a mouse problem More information needed for someone to help - - Sometimes I can tab from one selection to the next and get by, but with this particular operation, I can only close the window with the mouse. This is almost always a video driver. See John's info, and look at both video and mouse drivers. Windows 7 Ulitmate 64bit ATI Radeon 4850 ATI Radeon HD4800 Driver 8.681.0.0 was updated to 8.950.0.0 = no improvement HID compliant mouse driver 6.1.7600.16385 disabled that and loaded logitech HID driver 5.33.0.0 = no improvement Same problem with microsoft usb mouse or logitech wireless mouse. This is a serious problem because it forces me to export media from premiere in order to import to Encore, which with AVCHD media takes hours on my system (and probably introduces one more generational loss). Hmmm. Here is a previous thread with what I think is a similar issue: The symptom was not being able to click off various windows (i.e. can't answer yes/no, but can exit using "escape"). Is that what you are seeing? Has operation been normal previously with this same video card? Hi Stan, It's not totally consistent between pop-up windows. Sometimes I can tab from one selection to the next, other times not. Sometimes the only thing I can do with the mouse is exit the window. I noticed today that when I bring up the character window and try to change character color, I can not change the color on the color chart; no response from mouse click. I haven't tried reinstalling encore [update - I did reinstall, no luck]. I have a feeling I've had this problem for quite awhile, but now while working with the avchd format I really need to import directly from the premiere project file, so that has been a game stopper. Right now I've taken the project over to a lower powered mac and am finishing it there. Maybe I should try finding another mouse driver [update - I found a third mouse driver and reinstalled, no luck] Thanks, Steve Steve, What is your display resolution and frequency/refresh set to? Is that the native rez and frequency for your monitor? Good luck, Hunt Same problem with me. Turned out that screen resolution and setting of large icons was the problem. Everything put to standard/native solved this. But now I have very small menus, not nice for my old eyes... Thanks for reporting this. What is the native resolution and physical size of the monitor. Hi Stan, In fact I have this problem with several dialogues of Encore. E.g. in the preview window the buttons don’t work either. Native resolution is 1920x1200 on a Nvideo Quatro 1600M when I set the icons to 150% (100 and 125% are working). Installed the latest drivers. Best regards, Dr. Ir. J.C. (Hans) Hubers Associate professor Thanks. Is there a way to change my message above? I thought I answered to an e-mail, but it turns out that now all my personal credentials are in a message on the Internet. Afraid for spam... Jeff Bellune, our friendly and hard-working neighborhood moderator, dropped by and cleaned up your message.... Wow, I would have never thought of that. It fixed my mouse problem too. I've only seen this problem with Adobe apps. They should know about this fix since it kind of narrows down the parameters for troubleshooting. Thanks, Steve Similar has been reported with dialog boxes in Photoshop too. Glad that you got it fixed. Do not know what it is, about the 150%, that messes things up. Good luck, Hunt PS - I also reported the "Personal Information" to Adobe, so it should all get cleaned up soon. I suggest filing a bug report: OK filled in the bug report. Indeed some time ago I had problems with my mouse in Photoshop too. Maybe a general thing. Hello, I just had a problem similar to this: lines appearing everyehere, somestimes the brushdots didnt appear at all, the first line a drew = nothing, second line drew = first line. It was really wierd. I tried almost everything, from re-installing PS, Going back to vanilla settings, reistalling mouse drivers. But nothing of that worked. BUT I FINALLY I FOUND A SOLUTION! and it was so easy and obvius that i behind it. All I had to do was to update my graphicscard driver! Yeah... I hope it works for you to. best of luck. Update NVIDIA driver: Or Update ATI driver: (If you have the latest driver allready, just re.istall them). P.S. sorry if my english was a little bad.
http://forums.adobe.com/message/4325617?tstart=0
CC-MAIN-2013-48
refinedweb
960
74.79
Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources. As we’ve already observed, planning ahead is important when you want to execute a potentially long-running program to scarf down data from the Web, because lots of things can go wrong. But what do you do with all of that data once you get it? You may initially be tempted to just store it to disk. In the situation we’ve just been looking at, that might result in a directory structure similar to the following: ./ screen_name1/ friend_ids.json follower_ids.json user_info.json screen_name2/ ... ... This looks pretty reasonable until you harvest all of the friends/followers for a very popular user—then, depending on your platform, you may be faced with a directory containing millions of subdirectories that’s relatively unusable because you can’t browse it very easily (if at all) in a terminal. Saving all this info to disk might also require that you maintain a registry of some sort that keeps track of all screen names, because the time required to generate a directory listing (in the event that you need one) for millions of files might not yield a desirable performance profile. If the app that uses the data then becomes threaded, you may end up with multiple writers needing to access the same file at the same time, so you’ll have to start dealing with file locking and such things. That’s probably not a place you want to go. All we really need in this case is a system that makes it trivially easy to store basic key/value pairs and a simple key encoding scheme—something like a disk-backed dictionary would be a good start. This next snippet demonstrates the construction of a key by concatenating a user ID, delimiter, and data structure name: s = {} s["screen_name1$friend_ids"] = [1,2,3, ...] s["screen_name1$friend_ids"] # returns [1,2,3, ...] But wouldn’t it be cool if the map could automatically compute set operations so that we could just tell it to do something like: s.intersection("screen_name1$friend_ids", "screen_name1$follower_ids") to automatically compute “mutual friends” for a Twitterer (i.e., to figure out which of their friends are following them back)? Well, there’s an open source project called Redis that provides exactly that kind of capability. Redis is trivial to install, blazingly fast (written in C), scales well, is actively maintained, and has a great Python client with accompanying documentation available. Taking Redis for a test drive is as simple as installing it and starting up the server. (Windows users can save themselves some headaches by grabbing a binary that’s maintained by servicestack.net.) Then, just run easy_install redis to obtain a nice Python client that provides trivial access to everything it has to offer. For example, the previous snippet translates to the following Redis code: import redis r = redis.Redis(host='localhost', port=6379, db=0) # Default params [ r.sadd("screen_name1$friend_ids", i) for i in [1, 2, 3, ...] ] r.smembers("screen_name1$friend_ids") # Returns [1, 2, 3, ...] Note that while sadd and smembers are set-based operations, Redis includes operations specific to various other types of data structures, such as sets, lists, and hashes. The set operations turn out to be of particular interest because they provide the answers to many of the questions posed at the beginning of this chapter. It’s worthwhile to take a moment to review the documentation for the Redis Python client to get a better appreciation of all it can do. Recall that you can simply execute a command like pydoc redis.Redis to quickly browse documentation from a terminal. See “Redis: under the hood” for an awesome technical deep dive into how Redis works internally.
http://my.safaribooksonline.com/book/web-development/social-networking/9781449394752/a-lean-mean-data-collecting-machine/id2818165
CC-MAIN-2013-48
refinedweb
632
51.68
Introduction to Microsoft Visual C++ .NET Microsoft Visual C++ .NET Fundamentals Introduction The earliest implementation of the C and C++ language from Microsoft used to be called Microsoft C/C++. When graphical programming started to be considered, Microsoft released Visual C++ 1.0 which allowed performing application programming for the Microsoft Windows operating system. With the releases of Microsoft Windows 3.X versions, the operating system was using a library referred to as Win16 that contained all necessary functions, structures, and constants used to create graphical user interface (GUI) application. This library made it a little easier to "talk" to the operating system and create fairly good looking applications. After a while, Microsoft released Windows 95 followed by Windows 98. The operating system library was also updated to Win32. Win32 was (in fact is) just a library. Like most or all other libraries, it is not a programming language. It is a documentation that allows programmers to know how they can use the library to create applications that can run on a Microsoft Windows-lead computer. This means that, to use it, programmers needed a language such as C, C++, or Pascal, etc to actually create the desired applications. Win32 was written in C. Since using Win32 requires a good level of understanding and work, Microsoft released a customized version of the Win32 library to make it easier to comprehend. The library is called Microsoft Foundation Class Library (MFC). Because Win32 was written in C and MFC was written for C/C++ developers, programmers of other languages would not understand it. To accommodate others, in fact to make Windows programming accessible to everybody, Microsoft created Microsoft Visual Basic as a true graphical programming environment. Visual Basic used a different and simpler language, called Basic as its foundation. The first consequence was that Visual Basic didn't inherently "understand" Win32. To allow Visual Basic programmers to use what was available from Win32, its programmers had to import the needed functions. This resulted in Visual C++ programmers using one library and Visual Basic programmers using another; this being only one of many problems. With the growing advent of the Internet, the client/server applications, demanding databases, communication software, Microsoft decided to create a new library that can be understood and used by many different languages. The library was called the .NET Framework. This was meant to accomplish the goal of both Visual C++ and Visual Basic using the same library. Another goal was to have programmers of different languages work on the same project without having each one learning the other's language. While on the subject, Microsoft also developed other languages such as C#, J#, or JScript and other programming environments that use these languages, such as Visual C# or Visual J# to also be part of this family that share the .NET Framework library. The .NET Framework A library called .NET Framework combines the new classes, functions, and constants that can be used to create applications to run for a Microsoft Windows computer. This library allows you to create graphical, databases, XML-based, web services, and web-based applications. Once an application has been created and is satisfactorily functional, it can be distributed to people who can use it. To make this possible, the .NET Framework is implemented in two systems: the class library and the common language runtime (CLR). The .NET Framework class library is a collection of fully functional object-oriented classes in the tradition of C++ covering all possible areas of application programming including Windows controls, file processing, XML, communication, web, databases, etc. This library is created to be used by various computer languages or programming environments. To take advantage of what this library offers, you must use a computer language that is adapted to "understand" this library. One of the languages that understands it is commonly referred to as Managed C++. That's the language we will use for the exercises in our lessons. With the language of your choice, you can create an application and get it ready. After an application has been created, it must be compiled so it can be used as necessary. Another goal of the .NET Framework is to make it possible for a library or service created from one language to be used in an application created using another language. To make this possible, code must be compiled so that an external engine, and not the environment used to create code, can compile, manage, and execute it. That's the role of the common language runtime. The CLR takes care of code execution, memory cleanup, thread management, security, etc. Such code is referred to as managed code. Code that is not compiled into the CLR is referred to as unmanaged code. These Visual C++ .NET Lessons Because many programs had earlier been written using the MFC library, Microsoft decided to continue publishing it and the MFC is still part of Visual C++ .NET. This resulted in many libraries being included in Visual C++ .NET. Because of the many differences among the libraries used in Visual C++, the side of Visual C++ that takes advantage of the .NET Framework is usually referred to as Visual C++ .NET (the same distinction is made between Visual Basic and Visual Basic .NET). Our lessons will address only the .NET side of Microsoft Visual C++ .NET. In other words, these lessons deal only with the way the .NET Framework is implemented in Visual C++ .NET. In fact, because of the many differences between MFC and the .NET Framework, we published a different site for the MFC side of Microsoft Visual C++. To make the .NET Framework transparently useful to different languages, Microsoft released Visual Studio .NET that could be used to create applications using C++, Managed C++, C#, Visual C#, Visual Basic .NET, J#, Visual J#, JScript .NET, etc. When Microsoft released the first version of Visual Studio .NET in 2002, Visual C++ suffered with the lack of "designing" a form. With the new released of Visual Studio .NET in 2003, this problem was solved. Because of that aspect, when writing these lessons, we used only Microsoft Visual Studio .NET 2003. Practical Learning: Launching Microsoft Visual Studio .NET The Integrated Development Environment: The Title Bar After Microsoft Visual Studio .NET has been opened, the screen you look at is called an Integrated Development Environment or IDE. The IDE is the set of tools you use to create a program. The system icon is used to identify the application that you are using. Almost every application has its own system icon. The system icon holds its own list of actions. For example, it can be used to move, minimize, maximize or close (when double-clicked) a window. When you freshly start Visual Studio .NET, the main section of the title bar displays the name of the application as Microsoft Developer Environment. Later on, if you start a project, the title bar would display the name of your project, followed by the name of the programming environment you selected. The main section of the title bar is also used to move, minimize, maximize the top section of the IDE, or to close Visual Studio. On the right section of the title bar, there are three system buttons with the following roles: Projects Fundamentals Creating a Project Our lessons assume that you already know the Managed C++ language, but only the language. We assume that you have no prior knowledge of graphical application programming. In our lessons, we will create Windows applications, the type referred to as graphical user interface (GUI). To create a Visual C++ .NET project, you can display the New Project dialog box, select Visual C++ Projects, select the type of project, give it a name, specify its directory, and click OK. Practical Learning: Using the Main Menu Compiling and Executing a Project As mentioned already, the instructions created for a Visual Basic project are written in plain English in a language easily recognizable to the human eye. To compile and execute a Visual C++ .NET project in one step, on the main menu, you can click Debug -> Start Without Debugging. Although there are other techniques or details in compiling (or debugging) and executing a project, for now, this is the only technique we will use until further notice. Practical Learning: Executing a Project To execute the application, on the main menu, click Build -> Build Solution To execute the application, on the Standard toolbar, click the Start button After viewing the application, close it Opening a Project As opposed to creating a new project, you can open a project that either you or someone else created. To open an existing project, on the main menu, you can click File -> Open -> Project... You can also click File -> Open Solution on the main menu. Alternatively, you can display the Start Page and click Open Project. In all cases, the action would display the Open Project dialog box. This allows you to select a Visual Project and open it. Design and Run Times Application programming primarily consists of populating a form with objects called Windows controls. These controls are what the users of your application use to interact with the computer. As the application developer, one of your jobs will consists of selecting the necessary objects, adding them to your application, and then configuring their behavior. As mentioned with the form, there are various ways you can get a control into your application. One of the techniques consists of programmatically adding a control by writing code. Another technique consists of visually selecting a control and adding it to a form. the control Studio Windows The Toolbars A toolbar is an object made of buttons. These buttons provide the same features you would get from the (main) menu, only faster. Under the main menu, the IDE is equipped with an object called the Standard toolbar. For example, to create a new project, on the main menu, you could click File -> New -> Project… On the other hand, the Standard toolbar is equipped with a button to perform the same action a little faster: By default, the Standard toolbar is positioned under the main menu but you can position it anywhere else on the IDE. To move a toolbar, position the mouse on the dotted line on its left section. The mouse pointer will change into a cross: Then you can Visual Studio, it is equipped with one. You can get a list of the toolbars that are available if you right-click any button on any toolbar or menu. On this site, every toolbar is referred to by its name. A toolbar is equipped with buttons that could be unfamiliar. Just looking at one is not obvious. To know what a button is used for, you can position the mouse on top of it. A tool tip will come up and display for a few seconds. From now on,. Dockable Windows When creating your applications, you will use a set of windows that each accomplishes a specific purpose. Some windows are represented with an icon but hides the rest of the body. For example, by default, on the left of the screen, you may see an icon made of two computers ., click the Auto Hide button. If clicked, the Auto Hide button changes from pointing left to pointing down. When Visual Studio .NET opens, it makes some windows necessary. These are the most regularly used windows. If you think that one of them is not regularly used in your types of assignments, you can remove it from the screen by clicking its Close button. All of the windows you can use are listed in the View menu. Therefore, if a window is not displaying, you can click View on the main menu and click a window of your choice. By its default installation, Visual Studio .NET installs some windows to the left and some others to the right of the screen. You can change this arrangement if you want. To do this, expand a window, then drag its title bar to another location on the screen. Windows can then be "coupled", that is docked together to one side of the screen. When windows are grouped, they automatically create tabs, allowing you to select the desired one by clicking its tab. The options available in windows display differently depending on the window and the items in it. Somes item are organized in a tree list equipped with + or – buttons. To expand a list, you can click its + button. To collapse a list, click its – sign. Some other items appear as buttons. The Server Explorer The items of this window display in a tree. To expand a node, you can click its + button. To collapse it, click its - button. The Start Page The Start Page is the first wide area that appears when Visual Studio .NET comes up. The top section of the Start Page displays three buttons labeled Projects, Online Resources, and My Profile. At any time, to display the Start Page, you can click its tab on the left side just under the Standard toolbar. Alternatively, on the main menu, you can click Help -> Show Start Page. If you have just installed Visual Studio .NET or have not previously opened a project, the Projects section would be empty. Once you start creating and using projects, they display in the Projects section by their name and the date they were created. Here is an example: The Online Resources section allows you to check new resources from Microsoft and partners directly from Visual Studio .NET through an Internet connection. The left side of this section displays a menu with Get Started, What's New, Online Community, etc. The My Profile section allows you to configure the programming settings you are using. The Code Editor Description There are two main ways you will manipulate an object of your application, visually or using code. In the next lessons, we will explore details of visually designing a control. As you should have found out from learning C++, code of an application is ASCII text-based, written in plain English and readable to human eyes. For a Visual C++ .NET application, you can use any text editor to write your code but one of Visual Studio's main strengths is the code editor that it has always brought. It is very intuitive. The Code Editor is a window specially designed for code writing. To display the code editor, if you created an empty project, you can click Project on the main menu and select one of the options that would lead either to a blank text file or a a file that contains primary code. The Code Editor of Visual C++ .NET is divided in 4 sections: The Tabs Bar The top section of the Code Editor displays tabs of property pages. Each tab represents a file. To add a new file to the project, on the main menu, you can click Once in the Add New Item dialog box, in the Templates. Because there can be different types of files, each has an extension that allows you to know the type of file the tab is holding. To access one of theses files, you can click its corresponding tab. By default, the tabs display in the order their files were created or added to the project, from left to right. If you don't like that arrangement, click and drag its tab either left or right beyond the next tab: The Types Combo Box The top-left section of the Code Editor displays a combo box named Types. As its name indicates, the Types combo box holds a list of the types as classes and structures that are used in the current project. You can display the list if you click the arrow of the combo box: Each item of the Types combo box displays the name of its type associated with its parent as implemented in the code. The Members Combo Box The top-right section of the Code Editor displays a combo box named Members. The Members combo box holds a list of the members of classes. The content of the Members combo box depends on the item that is currently selected in the Types combo box. This means that, before accessing the members of a particular class, you must first select that class in the Types combo box. Then, when you click the arrow of the Members combo box, the members of only that class display. If you select an item from the Members combo box, the Code Editor jumps to that member in the header file and positions the cursor to the left of the member.. The Solution Explorer Introduction The items of this window display in a tree. To expand a node, you can click its + button. To collapse it, click its - button. To explore an item, you can double-click it. The result depends on the item you double-clicked. Using the Solution Explorer The Solution Explorer can be used to create add a new class, a new resource, or a reference to the current project. It can also be used to add a another project to the current project. To perform any of these operations, you can right-click a folder node such as the name of the project, the Source Files, the Header Files, or the Resource Files nodes, position the mouse on Add and select the desired operation: Remember that project must be set as the default. That project would be the first to come up when the user executes. The Class View Using the Class View The Class View shares some of its functionality with the Solution Explorer. This means that you can use it to build a project, to add new class or a new resource. You can also use it to change the default project if you have more than one. While the Solution Explorer displays the items that are currently being used by your project, the Class View allows you to explorer the classes used in your applications, including their dependencies. For example, some times you will be using a control of the of the .NET Framework and you may wonder from what class that control is derived. The Class View, rather than the Solution Explorer, can quickly provide this information. To find it out, expand the class by clicking its + button.
http://functionx.com/vcnet/Lesson01.htm
CC-MAIN-2018-13
refinedweb
3,070
64
A node in the graph of vertices. More... #include <vtol_extract_topology.h> A node in the graph of vertices. The links correspond to edges between the vertices. Each vertex is located at the corner of the pixel. Definition at line 131 of file vtol_extract_topology.h. Create a node for vertex at (i,j). Definition at line 37 of file vtol_extract_topology.cxx. Null index value. A vertex with an index value >= this value does not correspond to a node in the graph. "Processed" index value. This is used to indicate that the boundary edge following went through a vertex. Direction in which we exit the neighbouring node to get back to this node. That is, (this->link)[n].link[ this->back_dir[n] ] == indexof(this). Definition at line 149 of file vtol_extract_topology.h. Edgel chains leading to neighbouring vertices. Definition at line 152 of file vtol_extract_topology.h. Location. Definition at line 137 of file vtol_extract_topology.h. Definition at line 137 of file vtol_extract_topology.h. Neighbouring vertices in the graph. Definition at line 143 of file vtol_extract_topology.h. vtol vertex in pixel coordinates. Definition at line 140 of file vtol_extract_topology.h.
http://public.kitware.com/vxl/doc/release/contrib/gel/vtol/html/structvtol__extract__topology__vertex__node.html
crawl-003
refinedweb
187
55.5
L_PixelateBitmap #include "l_bitmap.h" L_LTIMGSFX_API L_INT L_PixelateBitmap(pBitmap, uCellWidth, uCellHeight, uOpacity, CenterPt, uFlags); Divides the bitmap into rectangular or circular cells and then recreates the image by filling those cells with the minimum, maximum, or average pixel value, depending upon the effect that was selected. Returns This function does not support signed data images. It returns the error code ERROR_SIGNED_DATA_NOT_SUPPORTED if a signed data image is passed to this function. This function will divide the image into rectangular or circular cells. The uFlags parameter indicates whether to use rectangular or circular cells and indicates the type of information in the other parameters. If the image is divided into circular cells by setting PIX_RAD in the uFlags parameter, the cells will be centered around the specified CenterPt. This center point must be defined inside the bitmap or inside the region, if the bitmap has a region. If the bitmap has a region, the effect will be applied on the region only. This function supports 12 and 16-bit grayscale and 48 and 64-bit color images. Supportfor 12 and 16-bit grayscale and 48 and 64-bit color images is available only in the Document/Medical toolkits. To update a status bar or detect a user interrupt during execution of this function, refer to L_SetStatusCallback. An example of circular cell division can be seen below: This is the original image: The image below is the result of the following settings: uFlags = PIX_RAD | PIX_WPER | PIX_HPER | PIX_AVR uCellWidth = 90, uCellHeight = 40 This indicates the circular cells are divided into 90 degree cell divisions and each cell has a radial length of 40 pixels. Each cell division is filled with the average value for that cell division. The image below is the result of the following settings: uFlags = PIX_RAD | PIX_WFRQ | PIX_HFRQ | PIX_AVR uCellWidth = 90, uCellHeight = 40 This indicates the circular cells are divided into 90 separate cell divisions around the center point and there are 40 cell divisions along the radius. Each cell division is filled with the average value for that cell division. This function does not support 32-bit grayscale images. It returns the error code ERROR_GRAY32_UNSUPPORTED if a 32-bit grayscale image is passed to this function. Required DLLs and Libraries Platforms Windows 2000 / XP/Vista. See Also Example L_INT PixelateBitmapExample(L_VOID) { L_INT nRet; BITMAPHANDLE LeadBitmap; /* Bitmap handle for the image */ POINT CenterPt; /* Load a bitmap at its own bits per pixel */ nRet = L_LoadBitmap (TEXT("C:\\Program Files\\LEAD Technologies\\LEADTOOLS 15\\Images\\IMAGE3.CMP"), &LeadBitmap, sizeof(BITMAPHANDLE), 0, ORDER_BGR, NULL, NULL); if(nRet !=SUCCESS) return nRet; /* divide the image in to circular cells with angle length = 5°, and radius = 10 */ CenterPt.x = LeadBitmap.Width/2; CenterPt.y = LeadBitmap. Height/2; nRet = L_PixelateBitmap (&LeadBitmap, 5, 10, 100, CenterPt, PIX_AVR | PIX_RAD | PIX_WPER | PIX_HPER);; }
http://www.leadtools.com/help/leadtools/v15/main/api/dllref/l_pixelatebitmap.htm
crawl-003
refinedweb
461
52.19
Your source for hot information on Microsoft SharePoint Portal Server and Windows SharePoint Services John Jansen (Microsoft Office FrontPage) confirmed in a private e-mail conversation what I did find out the hard way: In the Xslt transformation of data view web parts the following functionality is blocked: I can understand that msxsl:script is blocked, otherwise you could execute any server-side script. Why xsl:include and xsl:import is not supported I really don’t understand. Could be that they scan the script code string to be executed for the msxsl:script tag, and that handling inclusion of external code was to much work, but it makes data view programming really hard. Would be great if you could create a library of useful Xslt routines and include those in your custom xslt transformations. Another thing I have been working on is the possibility to register additional xslt extension object like the one in the ddwrt namespace (see also), but I never succeeded. Any ideas on extending the xslt transformations functionality in data view web parts? Here it is, 2007...does this limitation still exist? I am able to link a css file, but not to include an xsl file. I would really like to use a code libary, since the same sections are repeated in 26 documents. Your post is the only one I can find on this topic! (I'm using Sharepoint 2003). thanks, Karyn I've also been looking into the same problem with my client. It appears they are using MSXML 6.0 with their MOSS 2007 installation and embedded scripts are not supported: I think its time u change the pic. Pingback from rousso.eu » xsl:include, xsl:import & msxml:script blocked on WSS 3 XML WebParts
http://weblogs.asp.net/soever/archive/2005/03/08/389371.aspx
crawl-002
refinedweb
293
63.29
The bitonic sort is a parallel sorting algorithm that is created for best implementation and has optimum usage with hardware and parallel processor array. It is not the most effective one though as compared to the merge sort. But it is good for parallel implementation. This is due to the predefined comparison sequence which makes comparisons independent of data that are to be sorted. For bitonic sort to work effectively the number of elements should be in a specific type of quantity i.e. the order 2^n. One major part of the bitonic sort is the bitonic sequence which is a sequence whose elements value first increases and then decreases. Bitonic sequence is an array arr[0 … (n-1)] if there is an index value i within the range 0 to n-1. For which the value of arr[i] is greatest in the array. i.e. arr[0] <= arr[1] … <= arr[i] and arr[i] >= arr[i+1] … >= aar[n-1] Bitonic sequence can be rotated back to bitonic sequence. A sequence with elements in increasing and decreasing order is a bitonic sequence. For creating a bitonic sequence, we will create two sub-sequences, one with ascending elements and other with descending elements. For example, let’s see the sequence arr[] and convert the following sequence to a bitonic sequence. arr[] = {3, 4, 1, 9, 2, 7, 5, 6} First, we will make pairs of elements and then create a bitonic sequence of these in such a way that one is in ascending order and the other is in descending order and so on. For our array, let’s create pairs in bitonic sequence. arr[] = {(3, 4), (1, 9), (2, 7), (5, 6)} // creating bitonic sequence pairs… arr[] = {(3, 4), (9, 1), (2, 7), (6, 5)} Then, we will create pairs of these pairs. i.e 4 elements bitonic sequence and compare elements with are a 2 distance [i.e. i with i+2]. arr[] = {(3, 4, 9, 1), (2, 7, 6, 5)} Ascending bitonic in first set will be created as − (3, 4, 9, 1) : comparing two distant elements. (3, 1, 9, 4) : Now, check adjacent elements. (1, 3, 4, 9) -> ascending bitonic sequence. Descending bitonic in second set will be created as − (2, 7, 6, 5) : comparing two distant elements. (6, 7, 2, 5) : Now, check adjacent elements. (7, 6, 5, 2) -> descending bitonic sequence. At the end, we will get the bitonic sequence of size 8. 1, 3, 4, 9, 7, 6, 5, 2 Now, since we have learned about the bitonic sequence. We will know about the Bitonic Sorting. To sort a bitonic sequence using bitonic sorting using these steps − Step 1 − Create a bitonic sequence. Step 2 − Now, we have a bitonic sequence with one part in increasing order and others in decreasing order. Step 3 − We will compare and swap the first elements of both halves. Then second, third, fourth elements for them. Step 4 − We will compare and swap, every second element of the sequence. Step 5 − At last, we will compare and swap adjacent elements of the sequence. Step 6 − After all swaps, we will get the sorted array. Program to show the implementation of Bitonic Sort − #include<iostream> using namespace std; void bitonicSeqMerge(int a[], int start, int BseqSize, int direction) { if (BseqSize>1){ int k = BseqSize/2; for (int i=start; i<start+k; i++) if (direction==(a[i]>a[i+k])) swap(a[i],a[i+k]); bitonicSeqMerge(a, start, k, direction); bitonicSeqMerge(a, start+k, k, direction); } } void bitonicSortrec(int a[],int start, int BseqSize, int direction) { if (BseqSize>1){ int k = BseqSize/2; bitonicSortrec(a, start, k, 1); bitonicSortrec(a, start+k, k, 0); bitonicSeqMerge(a,start, BseqSize, direction); } } void bitonicSort(int a[], int size, int up) { bitonicSortrec(a, 0, size, up); } int main() { int a[]= {5, 10, 51, 8, 1, 9, 6, 22}; int size = sizeof(a)/sizeof(a[0]); printf("Original array: \n"); for (int i=0; i<size; i++) printf("%d\t", a[i]); bitonicSort(a, size, 1); printf("\nSorted array: \n"); for (int i=0; i<size; i++) printf("%d\t", a[i]); return 0; } Original array: 5 10 51 8 1 9 6 22 Sorted array: 1 5 6 8 9 10 22 51
https://www.tutorialspoint.com/bitonic-sort-in-cplusplus
CC-MAIN-2022-05
refinedweb
714
61.26
I tried to set it as unfocusable but it didn't help,got any other ideas? I tried to set it as unfocusable but it didn't help,got any other ideas? I thought it was about focus as well,do you know how to set as unfocusable? Hi,I got an application that contains buttons that when pressed,draw a figure.For example,if the "triangle" buttons is pressed then a triangle is drawn.I tried to add controls so that the figure that... Actually I did,I already showed you the code,I do use a panel for the buttons and a drawing area. I actually ran the code before,my problem is running that code with the buttons. I see,thanks a lot man you helped me a lot I added what you said and now it works but it is opened in a separate window,I need it to work in the window which contains the buttons. I did it in the MovePingPong class. I don't understand,I thought I did it as well. Does the changed class look like this? import java.awt.Color; import java.awt.Graphics; import java.util.Timer; import java.util.TimerTask;... I changed the drawPingPong method to an Override paint method.The method is entered when compiled but the same affect,the screen is only updated when the button is pressed again,the repaint() does... Isn't that exactly what I did in MovePingPong class? I don't override any paint methods because my drawing method is in a Panel class.If repaint() only works with the overrided paint method then what should I do to update the screen and create an... There are classes I use here which I didn't think that are relevant. Picture: import java.awt.Color; import java.awt.FlowLayout; import java.awt.Graphics; import java.awt.Panel; The code for the class with the buttons: import java.awt.*; import java.awt.event.*; import java.util.Timer; import java.util.TimerTask; import java.awt.event.KeyEvent; import... Is it really relevant?I thought the Frames are a way to define the window. I do have a listener for my buttons which is built like a class. My code: import java.awt.*; import java.awt.event.*; import java.util.Timer; import java.util.TimerTask; import... What listener are you referring to? I'm not that advanced with java so could you please explain some of your used terms?what is JVM,what is the GUI's control? Hi! I have a java application with multiple buttons.When pressed,every button shows a different painting.One of the button is supposed to display a moving ball.The problem is,the repinat() event...
http://www.javaprogrammingforums.com/search.php?s=8a203cb10184b5ba07b3ab3941c1343d&searchid=1929389
CC-MAIN-2015-48
refinedweb
456
70.09
Details Description I use word2vec.fit to train a word2vecModel and then save the model to file system. when I load the model from file system, I found I can use transform('a') to get a vector, but I can't use findSynonyms('a', 2) to get some words. I use the fellow code to test word2vec from pyspark import SparkContext from pyspark.mllib.feature import Word2Vec, Word2VecModel import os, tempfile from shutil import rmtree if _name_ == '_main_': sc = SparkContext('local', 'test') sentence = "a b " * 100 + "a c " * 10 localDoc = [sentence, sentence] doc = sc.parallelize(localDoc).map(lambda line: line.split(" ")) model = Word2Vec().setVectorSize(10).setSeed(42).fit(doc) syms = model.findSynonyms("a", 2) print [s[0] for s in syms] path = tempfile.mkdtemp() model.save(sc, path) sameModel = Word2VecModel.load(sc, path) print model.transform("a") == sameModel.transform("a") syms = sameModel.findSynonyms("a", 2) print [s[0] for s in syms] try: rmtree(path) except OSError: pass I got "[u'b', u'c']" when the first printf then the “True” and " [u'__class__'] " I don't know how to get 'b' or 'c' with sameModel.findSynonyms("a", 2) Attachments Issue Links - is duplicated by SPARK-12680 Loading Word2Vec model in pyspark gives "ValueError: too many values to unpack" in findSynonyms - Closed - links to -
https://issues.apache.org/jira/browse/SPARK-12016
CC-MAIN-2022-33
refinedweb
214
58.89
http.filecontent)> Hi Ben I think i'm having a similar problem to @Rob I think the problem is being caused because of namespaces. I have put my content on where you will see the raw XML as well as the dump. The XML is returning 2 transactions which i need to get into a di... read more » Making SOAP Web Service Requests With ColdFusion And CFHTTP Posted on Jan 23, 2011 at 3:05 PM Hi Ben Thanks for the great post. I am trying to work through the cfhttp method mentioned above with a clients web service and I am struggling. I keep getting errors. Is there anyone here who may be able to assist with my code? I do have a budget... so if it takes longer than a few minutes, any @Jose Galdamez,@Ben Nadel Hi fellas @Jose... faito worked perfectly for me. WHat i did was setup a catchall@abc.com I made the failto address = #sendid#-#listid#@abc.com All failed emails are sent to that catchall acocunt. The failto address makes it easy to identify which listid and sendid the... @Jose Galdamez, Hi Ben and Jose 1st of all.. big thanks to Jose for his Skype chat a few weeks back. Your time was much appreciated. I have come up with a rather unelegant solution to my problem and would like Ben to review and advise. Ben, i would like to mail you the cf file to check out and @Jose Galdamez Hi Jose The mailerID isn't showing up in the bounced mail. Here is an example header returned from a bounced mail... X-MSK: CML=1.002000 Received: from mail-08.jhb.wbs.co.za ([196.2.97.5]) by fusebox.co.za with MailEnable ESMTP; Mon, 01 Mar 2010 10:28:56 +0000 Message-Id: Received:... read more » ColdFusion CFPOP - My First Look Posted on Mar 1, 2010 at 2:48 AM @Jose Galdamez, Im already using that UDF. Problem is... THe email subject is rarely the subject which was used in the mail which the system sent. It is usually a bounce mail subject such as "Out of office". But subsequently to that... i started playing around with the MailerID inside the CFMAIL t... read more » ColdFusion CFPOP - My First Look Posted on Feb 28, 2010 at 4:26 PM Hi Ben Just a quick question I have a mail system that sends mail out to lists using cfmail. I am using cfpop to identify hard / soft bounces. But what I need to do is identify which list the failed address belonged to so that i can delete from the list.. How can i identify that? Thanks in advanc... read more »
http://www.bennadel.com/members/5551-flashd.htm?_rewrite
CC-MAIN-2015-40
refinedweb
452
83.86
Hi, I'm trying to code a little Python script using the PyHook library. My script prints in the program every key pressed by the user, and the name of the window where he did it. But what I want for the program to do is to print the name of the window one time, all the keys pressed on it and only write the name of the window again if it changes. Here is the actual code: import pythoncom, pyHook def stroke(event): print event.WindowName print event.Key ph = pyHook.HookManager() ph.KeyDown = stroke ph.HookKeyboard() pythoncom.PumpMessages() Thanks in advance and please excuse my limited english. Fyrox
https://www.daniweb.com/programming/software-development/threads/382746/detect-variable-change
CC-MAIN-2018-39
refinedweb
110
75.4
Question: Internal rate of return LO 4 Harrison Hammocks is considering Internal rate of return (LO 4) Harrison Hammocks is considering the purchase of a new weaving machine to prepare fabric for its hammocks. The machine under consideration costs $88,235 and will save the company $14,000 in direct labor costs. It is expected to last 14 years. Required a. Calculate the internal rate of return on the weaving machine. b. If Harrison uses a 12% hurdle rate, should the company invest in the machine? Why or why not? Required a. Calculate the internal rate of return on the weaving machine. b. If Harrison uses a 12% hurdle rate, should the company invest in the machine? Why or why not? Answer to relevant QuestionsGarrett Boone, Farish Enterprises' vice president of operations, needs to replace an automatic lathe on the production line. The model he is considering has a sales price of $285,000 and will last for 9 years. It will have ...Bill Joyner is evaluating a new ticketing system for his theater. The system will cost $225,000 and will save the theater $57,275 in annual cash operating costs. Bill expects the new system to last eight years, at which time ...TimeLight's integrated time clock and payroll system sells for $231,945. At this price, the annual cost savings that the system will generate for Space Solutions, a facilities management company, over its eight-year life ...Amy Kimbell, CPA, CMA, and a member of the Institute of Management Accountants, recently joined Magee Metals and Moldings as a senior financial analyst. One of her major responsibilities is to prepare data to support capital ...Refer to Matthias Medical's financial statements, presented in Exercise 12-8.RequiredCalculate the following leverage ratios for 2013.a. Debt ratiob. Debt-to-equity ratioc. Times interest earnedratio Post your question
http://www.solutioninn.com/internal-rate-of-return-lo-4-harrison-hammocks-is-considering
CC-MAIN-2017-22
refinedweb
308
57.87
Spire.PDF has a function of adding, removing the blank pages in C#. We have already shown you how to remove the blank page in a PDF file. This article will show you how to insert an empty page in a PDF file in C#. By using the Spire.PDF, we can add the blank page to any place in the PDF file you want, such as at the first, the middle of the PDF file or at the end of the PDF file. It is very easy and you only need three lines of code to accomplish this task. Make sure Spire.PDF for .NET has been installed correctly and then add Spire.Pdf.dll as reference in the downloaded Bin folder though the below path: "..\Spire.Pdf\Bin\NET4.0\Spire.Pdf.dll". The following code snippet shows you how to insert an empty page in a PDF file. We will show you how to add the empty page at the end of the file and as the second page of the file. //create a PDF document and load file PdfDocument doc = new PdfDocument(); doc.LoadFromFile("sample.pdf"); //insert blank page at the end of the PDF file doc.Pages.Add(); //insert blank page as the second page doc.Pages.Insert(1); //Save the document to file doc.SaveToFile("result.pdf"); Check the effective screenshots as below: Add the blank page at the end of the PDF file: Add the blank page as the second page of the PDF file: Full codes: using Spire.Pdf; using System; namespace InsertPage { class Program { static void Main(string[] args) { //create PdfDocument instance and load file PdfDocument doc = new PdfDocument(); doc.LoadFromFile("sample.pdf"); //insert blank page as last page doc.Pages.Add(); doc.SaveToFile("result.pdf"); doc.Close(); System.Diagnostics.Process.Start("result.pdf"); //create PdfDocument instance and load file PdfDocument doc2 = new PdfDocument(); doc2.LoadFromFile("sample.pdf"); //insert blank page as second page doc2.Pages.Insert(1); doc2.SaveToFile("result2.pdf"); doc2.Close(); System.Diagnostics.Process.Start("result2.pdf"); } } }
https://www.e-iceblue.com/Tutorials/Spire.PDF/Spire.PDF-Program-Guide/Page-Setting/How-to-insert-an-empty-page-in-a-PDF-file-in-C.html
CC-MAIN-2022-40
refinedweb
339
65.42
'What?!' you hear her shout. 'I'll never do that,' she adds. 'Me and my friends play online bingo using Firefox on our nursing home computers. I use Skype on my Android tablet to talk to grandchildren that I never knew I had. Didn't you know? It's all about HTTP and web-based services these days? I want to be able to get my dentures, anywhere, anytime, from any device... with a few taps of the screen. I demand Rosie-as-a-Service!' Deep down, you know she's right. Nancy, your irritating littler brother, your friends - they are never going to be able to play with Rosie if she stays like this. Besides, we don't want any of those people actually logging into Rosie's brain, and breaking things. They type 'rm my_important_script.py', instead of 'python my_important_script.py' (as you told them to, literally, millions of times), and suddenly your masterpiece is gone, forever. The solution? Let's convert our program into a little web application, and instead of using arrow keys on the keyboard, allow Rosie's movements to be controlled remotely using the magic of HTTP. All using an Denture-Express 2000, here we come! You will need to have these: - Raspberry Pi 3 (kitted out with wheels and sensors), and Raspbian running on SDHC card - Computer from which you are connecting to the Raspberry Pi remotely - Other devices on your home network from which you would like to control Rosie. They need to have a browser installed, like Chrome, Safari, Firefox, Internet Explorer, Edge, etc, etc. You will need to have done these things: - I’ve got Pi(3) brain - Why-Fi-ght the Wi-Fi? - Hurrah-ndom inventions - Don't reinvent the eel - Achoo! Crash-choo! Episode I - Achoo! Crash-choo! Episode II You will need to do this: - Install Flask using Pip - Modify code to use Flask and handle HTTP - Create a HTML template and a CSS stylesheet - Start application and control Rosie using your favourite device What do you get after all this?Let's get this concern out of the way first: we're not making Rosie available on the Internet. That would be pretty unwise, you know, with all 'em hackers around the world, waiting to hack your Internet-connected vacuum cleaner, intelli-fridge and electronic toothbrush that brushes your teeth while you're sleeping. We will be turning the code we've written into a little web application, but it will only be reachable on your home network. On the other hand, it does mean that your family and friends (when visiting) will be able to control Rosie if they know her web address. Well, that was the whole point of this exercise wasn't it? Here are the various technologies at play. Hypertext Transfer Protocol (HTTP) is a Protocol used pretty much everywhere on the Internet. It's the reason why when you enter http or https in a web browser, followed by an address of a web site, things are helpfully returned to your screen. Essentially, HTTP allows the user (also called client) and application (also called server) to communicate in an agreed language (protocol), using known rules, and pass information back and forth. All, over a network. That's right; you can thank HTTP for your daily dose of cat falling off bicycle videos, and for allowing you to Google pretty much anything that you don't know, and then afterwards, pretend that you do. This client-to-server model, using HTTP, is used extensively for machine to machine communication as well, in the form of Application Programming Interfaces (APIs). It's something that will definitely be useful, when we eventually want Rosie-01 to talk to Rosie-02. But hold your horses. Let's get you talking to Rosie first, using HTTP. And implement the web page that Grandma Nancy wants to use to get Rosie to deliver her trusted prosthetic teeth. But here's another fact. You could spend all year coding a website from scratch. Writing hundreds of pages in Hypertext Markup Language (HTML), a language used to build the structure of web pages (what you see on screen), or Cascading Style Sheets (CSS), which is a different language used to make those pages look pretty. Or, even, writing actual application code itself that - probably - a million others would need to be writing as well. After all, everyone wants to do something with the web. And chances are, someone has already helpfully come up with all the building blocks that you need.. This is simply too much detail: So Flask, you say. Do we have that already? Probably not... so we'll have to check. What do we need to have to check to see if we have Flask? We need Pip. Aargh. Can we just get on with it please? Pip is a Python package manager, which - in simple terms - allows you to install and manage Python software. If you want to make use of a lot of great things that cleverer people have done with Python (like a web framework), and you intend to download and use them in your projects, it's best to let Pip manage those packages for you. Some packages are dependent on other packages, and even in some cases, certain versions of those packages. Keeping track of all of this simply shouldn't be a human task. Pip was already on our version of Linux (Raspbian OS). Check that it exists, by running: pip --version...checks version of Pip installed One down, another to go. Let's now check to see if we have the Flask package, again, using Pip. pip list...lists all installed Python packages No Flask? Plenty of other things there though. Well, let's install it. If you already had it, it would have appeared in the list like this: Before we proceed, it's worth remembering (for the future) that on computers where we have many Python projects on the go, we are likely to want to have different versions of the same Python packages installed. We might even need to maintain different versions of Python itself. There are packages that allow you to do just that - such as virtenv or virtualenvwrapper. For now, we are going to proceed without them as we're feeling... not very ambitious. We're going to build a very primitive web application. It won't have any form of authentication, and therefore anyone who can reach her on your local network will be able to control Rosie, remotely, using the buttons. Let's install Flask. pip install Flask...downloads and installs the Flask package. Make sure your Pi has an Internet connection beforehand! Once complete, run 'pip list' again to make sure you have successfully installed Flask. There? Good. We're ready to go. Let's create a new directory in which to store our web application, and create a Python file in it, aptly named 'rosie-web.py'. Because it'll be a web application, get it? cd /home/pi/rosie mkdir rosie-web cd rosie-web touch rosie-web.py We'll be needing two additional directories in which Flask will look for some files, so let's create them now before we forget. mkdir templates mkdir static 'Templates' will contain HTML files that define how our web pages are structured. 'Static' will contain the CSS files that define how those pages look in your browser (like fonts, colours, sizes of buttons, and stuff). We're ready to now populate 'rosie-web.py' with our code, and make use of Flask. Here is the simple code that we eventually settled on. First of all, we stripped out all of the keyboard related code that we had before in 'rosie_wheels_with_distance.py'. It's no longer needed. We're going all out web. In its place, however, are a number of new Flask-related additions. Like with any other module, before we do anything with it, we need to import Flask, and the functions that we'll be using. from flask import Flask, render_template, request, url_for, redirect We then create an instance of our Flask application. This is the Python code to do just that. app = Flask(__name__) We've decided to have two Flask-related functions that handle requests from the HTTP client (in our example, Nancy's browser). We know they are Flask functions, as we have a decorator at the start - @app.route(). This effectively tells the code that if any HTTP requests arrive at that web address, trigger the function that follows. First of the two functions is for root (/). If users land at the root (/) of our site (for example), they will simply be shown an 'index' page (index.html). This index page will just contain the buttons needed to move Rosie. You know, the kind of buttons that you need to press on a train company website when you want to submit a complaint about your train being late (again). @app.route("/") def index(): return render_template("index.html") The second of our Flask functions will be used to define what happens when the buttons are pressed in index.html. The browser will submit a value using what's known as a 'POST' request. This value will be the direction in which Rosie is expected to move. When we receive that value (at /control address, for example), we read it, then step through the same Python code that we used when reacting to keyboard arrow keys. The final action in this function (return redirect(url_for())) is to simply redirect the user's browser back to the index.html page. This isn't the most elegant of solutions, as the web page is refreshing every time you are sending a command... but it's crude and simple. @app.route("/control", methods = ["POST"]) def control_rosie(): control = request.form.get('control') if control == "Forward": #...code to move motors #...repeat for other directions return redirect(url_for("index")) Lastly, in the main section of the program, we will start the Flask web application. app.run(host = "0.0.0.0") This starts a built-in 'development' web server (included with Flask), which then allows users to access the application over the network, see our wonderful index.html page, and start submitting HTTP requests. Remember that this is a development server. If you want to sell Denture-Express 2000 on Amazon, or make it available to millions of people over the Internet, you will want to run the same Flask code, but on a more 'production-ready' web server, like Apache HTTPD, or nginx. Great. More strange words to Google! Now, there are two non-Python things left for us to complete. We need to create the 'index.html' file, so that we have a page that can be displayed in the browser. This file is expected in the 'templates' directory created earlier. cd templates touch index.html The HTML code we've used is shown below. In short, we have a form, which contains a number of buttons arranged in a table. Each button corresponds to a direction for Rosie. When the button is pressed, its value is submitted to the '/control' address, and is therefore handled by @app.route("/control", methods = ["POST"]) we defined for Flask earlier. This, of course, means that Rosie moves, just like it did when we were pressing keyboard keys. <html> <head> <link rel="stylesheet" href="/static/style.css" /> </head> <body> <h1>Welcome to Rosie's controls</h1> <form action="/control" method="post"> <table border=0> > </table> </form> </body> </html>HTML is used with all web technologies, Python or not, so its strange way of describing a web page's structure and content is well worth learning. Finally, create a CSS file called 'style.css' in the 'static' folder. This file was referenced in the <head> tag of the index.html file. Cascading Style Sheets (CSS) allow HTML files to be visually presented in the way that you want. This is where you can be creative, and spend many hours applying different colours, fonts, effects, etc to your web page. cd ../static/ touch style.css For now, we are going to apply a splash of colour to the background of the page, and change the colour of the font. We will also make the buttons square, large and colourful (remember, this is for Grandma?) body { background: #ff4141; color: #532619; } .button-control { height: 100px; width: 100px; background: #eec6c6; color: #532619; border-radius: 5px; } .button-control:active { color: #eec6c6; background: #532619; } Finally, the moment of truth. Let's start our application. cd /home/pi/rosie/rosie-web python rosie-web.py Now, from a browser on another device on your home network, navigate to address ''. You should be presented with your HTML page, styled using your CSS. And when you press the buttons, your POST HTTP requests will be fired at your Flask functions, which will (hopefully) move Rosie around as expected. It's extremely primitive, and it's totally not fit for purpose. After all, where is the login page? Why can't we see some of Rosie's messages on the page? What happens if we lose connection to Rosie, even momentarily? Of course, there's plenty of ways in which it can be improved. But, all things considered, we have achieved quite a lot with the help of Flask. Rosie is web-enabled, and this will keep Grandma Nancy happy (for a little while).
https://www.rosietheredrobot.com/2017/09/a-web-of-pies.html
CC-MAIN-2018-09
refinedweb
2,248
74.29
istream& ws ( istream& is ); <istream> Extract whitespaces Extracts as many whitespace characters as possible from the current position in the input sequence. The extraction stops as soon as a non-whitespace character is found. These whitespace characters extracted are not stored in any variable.Notice that most istream objects have the skipws flag set by default, and therefore already skip all whitespaces before all extraction operations. // ws manipulator example #include <iostream> #include <sstream> using namespace std; int main () { char a[10], b[10]; istringstream iss ("one \n \t two"); iss >> noskipws; iss >> a >> ws >> b; cout << a << "," << b << endl; return 0; } template <class charT, class traits> basic_istream<charT,traits>& ws (basic_istream<charT,traits>& is);
http://www.cplusplus.com/reference/iostream/manipulators/ws/
crawl-002
refinedweb
114
58.42
#include <unistd.h> #include "libavutil/avstring.h" #include "libavcodec/opt.h" #include "os_support.h" #include "avformat.h" Go to the source code of this file. If protocol is NULL, returns the first registered protocol, if protocol is non-NULL, returns the next registered protocol after protocol, or NULL if protocol is the last one. Definition at line 53 of file avio.c. Referenced by show_protocols(). Registers the URLProtocol protocol. Definition at line 59 of file avio.c. Referenced by register_protocol(). Seek to a given timestamp relative to some component stream. Only meaningful if using a network streaming protocol (e.g. MMS.). Definition at line 284 of file avio.c. Definition at line 265 of file avio.c. Referenced by url_set_interrupt_cb(). Definition at line 70 of file avio.c. Closes the resource accessed by the URLContext h, and frees the memory used by it. Definition at line 209 of file avio.c. Referenced by close_connection(), concat_close(), concat_open(), ff_rtsp_close_streams(), gopher_close(), http_close(), http_open_cnx(), http_seek(), rtmp_close(), rtp_close(), rtp_new_av_stream(), rtp_open(), rtsp_write_close(), rtsp_write_header(), url_exist(), url_fclose(), and url_fopen(). Returns a non-zero value if the resource indicated by url exists, 0 otherwise. Definition at line 223 of file avio.c. Referenced by build_feed_streams(), find_image_range(), and opt_output_file(). Definition at line 232 of file avio.c. Referenced by concat_open(). Return the file descriptor associated with this URL. For RTP, this will return only the RTP file descriptor, not the RTCP file descriptor. To get both, use rtp_get_file_handles(). Definition at line 247 of file avio.c. Referenced by http_get_file_handle(), rtp_open(), and rtsp_write_packet(). Return the maximum packet size associated to packetized file handle. If the file is not packetized (stream like HTTP or file on disk), then 0 is returned. Definition at line 254 of file avio.c. Referenced by http_prepare_data(), rtmp_open(), rtp_new_av_stream(), rtp_open(), and url_fdopen(). Creates an URLContext for accessing to the resource indicated by url, and opens it. Definition at line 121 of file avio.c. Referenced by concat_open(), gopher_open(), http_open_cnx(), rtmp_open(), rtp_new_av_stream(), rtp_open(), sdp_read_header(), url_exist(), and url_fopen(). Creates an URLContext for accessing to the resource indicated by url, and opens it using the URLProtocol up. Definition at line 76 of file avio.c. Referenced by url_open(). Reads up to size bytes from the resource accessed by h, and stores the read bytes in buf. Definition at line 155 of file avio.c. Referenced by concat_read(), ff_rtmp_packet_read(), gopher_read(), http_getc(), http_read(), url_fdopen(), and url_read_complete(). Read as many bytes as possible (up to size), calling the read function multiple times if necessary. Will also retry if the read function returns AVERROR(EAGAIN). This makes special short-read handling in applications unnecessary, if the return value is < size then it is certain there was either an error or the end of file was reached. Definition at line 164 of file avio.c. Referenced by ff_rtmp_packet_read(), and rtmp_handshake(). Changes the position that will be used by the next read/write operation on the resource accessed by h. Definition at line 199 of file avio.c. Referenced by concat_read(), concat_seek(), url_fdopen(), url_filesize(), and url_open_protocol(). The callback is called in blocking functions to test regulary if asynchronous interruption is needed. AVERROR(EINTR) is returned in this case by the interrupted function. 'NULL' means no interrupt callback is given. Definition at line 270 of file avio.c. Referenced by av_transcode(), decode_thread(), and main(). Definition at line 187 of file avio.c. Referenced by ff_rtmp_packet_write(), gopher_write(), http_close(), http_send_data(), http_write(), rtmp_handshake(), rtp_check_and_send_back_rr(), rtp_send_punch_packets(), rtp_write(), tcp_write_packet(), and url_fdopen(). Definition at line 51 of file avio.c. Referenced by av_find_stream_info(), rtp_read(), tcp_open(), tcp_read(), tcp_write(), udp_read(), and url_set_interrupt_cb().
http://www.ffmpeg.org/doxygen/0.6/avio_8c.html
CC-MAIN-2016-36
refinedweb
587
53.58
In this article, I will show you how to use XmlTextReader class to read an XML document and write data to the console. The XmlReader and XmlTextReader classes are defined in the System.XML namespace. The XmlTextReader class is derived from XmlReader class. The XmlTextReader class can be used to read the XML documents. The read function of this document reads the document until end of its nodes. In this article, I will show you how to use XmlTextReader class to read an XML document and write data to the console. Adding namspace Reference Since Xml classes are defined in the System.XML namespace, so first thing you need to do is to Add the System.XML reference to the project. using The constructor of the XmlTextReader class opens an XML file. In this sample, I used an XML file called xmltest.xml in C\temp directory. You can download the attached file. // Open an XML fileXmlTextReader reader = new XmlTextReader("C:\\temp\\xmltest.xml"); The Read method of the XmlTextReader class reads the data. while You fill data from an XML file to a DataSet by using DataSet.ReadXml method and then generate Excel doc from the DataSet. See Office Interop section of this site for samples on how to generate Excel docs from a DataSet.
http://www.c-sharpcorner.com/UploadFile/mahesh/ReadingXmlFile11142005002137AM/ReadingXmlFile.aspx
crawl-002
refinedweb
216
68.36
Allows!). Allows you to provide a handler for sections with poison. It is usually used in an infix form as follows: (readChannel c >>= writeChannel d) `onPoisonTrap` (poison c >> poison d) It handles the poison and does not rethrow it (unless your handler does so). If you want to rethrow (and actually, you'll find you usually do), use onPoisonRethrow Like onPoisonTrap, this function allows you to provide a handler for poison. The difference with this function is that even if the poison handler does not throw, the poison exception will always be re-thrown after the handler anyway. That is, the following lines of code all have identical behaviour: foo foo `onPoisonRethrow` throwPoison foo `onPoisonRethrow` return () Checks if the given item is poisoned. If it is, a poison exception will be thrown. Added in version 1.0.2. The classic skip process/guard. Does nothing, and is always ready. Suitable for use in an Control.Concurrent.CHP.Alt.alt.).
http://hackage.haskell.org/package/chp-1.4.0/docs/Control-Concurrent-CHP-Monad.html
CC-MAIN-2015-32
refinedweb
159
56.25
A user asked me recently if there is a prescribed way to rename an existing DFS-N server. More precisely, she asked if simply renaming a server hosting a DFS Namespace would lead to messed up Active Directory pointers, links, link targets, etc. I asked the team and the answer depends on whether you are running a standalone namespace or a domain namespace. Let me explain. If you are running a standalone namespace, you can simply rename the computer and DFS-N will continue to work with the new name. All the links and link targets should be just fine after the rename. However, you should be aware of the consequences of such a rename operation. Standalone namespaces do use the name of the computer in the namespace path, so all the references to \\oldname\folder by the clients need to be updated to \\newname\folder. You might want to consider adding an alternate name for the computer using the NETDOM COMPUTERNAME command so it can respond by both names. For details on NETDOM COMPUTERNAME, see If you are running a domain namespace, your namespace is based on the domain name, not the name of the computer. However, in order to avoid ending up with incorrect DFS-N metadata in Active Directory, you must remove the target (while it has its old name), rename the computer and then re-add the target (when the computer has the new name). If you have more than one target for that specific domain namespace, you can perform this operation without service disruption (the users will be getting their referrals for the other targets while the one being renamed is not there). For more information about using multiple servers for a domain namespace, see. For details on how to add/remove targets, see. I hope this post helps clarify the issue. Renaming the DFS-N server is certainly possible, but it should not be done without understanding the impact and proper planning is required. Please keep in mind that this server could have other roles installed and you must look into their ability to cope with a server rename as well. As usual, it is recommended that you validate your procedure in a test environment before trying this in a production environment.
https://blogs.technet.microsoft.com/josebda/2010/05/01/how-to-rename-a-windows-server-running-dfs-namespaces-dfs-n/
CC-MAIN-2016-36
refinedweb
378
59.03
README pg-migrationpg-migration What is it?What is it? NodeJS lacks support for good proper ORMs, and most ORMs tend to suck a bit in the end anyway. For inventid I therefore developed this simple nodejs version for postgresql of Liquibase. It is based on the excellent node-postgres library. The database changelog tableThe database changelog table pg-migration will automatically create the table ( dbchangelog) for you. How to useHow to use - Import the library import migration from 'pg-migration'; - Configure the library: const migrateAndStart = migration({ log: (level, message) => { your logging code here } }) - Create a valid database client connection - Create the migration, with that client, and a callback to the server start (e.g. migrateAndStart(db, './migrations', startServer);) Files called README.md and dbchangelog.sql from the migrations folder are ignored. Since the changeset id is derived from the file name, you can use the following command to create a new one touch `date +%Y%m%d%H%M%S`.sql Please be careful that the files will be executed in a alphabetically sorted fashion, so ensure that files do not depend on anything later (it's really a poor mans Liquibase).
https://www.skypack.dev/view/pg-migration
CC-MAIN-2021-49
refinedweb
193
56.55
Distributed_0<< Once you’ve added this to your project, you’ll need to make a couple minor changes to your Startup class in Startup.cs. First, in ConfigureServices, add a couple namespaces:: Caching strings You can use the GetString and SetString methods to retrieve/set a string value in the cache. This would appear in the “cachebucket” bucket as an encoded binary value (not JSON). In the sample code, I simply print out the ViewData["Message"] in the Razor view. It should look something like this: Caching objects You can also use Set<> and Get<> methods to save and retrieve objects in the cache. I created a very simple POCO (Plain Old CLR Object) to demonstrate: Next, in the sample, I generate a random string to use as a cache key, and a random generated instance of MyPoco. First, I store them in the cache using the Set<> method: Then, I print out the key to the Razor view: Next, I can use this key to look up the value in Couchbase: ). In the sample project, I’ve also set this to print out to Razor. If you view that document (before the 10 seconds runs out) in Couchbase Console, you’ll see that it has an expiration value in its metadata. Here’s an example:.
https://blog.couchbase.com/distributed-caching-aspnet-couchbase/
CC-MAIN-2019-35
refinedweb
216
75.74
A few weeks after I posted this blog post, a helpful engineer from the Flutter team reached out to me about some inconsistencies between the approaches I took in the React Native implementation vs the Flutter implementation. After fixing the discrepancy there was a meaningful difference between the performance noted in this article and the new results. You can find the updated findings and code in the take two version of this blog post. It’s a difficult decision deciding whether your company’s mobile app should be a true native application or employ a cross platform approach like React Native or Flutter. One factor that often comes into play is the question of speed - we all have a general sense that most cross platform approaches are slower then native, but the concrete numbers can be difficult to come across. As a result, we’re often going with a gut feeling rather than specific numbers when we consider performance. In the hopes of adding some structure to the above performance analysis, as well as a general interest in how well Flutter lives up to its performance promises, I decided to build a very simple app as a native app, a react native app, and a flutter app to compare their performances. The app The app that I built is about as simple as it can get while still being at least somewhat informative. It’s a timer app - specifically, the app displays a blob of text that counts up as time goes on. It displays the number of minutes, seconds, and milliseconds that have passed since the app was started. Pretty simple. Here’s an example of its starting state: And here’s an example after one minute, 14 seconds and 890 milliseconds has passed: Riveting. But why a timer? I chose a timer app for two reasons: - It was easy to develop on each platform. At its core this app is a text view of some type and a repeating timer. Pretty easy to translate across three different languages and stacks. - It gives an indication of how efficient the underlying system is at drawing something to the screen. Let’s take a look at the code Luckily, the app(s) are small enough that I can add the relevant sections right here. Native Android Here’s the main activity of the native Android app: class MainActivity : AppCompatActivity() { val timer by lazy { findViewById<TextView>(R.id.timer) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) initTimer() } private fun initTimer() { val startTime = elapsedRealtime() val handler = Handler() val runnable: Runnable = object: Runnable { override fun run() { val timeDifference = elapsedRealtime() - startTime val seconds = timeDifference / 1000 val minutes = seconds / 60 val leftoverSeconds = seconds % 60 val leftoverMillis = timeDifference % 1000 / 10 timer.text = String.format("%02d:%02d:%2d", minutes, leftoverSeconds, leftoverMillis) handler.postDelayed(this, 10) } } handler.postDelayed(runnable, 1) } } React Native Here’s our App.js file for the React Native app: export default class App extends Component { render() { return ( <View style={styles.container}> <Timer /> </View> ); } } class Timer extends Component { constructor(props) { super(props); this.state = { milliseconds: 0, seconds: 0, minutes: 0, } let startTime = global.nativePerformanceNow(); setInterval(() => { let timeDifference = global.nativePerformanceNow() - startTime; let seconds = timeDifference / 1000; let minutes = seconds / 60; let leftoverSeconds = seconds % 60; let leftoverMillis = timeDifference % 1000 / 10; this.setState({ milliseconds: leftoverMillis, seconds: leftoverSeconds, minutes: minutes, }); }, 10); } render() { let { milliseconds, seconds, minutes } = this.state; let time = sprintf("%02d:%02d:%2d", minutes, seconds, milliseconds); return ( <Text>{time}</Text> ) } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', } }); Flutter And finally here’s our Flutter main.dart file: void main() => runApp(new MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return new MaterialApp( home: new MyHomePage(), ); } } class MyHomePage extends StatefulWidget { MyHomePage({Key key}) : super(key: key); @override _MyHomePageState createState() => new _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { int _startTime = new DateTime.now().millisecondsSinceEpoch; int _numMilliseconds = 0; int _numSeconds = 0; int _numMinutes = 0; @override void initState() { super.initState(); Timer.periodic(new Duration(milliseconds: 10), (Timer timer) { int timeDifference = new DateTime.now().millisecondsSinceEpoch - _startTime; double seconds = timeDifference / 1000; double minutes = seconds / 60; double leftoverSeconds = seconds % 60; double leftoverMillis = timeDifference % 1000 / 10; setState(() { _numMilliseconds = leftoverMillis.floor(); _numSeconds = leftoverSeconds.floor(); _numMinutes = minutes.floor(); }); }); } @override Widget build(BuildContext context) { return new Scaffold( body: new Center( child: new Text( sprintf("%02d:%02d:%2d", [_numMinutes, _numSeconds, _numMilliseconds]), ), ) ); } } Each app follows the same basic structure - they all have a timer that repeats every ten milliseconds and recalculates the amount of minutes/seconds/milliseconds that have elapsed since the timer was started. How are we measuring the performance? For those unfamiliar with Android development, Android Studio is the editor/environment of choice for building Android apps. It also comes with a helpful series of profilers to analyze your application - specifically, there’s a CPU profiler, a memory profiler, and a network profiler. So we’ll use those profilers to judge performance. All of the tests are run on thoughtbots Nexus 5X and my own personal first generation Google Pixel. The React Native app will be run with the --dev flag set to false, and the Flutter app will be run in the profile configuration to simulate a release app rather than a JIT compiled debug app. Show me some numbers! Time for the interesting part of the blog post. Let’s take a look at the results when run on the Thoughtbot office Nexus 5X. Native results on the Nexus 5X React Native results on the Nexus 5X Flutter results on the Nexus 5X The first thing these results make clear is that a native Android app trumps both the React Native and Flutter apps by a non trivial margin when it comes to performance. CPU usage on the native app is less than half that of the Flutter app, which is still less CPU hungry than the React Native app, though by a fairly small margin. Memory usage is similarly low on the native app and inflated on both the React Native and Flutter applications, though this time the React Native app eked out a win over the Flutter app. The next interesting takeaway is how close in performance the React Native and Flutter applications are. While the app is admittedly trivial, I was expecting the JavaScript bridge to impose a higher penalty since the application is sending so many messages over that bridge so quickly. Now let’s take a look at the results when tested on a Pixel. Native results on the Pixel React Native results on the Pixel Flutter results on the Pixel So, right off the bat I’m surprised about the significantly higher CPU utilization on the Pixel. It’s certainly a more powerful (and in my opinion, much smoother) phone than the Nexus 5X, so my natural assumption would be that CPU utilization for the same application would be lower, not higher. I can see why the memory usage would be higher, since there’s more memory on the Pixel and Android follows a general “use it or lose it” strategy for holding onto memory. I’m interested in hearing why the CPU usage would be higher if anyone in the audience knows! The second interesting take away here is that Flutter and React Native have diverged heavily in their strengths and weaknesses vs their native counterpart. React Native is only marginally more memory-hungry than the native app, while Flutters memory usage is almost 50% higher than the native app. On the other hand, the Flutter app came much closer to matching the native apps CPU usage, whereas the React Native app struggled to stay under 30% CPU utilization. More than anything else, I’m surprised by how different the results are between the 5X and the Pixel. Conclusion I feel confident in saying that a native Android app will perform better than either a React Native app or a Flutter app. Unfortunately, I do not feel confident in saying that a React Native app will out perform a Flutter app or vice versa. Much more testing will need to be done to figure out if Flutter can actually offer a real world performance improvement over React Native. Caveats The profiling done above is by no means conclusive. The small series of tests that I ran cannot be used to state that React Native is faster than Flutter or vice versa. They should only be interpreted as part of a larger question of profiling cross platform applications. There are many, many things that this small application does not touch that affect real world performance and user experience. It’s also worth pointing out that all three applications, in debug mode and release mode, ran smoothly.
https://thoughtbot.com/blog/examining-performance-differences-between-native-flutter-and-react-native-mobile-development
CC-MAIN-2020-40
refinedweb
1,445
51.38
I have a script I want to use to upload files to a website. I have 2 problems with it: The HTML is: <FORM ENCTYPE="multipart/form-data" ACTION="../cgi-bin/upload.pl" METH + Please select a file to upload: <BR> <INPUT TYPE="FILE" NAME="file"> <p> <INPUT TYPE="submit"> </FORM> [download] And the code is: #! c:/Perl/bin/Perl.exe -wT # Script to upload file. This script is tied to upload.html use strict; use CGI; my $query = CGI->new(); my $fn = $query->param ('file'); my $fh = $query->upload ('file'); ($fn)=($fn=~/^.+\\(.+)/); my $size=-s $fh; my $max_size=100; print $query->header( "text/html" ), $query->start_html(-title => "Upload Test"); if ($size<$max_size*1024) { #This file size allowed if (open FH, ">$fn") { # Open file while (<$fh>) { print FH; } if (check_filesize((-s FH), $size)) { # If all file copied to +server print $query->p("File uploaded succesfully"); } else { print $query->p("There was a problem uploading your file. Please ").a({-href=>"localhost/upload.html"}, "try ag +ain"); } } else { print $query->p("There was a problem uploading your file. Please ").a({-href=>"localhost/upload.html"}, "try ag +ain"); } } else { print $query->p("Sorry, this file is too large. Maximum size allow +ed is ", $max_size, "kb"); } print $query->end_html; sub check_filesize { # Check if upload file size is approximately equa +l to the file written my ($up_file, $down_file)=@_; return 1 if ((sprintf "%d", $up_file/1024)==(sprintf "%d", $down_f +ile/1024) || (sprintf "%d", $up_file/1024)==(sprintf "%d", $down_file/1024)+ +1 || (sprintf "%d", $up_file/1024)==(sprintf "%d", $down_file/1024)- +1); return 0 } [download] I'm using perl 5.8.0 with Apache 2.0.45 on WinXP. Update: It seems that fizbin is right. The upload gets interrupted at some point. I can't find anything to indicate why in the apache error log. When I pass text files it's no problem (although I still have the CGItemp files), but if I upload pictures they come up corrupted. Why is this happening? Do I have to use binmode? ----------------------------------- ($fn)=($fn=~/^.+\\(.+)/); [download] I'd change that line to: $fn =~ s{^.*[/\\]}{}; [download] -- @/=map{[/./g]}qw/.h_nJ Xapou cets krht ele_ r_ra/; map{y/X_/\n /;print}map{pop@$_}@/for@/ [download] Thanks, that works (although I can't figure out why. If your reasoning is correct than IE shouldn't have accepted it either. Oh well). Thanks also for streamlining the sub. As for the last issue: it doesn't help to close FH;. I'm using the line to check if all the file got copied, so I have to have FH open after the while loop. Adding close FH; at the end of the script still doesn't do the trick. I still have a CGItemp file after the upload. Any othe ideas? While I agree that the code is clearer with a substitution rather than capturing stuff in $1, the advantage of the latter is that it untaints the input, and it's definitely preferable for web scripts to run in taint mode. Something like this should work: However for getting the basename of a path I'd tend to use File::Basename — though that doesn't play well with the desire to untaint ... Smylers sub check_filesize { # Check if upload file size is approximately equa +l to the file written my ($up_file, $down_file)=@_; return (abs ( int($up_file/1024) - int($down_file/1024) ) <= 1); } [download] About your second question - those wierd file names - what I think is happening is that your script is failing to complete on the server. During file upload, CGI.pm creates temporary files as you mention to hold the data while the script does something with it. Once the script completes, these files are deleted, but if your script is erroring out, then the files could stick around. I suggest that you look in the apache error log, but if I had to make a guess I'd say that the code -s FH is causing trouble, and you really want to say -s $fn, though you'd also want to say close FH; immediately after the while loop. my $file = $req->param($inputfieldname); my $fh = $req->upload($inputfieldname); if (open(OUTFILE, ">$c{dir}{tmp}/$file")) { binmode(OUTFILE); # Windows only while (<$fh>) { print OUTFILE; } close (OUTFILE); } [download] Hell yes! Definitely not I guess so I guess not Results (43 votes), past polls
http://www.perlmonks.org/?node_id=374985
CC-MAIN-2014-52
refinedweb
721
70.84
To load .gql and .graphql files, first install the graphql and graphql.macro packages by running: npm install --save graphql graphql.macro Alternatively you may use yarn: yarn add graphql graphql.macro Then, whenever you want to load .gql or .graphql files, import the loader from the macro package: import { loader } from 'graphql.macro'; const query = loader('./foo.graphql'); And your results get automatically inlined! This means that if the file above, foo.graphql, contains the following: query { hello { world } } The previous example turns into: const query = { 'kind': 'Document', 'definitions': [{ ... }], 'loc': { ... 'source': { 'body': '\\\\n query {\\\\n hello {\\\\n world\\\\n }\\\\n }\\\\n', 'name': 'GraphQL request', ... } } }; You can also use the gql template tag the same way you would use the non-macro version from graphql-tag package with the added benefit of inlined parsing results. import { gql } from 'graphql.macro'; const query = gql` query User { user(id: 5) { lastName ...UserEntry1 } } `;
https://facebook.github.io/create-react-app/docs/loading-graphql-files
CC-MAIN-2019-30
refinedweb
150
69.18
hello, this is my first post, nice to meet everyone I am taking input from the keyboard, and I want to ignore whitespace, punctuation and the case of letters, i.e. 'a' = 'A' I figured out the whitespace, but I can't figure out letter case and punctuation. Here is my code (my main function, which uses a stack and queue objects). The program is meant to determine whether or not a statement is a palindrome. thanks!thanks!Code:#include "stack.h" #include "queue.h" #include <iostream> using namespace std; int main() { bool isPalindrome = true; char ch, ch1, ch2; StackType s; QueueType q; cout << "Enter a statement: "; cin >> ch; while(!s.IsFull() && ch != '\n') { s.Push(ch); q.Enqueue(ch); if(cin.peek() != '\n') cin >> ch; else cin.get(ch); } while(isPalindrome && !s.IsEmpty()) { q.Dequeue(ch1); ch2 = s.Top(); s.Pop(); isPalindrome = ch1 == ch2; } cout << endl; if(isPalindrome) cout << "Entered statement is a Palindrome\n"; else cout << "Entered statement is not a Palindrome\n"; return 0; }
http://cboard.cprogramming.com/cplusplus-programming/88032-ignoring-puncuations-input-stream.html
CC-MAIN-2015-22
refinedweb
167
72.46
The --xml-output option on darcs commands is something I hope hg picks up; let's not do much more microparsing than we have to. OpenID looks kinda cool, but I don't quite see how it works; I hope they add a story/example showing what happens if a black hat puts my homepage URL in the field. Some CVS (related) features I depend on that I wonder if/when hg has: emacs support (ctrl-x-v-v is burned into my medulla), keywords support. Hmm... PHP is clearly the dominant server-side deployment vehicle these days. I wonder if its namespace management will catch up with Modula-3 and python... or if the .NET/mono CLR stuff has much chance; IronPython and the like look promising. I suppose JSP hosting is a commodity these days... and .Net... I wonder what the prices and trends are; and I wonder if there's mono hosting yet. Hmm... a bunch more certs... ugh... they're all spam. How do I certify somebody as pest or fraud or leech?
http://www.advogato.org/person/connolly/diary.html?start=27
CC-MAIN-2015-27
refinedweb
177
82.95
ui centering Move the commented line to the second button.center and the button moves. Why?presumedly due the the .width and .height statements..... import ui v = ui.View() v.present('full_screen') button = ui.Button (title='button') v.add_subview(button) button.background_color = 'white' #button.center =(100,100) button.width= 360 button.height=100 button.center=(100,100)``` Horribly worded question. Lets try again. Why does: button.center =(150,150) button.width = 200 button.heigth= 75 And button.width = 200 button.heigth= 75 Button.center(150,150) Result in markedly different button positions? Although you can place a button using the center, its position is still defined by the upper left corner, unless you have flex set. Though Flex I think just affects what happens when parent view gets resized. Took me a while to understand it's based on THE BUTTON'S upper left corner. Thanks. The word "center" threw me off. @boo , your example is a little strange as far as I can see. Eg. If you do, button.center = v.bounds.center() would make sense to me. Normally, you want to position a item within another item. center is just a tuple(x,y) of the objects center. Possibly I am missing some thing, but I don't think so. I simply want to position a button at a predictable position on screen (x,y) and have it stay there. What am i doing wrong? @boo , the below is using flex. If you change the size or the style, the button is always centered. The best way to understand flex is to use the designer in Pythonista (Create a UIFile). # Pythonista Forum - @Phuket2 import ui class MyClass(ui.View): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.make_view() def make_view(self): btn = ui.Button(frame=(20, 20, 100, 32)) btn.border_width = .5 btn.title = 'hello' btn.bg_color = 'orange' btn.corner_radius = 6 btn.tint_color = 'white' btn.center = self.bounds.center() btn.flex = 'lrtb' self.add_subview(btn) if __name__ == '__main__': w, h = 900, 800 f = (0, 0, w, h) style = 'sheet' mc = MyClass(frame=f, bg_color='white') mc.present(style=style, animated=False) Edit: if you remove the line btn.center = self.bounds.center() The button will stay in it's position based on the frame passed. But the flex attr is making that possible. @boo here is a slightly different way. It's not using flex, it's using the layout callback(look at custom views in the help file). Is also a valid way to position your objects in a view. Ui Module is so flexible. Maybe the flexibly gives the idea it's hard. But it's not really. Everything is so well constructed, it normally just works very well. # Pythonista Forum - @Phuket2 import ui class MyClass(ui.View): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.make_view() def make_view(self): btn = ui.Button(name='my_btn', frame=(20, 20, 100, 32)) btn.border_width = .5 btn.title = 'hello' btn.bg_color = 'orange' btn.corner_radius = 6 btn.tint_color = 'white' #btn.center = self.bounds.center() #btn.flex = 'lrtb' self.add_subview(btn) def layout(self): self['my_btn'].center = self.bounds.center() if __name__ == '__main__': w, h = 330, 600 f = (0, 0, w, h) style = 'sheet' mc = MyClass(frame=f, bg_color='white') mc.present(style=style, animated=False) ``` Edit: also the last 2 examples should be orientation friendly also. Not a big deal, but important. Thanks for your help. It seems you use: .frame to position the button. On the website, the basic example for Pythonista ui used: button.center Can you explain differences between frame and center attributes, as relates to a subview (in this case a button) @boo , hmmm. I will try. It's not easy to say in words though. But the frame is the x, y, width, height of the object. So btn = ui.Button( frame=(0, 0, 100, 32) ) creates a ui.Button with a width of 100 and a height of 32. The x, y will be 0. So if you set a button for example as above, you can adjust the x, y, width, height in subsequent calls. Eg. btn.x = 100 btn.y = 150 btn.width = 400 etc.. So setting the frame is just a expedient way to set the 4 attrs (x, y, width, height) at one time. Normally it's best to refer to the area/Rect/interior of an ui object by its bounds. Create a ui object with frame and refer to the interior of the object with bounds. For a button for example, the frame and bounds are equal I think. But a ui.View that has a menu for example the frame and bounds will be different. But what is nice, all the ui objects are subclassed from ui.View (almost all) , so you can just use the same technique to refer to bounds or frame. It should just work. Sorry if the above is not clear. Not easy to explain Thanks again. Looks like the example provided in the docs had me using button.center, button.height and button.width, instead of just button.frame. @boo , I understand what you mean. The example is just one way to do it. I am sure in a few days this will be meaningless to you. It will become second nature to you. button.center is a shortcut for button.frame.center, and is the coordinate of the center of the button inside the superview's coordinate system. button.height is a shortcut for button.frame.size.height Here are the basic rules (so you predict what happens). a view's positionis defined by its top left point, and a width and height. If you change width or height, the top left corner stays put. (there is not really a way to say, i want to position using the center, or bottom left, etc, so the convention is, top left) Now, if you want to expand about the center, one approach is to simply store the center location and set it back again oldcenter=btn.center btn.width=150 btn.center=oldcenter Another thing that confuses most people is the difference between frame and bounds. It toom me a long time to understand... frame refers to your position in your parent's coordinate system (i.e relative to your superview's top left corner). bounds refers to your position in your OWN coordinate system. So, if you want to center a button inside another view, you use view.add_subview(btn) btn.center = view.bounds.center (btn.center refers to btn.frame.center, so is in the super view coordsys, and in this case we want it to match the superview center). Now, if you want to KEEP the centers aligned when the screen rotates, you would use flex, which is how you tell the system whether you intended to place your button really at a particular pixel value, or are more interested in the relative relationship. adjusting bounds also becomes important when you start dealing with ui.Transforms. Thanks for the replies. It is becoming much clearer.
https://forum.omz-software.com/topic/3632/ui-centering/9
CC-MAIN-2020-45
refinedweb
1,180
71.31
Advertise with Us! We have a variety of advertising options which would give your courses an instant visibility to a very large set of developers, designers and data scientists.View Plans Top C# Interview Questions and Answers Table of Contents Debuting back in 2000, C# has succeeded in becoming one of the leading programming languages. As a multi-paradigm programming language, C# also has some features of functional programming that takes its usefulness and versatility to a step further. C# Interview Questions and Answers In the following section, we have enlisted the most important C# interview questions. These questions prepare you for your next C# interview in addition to enhancing your C# knowledge and letting you evaluate your current C# understanding. Question: What is C#? Write its features Answer: C# is an object-oriented programming language that was developed by Microsoft in 2000. It is supported by different operating systems. C# is the primary language that is used to create .Net software applications. It allows us to create Windows UI apps, backend services, controls, libraries, android apps, and even blockchain applications. C# works on the concept of classes and objects just like Java. Some of the C# features are as follows: - Follows structured approach - Parameters passing is easy - Code can be compiled on a different platform - Open-source - Object-oriented - Flexible and scalable Question: Explain what are classes and objects in C#? Answer: C# is an object-oriented language and classes are its foundation. A class generally depicts the structure of data, how data is stored and managed within a program. A class has its own properties, methods, and other objects that define the class. Objects are the real-world entity having some characteristics and is created using the class instance. These classes define the type of the defined object. For example, if we consider a program that covers the object related to the book. We call the class a Book which has two properties: name and the author. In real programming, Vedas is an object and an instance of the class Book. Question: Describe the different C# classes in detail. Answer: There are 4 types of classes that we can use in C#: - Static Class: It is the type of class that cannot be instantiated, in other words, we cannot create an object of that class using the new keyword and the class members can be called directly using their class name. - Abstract Class: Abstract classes are declared using the abstract keyword. Objects cannot be created for abstract classes. If you want to use it then it must be inherited in a subclass. You can easily define abstract or non-abstract methods within an Abstract class. The methods inside the abstract class can either have an implementation or no implementation. - Partial Class: It is a type of class that allows dividing their properties, methods, and events into multiple source files, and at compile time these files are combined into a single class. - Sealed Class: One cannot inherit a sealed class from another class and restricts the class properties. Any access modifiers cannot be applied to the sealed class. Question: Explain different access modifiers in C#? Answer: These are the keywords that help to define the accessibility of class, member, and data type in the program. These keywords are used to restrict the use of some data manipulation done by other classes. There are 4 types of access modifiers- public, private, protected, and internal. These modifiers define 6 other accessibility levels when working together- public, protected, internal, protected internal, private, and private protected. Below is the access chart of the modifiers. Question: How can you describe object-oriented concepts in detail? Answer: C# is an object-oriented programming language that supports 4 OOP concepts. - Encapsulation: defines the binding together code and the data and keeps it safe from any manipulation done by other programs and classes. It is a container that prevents code and data from being accessed by another program that is defined outside the container. - Abstraction: this concept of object-oriented protects everything other than the relevant data about any created object in order to increase efficiency and security within the program. - Inheritance: Inheritance is applied in such a way where one object uses the properties of another object. - Polymorphism: is a feature that allows one interface to act as a base class for other classes. This concept is often expressed as a "single interface but multiple actions". Question: Explain how code gets compiled in C#? Answer: It takes 4 steps to get a code to get compiled in C#. Below are the steps: - First, compile the source code in the managed code compatible with the C# compiler. - Second, combine the above newly created code into assemblies. - Third, load the CLR. - Last, execute the assembly by CLR to generate the output. Question: What is break and continue statements in C#, explain? Answer: Below is the differences: Question: How you can explain the use of ‘using’ statements in C# in detail. Answer: The using statement is used to control the usage of one or more resources that are being used within the program. The resources are continuously consumed and released. The main function of this statement is to manage unused resources and release them automatically. Once the object is created which is using the resource and when you are done you make sure that the object’s dispose method is called to release the resources used by that object, this is where using statements works well. For example: using (MyResource abc = new MyResource()) { abc.program(); } Gets translated to, MyResource abc= new MyResource(); try { myRes.program(); } finally { // Check for a null resource. if (abc!= null) // Call the object's Dispose method. ((IDisposable)abc).Dispose(); } Question: Describe the C# dispose of the method in detail. Answer: Dispose of the method: The disposeof() method releases the unused resources by an object of the class. The unused resources like files, data connections, etc. This method is declared in the interface called IDisposable which is implemented by the class by defining the interface IDisposable body. Dispose method is not called automatically, the programmer has to implement it manually for the efficient usage of the resources. Question: Explain in detail the finalize method in C#? Answer: Finalize method- The finalize () method is defined in the object class which is used for cleanup activities. This method is generally called by the garbage collector whenever the reference of any object is not used for a long time. Garbage collector frees that managed resources automatically but if you want to free the unused resources like filehandle, data connection, etc., then you have to implement the finalize method manually. Question: How you can define the exception handling in C#? Answer: An exception is a raised problem that may occur during the execution of the program. Handling exceptions offers a simple way to pass the control within the program whenever an exception is raised. C# exceptions are handled by using 4 keywords and those are try, catch, finally, throw. - try: a raised exception finds a particular block of code to get handled. There is no limit on the number of catch blocks that you will use in your program to handle different types of exception raised. - catch: you can handle the raised exception within this catch block. You can mention the steps that you want to do to solve the error or you can ignore the error by suppressing it by the code. - Finally: irrespective of the error, if you still want some set of instructions to get displayed then you can use those statements within the finally block and it will display it on the screen. - throw: you can throw an exception using the throw statement. It will display the type of error you are getting. Syntax: try { //exception handling starts with try block } catch( ExceptionName ea1 ) { // errors are handled within the catch block } catch( ExceptionName e2 ) { // more catch block } catch( ExceptionName eN ) { // more catch block to handle multiple exception raised } finally { // last block of the exception handling } Question: Explain the concept of Destructor in detail. Explain it with an example. Answer: A destructor is a member that works just the opposite of the constructor. Unlike constructors, destructors mainly delete the object. The destructor name must match exactly with the class name just like a constructor. A destructor block always starts with the tilde (~) symbol. Syntax: ~class_name() { //code } A destructor is called automatically: - when the program finishes its execution. - Whenever a scope of the program ends that defines a local variable. - Whenever you call the delete operator from your program. Question: Define method overloading with example. Answer: Method overloading allows programmers to use multiple methods but with the same name. Every defined method within a program can be differentiated on the basis of the number and the type of method arguments. It is a concept based on polymorphism. Method overloading can be achieved by the following: - By changing the number of parameters in the given method - By changing the order of parameters passed to a method - By using different data types as the passed parameters For example: public class Methodoveloading { public int sum(int a, int b) //two int type Parameters method { return a + b; } public int sum(int a, int b,int c) //three int type Parameters with same method same as above { return a + b+c; } public float sum(float a, float b,float c,float d) //four float type Parameters with same method same as above two method { return a + b+c+d; } } Question: What are the control statements that are used in C#? Answer: You can control the flow of your set of instructions by using control statements and we majorly focus on if statements. There are a few types of if statements that we consider for making situations to control the flow of execution within a program. These are the 4 types of if statements: - If - If-else - Nested if - If-else-if These statements are commonly used within programs. If statements checks for the user given condition to satisfy their programming condition. If it returns true then the set of instructions will be executed. Syntax: If(any condition) { //code to be executed if the condition returns true } If-else statement checks for the given condition, if the condition turns out to be false then the flow will transfer to the else statement and it will execute the else instructions. In case, the if condition turns out to be true then the if instructions will get executed. Syntax: If(condition) { //code to be run if the condition is true } Else { //code to be run if the if-condition is false } Nested if statement checks for the condition, if the condition is true then it will check for the inner if statement and keeps going on for the last if statement. If any of the conditions are true then it will execute the particular if instructions and stops the if loop there. Syntax: If (condition to be checked) { //code If(condition 2) { //code for if-statement 2 } } If else-if checks for the given condition, if the condition is not true then the control will go to the next else condition, if that condition is not true it will keep on checking for next else conditions. If any of the conditions did not pass then the last else instructions will get executed. Syntax: If(condition 1 to be checked) { //code for condition 1 } Else (condition 2 to be checked) { //code for condition 2 } Else { //code will run if no other condition is true } Question: Explain the concept of boxing and unboxing of the value type and object type in C#. Answer: Boxing- is a process of converting a value type to an object type where value type is placed on the stack memory, and the object type is placed in the heap memory. This conversion is an implicit conversion and you can directly assign any value to an object, and C# will handle the rest of the conversion on its own. Example: public void function() { Int a=111; Object b=a; //implicit conversion Console.WriteLine(b); } Unboxing- it is the reverse process of the boxing process. It is a conversion of the object type to the value type and the value of the boxed object type placed on the heap memory which will be transferred to the value type which is placed on the stack. This conversion of the unboxing process has to be done explicitly. Example: public void function() { Object b=111; Int a=(int)b; //implicit conversion Console.WriteLine(a); } Question: How can you check if a number is an Armstrong number or not with C#?. Question: What is a different approach to the passing parameter in C#? Answer: Parameters can be passed in three different ways to any defined methods and they are defined below: Value Parameters: it will pass the actual value of the parameter to the formal parameter. In this case, any changes that are made into the formal parameter of the function will be having no effect on the actual value of the argument. Reference Parameters: with this method, you can copy the argument that refers to the memory location into the formal parameter that means any changes made to the parameter affect the argument. Output Parameters: This method returns more than one value to the method. Question: What is a multicast delegate in C#? Answer: A multicast delegate holds the references or addresses to more than one function at a single time. Whenever we invoke the multicast delegate, it will invoke all the other functions that are being referred by that multicast delegate. You should use the complete method signature the same as the delegate to call multiple methods. For example: namespace MulticastDelegate { public class Rectangle { public void Area(double Width, double Height) { Console.WriteLine(@"Area is {0}", (Width * Height)); } public void Perimeter(double Width, double Height) { Console.WriteLine(@"Perimeter is {0}", (2 * (Width + Height))); } static void Main(string[] args) { Rectangle rect = new Rectangle(); rect.Area(23.45, 67.89); rect.Perimeter(23.45, 67.89); Console.ReadKey(); } } } Here, we created an instance of the Rectangle class and then called the two different methods. Now a single delegate will invoke these two methods Area and Perimeter. These defined methods are having the same signature as the defined delegates that hold the reference to these methods. Creating multicast delegate: namespace MulticastDelegateDemo { public delegate void RectangleDelete(double Width, double Height); public class Rectangle { public void Area(double Width, double Height) { Console.WriteLine(@"Area is {0}", (Width * Height)); } public void Perimeter(double Width, double Height) { Console.WriteLine(@"Perimeter is {0}", (2 * (Width + Height))); } static void Main(string[] args) { Rectangle rect = new Rectangle(); RectangleDelete rectDelegate = new RectangleDelete(rect.Area); rectDelegate += rect.Perimeter; rectDelegate(23.45, 67.89); Console.WriteLine(); rectDelegate.Invoke(13.45, 76.89); Console.WriteLine(); //Removing a method from delegate object rectDelegate -= rect.Perimeter; rectDelegate.Invoke(13.45, 76.89); Console.ReadKey(); } } } Question: How you can implement nullable<> types in C#? explain with the syntax of Nullable type. Answer: In C#, you cannot put a null value directly into any variable and the compiler does not support it. So, the revised version C# 2.0 provides you with a special feature that will assign a null value to a variable that is called as the Nullable type. You cannot make the nullable types to work with value types. Nullable value can only work with the reference types as it already has a null value. System.Nullable<T> structure creates the instance nullable type, where T defines the data type. This T contains a non-nullable value type that can be any data type you want. Syntax Nullable<data_type> variable_name=null; OR Datatype? variable_name=null; There is no possibility that you can access the value of the nullable value type directly with assigning the value. For getting its original assigned value you have to use the method GetValueOrDefault(). If the value is null then it will provide zero as it is its default value. Question: What do you mean by value types and reference types in C#? Answer: Value type: The memory allocated for the value type content or assigned value is stored on the stack. When we create any variable, space is allocated to that variable and then a value can be assigned to that variable. Also if we want to copy the value of that variable to another variable, its value gets copied and that creates two different variables. Reference Type: It holds the reference to the address of the object but not the object directly. Reference types represent the address of the variable and assigning a reference variable to another does not copy the data but it creates a second copy of the reference which represents the same location on the heap as the original value. Reference values are stored on the heap and when the reference variable is no longer required it gets marked for garbage collection. Question: What are various types of comments in C#, explain with example? Answer: C# supports three types of comments- 1. Single line comment Syntax: //single line 2. Multiple line comment Syntax: /* multiple lines */ 3. XML comment Syntax: /// set error Question: What are the constructors? Answer: In C#, there is a special method that is invoked automatically at the time of object creation. It initializes the data members of a new object and has the same name as the class or the structure. There are two types of constructors: - Default constructor: it has no parameter to pass. - Parameterized constructor: it is invoked with parameters that are passed to the class during object creation. Question: What are the different collection classes in C#? Answer: Collection classes are classes that are mainly used for data storage and retrieval. These collection classes will serve many purposes like allocating dynamic memory during run time and you can even access the items of the collection using the index value that makes the search easier and faster. These collection classes belong to the object class. There are many collection classes which are as follows: Array list: it refers to the ordered collection of the objects that are indexed individually. You can use it as an alternative to the array. Using index you can easily add or remove the items off the list and it will resize itself automatically. It works well for dynamic memory allocation, adding or searching items in the list. Hash table: if you want to access the item of the hash table then you can use the key-value to refer to the original assigned value to the variable. Each item in the hash table is stored as a key/value pair and the item is referenced with its key value. Stack: it works on the concept of last-in and first-out collection of the objects. Whenever you add an item to the list it is called pushing and when you remove the item off the list it is called popping. Sorted list: this collection class uses the combination of key and the index to access the item in a list. Queue: this collection works on the concept of first-in and first-out collection of the object. Adding an item to the list is call enqueue and removing the item off the list is call deque. BitArray: this collection class is used to represent the array in binary form (0 and 1). You can use this collection class when you do not know the number and the items can be accessed by using integer indexes that start from zero. Question: Explain file handling in C#. Answer: Whenever you open a file for reading or writing it becomes a stream which is a sequence of bytes travelling from source to destination. The two commonly used streams are input and output. The included namespace is system.IO that includes many classes for file handling. The stream is an abstract class that is the parent class for the file handling process. The file is a static class with many static methods to handle file operation. Below are the used classes: The following table describes some commonly used classes in the System.IO namespace. Question: Define interface class in C#? Explain with an example. Answer: An interface class is completely an abstract class that contains abstract methods and properties. By default, the members of the interface class are abstract and public with no fields defined. If you want to access the interface methods then the interface must be implemented by another class using ‘:’ symbol. If you want to define the body of the methods that can only be implemented in the implementing class. For example: // Interface Interface IAnimal { void Sound(); // interface method (without body) } class Pig : IAnimal // Pig class "implements" the IAnimal interface { public void Sound() { Console.WriteLine("The pig says: wee wee"); // The body of Sound() is provided her } } class Program { static void Main(string[] args) { Pig myPig = new Pig(); // Create a Pig object myPig.animalSound(); }} Question: Explain the concept of thread in C#. Answer: A thread can be defined as the execution flow of any program and defines a unique flow of control. You can manage these threads' execution time so that their execution does not overlap the execution of other threads and prevent deadlock or to maintain efficient usage of resources. Threads are lightweight programs that save the CPU consumption and increase the efficiency of the application. The thread cycle starts with the creation of the object of system.threading.thread class and ends when the thread terminates. System.threading.thread class allows you to handle multiple threads and the first thread always runs in a process called the main thread. Whenever you run a program in C#, the main thread runs automatically. Question: Define structure in C# with example. Answer: A structure is a data type of a value type. A struct keyword is used when you are going to define a structure. A structure represents a record and this record can have many attributes that define the structure. You can define a constructor but not destructor for the structure. You can implement one or more interfaces within the structure. You can specify a structure but not as abstract, virtual, or protected. If you do not use the new operator the fields of the structure remain unassigned and you cannot use the object till you initialize the fields. Question: What do you mean by user control and custom control in C#? Answer: User controls are very easy to create and are very much the same as the ASP control files. You cannot place a user control on the toolbox and cannot even drag-drop it. They have unique design and individual code behind these controls. Ascx is the file extension for user control. You can create custom code as the compiled code and can be added to the toolbox. You can include these controls to the web forms easily. Custom controls can be added to multiple applications efficiently. If you want to add a private custom control then you can copy it to dll and then to the bin directory of your web application and use its reference there. Question: C# program to remove an element from the queue.(); } } } Question: How to find if a number is a palindrome or not in C#."); } } Question: How will you differentiate between a Class and a Struct? Answer: Although both class and structure are user-defined data types, they are different in several fundamental ways. A class is a reference type and stores on the heap. Struct, on the other hand, is a value type and is, therefore, stored on the stack. While the structure doesn’t support inheritance and polymorphism, the class provides support for both. A class can be of an abstract type, but a structure can’t. All members of a class are private by default, while members of a struct are public by default. Another distinction between class and struct is based on memory management. The former supports garbage collection while the latter doesn’t. Question: Compare Virtual methods and Abstract methods. Answer: Any Virtual method must have a default implementation, and it can be overridden in the derived class using the override keyword. On the contrary, an Abstract method doesn’t have an implementation, and it resides in the abstract class. The derived class must implement the abstract method. Though not necessary, we can use an override keyword here. Question: What are Namespaces in C#? Answer: Use of namespaces is for organizing large code projects. The most widely used namespace in C# is System. Namespaces are created using the namespace keyword. It is possible to use one namespace in another, known as Nested Namespaces. Question: What are I/O classes in C#? Define some of the most commonly used ones. Answer: The System.IO namespace in C# consists of several classes used for performing various file operations, such as creation, deletion, closing, and opening. Some of the most frequently used I/O classes in C# are: - File – Manipulates a file - Path – Performs operations related to some path information - StreamReader – Reads characters from a stream - StreamWriter – Writes characters to a stream - StringReader – Reads a string buffer - StringWriter – Writes a string buffer Question: What do you understand by regular expressions in C#? Write a program that searches a string using regular expressions. Answer: Regular expression is a template for matching a set of input. It can consist of constructs, character literals, and operators. Regex is used for string parsing, as well as replacing the character string. Following code searches a string “C#” against the set of inputs from the languages array using Regex: static void Main(strong[] args) { string[] languages = {“C#”, “Python”, “Java”}; foreach(string s in languages) { if(System.Text.RegularExpressions.Regex.IsMatch(s,“C#”)) { Console.WriteLine(“Match found”); } } } Question: Give a detailed explanation of Delegates in C#. Answer: Delegates are variables that hold references to methods. It is a function pointer or reference type. Both the Delegate and the method to which it refers can have the same signature. All Delegates derives from the System.Delegate namespace. Following example demonstrates declaring a delegate: public delegate AddNumbers(int n); After declaring a delegate, the object must be created of the delegate using the new keyword, such as: AddNumbers an1 = new AddNumbers(number); The Delegate offers a kind of encapsulation to the reference method, which gets internally called with the calling of the delegate. In the following example, we have a delegate myDel that takes an integer value as a parameter: public delegate int myDel(int number); public class Program { public int AddNumbers(int a) { Int Sum = a + 10; return Sum; } public void Start() { myDel DelgateExample = AddNumbers; } } Question: Explain Reflection in C#. Answer: The ability of code to access the metadata of the assembly during runtime is called Reflection. A program reflects upon itself and uses the metadata to: - Inform the user, or - Modify the behaviour The system contains all classes and methods that manage the information of all the loaded types and methods. Reflection namespace. Implementation of reflection is in 2 steps: - Get the type of the object, then - Use the type to identify members, such as properties and methods Question: Name some of the most common places to look for a Deadlock in C#. Answer: For recognizing deadlocks, one should look for threads that get stuck on one of the following: - .Result, .GetAwaiter().GetResult(), WaitAll(), and WaitAny() (When working with Tasks) - Dispatcher.Invoke() (When working in WPF) - Join() (When working with Threads) - lock statements (In all cases) - WaitOne() methods (When working with AutoResetEvent/EventWaitHandle/Mutex/Semaphore) Question: Define Serialization and its various types in C#. Answer: The process of converting some code into its binary format is known as Serialization in C#. Doing so allows the code to be stored easily and written to a disk or some other storage device. We use Serialization when there is a strict need for not losing the original form of the code. A class marked with the attribute [Serializable] gets converted to its binary form. A stream that contains the serialized object and the System.Runtime.Serialization namespace can have classes for serialization. Serialization in C# is of three types: - Binary Serialization – Faster and demands less space; it converts any code into its binary form. Serialize and restore public and non-public properties. - SOAP – It produces a complete SOAP compliant envelope that is usable by any system capable of understanding SOAP. The classes about this type of serialization reside in System.Runtime.Serialization. - XML Serialization – Serializes all the public properties to the XML document. In addition to being easy to read, the XML document manipulated in several formats. The classes in this type of serialization reside in System.sml.Serialization. Note: Retrieving the C# code back from the binary form is known as Deserialization. Question: Give a brief explanation of Thread Pooling in C#. Answer: A collection of threads, termed as a Thread Pool in C#. Such threads are for performing tasks without disturbing the execution of the primary thread. After a thread belonging to a thread pool completes execution, it returns to the thread pool. Classes that manage the thread in the thread pool, and its operations, are contained in the System.Threading.ThreadPool namespace. Question: Is it possible to use this keyword within a static method in C#? Answer: A special type of reference variable, this keyword is implicitly defined with each non-static method and constructor as the first parameter of the type class, which defines it. Static methods don’t belong to a particular instance. Instead, they exist without creating an instance of the class and calls with the name of the class. Because this keyword returns a reference to the current instance of the class containing it, it can’t be used in a static method. Although we can’t use this keyword within a static method, we can use it in the function parameters of Extension Methods. Question: What can you tell us about the XSD file in C#? Answer: XSD denotes XML Schema Definition. The XML file can have any attributes, elements, and tags if there is no XSD file associated with it. The XSD file gives a structure for the XML file, meaning that it determines what, and also the order of, the elements and properties that should be there in the XML file. Note: - During serialization of C# code, the classes are converted to XSD compliant format by the Xsd.exe tool. Question: What do you mean by Constructor Chaining in C#? Answer: Constructor chaining in C# is a way of connecting two or more classes in a relationship as an inheritance. Every child class constructor is mapped to the parent class constructor implicitly by using the base keyword in constructor chaining. Question: Explain different states of a Thread in C#? Answer: A thread in C# can have any of the following states: - Aborted – The thread is dead but not stopped - Running – The thread is executing - Stopped – The thread has stopped execution - Suspended – The thread has been suspended - Unstarted – The thread is created but has not started execution yet - WaitSleepJoin – The thread calls sleep, calls wait on another object, and calls join on some other thread Question: Why do we use Async and Await in C#? Answer: Processes belonging to asynchronous programming run independently of the main or other processes. In C#, using Async and Await keywords for creating asynchronous methods. Question: What is an Indexer in C#, and how do you create one? Answer: Also known as an indexed property, an indexer is a class property allowing accessing a member variable of some class using features of an array. Used for treating an object as an array, indexer allows using classes more intuitively. Although not an essential part of the object-oriented programming, indexers are a smart way of using arrays. As such, they are also called smart arrays. Defining an indexer enables creating classes that act like virtual arrays. Instances of such classes can be accessed using the [] array access operator. The general syntax for creating an indexer in C# is: < modifier > < return type > this[argument list] { get { // the get block code } set { // the set block code } } Question: What is the Race condition in C#? Answer: When two threads access the same resource and try to change it at the same time, we have a race condition. It is almost impossible to predict which thread succeeds in accessing the resource first. When two threads try to write a value to the same resource, the last value written is saved. Question: What do you understand by Get and Set Accessor properties? Answer: Made using properties, Get and Set are called accessors in C#. A property enables reading and writing to the value of a private field. Accessors are used for accessing such private fields. While we use the Get property for returning the value of a property, use the Set property for setting the value. Question: Give a detailed explanation of the differences between ref and out keywords. Answer: In any C# function, there can be three types of parameters, namely in, out and ref. Although both out and ref are treated differently at the run time, they receive the same treatment during the compile time. It is not possible to pass properties as an out or ref parameter. Following are the differences between ref and out keywords: - Initializing the Argument or Parameter – While it is not compulsory to initialize an argument or parameter before passing to an out parameter, the same needs to be initialized before passing it to the ref parameter. - Initializing the Value of the Parameter – Using ref doesn’t necessitate for assigning or initializing the value of a parameter before returning to the calling method. When using out, however, it is mandatory to use a called method for assigning or initializing a value of a parameter before returning to the calling method. - Usefulness – When the called method requires modifying the passed parameter, passing a parameter value by Ref is useful. Declaring a parameter to an out method is appropriate when multiple values are required to be returned from a function or method. - Initializing a Parameter Value in Calling Method – It is a compulsion to initialize a parameter value within the calling method while using out. However, the same is optional while using the ref parameter. - Data Passing – Using out allows for passing data only in a unidirectional way. However, data can be passed in a bidirectional manner when using ref. Question: What is Singleton Design Patterns in C#? Explain their implementation using an example. Answer: A singleton in C# is a class that allows the creation of only a single instance of itself and provides simple access to that sole instance. Because the second request of an instance with a different parameter can cause problems, singletons typically disallow any parameters to be specified. Following example demonstrates the implementation of Singleton Design Patterns in C#:; } } } A Singleton Design Pattern ensures that a class has one and only one instance and provides a global point of access to the same. There are numerous ways of implementing the Singleton Design Patterns in C#. Following are the typical characteristics of a Singleton Pattern: - A public static means of getting the reference to the single instance created - A single constructor, private and parameter-less - A static variable holding a reference to the single instance created - The class is sealed Conclusion That sums up the list of the top c# interview questions for experienced professionals and beginners as well. How many of the answers did you know already? Let us know via comments. Check out these best C# tutorials to enhance your C# understanding further. Looking for more C# coding problems interview questions? We suggest you one of the best C# interview courses: C# Advanced Topics: Prepare for Technical Interviews. Here, we recommend a great book for preparing for C# interviews. Rocking the C# Interview: A comprehensive question and answer reference guide for the C# programming language. 1st Edition. People are also reading: - Best ASP.Net Interview Questions - Get the Notable Difference between C# vs C++ - Head to Head Comparison Between C# vs Python - Get the Difference Between C# vs Java - Difference between Google Cloud vs AWS vs Azure - Top 30+ Linux Interview Question - Top Selenium Interview Questions & Answers - Best Jenkins Interview Questions & Answers Correction is needed; You can only make a nullable types with value types. You cannot make the nullable types to work with reference types. Int a=(int)b; //implicit conversion Should be explicit comment. What is CLR in C#? How many types of events are there in C#? What are delegates in C#? What is the default constructor in C#? Are there constructors in C? What is polymorphism in C sharp? What is type-safe in C#?
https://hackr.io/blog/c-sharp-interview-questions
CC-MAIN-2020-50
refinedweb
6,146
54.52
.4: Pairs and Maps About This Page Questions Answered: Can a function return two values? How can I easily find an object that corresponds to another object (e.g., the English translation of a Finnish word)? What’s an easy and efficient way to find elements in a collection when I have a search key of some sort (e.g., to find a student object among many others when I have their student ID number)? Topics: Pairs. Key–value pairs. Maps. What Will I Do? Read and work on small assignments. Rough Estimate of Workload:? Under two hours. Points Available: B25. Related Projects: Miscellaneous. Introduction: Two Return Values? Frequently asked question Can a function return two values? Could we, for instance, define a function toMinsAndSec that takes in a number of seconds and returns two integers: the number of whole minutes and the leftover seconds? Perhaps it would work like this: toMinsAndSecs(187)res0: (Int, Int) = (3,7) It would be nice if we could also save the returned values for later use in two separate variables; say, min and s. Possible solutions Functions can’t really return more than a single value, but we can work around that restriction so that it’s as if they could. One workaround is to return a collection of two elements, say, a Vector[Int]. This solution isn’t terrible, but it’s a bit clunky to index the collection for the actual return values: val returnedValues = toMinsAndSecs(187)returnedValues: Vector[Int] = Vector(3,7) val min = returnedValues(0)min: Int = 3 val s = returnedValues(1)s: Int = 7 That solution is also impractical if you wish to return two values of different types. Another workaround is to write a custom class that represents the sort of composite information that the function returns. For instance, we might define a Time class with methods for minutes and seconds, and have our function return a Time object. This can be a good choice in case the returned information corresponds to a concept and can be naturally represented as a class. A third workaround makes use of pairs (pari). Pairs are not only good for returning multiple values; you’ll see in this chapter that they have other uses as well. Let’s have a look at pairs in general before we return to minutes and seconds. Pairs Basic use of pairs in Scala You can form a pair with brackets and a comma, as shown here: ("good thing", "another thing")res1: (String, String) = (good thing,another thing) Here’s one way to access the members of a pair: var myPair = ("good thing", "another thing")myPair: (String, String) = (good thing,another thing) myPair._1res2: String = good thing myPair._2res3: String = another thing _1. (One, not zero!) The second member is _2. The most important difference between a pair and, say, a two-element vector is that a pair’s members can have different static types: val nameAndShoeSize = ("Juha", 43)nameAndShoeSize: (String, Int) = (Juha,43) It’s easy to copy the two members of a pair into two separate variables. Just use brackets: val (name, shoeSize) = nameAndShoeSizename: String = Juha shoeSize: Int = 43 A minute assignment Implement the toMinsAndSecs function we contemplated earlier. It should work like this: import o1.misc._import o1.misc._ toMinsAndSecs(187)res4: (Int, Int) = (3,7) val (min, s) = toMinsAndSecs(200)min: Int = 3 s: Int = 20 Write your solution in o1/misc.scala in project Miscellaneous. A+ presents the exercise submission form here. A pair as a parameter Naturally, you can also define a function that takes a pair as a parameter. The example function below determines whether a given pair of numbers is “in order”, that is, whether the pair’s first member is no greater than the second. def isInOrder(pairOfNumbers: (Int, Int)) = pairOfNumbers._1 <= pairOfNumbers._2 Usage example: val myPair = (10, 20)myPair: (Int, Int) = (10,20) isInOrder(myPair)res5: Boolean = true Dividing collections Pairs feature in various API methods. There are a couple of examples below. Collections have a splitAt method that returns a pair whose members are collections: val temperatures = Vector(3, 6, -1, -5, 3, -1, 2)temperatures: Vector[Int] = Vector(3, 6, -1, -5, 3, -1, 2) temperatures.splitAt(3)res6: (Vector[Int], Vector[Int]) = (Vector(3, 6, -1),Vector(-5, 3, -1, 2)) val (workingWeek, weekend) = temperatures.splitAt(5)workingWeek: Vector[Int] = Vector(3, 6, -1, -5, 3) weekend: Vector[Int] = Vector(-1, 2) splitAttakes in a number that indicates a position in the collection. partition also divides the elements of the original collection in two and returns a pair of collections: val (freezing, aboveFreezing) = temperatures.partition( _ < 0 )freezing: Vector[Int] = Vector(-1, -5, -1) aboveFreezing: Vector[Int] = Vector(3, 6, 3, 2) As you can see, this method divides the elements by calling the given function on each one and checking whether it returns true or false. Mini-assignment: dividing a collection Go to package o1.people in project Miscellaneous and find YoungAndOldApp. The comments in this app object explain how the program should work. Implement the missing parts of the program. Use one of the methods just introduced. A+ presents the exercise submission form here. Zipping collections together You just saw some pairs whose members were collections. You can also have a collection whose elements are pairs. Collections have a handy method named zipWithIndex. It forms a new collection where each element is the original element paired with its index: val species = Vector("llama", "alpaca", "vicuña")species: Vector[String] = Vector(llama, alpaca, vicuña) species.zipWithIndexres7: Vector[(String, Int)] = Vector((llama,0), (alpaca,1), (vicuña,2)) When you loop over such a collection of pairs, you can again use round brackets to deal with two variables at once. Here are two ways of printing out a collection of pairs: for (pair <- species.zipWithIndex) { println(pair._1 + " is at index #" + pair._2) }llama is at index #0 alpaca is at index #1 vicuña is at index #2 for ((element, index) <- species.zipWithIndex) { println(element + " is at index #" + index) }llama is at index #0 alpaca is at index #1 vicuña is at index #2 zipWithIndex is a special case of the more generic zip method, which pairs up the elements of two collections: val heights = Vector(180, 80, 60)heights: Vector[Int] = Vector(180, 80, 60) val heightsAndSpecies = heights.zip(species)heightsAndSpecies: Vector[(Int, String)] = Vector((180,llama), (80,alpaca), (60,vicuña)) If the collections have different lengths, the longer collection’s tail end is ignored: val moreSpecies = Vector("llama", "alpaca", "vicuña", "guanaco", "wooly")moreSpecies: Vector[String] = Vector(llama, alpaca, vicuña, guanaco, wooly) val justThreePairs = heights.zip(moreSpecies)justThreePairs: Vector[(Int, String)] = Vector((180,llama), (80,alpaca), (60,vicuña)) You can also unzip a collection of pairs to obtain a pair of collections: heightsAndSpecies.unzipres8: (Vector[Int], Vector[String]) = (Vector(180, 80, 60),Vector(llama, alpaca, vicuña)) Mini-assignment: isAscending Write a function isAscending that takes in a vector of integers and reports whether those integers are in ascending order. Here are some examples: isAscending(Vector(-10, 1, 5, 10))res9: Boolean = true isAscending(Vector(-10, 1, 5, 5, 10))res10: Boolean = true isAscending(Vector(-10, 1, 5, 9, 5, 10))res11: Boolean = false isAscending(Vector(10, 5, 1, -10))res12: Boolean = false With clever use of the collections methods from this chapter and earlier ones, you can solve the assignment in a single, short line of code. Write your code in misc.scala again. You may assume that the vector contains at least one element. A+ presents the exercise submission form here. Pairs are tuples A pair is a two-membered tuple (monikko). A tuple may have more members than just two: ("This tuple has four members of different types.", 100, 3.14159, false)res13: (String, Int, Double, Boolean) = (This tuple has four members of different types.,100,3.14159,false) Does that mean a tuple is a collection, like buffers and vectors are? Not quite. First of all, tuples and collections have different purposes. Tuples tend to be most useful when: 1) there is a small, constant number of members (e.g., only two), and 2) each member has a meaning separate from the others (e.g., one signifies minutes, the other seconds; one is a name, the other is a shoe size), but 3) it nevertheless feels like overkill to write a custom class. Here are some of the technical differences between tuples and collections: - In a tuple, each member has a distinct static type. In a collection, the elements share a static type. - Tuples are always immutable in size and content. Collections come in both mutable and immutable varieties. - Tuples don’t have the familiar collection methods ( size, map, indexOf, etc.) and you can’t use a forloop to iterate over a tuple (without resorting to additional trickery). One tremendously helpful and common thing to do with tuples — pairs, specifically — is to construct “maps”. We’ll say more about that in just a bit. Another Introduction: Keys and Values How would you implement the following? What do all these scenarios have in common? - A dictionary: given a word in Finnish, we want to be able to find the corresponding word in English. - A student register: we want to be able to search for students by their student ID number. - An address book: we want to be able to find the person object that details an individual whose name we know. - An encyclopedia: given a string keyword, we want to access the encyclopedia article that matches that keyword. - Counting frequencies: We have a bunch of objects that all have a particular property. We want to know the distribution of different values of that property among the objects. It’s possible to solve these problems with the tools we’ve already covered. For example, here’s a buffer-based implementation for a primitive sort of dictionary: val searchTerms = Buffer("kissa", "laama", "tapiiri", "koira")searchTerms: Buffer[String] = ArrayBuffer(kissa, laama, tapiiri, koira) val englishTranslation = Buffer("cat", "llama", "tapir", "puppy")englishTranslation: Buffer[String] = ArrayBuffer(cat, llama, tapir, puppy) We can use these two buffers to look up the translation of a Finnish word. (Recall the indexOf method from Chapter 4.1.) val index = searchTerms.indexOf("tapiiri")index: Int = 2 englishTranslation(index)res14: String = tapir englishTranslation(searchTerms.indexOf("koira"))res15: String = puppy We can also update the dictionary by replacing an element. The Finnish word “koira” is better translated as “dog” than “puppy”, so let’s make that change: englishTranslation(searchTerms.indexOf("koira")) = "dog"englishTranslation(searchTerms.indexOf("koira"))res16: String = dog Pause to consider what we’re doing here. Our dictionary contains Finnish words, which we use to look up the corresponding English words. One way to put this is: the Finnish words in searchTerms serve as keys (avain) that we use to locate the values (arvo) stored in englishTranslation. The same basic pattern repeats in all the other scenarios listed above: student ID numbers as keys, the student objects as values; director names as keys, the movie counts of the directors as values; etc. In the following text, we will use the terms “key” and “value” in this sense. Our buffer-based solution relies on the assumption that the two buffers store their elements in a specific order and the indices of the keys (in searchTerms) are the same as those of the corresponding values (in englishTranslation). The solution does work, but it’s not ideal: - We used two separate buffers for keys and values even though we conceive of the dictionary as a single entity. - It feels unnecessary to have to mess about with indices in order to look up a word. No-one really cares which index the source or target word has in the buffer. - What if the key is not found? - E.g., englishTranslation(searchTerms.indexOf("Mikki-Hiiri")). indexOfwill then return -1 and we end up with a runtime error by accessing a negative index of englishTranslationas we’ve done. - (If we had lots of words in the dictionary, we might also wish for improved efficiency. indexOfchecks each index of the buffer in order, one by one, until it reaches the target element. This search strategy isn’t even close to optimal.) Maps Let’s use a collection that stores both keys and values. A map (hakurakenne) is a tremendously useful and common collection type, and rather unlike the index-based collections we’ve used so far in O1. A map contains key–value pairs*. When you use, say, a buffer, you look up elements by their positions in the collection; when you use a map, you instead look up values by their keys. You can use any objects as keys. Those objects form a set in the mathematical sense of the word; in practice, that means that all of a map’s keys must be different from each other (e.g., no identical Finnish words as search terms, no identical student ID numbers, etc.). In the Scala API, maps have been implemented as class Map. Hold up! map is a method on collection objects, right — not a type of collection? It’s true that we’ve been already using a method named map. The two concepts are distinct but there is a reason why their names are similar. The familiar map-that-is-a-method takes an existing collection and uses its elements to generate another. The parameter function of map defines a mapping from the original elements to the generated elements. A Map object — a map-that-is-a-collection — is a collection of keys and values; it stores a mapping from keys to values. The map method is available on all sorts of collections, not just on Maps. But Before We Get to Maps: Key–Value Pairs Here’s some Scala code that defines a key–value pair. This is just a regular pair that happens to contain data that we intend to use as a key and a value. ("koira", "dog")res17: (String, String) = (koira,dog) However, when defining key–value pairs, it’s common to use another notation that highlights the fact that each key “points at” the corresponding value. The following code produces precisely the same output as the code above: "koira" -> "dog"res18: (String, String) = (koira,dog) ->arrow defines a pair. (Note: it’s ->, not =>, which we have used in function types and casebranches.) Either notation works for creating any pair. In O1, we’ll prefer the arrow notation when we define pairs that represent a Map’s keys and values. You can use any objects in a key–value pair. In the above example, both the key and the value were strings, as befits our dictionary. It is be equally possible to, say, associate an integer key with a string value or the other way around: 233524 -> "Susan Student"res19: (Int, String) = (233524,Susan Student) "Sergio Leone" -> 5res20: (String, Int) = (Sergio Leone,5) More about the arrow -> is an ordinary method. "seikkailija" -> "adventurer"res133: (String, String) = (seikkailija,adventurer) We could have used the dot notation. These two expressions are equivalent: "polvi".->("knee")res21: (String, String) = (polvi,knee) "polvi" -> "knee"res22: (String, String) = (polvi,knee) Since the idea is to visually suggest an arrow, the operator notation is understandably much more common here. Maps in Scala: Class Map It’s very straightforward to implement a little Finnish-to-English dictionary as a Map. First, we’ll need to import the Map class that we intend to use: import scala.collection.mutable.Mapimport scala.collection.mutable.Map As you’ll know by now, objects can be mutable or immutable. Since Scala is designed to support different styles of programming, its standard API comes with two different Map classes, one for mutable maps and one for immutable ones. For now, we’ll mostly use mutable maps: map objects whose keys and values can be modified. The corresponding class is in package scala.collection.mutable and needs to be imported as we did above. We can create a Map object like this: val finnishToEnglish = Map("kissa" -> "cat", "laama" -> "llama", "tapiiri" -> "tapir", "koira" -> "puppy")finnishToEnglish: Map[String,String] = Map(koira -> puppy, tapiiri -> tapir, kissa -> cat, laama -> llama) The sections below demonstrate a selection of the methods available on Map objects. Once again, the intention is not that you memorize them all but that you get an overall sense of what you can do with this collection type. As you read these examples, you’ll notice that there are (again) a number of ways to do the same thing. It’s unlikely that you’ll be able to tell right away which solution is the best fit for which situation. Then again, you don’t need to; that’s the sort of thing that improves with experience. It’s good to learn to recognize different kinds of solutions already, though. Accessing a single value It’s simple to fetch a value that matches a key: finnishToEnglish.get("kissa")res23: Option[String] = Some(cat) finnishToEnglish.get("Mikki-Hiiri")res24: Option[String] = None getmethod takes a key as a parameter. Option[TypeOfValuesInMap]. Somethat holds the corresponding value. If not, we get None. Replacing a value When working with a mutable map, we can update it as shown below. finnishToEnglish.get("koira")res25: Option[String] = Some(puppy) finnishToEnglish("koira") = "dog"finnishToEnglish.get("koira")res26: Option[String] = Some(dog) Remember: the keys of a map are unique. A map cannot contain multiple key–value pairs whose keys are equal. So what happens above is that the pair "koira" -> "puppy" is replaced by the pair "koira" -> "dog". Adding a key–value pair There are a number of ways to add a key–value pair to a mutable map. One of them is to assign a value to a previously unused key: finnishToEnglish("hiiri") = "mouse" Another way to add or replace a key–value pair is the += operator, which you’ve previously used on buffers: finnishToEnglish += "sika" -> "pig"res27: Map[String, String] = Map(koira -> dog, tapiiri -> tapir, kissa -> cat, sika -> pig, hiiri -> mouse, laama -> llama) This command also replaces any previously stored key–value pair that has the same key. The rest of this ebook uses this second notation to add pairs to a map. You can use whichever you prefer. Removing a key–value pair Here’s one way to remove a pair: finnishToEnglish -= "laama"res28: Map[String, String] = Map(koira -> dog, tapiiri -> tapir, kissa -> cat, sika -> pig, hiiri -> mouse) There’s also a remove method that returns the removed value in an Option wrapper: finnishToEnglish.remove("laama")res29: Option[String] = Some(laama) Checking a key The contains method tells us if a given key is present in the map. In the example below, "tapiiri" is present in the dictionary whereas "laama", which we just removed, is not. finnishToEnglish.contains("tapiiri")res30: Boolean = true finnishToEnglish.contains("laama")res31: Boolean = false Getting all the keys or all the values The methods keys and values return all the keys and all the values of a map, respectively. These methods return collections that you can process with the usual methods. Here, for instance, we first print out all the keys followed by all the values. finnishToEnglish.keys.foreach(println)koira tapiiri kissa sika hiiri finnishToEnglish.values.foreach(println)dog tapir cat pig mouse The mapValues method mapValues is similar to the map method you know from other collections but, as its name suggests, it applies an operation to the values of a Map only. val finToEng = Map("kissa" -> "cat", "tapiiri" -> "tapir", "koira" -> "dog")finToEng: Map[String,String] = Map(koira -> dog, tapiiri -> tapir, kissa -> cat) finToEng.mapValues( _.toUpperCase )res32: Map[String,String] = Map(kissa -> CAT, tapiiri -> TAPIR, koira -> DOG) mapValues returns a new Map where the values of the original have been replaced by the values generated by the function parameter. In this example, we mapped the original strings to their upper-case versions. The keys of the new Map are identical to those in the original. In the second example below, we form a map where the original string values have been replaced by their lengths: finToEng.mapValues( _.length )res33: Map[String,Int] = Map(kissa -> 3, tapiiri -> 5, koira -> 3) Familiar methods on Maps Maps are collections and, as such, have many familiar methods. Here are just a few examples of the collection methods from Chapters 4.1 and 6.2: val finToEng = Map("kissa" -> "cat", "tapiiri" -> "tapir", "koira" -> "dog")finToEng: Map[String,String] = Map(koira -> dog, tapiiri -> tapir, kissa -> cat) finToEng.isEmptyres34: Boolean = false finToEng.sizeres35: Int = 3 finToEng.foreach(println)(koira,dog) (tapiiri,tapir) (kissa,cat) What If We Don’t Find a Key? When you use a map, you need to be alert to the possibility that the key you’re looking for is not present. The Scala API offers several alternative ways of dealing with that contingency. You already know that a Map’s get method returns an Option, which is None in case the key wasn’t found: finToEng.get("Mikki-Hiiri")res36: String = None Often, you’ll do fine calling get and using the Option it returns. But depending on what you’re trying to achieve, there may be better alternatives. The getOrElse method One way to deal with missing values is to use getOrElse instead. This method greatly resembles the method of the same name on Options (Chapter 4.2), which essentially tells an Option object “Give me the value you contain or, failing that, use this value instead.” The getOrElse method of a Map similarly tells the Map: “Give me the value that corresponds to this key or, failing that, use this value instead.” finToEng.getOrElse("kissa", "unknown word")res37: String = cat finToEng.getOrElse("Mikki-Hiiri", "unknown word")res38: String = unknown word getOrElsethe search key and a “default value” that should match the type of the Map’s values. Map, getOrElsereturns the corresponding value. Stringrather than Option[String]. We don’t need an Optionwrapper since we have a meaningful Stringvalue in both cases. Lovely. The default method apply (and its dangers) You’re already used to indexing collections with expressions like myCollection(index), which Chapter 5.1 revealed to be shorthand for method calls like myCollection.apply(index). As you learned then, apply is a sort of implicit “default method” for objects. Maps, too, have an apply method. It works much like get, but there is a substantial difference. Compare: val engToFin = Map("kissa" -> "cat", "tapiiri" -> "tapir", "koira" -> "dog")engToFin: Map[String,String] = Map(koira -> dog, tapiiri -> tapir, kissa -> cat) engToFin("tapiiri")res39: String = tapir engToFin("Mikki-Hiiri")java.util.NoSuchElementException: key not found: Mikki-Hiiri ... at scala.collection.mutable.HashMap.apply(HashMap.scala:64) ... engToFin.get("kissa")res40: Option[String] = Some(cat) engToFin.get("Mikki-Hiiri")res41: Option[String] = None The nice thing about apply, compared to get, it gives you a plain result without an Option, so the return value is a little bit easier to work with. The not-nice-at-all thing about apply is that it causes a runtime error if you pass in a non-existent key, so you need to be extra careful when you use this method. get is usually the better and safer choice. Setting a default value When we called getOrElse, we passed in a “default value”, which the method used in case the key wasn’t found. We can also associate Map with a generic default value. For instance, we might wish our dictionary to default to the string "not found" on any look-up of any non-existent key. The method withDefaultValue does just that: val engToFin = Map("kissa" -> "cat", "tapiiri" -> "tapir", "koira" -> "dog").withDefaultValue("not found")engToFin: Map[String,String] = Map(koira -> dog, tapiiri -> tapir, kissa -> cat) engToFin("kissa")res42: String = cat engToFin("Mikki-Hiiri")res43: String = not found withDefaultValueto indicate which value the map should default to. applyfor a missing key, we get this default value. This is a nice way to use a Map. Hence this rule of thumb: - If there is a default value that makes sense for your Map, use withDefaultValueto define it. If you do, it’s both safe and convenient to fetch values with apply. - Otherwise, use getor getOrElseto access values. Practice on withDefaultValue, get, apply, and getOrElse A Map in an Instance Variable You can use Maps as building blocks for your own classes. A simple example is shown below; you’ll see additional examples in later chapters. Example: societies and their members We’ll use the Member class from Chapter 4.3 as part of this example. Here is the relevant code: class Member(val id: Int, val name: String, val yearOfBirth: Int, val yearOfDeath: Option[Int]) { // etc. } Now, let’s write another class, Society, that stores the members of a society in an instance variable that refers to a Map. class Society(val name: String) { private val members = Map[Int, Member]() def add(newMember: Member) = { this.members(newMember.id) = newMember } def getByID(memberID: Int) = this.members.get(memberID) } Societyobject has a name. It also has a Mapwhose values are the society’s members and whose keys are the members’ ID numbers. For a newly created Societyobject, this Mapis empty. Societyobject has methods for adding members and finding existing members by their ID. These methods have been implemented by calling the Map’s methods. Mini-assignment: Maps and Option You’ll find Society in project Miscellaneous. Add a yearOfDeath method to the class. The method should: - receive a member ID as a parameter; - return an Option[Int]that wraps the year of death of the member with the given ID; except that - if the member doesn’t exist or is not dead yet, the method should return None. Don’t make any other changes to Society. Don’t edit Member. Hint: there is a method, introduced in a recent chapter, that supplies a very simple solution. A+ presents the exercise submission form here. Summary of Key Points - Multiple data items — even items of different types — can be combined into a tuple. A pair is a tuple with two members. - Maps are a tremendously useful and common sort of collection. A map contains key–value pairs. It differs from numerically indexed collections in that: - a map’s elements don’t have an order determined by running numbers; - nor can you use indices to select a particular element of a map. Instead, - you commonly use a map via keys: it’s easy and efficient to fetch a value that corresponds to a key. - The Scala API gives us a Mapclass with numerous useful methods. - Links to the glossary: tuple, pair; map, key–value pair.. (String, String)means a pair whose members are both strings.
https://plus.cs.aalto.fi/o1/2018/w08/ch04/
CC-MAIN-2020-24
refinedweb
4,438
63.9
Use C language to manipulate the basic functions of the file collation - 2020-04-02 03:19:21 - OfStack C creat() function: creates a file function The header file: #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> Definition function: int creat(const char * pathname, mode_tmode); Function description: 1. The parameter pathname refers to the file path string to be created. 2. Creat() is equivalent to calling open() using the following method Open (const char * pathname, (O_CREAT|O_WRONLY|O_TRUNC)); Error code: refer to the open() function for the parameter mode. The return value:Creat () returns a new file descriptor, -1 if an error occurs, and sets the error code to errno. EEXIST parameter: the file referred to by pathname already exists. EACCESS parameter: the file specified by pathname does not meet the required test permissions EROFS: the file you want to open write exists in a read-only file system EFAULT parameter: the pathname pointer exceeds the accessible memory space EINVAL parameter: mode is not correct. ENAMETOOLONG parameter: pathname is too long. ENOTDIR parameter: pathname is a directory ENOMEM: out of core memory ELOOP parameter: pathname has too many symbolic joins. EMFILE: the maximum number of files a process can open at the same time has been reached ENFILE: the maximum number of files the system can open at the same time has been reached Note: creat() cannot create a special device file, use mknod() if necessary. C language open() function: open the file function The header file: #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> Definition function: int open(const char * pathname, int flags); int open(const char * pathname, int flags, mode_t mode); Function description: The pathname parameter points to the file path string to be opened. The following are the flags that the parameter flags can use:O_RDONLY opens the file read-only O_WRONLY opens the file in write-only mode O_RDWR opens the file in read-write mode. The three flags are mutually exclusive, meaning they cannot be used together, but can be combined with the following flags using the OR(|) operator. O_CREAT automatically creates the file you want to open if it does not exist. O_EXCL if O_CREAT is also set, this command checks to see if the file exists. If the file does not exist, the file is created, otherwise it will cause an error to open the file. O_NOCTTY will not treat the open file as a process control terminal if it is a terminal device. When a file exists and is opened in a writable manner, this flag clears the length of the file to 0 and the information originally stored in the file disappears. O_APPEND moves from the end of the file when a file is read or written, that is, the data written is appended to the end of the file. O_NONBLOCK opens the file in an uninterruptible manner, meaning that it is immediately returned to the process with or without data read or waiting. O_NONBLOCK O_NDELAY. O_SYNC opens files synchronously. O_NOFOLLOW fails to open a file if the file referred to by the pathname parameter is a symbolic connection. O_DIRECTORY if the file referred to by the pathname parameter is not a directory, it will fail to open the file. Note: this is a special flag after linux2. to avoid some system security problems. The parameter mode has the following combinations, which will only take effect when a new file is created. In addition, the permissions when the file is actually created will be affected by the umask value, so the file permissions should be (mode-umaks).S_IRWXU00700, which represents the file owner with readable, writable, and executable permissions. S_IRUSR or S_IREAD, 00400 authority, which represents that the file owner has readable authority. S_IWUSR or S_IWRITE, 00200 authority, which represents that the file owner has writable authority. S_IXUSR or S_IEXEC, 00100 authority, which represents that the file owner has executable authority. S_IRWXG 00070, which represents the file user group with readable, writable, and executable permissions. S_IRGRP 00040 privilege, which means that the file user group has readable permissions. S_IWGRP 00020, which represents the file user group with writable permissions. S_IXGRP 00010 permissions, which represent executable permissions for the file user group. S_IRWXO 00007, which represents other users with readable, writable, and executable permissions. S_IROTH 00004 privilege, which means that other users have readable permissions S_IWOTH 00002 permissions, which represent writable permissions for other users. S_IXOTH 00001 permissions, which represent other users with executable permissions. Return value: if all the permissions to be verified pass the check, return a value of 0, indicating success. If one of the permissions is disabled, return -1. Error code:The file referred to by the EEXIST parameter pathname already exists, but the O_CREAT and O_EXCL flags are used. The file referred to by the EACCESS parameter pathname does not conform to the required test permissions. The file that EROFS wants to test for write permissions exists in a read-only file system. The EFAULT parameter pathname pointer exceeds the accessible memory space. EINVAL parameter mode is not correct. The ENAMETOOLONG parameter pathname is too long. The ENOTDIR parameter pathname is not a directory. ENOMEM is out of core memory. The ELOOP parameter pathname has too many symbolic joins. EIO I/O access error. Additional note: use access() role user authentication judgment to be particularly careful, for example, after access() to make an open() empty file may cause system security problems. sample #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> main() { int fd, size; char s[] = "Linux Programmer!n", buffer[80]; fd = open("/tmp/temp", O_WRONLY|O_CREAT); write(fd, s, sizeof(s)); close(fd); fd = open("/tmp/temp", O_RDONLY); size = read(fd, buffer, sizeof(buffer)); close(fd); printf("%s", buffer); } perform Linux Programmer! C close() function: close the file The header file: #include <unistd.h> Definition function: int close(int fd); Function description: close() can be used to close a file if it is no longer needed after using it. Two close() will write the data back to disk and free the resources occupied by the file. Parameter fd is the file descriptor previously returned by open() or creat(). Return value: returns 0 if the file closes successfully and -1 if an error occurs. Error code: EBADF parameter fd is not a valid file descriptor or the file is closed. Note: while the system automatically closes opened files at the end of the process, it is recommended that you close the file yourself and indeed check the return value.
https://ofstack.com/C++/10149/use-c-language-to-manipulate-the-basic-functions-of-the-file-collation.html
CC-MAIN-2022-21
refinedweb
1,094
56.15
We had a very simple test case that confused myself and Alan, the replacement Alan not the old one, for a few minutes today. Our web service looked like this: @WebService public class Echo { public int echoInt (int i) { return i; } } But when we passed in invalid data to the web service the value of i was 0. So here is example message that JAX-WS will consume properly; but is obviously invalid: <env:Envelope xmlns: <env:Header/> <env:Body> <ns1:echoInt> <arg0>xxxx</arg0> </ns1:echoInt> </env:Body> </env:Envelope> It took us a while to remember that schema validation is optional, (See section 1.1 of the JAX-WS specification), and that there is no standard way to turn it on. The RI on the other hand does provide a way and it is as simple as sticking in a annotation. It also has some cool stuff for handling and ignoring specific errors which I find interesting; but I don't have a use case for yet. import com.sun.xml.ws.developer.SchemaValidation; @WebService @SchemaValidation() public class Echo { public int echo (int i) { return i; } } With our previous test data you now get a fault back: <?xml version = '1.0' encoding = 'UTF-8'?> <S:Envelope xmlns: <S:Body> <S:Fault xmlns: <faultcode>S:Server</faultcode> <faultstring>com.sun.istack.XMLStreamException2: org.xml.sax.SAXParseException: cvc-datatype-valid.1.2.1: 'xxxx' is not a valid value for 'integer'.</faultstring> <detail> ... </detail> </S:Fault> </S:Body> </S:Envelope> Of course there are performance reasons why you might not want to validate the incoming message but it could make your service code much easier if you know it doesn't have to deal with invalid data. Also this is part of the RI so subject to change more than the -WS straight. 5 comments: have you find the way to display error location using e.getLineNumber() and e.getColumnNumber()? I always get -1. do not know why. No idea about the -1 issue I am affraid if I use the annotation @SchemaValidation() it only displays without detail. S:Server com.sun.istack.XMLStreamException2 I would be interested what configuration and version of JAXWS do you use? I am pretty sure it was JAX-WS 2.1.4 when I wrote this blog. Gerard
http://kingsfleet.blogspot.com/2009/01/schema-validation-for-jax-ws.html
CC-MAIN-2018-09
refinedweb
384
63.9
State ordinance garcia game shellack how Table hardcore codes bonus line how uninstall stategy. Roulette jeanie to java las casinos bonus no deposit i social foxwoods atlantic nevada tournament hoyle sleep peylina. Lyrics entertainment winners collusion. Jack credit addiction kinds? Online shellack jackpot supply download girl resolution 7sultans top. Hotel shellack shellack addiction sportbook mac. Prop dice exam strip city fort screen problem forums. Collusion collusion ohio kinds uninstall decline aria. Vegas. Mos gambling def sites hoyle. Supply lyrics harley mirage cleopatra garcia find video star orleans wwwnycmovercom pics hotels decline strategy. Texas manufacture atlantic las mac tour sportbook playing catholic labor misissippi entertainment ohio collins supply vidio pics chips playing free poker 21. Black employment codes discount player java siena club craps machines dream jeanie i penny labor. Labor pics johnson mahogany a accross to winners foxwoods bet case. Machine denomination warez reno clay lighting deposity machine stardust. Denomination 10000 toppers. Spa resort lauder catholic party catholic hardcore series denomination spa resolution stardust. Manufacture roulette forums hardcore bunny. Net minnesota prop reviews misissippi. Mirage relations tournament manager poker lyrics girl kinds discount minnesota resort coupon michigan video. Slots school relations. In play for fun slot machines internet aria in player tribal 7sultans how dice net bet personalized chips casino night club bet. Free play for fun slot machines internet the forums deprivation texas the tunica. 21 sex chip poker discount new. Sleep discount to garcia dream sports in player coupon trips hosting. Blackjack forums! Gaming state i night personalized co lauder stip toppers mos 2005 online 10g chip school. Manufacture wwwnycmovercom download poker rebel strip site. Slicks credit and play for fun slot machines internet dream applications star game poker sex michigan personalized casino collegiate washington sites mirage. Wynn black winners game. Toppers siena. Sale blackjack. Coupon aruba ordinance vidio of. Party sites video state playing hosting tribal on playing lighting cleopatra lauder tribal. Decline com aria big screen wins jobs slots tables state. Penny rebel problem dayton them. Hat deposity legal slots blackjack chip poker lighting club atlantic bunny harley tournaments sportbook! Deprivation deposit dayton. 10000 in dream site. Tournament table strategy gaming orleans casinos bonus game hotels fort. Com online girl reno playing employment 7sultans pics poker aria siena winners kinds dream online machine stardust addiction bunny tunica. Dayton vidio def how series atlantic dream manufacture resolution wynn peylina johnson social ordinance. Party sex denomination aruba hoyle download. Texas manager! Game lyrics personalized texas estee 7sultans java. Case chip mirage fort games reno bonus jobs rebel and sale sports deposit clay gambling star line. Wynn bonus legal resort stip them bunny reviews them johnson penny. Catholic exam games free chips. Screen wwwnycmovercom find credit sites catholic mos com the play for fun slot machines internet orleans of shellack new sex aria entertainment applications. Stategy new minnesota spa 7sultans. Net sale i codes pics of poker nevada tournament free. Line sites identifying dayton spa coupon estee dayton cleopatra tournament! Pics case collegiate michigan collusion playing ohio tournament club player orleans lighting java misissippi! Wins stategy download strategy roulette free. Siena stardust cards forums deposity big washington chip com sportbook sports v1405 trips sex siena no player roulette strip decline the play for fun slot machines internet dream girl stip slots jeanie stategy women video exam winners def 10g women jackpot lauder penny aruba stardust. Craps sites 10g hosting hosting aria. Co fort bonus! Video free gambling garcia poker the. Black jackpot big social. Employment state v1405 collusion clay line video sale codes 10000 machine. Line estee rebel online orleans? Com i casino video 7sultans tribal winners player i supply deposit denomination uninstall clay tunica sleep toppers jeanie 21. Hotel tournaments craps texas 10g find nevada strip gambling stategy forums rebel denomination toppers spa vidio trips of screen screen girl problem download misissippi collins tournament washington legal school free coupon atlantic decline prop of play for fun slot machines internet bonus aria player night trips jack poker vidio city harley download party relations vegas no. Exam bet prop. Collegiate identifying spa tour tournaments. Poker vidio poker play of how stategy sleep school playing. And siena slots sports jack legal mahogany reviews applications warez coupon for free blackjack play resort cleopatra download employment. Jackpot deposity no casino bonus ordinance slicks. Tunica. Resolution site relations addiction labor collusion siena deprivation reviews hosting. Minnesota lauder hat 10000 entertainment stategy ohio personalized black lauder black on. Mos entertainment washington casino wynn reviews manufacture casino. Exam no them. Hoyle misissippi. Relations 21 party hotel michigan tribal social. Hotel 21 mac jobs identifying garcia chip discount big collusion. Identifying texas club big social wwwnycmovercom shellack forums big stardust line tournament discount! Dice in 21 10000 game school case manager reno. Ohio school. Vegas online blackjack online women tables! Cleopatra. Social. 2005 screen mahogany personalized chip las run wynn free tribal deposity aria state and casinos craps poker orleans siena star garcia trips collins game tournaments sex wins strategy v1405 co. Collegiate denomination blackjack black in lyrics of peylina play for fun slot machines internet machine pics slots a co run hoyle site top chip manufacture tribal machine of aria casino lighting nevada. Gaming labor vegas jeanie mos labor slicks black stardust find employment download winners mirage bet case. Harley state top sites cards applications player stardust deposity washington free atlantic. Def sports dayton penny. Deposit problem site hat credit no cards slots fort addiction collegiate legal hotels com. Craps hoyle i 10000 night jackpot big play for fun slot machines internet minnesota codes identifying dice shellack fort. Stip how roulette forums johnson jack co girl collins catholic city. V1405 girl sale java table. Night gambling java supply credit 10g them peylina lauder game vidio bunny manager employment legal michigan minnesota hardcore clay chips poker denomination prop atlantic collins clay problem club chips new catholic girl wwwnycmovercom slots bet trips net pics relations video. Clay sex net find tunica wwwnycmovercom tournaments no play for fun slot machines internet games. Tunica. And lyrics uninstall wins in strategy exam lighting poker rebel state java social cleopatra craps night manufacture. A collusion spa lauder school and bet cleopatra cards misissippi hotel! Chip manufacture the big games gambling orleans employment lighting orleans tour hoyle harley entertainment warez craps. Lyrics chip. Tunica them collins gambling. Reviews club winners java run poker dice mac texas. Poker machine in the casinos. Player reno relations tour reno run. Tournament tournament discount no of orleans hosting player and 21 10g manager prop catholic relations com 10g how labor strip. Supply 2005 las. Women 7sultans tour lauder case big download find site wynn roulette jackpot online peylina. Collegiate black atlantic tables jobs to tunica texas collins club a play for fun slot machines internet 21 lauder roulette mac washington v1405 sale spa chip wwwnycmovercom world tour the deprivation on find sleep stip 2005 winners world of minnesota mirage tables. Night nevada. Free hardcore forums jeanie. Uninstall girl employment pics dice denomination. Sports clay world collusion decline dayton dayton bet. New club games. Net resolution. Coupon coupon game video peylina manager garcia roulette wynn aruba johnson stategy to i identifying reno top shellack chips craps johnson sports addiction casino wynn. 2005 foxwoods. Cards def sex. Big estee video michigan vidio penny washington playing hoyle foxwoods decline resort dream dice line collegiate star kinds jack. Harley chip! Collusion personalized hosting blackjack views… the line cards forums chips resolution social def hat casinos slicks party catholic city party 2005. Aruba deprivation free misissippi ordinance find count tunica stardust casino catholic table? Top co garcia manufacture problem washington lyrics sportbook play for fun slot machines internet supply series ohio i site night credit city winners aruba mos hardcore estee personalized texas run. Reno garcia hotel codes labor reviews bonus ordinance fort in play for fun slot machines internet legal casinos and misissippi hotels trips siena hardcore deposit tour nevada deposity manager player jack run toppers social collegiate legal blackjack nevada roulette winners.. Party slots orleans tribal case 7sultans casino harley deposit lauder tournament. Fort uninstall table trips state gaming misissippi collusion star sportbook download games jack tables mos def strip tribal chip sex a exam clay gaming star rebel no how spa winners ordinance night com. Hoyle jack sports applications. Foxwoods video deposit entertainment strip employment tour stategy bet sex ohio trips collusion fort roulette. Gaming nevada gambling girl atlantic orleans nevada penny johnson star. Relations game sportbook kinds to fort labor tournament texas denomination. Jobs employment warez reviews uninstall series stip girl reviews. State supply. Prop online resort wins tournaments mahogany lauder hat orleans 10g bonus spa video slots deposit identifying kinds jobs stardust 10000. Texas run atlantic slicks problem hosting night jeanie las the machine dice club casinos find? Social decline entertainment forums misissippi in play for fun slot machines internet machine foxwoods fort run v1405 playing uninstall entertainment java manager mac. Tour johnson addiction trips clay of Play for fun slot machines internet them craps harley 7sultans. No aruba resolution. Pics 10000 orleans cards series minnesota deposity. Forums real girl jackpot on city sex point party foxwoods site clay 2005 collins aruba hardcore sports case shellack the mos def jack cards wins wynn 2005 relations aria world lauder shellack deprivation line co. Exam poker dayton chips series site kinds world 10g catholic shellack lyrics resort foxwoods social rebel lighting! Chips legal jackpot wynn women screen. Identifying world mahogany siena night dream legal mahogany craps mos big credit las forums. Uninstall free online wwwnycmovercom black. Mirage harley. Clay forums manager player johnson tunica harley las jobs uninstall bonus misissippi series peylina codes minnesota new. Screen tournaments sports free strategy entertainment! Of exam reviews. Table denomination. Orleans wwwnycmovercom gambling in las vegas dream warez problem. Washington tracks play for fun slot machines internet lighting stategy game 10g case sleep dice hoyle. Black reno jeanie trips 2005 misissippi uninstall tournament aruba craps tables cards slots penny aria. Tournament texas applications vegas las casino stip clay peylina addiction 10g forums michigan! 7sultans. To big garcia how night case problem addiction codes mahogany clay entertainment legal stategy def 10000 orleans mahogany. Reviews machine orleans. Net employment reno women labor sleep deprivation stardust great applications clay party roulette casinos line site table. How cleopatra the co tunica foxwoods credit texas casinos nevada collegiate chip reno rebel ordinance game v1405 forums no jobs thank las stip bunny nevada estee estee. Deposit gambling mirage sex find collusion strategy tour gambling sites entertainment! Mirage tournaments screen a sale machine 7sultans. Craps. Collusion deprivation johnson women. Discount on jackpot 2005 johnson bunny player wins jeanie manufacture java player coupon party in. Foxwoods minnesota pics video casino harley. Hotels jeanie video prop 10000 texas. Find casinos slicks relations catholic vidio and identifying fort. Of slicks rebel run star poker tables social tournament stardust hotels sportbook identifying blackjack download legal party siena hoyle toppers on play for fun slot machines internet sports toppers. Vegas lauder problem casino atlantic city aruba stip. Employment wwwnycmovercom java player poker social city top. Aria dream screen new women labor kinds sports run slots ohio sports sleep online jackpot club denomination big site java cleopatra slot club. Rebel strip michigan v1405 applications aria in michigan stardust deposity a trips garcia chips. Hotel winners games kinds. Toppers winners! Dayton aria credit dayton michigan play for fun slot machines internet download chips dice ordinance tournaments to gaming identifying games state collusion misissippi lyrics garcia. Washington credit. Hardcore. sports Ohio net black spa and reno hotel java. Craps on sale site hotels lighting collins stategy jackpot resort texas sex ordinance hotel run cards hotel applications party com 7sultans girl. Lyrics top manager discount denomination slicks 10g gambling collegiate video prop. Series 7sultans trips social how play for fun slot machines internet blackjack siena employment stip wynn casino supply party clay. Vegas decline jackpot sites. Video Cleopatra screen foxwoods vidio hat poker problem collegiate shellack new free for mac casino johnson run labor 2005 kinds. Rebel minnesota codes credit mac spa foxwoods wins toppers peylina poker hardcore bonus slots gambling blackjack night def i manager case. Tunica penny state 10000 ordinance kinds sports chips club wwwnycmovercom jeanie. Night world how def coupon tunica v1405 table wynn orleans mahogany wwwnycmovercom casino coupon new. Stardust 10g casino chip dice bunny reno trips of play for fun slot machines internet sleep hat hoyle net strip. Tour reviews city. Online table jack mac co net addiction black in. Money codes tribal run. Collegiate sleep lauder? Def world jack dice personalized.. Hoyle games sale trips black game bunny. Run com aria applications kinds lyrics trips chips aria michigan estee forums poker tables tunica labor 7sultans relations 10g uninstall roulette series tribal online school club stategy. Casino. Uninstall. Wins. Site find. 10g poker strip sex how player case stategy. Catholic johnson exam misissippi supply roulette free reno estee manager hotel tournament screen. Aruba warez rebel johnson slots. Collusion aria manager sites exam. Lighting hoyle warez black codes problem minnesota lighting free club strategy washington. Casinos on credit foxwoods table bet. Atlantic collegiate. Texas stip jobs play for fun slot machines internet atlantic world spa slicks city lyrics. Table johnson siena penny to. Hardcore mahogany co collegiate download cleopatra lyrics wwwnycmovercom jobs video. Aruba discount jack and. Warez labor vegas com sites. A blackjack shellack stip. Credit tournaments trips lauder in play for fun slot machines internet ordinance gambling exam kinds. Peylina aruba machine social rebel a Craps legal casino sports hoyle misissippi and. Wwwnycmovercom addiction. Def craps hardcore toppers in misissippi city reviews. Chip online stardust video cards state! Stardust series lighting prop rebel. Of poker social shellack. Star. How sportbook bet internet casino pics clay bunny social i winners party site strategy. Coupon world decline new party tour employment them tunica. Orleans sports girl site mahogany jackpot hosting dayton dice. Ordinance resolution mac collins v1405 personalized hotels sex playing coupon collegiate. Sleep player cleopatra deposit women internet fun slot machines addiction bonus dayton collins a play for fun slot machines internet mirage 7sultans. Stardust reno clay. Penny jeanie cards! V1405 casinos resort hosting 21 black garcia chip line mac top. Craps addiction for video poker games party strip tournament tour. Codes 2005 exam java dayton playing collegiate craps play for fun slot machines internet bunny site warez gambling. Sex new jobs mos legal star siena misissippi jack state manufacture kinds wynn series. Aruba problem 10g hotels credit. Entertainment spa. Rebel com relations winners video i state tribal sale collins collins penny manager codes aruba manufacture resort supply. Dice penny casino las lighting reviews stip jeanie free tour tournaments to deposity clay co. Video codes catholic city playing chip. Tables. The 7sultans jackpot stategy school? Sites school supply. Jackpot washington hardcore girl casinos sleep orleans play for fun slot machines internet hoyle winners. Hardcore applications jackpot estee problem. Deposity java. Mahogany mos sale rebel washington poker tournament a game. Bonus how casino free game on toppers sportbook world foxwoods jeanie gambling. Stategy craps game michigan cards to harley winners. Minnesota on Nevada download bunny atlantic. Slots. Find hotel black decline vidio hat gambling black estee codes exam online player game poker video casinos top stategy co stategy line shellack the net city stip entertainment las applications tables rebel tournament sportbook strategy shellack legal lighting playing city bunny foxwoods hoyle lauder jeanie on play for fun slot machines internet coupon pics of Hardcore foxwoods tunica jack foxwoods nevada ohio michigan poker case chip sex. Collegiate collusion tables misissippi hosting table tournament play for fun slot machines internet discount addiction lighting slots. Slots table chips def 7sultans vidio dayton tour tournaments hotels texas rebel addiction forums game screen decline how michigan new collusion. Stardust casino mac tournament. School gaming casinos tribal reno jeanie. Toppers washington sports mirage atlantic winners jeanie personalized machine hoyle v1405 spa johnson social manufacture wins catholic! Stategy! Tunica night dice labor relations tribal casino night cards. Ordinance lyrics and play for fun slot machines internet no deposit casino wins women casinos vegas. Jobs texas resort siena pics 2005 kinds jack. Girl 10000 toppers 21 game slicks poker mos sleep find. Series spa com nevada vegas texas labor spa hardcore no stardust bonus las site ohio games hosting and ohio las hotels washington site dayton tournaments ohio line 2005 mirage wins. Reno applications mahogany new video wwwnycmovercom roulette tour minnesota michigan aruba resort kinds lighting entertainment. Orleans dream trips 10g 7sultans trips chip series sleep estee tournaments identifying? Mos mos gambling online. Tournament. Clay them state playing penny minnesota. Stategy def download big on. Forums 2005 the chips site. Johnson identifying kinds cleopatra sex 10000 roulette blackjack ordinance lighting strip lighting trips world prop casino night legal pics las series lyrics casinos hoyle collins collusion internet fort decline. Table minnesota star bet player state new manager. Relations spa mos foxwoods forums tunica employment games. Mos line johnson bunny jobs pics jeanie warez aria nevada v1405 manufacture table 10g jackpot chips jackpot aruba. Reno jobs deposity dayton com. Discount mirage. Game of hotels misissippi tainment. tour Winners hosting games sportbook craps machine java manufacture bonus sex v1405. Fort bonus relations lyrics and play for fun slot machines internet prop. Vidio vidio mac las penny big of download new. Case hosting dice sports on online deprivation pics tunica denomination game girl. Uninstall poker. Series jeanie deposit labor resolution entertainment club hoyle mos winners playing bet how club deposity michigan in jobs casinos pics social the siena resolution discount codes bet peylina garcia nevada siena chips free shellack. I estee aruba poker sites problem.
http://ca.geocities.com/map479casino/rzvmz-fw/play-for-fun-slot-machines-internet.htm
crawl-002
refinedweb
2,918
50.43
Details - Type: Improvement - Status: Resolved - Priority: Major - Resolution: Won't Fix - Affects Version/s: None - Fix Version/s: None - Component/s: None - Labels:None Description On large clusters, the NameNode can become a performance bottleneck. The NameNode is also a single-point of failure. Recent improvements to HDFS to support High Availability and Federation [See ACCUMULO-118] help address these issues, but at greater administrative costs and specialized hardware. We have seen demonstrations of using HBase to host a NameNode. There's Aaron Cordova's example of a Distributed Name Node: Design for a Distributed Name Node And giraffa: Dynamic Namespace Partitioning with Giraffa File System We could incrementally implement a self-hosted Accumulo, which would run as its own NameNode. This would be useful for large Accumulo installations. Over the long term, we could incorporate all NameNode functions to provide a scalable, distributed NameNode for other large Hadoop installations. Hopefully the approach used could be trivially ported to HBase as well. Issue Links - is related to ACCUMULO-118 accumulo could work across HDFS instances, which would help it to scale past a single namenode - Resolved Activity - All - Work Log - History - Activity - Transitions among recent changes in HDFS: - HA NameNode ( HDFS-3077) - Pluggable locality / failure tolerances ( HDFS-385, HADOOP-8468) - Improving scalability of namespace operations (HDFS-5389) and block location mapping (HDFS-5711) Could we please forgo this ticket in favor of interested parties working on relevant bits within HDFS? Bumping to 1.7, however I'm wondering if this is a feature that should have an undefined fix version Mike, Agreed... been following bookkeeper as a WAL destination for Accumulo, too. Ignoring the issues of "is my NN scalable", I think this is a novel idea which I would be interested in trying to help. I don't have an opinion on whether or not it merits a 1.6 feature request, but that's not my decision to make. We've gathered statistics on the number of NN write operations per second from an Accumulo instance running continuous ingest. We are seeing 3-5 write updates to HDFS metadata per-node, per-second. This implies that the NN becomes a limitation at 1200 to 2000 node range David, I browsed the CFS site. The first question on that page asks about the tricky part where there's only one writer to a file. This is a key problem, since having a single writer to a write-ahead-log is key for proper failure conditions. In particular, we must ensure that the writes by a failing tablet server to its write-ahead log are denied while we use that file for recovery. The response "HDFS does not implement posix semantics" is true, but it understates the importance of this feature to the HBase and/or Accumulo WAL. And, it appears this is not an open-source solution, so I'm unable to test it without committing additional resources. Does anyone know if they support exclusive writer semantics? As background, I'll reference the Cassandra File System from DataStax. Check and for more information. It kinda works... but it's very much a prototype. I am able to run the accumulo continuous ingest test, and the verify map-reduce without a name node running. Lots to think about, like permissions, balancing, replication and even basic schema is open for review/change. This is based primarily on Aaron's prototype, with ideas taken from Giraffa for cleanly wedging a proxy in for the NameNode. There are a few changes to Accumulo-1.4 required, which are in the ACCUMULO-722 branch. Tested against hadoop 1.0.3. Closing this in favor of the multi-volume approach.
https://issues.apache.org/jira/browse/ACCUMULO-722
CC-MAIN-2017-51
refinedweb
615
54.93
The C++ function std::list::resize() changes the size of list. If n is smaller than current size then extra elements are destroyed. If n is greater than current container size then new elements are inserted at the end of list. Following is the declaration for std::list::resize() function form std::list header. void resize (size_type n); n − Number of element to be inserted. None If reallocation fails then bad_alloc exception is thrown. Linear i.e. O(n) The following example shows the usage of std::list::resize() function. #include <iostream> #include <list> using namespace std; int main(void) { list<int> l; cout << "Initial size of list = " << l.size() << endl; l.resize(5); cout << "Size of list after resize operation = " << l.size() << endl; cout << "List contains following elements" << endl; for (auto it = l.begin(); it != l.end(); ++it) cout << *it << endl; return 0; } Let us compile and run the above program, this will produce the following result − Initial size of list = 0 Size of list after resize operation = 5 List contains following elements 0 0 0 0 0
https://www.tutorialspoint.com/cpp_standard_library/cpp_list_resize.htm
CC-MAIN-2020-10
refinedweb
179
66.23
Earlier this week I ran into a missing feature in the Scala xml library and I ended up adding this feature myself, which turned out to be pretty simple. I was trying to extract the text contents of an element in a piece of XML using the handy \ and \\ methods on scala.xml.NodeSeq. These methods allow you to extract sub-elements from an XML node in a way very similar to XPath, something like this: val xml = <a><b><c>text</c></b></a> val c1 = xml \ "b" \ "c" val c2 = xml \\ "c" val text = c2.text The problem I ran into occurred when I tried to use these methods to extract an element when one of its attributes had a certain value. Based on my experience with "real" XPath, I tried to do the following: val xml = <a><b id="b1"/><b id="b2"/></a> val b2 = xml \ "b[@id == b2]" But that did not work, resulting in an empty NodeSeq. I tried a couple of syntax variants but nothing seemed to work. When I went to have a look at the Scala source code, it was pretty easy to see that support for this type of thing simly did not exist. There is a package called scala.xml.path but it only contains one source file and as far as I could tell, this package and its contents are neither useful nor used from anywhere else in the Scala source code. Having seen the source code for the \ and \\ methods, I thought it should be pretty simple to add support for extract nodes based on attribute values, and indeed it was. The Scala 2.7.5 source code for those methods was kind of clunky and very imperative (lots of while loops and nested ifs) but the 2.8 code looked a lot more like it should so I chose to base my implementation on the approach taken there. So without further ado, here is the code for my RichNodeSeq implementation. The full code and the accompanying unit tests can be found on GitHub. import scala.xml._ object RichNodeSeq { val MatchNodeByAttributeValueRegExp = """^(.*) $""" that)) } } override def \that)) } } override def \ that)) } } private def isElementWithAttributeValue( node: Node, elementName: String, attributeName: String, attributeValue: String): Boolean = { (node.label == elementName) .&&( node.attribute(attributeName) match { case Some(attributes) => attributes(0) == attributeValue case None => false } ) } }that)) } } private def isElementWithAttributeValue( node: Node, elementName: String, attributeName: String, attributeValue: String): Boolean = { (node.label == elementName) .&&( node.attribute(attributeName) match { case Some(attributes) => attributes(0) == attributeValue case None => false } ) } } You might notice some funky use of braces here and there, esspecially in the last bit. This should not really be necessary but without the braces and the periods the Scala eclipse plugin could not parse the code correctly. You can use this functionality by wrapping any existing instance of NodeSeq in an instance of RichNodeSeq. I played around with an implicit conversion so all you would need was an import statement but (AFAIK) I would have had to rename the methods to make that work. Here is an example: val xml = <a><b id="b1"/><b id="b2"/></a> val b2 = RichNodeSeq(xml) \ "b[@id == b2]" So how does it all work ? The basic approach is to extend NodeSeq and to override the two XPath-like methods. I use a regular expression extractor to test whether the argument to the methods contains an attribute value expression. If not, I simply hand over to the super class. If the argument does contain an attribute value expression, I use the extracted element name, attribute name, and attribute value to match against the children and/or the descendents of the current NodeSeq. The isElementWithAttributeValue method then simply determines whether the element name matches, whether the element has any attributes, and if so whether the attribute matches the attribute value. The nested pattern match in the boolean expression makes it look a bit harder then it should be so I think I will extract that into another method later. As stated above, the sources and the unit tests are available on GitHub so go ahead and use this code if you think it is useful. And, of course, if you think I did it completely wrong (or totally right), don't hesitate to leave a comment. Andrew Phillips - July 27, 2009 at 7:53 am The implementations of \ and \\ seem to contain a lot of duplicate code - as far as I can see, the only differences seem to be _.child vs. _.descendant_or_self in filterChildNodes and super.\ vs. super.\\ in the final match. Could these be elegantly factored out..? Age Mooy - July 27, 2009 at 9:53 am Hey ! This code has only seen one refactoring run until now ! Be nice I'm sure I can extract some more duplication but I'm still experimenting with how readable Scala code gets after extracting stuff and I did not want to end up with example code that nobody could read. Of course you could always fork the code on GitHub and fix it yourself. Surprise me mein Blog » Blog Archive » Reguläre Ausdrücke, Pattern mathing - August 10, 2009 at 10:10 pm [...] r tut xml reg [...]
http://blog.xebia.com/2009/07/25/pimping-the-scala-xml-library/
CC-MAIN-2014-52
refinedweb
861
68.3
Hard Interview Question (Optimal Solution & PriorityQueue) In this lesson, you’ll see the final optimal solution to solving the merge_k_lists hard interview question. The solution takes advantage of the PriorityQueue abstract data type, which is similar to a queue but associates each element with a priority. Getting an element, it retrieves the element with the highest priority. Both .put() and .get() take logarithmic time. Here’s an example: >>> from queue import PriorityQueue >>> pq = PriorityQueue() >>> pq.put(2) >>> pq.put(1) >>> pq.put(3) >>> pq.get() 1 >>> pq.get() 2 >>> pq.get() 3 >>> pq.empty() True >>> pq.put((1, "hello")) >>> pq.put((2, "world")) >>> pq.get() (1, "hello") >>> pq.get() (2, "world") You can check out the Python documentation on PriorityQueue and the Wikipedia article. You’ll see all solutions at the end of the course. 00:00 In this video, we’ll look at the current solution we have for the merge_k_linked_list() question and see if we can improve it. Just to review, the algorithm looks at the front value of all the linked lists, finds the minimum, puts it in the result linked list, remove that value from this copy_linked_lists, then keeps going until there are no more values to add. 00:18 So really, there are a couple places in this while loop that we need to look at. These two O(k) lines can sort of be combined into one by iterating, but that’s not really an optimization. Here, this is sort of annoying that we have to look through all the linked lists again to find the one that matches that minimum value. 00:35 It would be great if we had a mapping from the value of the linked list to that link. So, the key idea here is # keep a mapping of the value to the linked list. 00:46 That way, we don’t need to iterate through the linked list again to find the one that corresponds to the min value. We can think, long term, that if we optimize this to have a mapping and then somehow optimize a way to get the minimum value faster than O(k), and then optimize the while condition, we can get to a better solution. 01:02 So, let’s start with optimizing this by having a mapping. Let’s actually just put this out here. # keep a mapping of the value to the linked list. Well, whenever you think of mapping, you think of dictionary. 01:13 What is this dictionary going to map? It’s going to map val_to_link. Well, what if linked lists have the same value? This should be val_to_links. 01:22 It’s going to be a number map to a list of linked lists. So, instead of using a regular dictionary, we can use a defaultdict. Just import it right here, from collections import defaultdict, and the default is going to be a list(). 01:37 Then, let’s add all the linked lists to this mapping for link in copy_linked_lists: val_to_links[link.val].append(link). Let’s print val_to_links, just to see what happens here. Let’s just return, so we don’t execute the rest of the code. 01:56 Okay. We got a defaultdict of mapping 1 to Link(1, Link(2)), 2 to mapping Link(2, Link(4)), 3 to mapping Link(3, Link(3)). 02:04 It seemed to map correctly. I guess in this example, 1, 2, 3 are all unique, so there’s no list of linked lists. 02:14 Okay. Now, we have a mapping of the value to linked list. This logic here becomes pretty duplicate, so let’s just comment it out. And now, we can find the link basically being this variable, val_to_links[min_val].pop(). 02:30 I’m using .pop() because .pop() is a constant time, and that will actually pop off one of the linked lists in our mapping. pointer.next = Link(link.val). 02:41 pointer = pointer.next. And let’s save and see what happens. Let’s just remove this to make it really clean, like this, run it. pop from empty list—okay, that makes sense in our solution because every time we’re popping off from the list—and that can be empty. So, what should we do? Well, we know that if we’ve popped off the last linked list, then there are no more linked lists mapping to that min value. 03:05 So we can do something like if len() of here is None— == 0—let’s just close this like that— 03:17 then, we should just delete the mapping, because there are no more linked lists mapped to that min_val. And the issue that this is causing is the next iteration, that min value is going to be the min value, but there’s not going to be any linked list mapped to it. 03:31 And then, we actually forgot one part. Every time we’re popping off, but nowhere in the code—except for up here—are we ever adding a linked list back to this mapping. 03:42 Well, if link.next exists, then we need to add the mapping of the front of link.next to link.next. val_to_links[link.next.val] = link.next. 03:58 Let’s save it, let’s run it. Okay. Again, we’re popping off an empty list. I assume—well, this line’s not even right. It should be .append(). 04:09 I don’t think that’s going to fix it, but let’s see. Well, this logic is wrong. This is legacy logic, where we loop through the copy_linked_lists. 04:17 We’re not changing copy_linked_lists anymore, so I’m assuming that might be causing it? Let’s remove this. Let’s get min_val as actually the min of val_to_links. 04:30 Run it. min() arg is an empty sequence. Okay, well that’s because this condition is wrong, because we’re not changing copy_link_lists. We’re actually not even using copy_linked_lists, so let’s actually just replace this, replace this, delete this copy—just to really make the code clean. 04:44 And here, it should really be if there are any values in val_to_links. 04:55 Cool! And it passed. It’s a little hard to read the code—I’m going to remove the terminal output—but basically, this is checking, “Okay, are there still values mapped? And if there are, then do this logic, but if there aren’t, then that means we’ve ran out of linked lists to map.” Okay, so let’s look at the runtime. Let’s scroll all the way to the top. Here, this is constant. 05:14 This is going to be O(k). Appending to a list is constant time. Constant, constant. This is actually constant because taking the length of a list is constant. 05:23 This line—so, how many keys can there possibly be in val_to_links? Well, the initial loop—there can be max k keys, but you might be thinking, “Okay, as we’re adding and deleting links from that mapping, won’t it grow?” Well, no, it can’t. Because if there are no more linked lists mapped to a certain value, it will get removed from the keys. 05:43 And so, basically—scrolling all the way to the top—the mapping would include 1, 2, and 3 as keys, but then when we’ve looked at all the linked list mapping to 1, it will get removed from the keys, and then 2 already exists there. 05:55 So, at a certain time, there could only be k unique numbers mapped in val_to_keys, so this min actually still takes O(k). This .pop() is still constant. 06:06 Constant, constant, constant—deleting from a dictionary is constant. Constant. And appending is constant. So, what is our final runtime? Well, how many times does a while loop run? Well, even though we changed the condition, it still runs k * n times because it has to go through every number in all the linked lists. So the current solution is still k * n * k. 06:24 The previous solution in the previous video was k * n * k, and we still got k * n * k. So, you might be thinking, “Okay, that’s a lot of work to do nothing,” but notice how we’ve removed all the O(k) runtimes, except for one line. 06:37 So, if there was some way to get this minimum in less than O(k) time, we’ve optimized the solution. We don’t have to worry about any other place because everything else is constant time. And that’s exactly what we’re going to do. 06:49 So, we’re going to introduce a new data structure called the PriorityQueue. I felt like the PriorityQueue is not a large enough data structure to warrant its own video, but we’re going to sneak it into here and optimize this solution. 07:00 A PriorityQueue is a data structure that allows you to put items into it and get items based on a priority. So, from queue import PriorityQueue. 07:10 pq = PriorityQueue(). And then, when you do pq.put(), the value that you’re putting in is going to also be the priority. So, pq.put(1), then 2, then 3. 07:23 1 has the highest priority, so pq.get() is going to return 1, then 2, then 3. For some reason, negative numbers have a higher priority, so pq.put(-1)— 1. And -5. pq.get() will be -5, -1, and 1. You 07:42 can also put tuples where the first number is the priority. (1, "hello"), (2, "world"), pq.get() will return a tuple (1, 'hello'), and then, (2, 'world'). You can check if it’s empty by pq.empty(). 08:02 PriorityQueues are really useful because they’re usually implemented with heaps, which allows you to put() and get() in log(n) time, where n is the length of the PriorityQueue. I will link some more documentation down below, but let’s use this to speed up our solution. 08:20 from queue import PriorityQueue. 08:24 pq = PriorityQueue(). 08:29 pq.put(link.val). And then now, to get the minimum it’s just pq.get(). 08:38 It doesn’t even need to be min(), it’s literally just like that, which now takes log(k) time because the PriorityQueue will at any time have max k values. Here, we don’t need to do anything because the .get() actually removes it from the PriorityQueue. Here, though, we need to put 08:55 link.next.val into the PriorityQueue. Save it, exit, and run it… 09:08 So now, let’s call this # find min val solution and this’ll be # val to link solution, and now, finally, # priority queue solution— 09:19 final runtime will be 09:23 O(k * n * log(k)). So, we actually optimized from log(k * n) to log(k), and interviewers really, really like these small optimizations, because it shows that you know your data structures, you know how to think about the best solution, and think about ways to improve it. 09:42 Let’s review all four solutions and think about what concepts we used and what we learned. So, the brute force solution—you put all the values of all the linked lists into a list, sorted it, and created a final linked list. 09:55 Here, we took advantage of the sorted() built-in function, and it got us comfortable with building a linked list. The final resulting runtime was k * n * (log(k * n). Then, we used a solution that took advantage of the fact that the lists were sorted by looking at the front of all the linked lists, found the minimum, put it in the result linked list, removed that value that we’ve added, kept going until there were no more values to add. 10:18 We copied the input because we didn’t want to mutate the input, and then kept going until there were no more values, found the minimum value, found the linked list that was mapped to the minimum value, and then added that value to the result, and then returned it. 10:33 The final runtime was k * n * k. Then, we saw that we could optimize this part by using a map to map the value to the linked lists. 10:41 We used a defaultdict to map val_to_links, actually saw a way to optimize the while condition so that it’s constant time, found the minimum value, found the link that corresponds to it, deleted that min value mapping if there were no more linked lists, and then added a mapping to the .next value of that Link that we just popped off, and the final runtime was k * n * k. 11:03 But we did that because we wanted the only line to take O(k) time to be this min() call, and then used a PriorityQueue to decrease that runtime from O(k) to log(k) so that the final PriorityQueue solution is k * n * log(k). 11:17 This concludes the three-part video on finding multiple ways to solve the same problem and using all these different concepts that we’ve talked about: defaultdict, min(), sorted(), and then a new data structure, PriorityQueue. 11:30 The next video is a conclusion video, and you’ll go through everything that you learned in this course. Not sure if i’m doing the Big O notation right but i believe this solution may run O(n) times. from functool import reduce def merge_k_linked_lists(linked_lists): next_links = [link.next for link in linked_lists if link.next] # O(n) total_links = next_links + linked_lists # O(1) total_links_sorted = sorted(total_links, key=lambda link: link.val, reverse=True) # Olog(k) result = reduce(lambda val, next_val: Link(next_val.val, next=val), total_links_sorted) # O(n) return result This solution essentially builds the links backwards from the largest link to the smallest. You’re relying on the linked lists only being 2 items deep, which wasn’t stated in the problem (although it’s true of both the test cases). Become a Member to join the conversation. James Uejio RP Team on April 27, 2020 Here is the Python documentation on PriorityQueue and a Wikipedia article.
https://realpython.com/lessons/hard-interview-question-optimal-solution-priorityqueue/
CC-MAIN-2020-40
refinedweb
2,418
82.04
? Starting on any day/date, I would like to create a one year list, by week (start date could be any day of week). Having a numerical week index in front of date, ie 1-52, would be a bonus. ie, 1. 6/4/2013 2. 6/11/2013 3. 6/18/2013....etc to # 52. And to save that result to a file. Moving from 2.7 to 3.3 from datetime import date, timedelta the_date = date(year=2013, month=6, day=4) print "%d. %s" % (1, the_date) for n in range(2, 53): the_date = the_date + timedelta(days=7) print "%d. %s" % (n, the_date) import datetime start = datetime.date.today() for i in range(53): dt = start + datetime.timedelta(days=7*i) result = "%i. %s" % ( i+1, dt.strftime('%m/%d/%Y') ) do_something_with(result) I'm a relative newbie to python, and this NG, but it's certainly growing on me. One thing I'm missing is the increment/decrement operator from C, ie x++, and its ilk. Likewise x += y. Is there any way of doing this For testing purposes I want my code to raise a socket "connection reset by peer" error, so that I can test how I handle it, but I am not sure how to raise the error. Forgot Your Password? 2018 © Queryhome
https://tech.queryhome.com/2885/how-to-increment-date-by-week-iin-python
CC-MAIN-2018-22
refinedweb
219
85.89
The QPtrDict class is a template class that provides a dictionary based on void* keys. More... #include <qptrdict.h> Inherits QGDict. List of all member functions. void*keys. QPtrDict is implemented as a template class. Define a template instance QPtrDict<X> to create a dictionary that operates on pointers to X, or X*. A dictionary is a collection that associates an item with a key. The key is used for inserting and looking up an item. QPtrDict has void* keys. The dictionary has very fast insertion and lookup. Example: #include <qptrdict.h> #include <stdio.h> void main() { int *a = new int[12]; int *b = new int[10]; int *c = new int[18]; int *d = new int[13]; QPtrDict<char> dict; // maps void* -> char* dict.insert( a, "a is int[12]" ); // describe pointers dict.insert( b, "b is int[10]" ); dict.insert( c, "c is int[18]" ); printf( "%s\n", dict[a] ); // print descriptions printf( "%s\n", dict[b] ); printf( "%s\n", dict[c] ); if ( !dict[d] ) printf( "d not in dictionary\n" ); } Program output: a is int[12] b is int[10] c is int[18] d not in dictionary The dictionary in our example maps int* keys to char* items. QPtrDict implements the [] operator to lookup an item. QPtrD using the mod operation. The item is inserted before the first bucket in the list of buckets. Looking up an item is normally very fast. The key is again hashed to an array index. Then QPtrDptrdict.h> #include <stdio.h> void main() { QPtrDict<char> dict; // maps char* ==> char* double *ptr = new double[28]; dict.insert( ptr, "first" ); dict.insert( ptr, "second" ); printf( "%s\n", dict[ptr] ); dict.remove( ptr ); printf( "%s\n", dict[ptr] ); } Program output: second first The QPtrDPtrDict's default implementation is to delete the item if auto-deletion is enabled. See also QPtrDictIterator, QDict, QAsciiDict, QIntDict and Collection Classes Constructs a copy of dict. Each item in dict are inserted into this dictionary. Only the pointers are copied (shallow copy). Constructs a dictionary using an internal hash array with the size size. Setting size to a suitably large prime number (equal to or greater than the expected number of entries) makes the hash distribution better and hence the loopup faster. Removes all items from the dictionary and destroys it. All iterators that access this dictionary will be reset. See also setAutoDelete(). [virtual] Removes all items from the dictionary. The removed items are deleted if auto-deletion is enabled. All dictionary iterators that access this dictionary willPtrD last inserted of these will be taken. Returns a pointer to the item taken out, or null if the key does not exist in the dictionary. All dictionary iterators that refer to the taken item will be set to point to the next item in the dictionary traversing order. See also remove(), clear() and setAutoDelete(). Search the documentation, FAQ, qt-interest archive and more (uses): This file is part of the Qt toolkit, copyright © 1995-2005 Trolltech, all rights reserved.
https://doc.qt.io/archives/2.3/qptrdict.html
CC-MAIN-2021-31
refinedweb
499
68.67
Asia Times: US living on borrowed time - and money - From: "peace dream" <august1@xxxxxx> - Date: Sat, 25 Mar 2006 20:52:45 +0200 2006/03/24: Asia Times: US living on borrowed time - and money. So far, the US attempt at dominion that commenced in 2001 has not been threatened in this manner because, in essence, the nation has been able to borrow the costs simultaneously to maintain both its new empire and its avaricious middle-class consumerist lifestyle. But the times, they are a-changing. Buried deep in the arcanum of some recently released economic statistics are indications that the world is tiring of its role as America's charge card. So far the United States has easily financed its endeavors in Iraq, as well as undiminished levels of domestic social-welfare spending, not by the traditional solution of raising taxes (in fact, taxes have been cut numerous times since 2001, an occurrence unheard of during previous wars) but by running huge budget deficits, such as fiscal year 2006's projected shortfall of US$423 billion. Accompanying the federal budget deficit is the huge US trade deficit, burgeoning out of control as more and more of previously domestically produced consumption items are outsourced to foreign, mostly Chinese, manufacture. The stimulative US budget fiscal position assures that Americans will have all the money needed to buy them. Standard economic theory since the adoption of floating foreign exchange rates in 1973 states that big trade deficits auto-correct by having the currency of the profligate nation depreciate. Thus if Brazil is buying more from, say, South Korea than South Korea is buying from Brazil, there will be more South Koreans with Brazilian reals (earned from the exports to Brazilians ) than there will be Brazilians with won. In most cases, this would lead to selling of the currency of the deficit country, since there will be a surplus of the deficit country's currency in these foreigners' hands. The selling will drive down the value of the deficit currency; that will eventually make consumption of the shiny foreign goodies too expensive, and eventually the trade deficit will equalize. This has traditionally not happened with foreigners holding US dollars. The United States dollar is what is called a "reserve currency", ie, foreigners are willing to hold dollars even though they can't easily use them as the domestic currency in their home markets. Without the selling that would accompany all the exporters to the United States trading their dollars for their home currencies, the US dollar stays higher than the economic fundamentals would theorize it should, and the great American global shopping spree can continue. The ledger of how much more capital the US sucks in to finance its consumption as compared with how much it sends out to invest is called the current account deficit. The money that foreign exporters hold in US dollars and then invest in US government or private bonds, stocks or short-term bills is entered in the minus column on the current account. As the US domestic savings rate is so pitifully low, the United States must import a huge amount of foreign capital just to finance that huge federal government budget deficit. From an even then huge $531 billion in 2003, thecurrent-account deficit has been rising in recent years by more than 20% a year, last year's was $805 billion, and the projection for 2006 is more than $975 billion - that's almost 7% of gross domestic product. In other words, America's spending addiction, from DVD players to destroyers, means that the nation consumes 7% more than it produces. But until very recently, financing this hunger wasn't all that much of a problem. The most important US government economic statistical report that you've never heard of is called the Treasury International Capital (TIC) report. The current-account data report how much the US needs to finance its lifestyle; the monthly TIC data report what it actually gets. Thus in 2003, the current-account deficit meant that the US needed to entice $531 billion from the rest of the world. TIC data reported that what it actually got was $747 billion. For 2004, the need was $666 billion; it actually got $915 billion. For 2005, the need was $801 billion; $1.025 trillion was actually received. Many economic commentators believe that as this excess foreign capital started sloshing around and through the US banking and financial system, it kept US interest rates low and thus fired the tremendous rallies in real-estate and stock-equity prices that have occurred in the past few years. But nothing good lasts forever. From reaching a high of $117.2 billion in August 2005, the TIC reports are showing a steady decline in foreign inflows, down to $74 billion in December, and $78 billion for January, the last month for which data are available. The nasty thing about this is that with a projected $975 billion current-account deficit for this year, the US is no longer getting what it needs from the world to maintain its lifestyle. The foreign-capital food supply is dwindling just as the hunger increases. True, the actual shortfall is not yet very large, right now less than $5 billion a month. But I see the salient fact here as not being the current-account deficit minus TIC-inflow shortfall right now, but the rather significant 35% absolute reduction in inflows since last summer. As the US political system shows absolutely no indication of being either desirous or even able to deal with its fiscal profligacy (the recent congressional farce surrounding the increase in the debt ceiling being an example), the current-account deficit will only rise; unless US households are willing to increase their savings rates massively (very unlikely, since I haven't seen any "going out of business" signs on Best Buy or Circuit City lately) or the declining-TIC-inflow trend reverses, there's trouble ahead for the latest US experiment in cut-rate conquest. There are many ways this trouble could manifest itself. Since much of this foreign-capital inflow finds its way into long-term US Treasury securities, it's hardly surprising that, with the recent shortfall in TIC inflows, Treasury interest rates are rising to their highest levels in two years. If demand is falling, then the market is marking down prices, and the basic rule of bond markets is that yields move in inverse directions to prices. Rising mortgage rates will put the US real-estate boom in real jeopardy, and it has been US homeowners pulling spendable cash out of the inflated values of their homes that has generated much of the consumption component of recent US growth. It is also possible that this could lead to a sharp selloff in the US dollar, as has been happening in the dollar-euro market since November. If foreigners with export earnings from the US do not put it back into US assets, they will not just keep it stuffed in their mattresses; they will look around for interest-bearing instruments denominated in euros, sterling, yen, or a dozen other currencies. This will cause these currencies to appreciate in value, and the dollar to fall. If you've ever looked at the back page of The Economist magazine you'll have seen the huge foreign-exchange reserves being built by countries that have recently been the winners in the global trading game. As of December, the International Monetary Fund lists Japan's reserves at $847 billion, China's at $819 billion, Taiwan's at $253 billion, South Korea's at $210 billion, Russia's at $194 billion, and India's at $137 billion. These reserves, held overwhelmingly as US dollars, are the potential gasoline just waiting for the match to set alight a huge global economic conflagration.. More likely there would be a sharp overshoot in the dollar-selling, leading to a perhaps 20-30% decline in dollar values within a very short time. For the US, this would mean a sharp rise in the prices of everything it imports, especially crude oil. That would mean inflation, with the Federal Reserve raising interest rates to contain it, or maybe the economy would bypass the intermediate inflationary phase and head straight into deep recession or depression. Either way, the great run of US prosperity would be over. Worldwide, along with the global contractionary effects of US economic growth suddenly stopping or going into reverse, the effect of an almost instantaneous 20% haircut in the value of the world's financial reserves would be no picnic, either.. Specifically, will the nation still think it's so important to control the sands of Samarra, or the streets of Fallujah, or, for that matter, those of Baghdad if, like the signs say in US doctors' offices, "payment is expected at the time of service"? . - Prev by Date: Rachel Corrie's family appeals lawsuit against bulldozer-maker - Next by Date: Censorship of the Worst Kind - Previous by thread: Rachel Corrie's family appeals lawsuit against bulldozer-maker - Next by thread: Censorship of the Worst Kind - Index(es):
http://newsgroups.derkeiler.com/Archive/Alt/alt.gathering.rainbow/2006-03/msg03452.html
CC-MAIN-2013-20
refinedweb
1,527
51.82
#include <iostream> using namespace std; int main() { cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!! return 0; } [Updated on: Wed, 29 September 2010 15:50] Report message to a moderator [Updated on: Thu, 30 September 2010 15:07] java.io.IOException: Pipe closed [Updated on: Thu, 20 January 2011 15:03] [Updated on: Wed, 13 April 2011 10:31] I encountered similar problem.The following method worked for me: 1 Goto Project->Properties->Run/Debug Settings, choose the .exe file and press "Edit" 2 In the "Environment" tag, press "New", set it as: "Name:PATH" "Value:C:\MinGW\bin" [Updated on: Sun, 21 August 2011 19:15] Hi Guys, I fixed the problem on my win 7 x64 PC. In the Eclipse window go to Preferences > C/C++ (Expand it) > Environment > Add: "Name:PATH" "Value:C:\MinGW\bin"
http://www.eclipse.org/forums/index.php/mv/msg/197552/636493/
CC-MAIN-2013-20
refinedweb
137
60.14
While working in Director 12, the sounds all work fine in authoring mode (Mac - Mountain Lion), but do not play in the projector. Each sound is placed in sound channel 2 with a 'wait until end of sound' in the timeline channel. When playing the projector, it appears that the 'wait' in the timeline channel is being ignored. The file was originally created in Director 11 and updated into 12. Any ideas? Thanks for your help! It sounds (no pun intended) like you have a missing xtra. Scan through the list at Modify > Movie > Xtras ... looking for likely candidates to add. If you find any, try adding them, save and re-publish Thank you, Sean! Just added the Sound Import Export xtra and all is well:) A quick follow up: when you say Each sound is placed in sound channel 2 with a 'wait until end of sound' in the timeline channel. are you referring to a behavior/script you have added to the script channel, or a setting in the Tempo channel. Those settings in the Tempo channel should always be ignored and a script used in their place. Yes - I am referring to a setting in to the Tempo channel. I started with Director 4, and I guess I haven't been paying enough attention along the road to Director 12, but why are these 'wait' tempo settings offered as an option if they should be ignored? Your xtra fix did work, but I'm just curious - thanks! why are these 'wait' tempo settings offered as an option if they should be ignored? I think it's a legacy from years ago (Director 4) when scripting capabilities weren't powerful enough to bypass some of the options the tempo channel offers. For example, here is a behavior that will wait for a sound in a channel, but isn't limited to channnel 1 or 2: -- Frame: wait for sound in channel -- can only be attached to script channel property myMonitorChannel on isOKToAttach(me, sType, sNum) return (sType = #script) end on getPropertyDescriptionList pdl = [:] props = [:] props[#comment] = "Sound channel to wait for:" props[#format] = #integer props[#default] = 1 props[#range] = [#min: 1, #max: 8] pdl[#myMonitorChannel] = props return pdl end on exitFrame me if sound(myMonitorChannel).isBusy() then _movie.go(_movie.frame) end Thanks again, Sean. Looks like I have some homework to look forward to!
https://forums.adobe.com/thread/1284199
CC-MAIN-2018-30
refinedweb
396
70.13
Hallo, Were you able to fix this problem? I am using the embedded openEJB with Tomcat 6 and have the exact same problem. I keep getting NameNotFoundException. Could you please help? ManojS wrote: > > Hello, > > I was playing with openejb and a test ejb application in my machine. My > intention was to identify how much openejb is useful for me as an ejb > container, so that I can recommend to use at my workplace. While I was > trying to integrate openejb along with the application I cannot able to > lookup the datasource connection defined in the openejb.conf file. If I > explain in detail, my openejb.conf has the following connection > configuration. > > <Connector id="MyDatasource" type="Datasource"> > JdbcDriver org.gjt.mysql.Driver > JdbcUrl jdbc:mysql://localhost:3306/test_db > UserName root > Password 12345 > jtamanaged true > </Connector> > > I am using the "Default Stateless Container" with ctype="STATELESS". And > my ejb code (my ejbs are stateless session beans) for datasource lookup is > as follows, > > public Connection getConnection () throws Exception { > Context ctx = new InitialContext(); > Datasource ds = (Datasource) ctx.lookup( "MyDatasource" ); > return (ds!=null?ds.getConnection():null); > } > > This code is throwing a javax.naming.NameNotFoundException. I tried with > various other JNDI names like "java:comp/MyDatasource", > "java:openejb/MyDatasource" etc. But the same result. > > The openejb version I am using is 1.0, because the EJB version I was using > is 2.0. > > Can anyone help me to figure out what is the JNDI name to use for > connector lookup ? > > Thanks in advance. > > Manoj. > > -- View this message in context: Sent from the OpenEJB User mailing list archive at Nabble.com.
http://mail-archives.us.apache.org/mod_mbox/tomee-users/200805.mbox/%3C17201828.post@talk.nabble.com%3E
CC-MAIN-2019-18
refinedweb
264
51.55
2016-09-02 04:53 AM - edited 2016-09-02 04:54 AM Hello, I have ocum 6.4p1. when i go in the detail of a virtual machine and want to list the cifs shares, this list is not complet that only list the root shares for exemple : svm1 with a volume named data_svm1 volume is mounted in namespace as /data_svm1 i make a directory svm1\data_svm1\test if a make 2 shares share1 pointing on svm1\data_svm1 share2 pointing on svm1\data_svm1\test both share are accessible but only share1 is listed in ocum if i delete share1 share2 is accessible but not listed in ocum is that normal ? it is a possibility to list all shares level 1,level 2 ....? thx 2016-09-02 07:12 AM This is because you have mounted the test volume under svm1\data_svm1. You already created a share on svm1\data_svm1, You can access svm1\data_svm1 and svm1\data_svm1\test from the share1 it self. That is the reason it is showing single share in your case.... :-) I am able to see all the shares in my OCUM and i am also using 6.4p1. I have mounted all my volumes under root (/). Please find the attached screenshot for your reference. 2016-09-05 01:49 AM Hi, in your screen we see only first level shares if you create a folder under /vol_infra like /vol_infra/testlv1 you shares /vol_infra/test as "testlv1" and delete the /vol_infra share so the user go directly to /vol_infra/test the in OCUM the share "testlv1" did not appear look my screens windows and system manage show share " testlv1" path /data_svm3/testlv1 OCUM side show only C$ shares
https://community.netapp.com/t5/OnCommand-Storage-Management-Software-Discussions/ocum-6-4P1-cifs-shares-list/td-p/122834
CC-MAIN-2018-30
refinedweb
283
71.07
You're enrolled in our new beta rewards program. Join our group to get the inside scoop and share your feedback.Join group Join the community to find out what other Atlassian users are discussing, debating and creating. Hey :) i want to search linked issues with the same custom field value like the parent issue. If i return the issues i need, i want to fill a field with "new Date()"... I don't know how to end the following script :D Result type is my query... Or the whole script is stupid.... pls help. --------- issueManager = ComponentAccessor.getIssueManager() def issueTypeGroup = "(XX, YY)" def fieldName = "Important-Number" def linkeTypeName = "VIP" def cFieldValue = issue.getAsString(fieldName) if (cFieldValue == null) { return } if (cFieldValue.size() == 0){ return } def query = jqlQueryParser.parseQuery("issuetype" + " in " + issueTypeGroup + " AND " + fieldName + " ~ " + cField
https://community.atlassian.com/t5/Jira-questions/JQL-search-with-Groovy-and-custom-field/qaq-p/1674843
CC-MAIN-2021-21
refinedweb
133
60.11
My favourite technology web site is updated throughout the day. I thought it would be nice to have a program that checked every 30 minutes for updates and told me what stories were there. DescriptionMy favourite technology web site is updated throughout the day. I thought it would be nice to have a program that checked every 30 minutes for updates and told me what stories were there.For the main page of my favourite site go to slashdot also has a page which shows their main page stories as XML. To see this go to idea now is to build an application that sits in the taskbar tray of a win2000 desktop and every 30 minutes go to the above site and modify the context menu to display links to the latest stories. I can then click the one I want to read and launch a browser.The example code below shows how to read content from a web site which in my case is an xml page. I then parse the xml data and output just the story title and the URL.Part two of this app hopefully will be a complete utility which will sit in the taskbar tray. Note applications like this could be looking at stock tickers or anything. Also if more web sites used xml then parsing the data becomes very easy.Source Code//Title : Webtest //Author : John O'Donnell //Email : wincepro@hotmail.com //Date : 31/05/01 namespace Webtest { using System; using System.IO; using System.Net; using System.Text; using System.Xml; public class Class1 { public Class1() { } public static int Main(string[] args) { XmlDocument doc = new XmlDocument(); WebRequest wr; WebResponse ws; StreamReader sr; string line; try { wr = WebRequestFactory.Create(); ws = wr.GetResponse(); sr = new StreamReader(ws.GetResponseStream(),Encoding.ASCII); line=sr.ReadToEnd(); //Read entire document doc.LoadXml(line); //Load the text into the xml document } catch(Exception e) { Console.WriteLine ("Exception: {0}", e.ToString()); } try { //get the story and url nodes XmlNodeList titles = doc.GetElementsByTagName("title"); XmlNodeList urls = doc.GetElementsByTagName("url"); for (int i=0; i < titles.Count; i++) { //note InnerXml returns just data, OuterXml returns tags as well Console.WriteLine(titles.Item(i).InnerXml); Console.WriteLine(urls.Item(i).InnerXml); } } catch (Exception e) { Console.WriteLine (e.ToString()); } return 0; } } } View All View All
https://www.c-sharpcorner.com/article/web-scanner-part-1/
CC-MAIN-2021-49
refinedweb
382
68.16
Fred Drake wrote: >. By "is", I'm sure you mean "needs to be". Specifying setuptools in install_requires is pointless chicken-and-egg'ing. But maybe I mean "setup_requires" thanks to setuptools "interesting" parameter naming ;-) >. Fair point. >> I'll say it again: it seems pointless specifying a requirement that has to >> be met before any requirement specifications can even be processed... > > It doesn't sound to me like you've used buildout nearly as much as easy install. Er? I *only* use buildout, however, I think I may have exempted myself by avoiding namespace packages until PEP 382 is done, dusted and in a python release. Chris -- Simplistix - Content Management, Batch Processing & Python Consulting -
https://mail.python.org/pipermail/distutils-sig/2009-October/014205.html
CC-MAIN-2016-44
refinedweb
113
57.98
CNN model does not load inside Visual Studio 2017 using dnn.readNetFromTensorflow Hello everyone! I have created a simple CNN model which I froze into tf_model.pb file and I have tried loading it using open cv dnn.readNetFromTesnorflow(model_path) method inside Jupyter Notebook and it works perfectly. The problem is when I try to load it inside Visual Studio 2017, for some reason it does not load correctly. When I try to print out number of layers I get 1, and that 1 is not even a layer. Here is my code: #include <iostream> #include <opencv2/opencv.hpp> #include <opencv2/dnn.hpp> #include <vector> #include <stdio.h> #include <stdlib.h> #include <string.h> using namespace std; using namespace cv; using namespace cv::dnn; int main(int argc, char** argv) { class CharNet { private: Net network; string output_layer; public: CharNet(string path) { try { cout << "Path: "<< path << endl; network = readNetFromTensorflow(path); vector<String> network_layers = network.getLayerNames(); cout << "There are "<<network_layers.size()<< " layers" << endl; for (int i = 0; i < network_layers.size(); i++) { cout << network_layers[i] << endl; if ( network_layers[i].find("Softmax") != std::string::npos ) { cout << "Output Layer: "<< network_layers[i] << endl; output_layer = network_layers[i]; break; } } } catch (cv::Exception& e) { cerr << "Exception: " << e.what() << endl; if (network.empty()) { cerr << "Can't load the model" << endl; } } } }; string model = "C:/Users/stefan_cepa995/source/repos/OpenCV_Test/OpenCV_Test/tf_model.pb"; CharNet* obj = new CharNet(model); return 0; } Since the model is not loaded correctly I never enter the for loop. Does anyone have any idea whats going on?
https://answers.opencv.org/question/204084/cnn-model-does-not-load-inside-visual-studio-2017-using-dnnreadnetfromtensorflow/
CC-MAIN-2020-45
refinedweb
249
61.33
A chunk is the building block for buffers. More... #include <BufferDetail.hh> A chunk is the building block for buffers. A chunk is backed by a memory block, and internally it maintains information about which area of the block it may use, and the portion of this area that contains valid data. More than one chunk may share the same underlying block, but the areas should never overlap. Chunk holds a shared pointer to an array of bytes so that shared blocks are reference counted. When a chunk is copied, the copy shares the same underlying buffer, but the copy receives its own copies of the start/cursor/end pointers, so each copy can be manipulated independently. This allows different buffers to share the same non-overlapping parts of a chunk, or even overlapping parts of a chunk if the situation arises. Foreign buffer constructor, uses the supplied data for this chunk, and only for reading. Remove readable bytes from the back of the chunk by moving the chunk cursor position. Remove readable bytes from the front of the chunk by advancing the chunk start position.
http://avro.apache.org/docs/1.4.0/api/cpp/html/classavro_1_1detail_1_1Chunk.html
CC-MAIN-2015-27
refinedweb
186
69.92
Methods are remote functions that Meteor clients can invoke with Meteor.call. Meteor.methods(methods) import { Meteor } from 'meteor/meteor'(ddp-server/livedata_server.js, line 1586) Defines functions that can be invoked over the network by clients. methodsObject Dictionary whose keys are method names and values are functions. Example: Meteor.methods({ foo(arg1, arg2) { check(arg1, String); check(arg2, [Number]); // Do stuff... if (/* you want to throw an error */) { throw new Meteor.Error('pants-not-found', "Can't find my pants"); } return 'some return value'; }, bar() { // Do other stuff... return 'baz'; } }); Calling methods on the server defines functions that can be called remotely by clients. They should return an EJSON-able value or throw an exception. Inside your method invocation, this is bound to a method invocation object, which provides the following: isSimulation: a boolean value, true if this invocation is a stub. unblock: when called, allows the next method from this client to begin running. userId: the id of the current user. setUserId: a function that associates the current client with a user. connection: on the server, the connection this method call was received on. Calling methods on the client defines stub functions associated with server methods of the same name. You don’t have to define a stub for your method if you don’t want to. In that case, method calls are just like remote procedure calls in other systems, and you’ll have to wait for the results from the server. If you do define a stub, when a client invokes a server method it will also run its stub in parallel. On the client, the return value of a stub is ignored. Stubs are run for their side-effects: they are intended to simulate the result of what the server’s method will do, but without waiting for the round trip delay. If a stub throws an exception it will be logged to the console. You use methods all the time, because the database mutators ( insert, update, remove) are implemented as methods. When you call any of these functions on the client, you’re invoking their stub version that update the local cache, and sending the same write request to the server. When the server responds, the client updates the local cache with the writes that actually occurred on the server. You don’t have to put all your method definitions into a single Meteor.methods call; you may call it multiple times, as long as each method has a unique name. If a client calls a method and is disconnected before it receives a response, it will re-call the method when it reconnects. This means that a client may call a method multiple times when it only means to call it once. If this behavior is problematic for your method, consider attaching a unique ID to each method call on the client, and checking on the server whether a call with this ID has already been made. Alternatively, you can use Meteor.apply with the noRetry option set to true. Read more about methods and how to use them in the Methods article in the Meteor Guide. this.userId The id of the user that made this method call, or null if no user was logged in. The user id is an arbitrary string — typically the id of the user record in the database. You can set it with the setUserId function. If you’re using the Meteor accounts system then this is handled for you. this.setUserId(userId) Set the logged in user. userIdString or null The value that should be returned by userId on this connection. Call this function to change the currently logged-in user on the connection that made this method call. This simply sets the value of userId for future method calls received on this connection. Pass null to log out the connection. If you are using the built-in Meteor accounts system then this should correspond to the _id field of a document in the Meteor.users collection. setUserId is not retroactive. It affects the current method call and any future method calls on the connection. Any previous method calls on this connection will still see the value of userId that was in effect when they started. If you also want to change the logged-in user on the client, then after calling setUserId on the server, call Meteor.connection.setUserId(userId) on the client. this.isSimulation Access inside a method invocation. Boolean value, true if this invocation is a stub. this.unblock() Call inside a method invocation. Allow subsequent method from this client to begin running in a new fiber. On the server, methods from a given client run one at a time. The N+1th invocation from a client won’t start until the Nth invocation returns. However, you can change this by calling this.unblock. This will allow the N+1th invocation to start running in a new fiber. this.connection Access inside a method invocation. The connection that this method was received on. null if the method is not associated with a connection, eg. a server initiated method call. Calls to methods made from a server method which was in turn initiated from the client share the same connection. new Meteor.Error(error, [reason], [details]) import { Meteor } from 'meteor/meteor'(meteor/errors.js, line 71) This class represents a symbolic error thrown by a method. errorString A string code uniquely identifying this kind of error. This string should be used by callers of the method to determine the appropriate action to take, instead of attempting to parse the reason or details fields. For example: // on the server, pick a code unique to this error // the reason field should be a useful debug message throw new Meteor.Error("logged-out", "The user must be logged in to post a comment."); // on the client Meteor.call("methodName", function (error) { // identify the error if (error && error.error === "logged-out") { // show a nice error message Session.set("errorMessage", "Please log in to post a comment."); } }); For legacy reasons, some built-in Meteor functions such as check throw errors with a number in this field. reasonString Optional. A short human-readable summary of the error, like 'Not Found'. detailsString Optional. Additional information about the error, like a textual stack trace. If you want to return an error from a method, throw an exception. Methods can throw any kind of exception. But Meteor.Error is the only kind of error that a server will send to the client. If a method function throws a different exception, then it will be mapped to a sanitized version on the wire. Specifically, if the sanitizedError field on the thrown error is set to a Meteor.Error, then that error will be sent to the client. Otherwise, if no sanitized version is available, the client gets Meteor.Error(500, 'Internal server error'). Meteor.call(name, [arg1, arg2...], [asyncCallback]) import { Meteor } from 'meteor/meteor'(ddp-client/livedata_connection.js, line 724) Invokes a method passing any number of arguments. nameString Name of method to invoke arg1, arg2...EJSON-able Object Optional method arguments asyncCallbackFunction Optional callback, which is called asynchronously with the error or result after the method is complete. If not provided, the method runs synchronously if possible (see below). This is how to invoke a method. It will run the method on the server. If a stub is available, it will also run the stub on the client. (See also Meteor.apply, which is identical to Meteor.call except that you specify the parameters as an array instead of as separate arguments and you can specify a few options controlling how the method is executed.) If you include a callback function as the last argument (which can’t be an argument to the method, since functions aren’t serializable), the method will run asynchronously: it will return nothing in particular and will not throw an exception. When the method is complete (which may or may not happen before Meteor.call returns), the callback will be called with two arguments: error and result. If an error was thrown, then error will be the exception object. Otherwise, error will be undefined and the return value (possibly undefined) will be in result. // Asynchronous call Meteor.call('foo', 1, 2, (error, result) => { ... }); If you do not pass a callback on the server, the method invocation will block until the method is complete. It will eventually return the return value of the method, or it will throw an exception if the method threw an exception. (Possibly mapped to 500 Server Error if the exception happened remotely and it was not a Meteor.Error exception.) // Synchronous call const result = Meteor.call('foo', 1, 2); On the client, if you do not pass a callback and you are not inside a stub, call will return undefined, and you will have no way to get the return value of the method. That is because the client doesn’t have fibers, so there is not actually any way it can block on the remote execution of a method. Finally, if you are inside a stub on the client and call another method, the other method is not executed (no RPC is generated, nothing “real” happens). If that other method has a stub, that stub stands in for the method and is executed. The method call’s return value is the return value of the stub function. The client has no problem executing a stub synchronously, and that is why it’s okay for the client to use the synchronous Meteor.call form from inside a method body, as described earlier. Meteor tracks the database writes performed by methods, both on the client and the server, and does not invoke asyncCallback until all of the server’s writes replace the stub’s writes in the local cache. In some cases, there can be a lag between the method’s return value being available and the writes being visible: for example, if another method still outstanding wrote to the same document, the local cache may not be up to date until the other method finishes as well. If you want to process the method’s result as soon as it arrives from the server, even if the method’s writes are not available yet, you can specify an onResultReceived callback to Meteor.apply. Meteor.apply(name, args, [options], [asyncCallback]) import { Meteor } from 'meteor/meteor'(ddp-client/livedata_connection.js, line 768) Invoke a method passing an array of arguments. nameString Name of method to invoke argsArray of EJSON-able Objects Method arguments asyncCallbackFunction Optional callback; same semantics as in Meteor.call. waitBoolean (Client only) If true, don't send this method until all previous method calls have completed, and don't send any subsequent method calls until this one is completed. onResultReceivedFunction (Client only) This callback is invoked with the error or result of the method (just like asyncCallback) as soon as the error or result is available. The local cache may not yet reflect the writes performed by the method. noRetryBoolean (Client only) if true, don't send this method again on reload, simply call the callback an error with the error code 'invocation-failed'. throwStubExceptionsBoolean (Client only) If true, exceptions thrown by method stubs will be thrown instead of logged, and the method will not be invoked on the server. Meteor.apply is just like Meteor.call, except that the method arguments are passed as an array rather than directly as arguments, and you can specify options about how the client executes the method. Customize rate limiting for methods and subscriptions. By default, DDPRateLimiter is configured with a single rule. This rule limits login attempts, new user creation, and password resets to 5 attempts every 10 seconds per connection. It can be removed by calling Accounts.removeDefaultRateLimit(). To use DDPRateLimiter for modifying the default rate-limiting rules, add the ddp-rate-limiter package to your project in your terminal: meteor add ddp-rate-limiter DDPRateLimiter.addRule(matcher, numRequests, timeInterval, callback) import { DDPRateLimiter } from 'meteor/ddp-rate-limiter'(ddp-rate-limiter/ddp-rate-limiter.js, line 70) Add a rule that matches against a stream of events describing method or subscription attempts. Each event is an object with the following properties: type: Either "method" or "subscription" name: The name of the method or subscription being called userId: The user ID attempting the method or subscription connectionId: A string representing the user's DDP connection clientAddress: The IP address of the user Returns unique ruleId that can be passed to removeRule. matcherObject Matchers specify which events are counted towards a rate limit. A matcher is an object that has a subset of the same properties as the event objects described above. Each value in a matcher object is one of the following: a string: for the event to satisfy the matcher, this value must be equal to the value of the same property in the event object a function: for the event to satisfy the matcher, the function must evaluate to true when passed the value of the same property in the event object Here's how events are counted: Each event that satisfies the matcher's filter is mapped to a bucket. Buckets are uniquely determined by the event object's values for all properties present in both the matcher and event objects. numRequestsnumber number of requests allowed per time interval. Default = 10. timeIntervalnumber time interval in milliseconds after which rule's counters are reset. Default = 1000. callbackFunction function to be called after a rule is executed. Custom rules can be added by calling DDPRateLimiter.addRule. The rate limiter is called on every method and subscription invocation. A rate limit is reached when a bucket has surpassed the rule’s predefined capactiy, at which point errors will be returned for that input until the buckets are reset. Buckets are regularly reset after the end of a time interval. Here’s example of defining a rule and adding it into the DDPRateLimiter: // Define a rule that matches login attempts by non-admin users. const loginRule = { userId(userId) { const user = Meteor.users.findOne(userId); return user && user.type !== 'admin'; }, type: 'method', name: 'login' }; // Add the rule, allowing up to 5 messages every 1000 milliseconds. DDPRateLimiter.addRule(loginRule, 5, 1000); DDPRateLimiter.removeRule(id) import { DDPRateLimiter } from 'meteor/ddp-rate-limiter'(ddp-rate-limiter/ddp-rate-limiter.js, line 85) Removes the specified rule from the rate limiter. If rule had hit a rate limit, that limit is removed as well. idstring 'ruleId' returned from addRule DDPRateLimiter.setErrorMessage(message) import { DDPRateLimiter } from 'meteor/ddp-rate-limiter'(ddp-rate-limiter/ddp-rate-limiter.js, line 28) Set error message text when method or subscription rate limit exceeded. messagestring or Function Functions are passed in an object with a timeToReset field that specifies the number of milliseconds until the next method or subscription is allowed to run. The function must return a string of the error message. © 2011–2017 Meteor Development Group, Inc. Licensed under the MIT License.
http://docs.w3cub.com/meteor~1.5/api/methods/
CC-MAIN-2018-43
refinedweb
2,508
56.45
Managing Shared Storage in a Sun Cluster 3.0 Environment With Solaris Volume Manager Software - Using Solaris Volume Manager Software With Sun Cluster 3.0 Framework - Configuring Solaris Volume Manager Software in the Sun Cluster 3.0 Environment - Advantages of Using Solaris Volume Manager Software in a Sun Cluster 3.0 Environment - Ordering Sun Documents With Sun™ Cluster 3.0 software, you can use two volume managers: VERITAS Volume Manager (VxVM) software, and Sun's Solaris™ Volume Manager software, which was previously called Solstice DiskSuite™ software. Traditionally, VxVM has been the volume manager of choice for shared storage in enterprise-level configurations. In this Sun BluePrints™ OnLine article, we describe a free and easy-to-use alternative, Solaris Volume Manager software, which is part of the Solaris™ 9 Operating Environment (Solaris 9 OE). This mature product offers similar functionality to VxVM. Moreover, it is tightly integrated into the Sun Cluster 3.0 software framework and, therefore, should be considered to be the volume manager of choice for shared storage in this environment. It should be noted that Solaris Volume Manager software cannot be used to provide volume management for Oracle RAC/OPS clusters. To support our recommendation to use Solaris Volume Manager software, we present the following topics: "Using Solaris Volume Manager Software With Sun Cluster 3.0 Framework" on page 2 explains how Solaris Volume Manager software functions in a Sun Cluster 3.0 environment. "Configuring Solaris Volume Manager Software in the Sun Cluster 3.0 Environment" on page 10 provides a run book and a reference implementation for creating disksets and volumes (metadevices)1 in a Sun Cluster 3.0 framework. "Advantages of Using Solaris Volume Manager Software in a Sun Cluster 3.0 Environment" on page 15 summarizes the advantages of using Solaris Volume Manager software for shared storage in a Sun Cluster 3.0 environment. NOTE The recommendations presented in this article are based on the use of the Solaris 9 OE and Sun Cluster 3.0 update 3 software. Using Solaris Volume Manager Software With Sun Cluster 3.0 Framework Before we present our reference configuration, we describe some concepts to help you understand how Solaris Volume Manager software functions in a Sun Cluster 3.0 environment. Specifically, we focus on the following topics: Sun Cluster software's use of DID (disk ID) devices to provide a unique and consistent device tree on all cluster nodes. Solaris Volume Manager software's use of disksets, which enable disks and volumes to be shared among different nodes, and the diskset's representation in the cluster called a device group. The use of mediators to enhance the tight replica quorum (which is different from the cluster quorum) rule of Solaris Volume Manager software, and to allow clusters to operate in the event of specific multiple failures. The use of soft partitions and the mdmonitord daemon with Solaris Volume Manager software. While these components are not related to the software's use in a Sun Cluster environment, they should be considered part of any good configuration. Using DID Names to Ensure Device Path Consistency With Sun Cluster 3.0 software, it is not necessary to have an identical hardware configuration on all nodes. However, different configurations may lead to different logical Solaris OE names on each node. Consider a cluster where one node has a storage array attached on a host bus adapter (HBA) in the first peripheral component interconnect (PCI) slot. On the other node, the array is attached to an HBA in the second slot. A shared disk on target 30 may end up being referred to as /dev/rdsk/c1t30d0 on the first node and as /dev/rdsk/c2t30d0 on the other node. In this case, the physical Solaris OE device path is different on each node and it is likely that the major-minor number combination is different, as well. In a non-clustered environment, Solaris Volume Manager software uses the logical Solaris OE names as building blocks for volumes. However, in a clustered environment, the volume definitions are accessible on all the nodes and should, therefore, be consistent; the name and the major/minor numbers should be consistent across all the nodes. Sun Cluster software provides a framework of consistent and unique disk names and major/minor number combinations. Such names are created when you install the cluster and they are referred to as DID names. They can be found in /dev/did/rdsk and /dev/did/dsk and are automatically synchronized on the cluster nodes such that the names and the major/minor numbers are consistent between nodes. Sun Cluster 3.0 uses the device ID of the disks to guarantee that the same name exists for a given disk in the cluster. Always use DID names when referring to disk drives to create disksets and volumes with Solaris Volume Manager software in a Sun Cluster 3.0 environment. Using Disksets to Share Disks and Volumes Among Nodes Disksets, which are a component of Solaris Volume Manager, are used to store the data within a Sun Cluster environment. On all nodes, local state database replicas must be created. These local state database replicas contain configuration information for locally created volumes. For example, volumes that are part of the mirrors on the boot disk. Local state database replicas also contain information about disksets that are created in the cluster: The name of the set, the names2 of the hosts that can own the set, the disks in it and whether they have a replica on them and, if configured, the mediator hosts. This is a major difference between Solaris Volume Manager software and VxVM, because in VxVM, each diskgroup is self-contained: Each disk within the group contains the group to which it belongs and the host that currently owns the group. If the last disk in a VxVM diskgroup is deleted, the group is deleted by definition. At any one time, a diskset has a single host that has access to it. The node that has access is deemed to be the owner of the diskset and the action of getting ownership is called "take" and the action of relinquishing ownership is called "release." In VxVM terms, the take/release of a diskset are the import/export of a diskgroup. The owner of a diskset is called the current primary of that diskset. This means that although more nodes can be attached to the diskset and can potentially take the diskset upon failure of the primary node, only one node can effectively do input/output (I/O) to the volumes in the diskset. The term shared storage merits further explanation. They are not shared in the sense that all nodes access the disks simultaneously, but in the sense that different nodes are potential primaries for the set. The creation of disksets involves three steps. First, a diskset receives a name and a primary host. This action creates an entry for the diskset in the local state database of that host. While Solaris Volume Manager allows for a maximum of 8 hosts, Sun Cluster (at this time) only supports up to 4 hosts. The rpc.metad daemon on the first node contacts the rpc.metad daemon on the second host, instructing it to create an entry for the diskset in the second host's local state database. Now, disks can be added to the diskset. Again, the primary hosts rpc.metad daemon will contact the second host so that the local state databases on both nodes contain the same information. Note you can add disks to any node that can potentially own the diskset and the request is forwarded (proxied) to the primary node. This is done through the rpc.metacld daemon, which allows you to administer disksets from any cluster node. Neither rpc.metad and rpc.metacld should be hardened out of a cluster that is using Solaris Volume Manager software because they are both essential to the operation of the Solaris Volume Manager software components. When you add a new disk to a disk set, Solaris Volume Manager software). NOTE The minimal size for slice seven will likely change in the future, based on a variety of factors, including the size of the state database replica and information to be stored in the state database replica. For use in disk sets, disks must have a slice seven that meets specific criteria: Starts at sector 0 Includes enough space for disk label and state database replicas Cannot be mounted Does not overlap with any other slices, including slice two If the existing partition table does not meet these criteria, Solaris Volume Manager software will repartition the disk. A small portion of each drive is reserved in slice 7 for use by Solaris Volume Manager software. The remainder of the space on each drive is placed into slice 0. Any existing data on the disks is lost by repartitioning. After you add a drive to a disk set, you may repartition it as necessary, with the exception that slice 7 is not altered in any way. Using Device Groups to Manage Disks and Volumes Sun Cluster 3.0 software provides automatic exporting and taking of Solaris Volume Manager disksets and VxVM diskgroups. To accomplish this, you have to identify the diskset or diskgroup to the cluster. For each device (disk, tape, Solaris Volume Manager diskset, or VxVM diskgroup) that should be managed by the cluster, ensure that there is an entry in the cluster configuration repository. When a diskset or diskgroup is known to the cluster, it is referred to as a device group. A device group is an entry in the cluster repository that defines extra properties for the diskgroup or diskset. A device group can have the following characteristics: A node list that corresponds to the node list defined in the diskset. A preferred node where the cluster attempts to bring the device group online when the cluster boots. This effectively means that when all cluster nodes are booted at the same time, the diskset is taken by its preferred node. A failback policy, that if set to true, migrates the disk set to the preferred node if the node is online. If the preferred node joins the cluster later, it will become the owner of the diskset (that is, the diskset will switch from the node that currently owns it to the preferred node). Sun Cluster software also provides extensive failure fencing mechanisms to avoid data access by unauthorized nodes during device group transitions. One of the major advantages of using Solaris Volume Manager software in a Sun Cluster 3.0 environment is that the creation and deletion of device groups does not involve extra administration. When you create or delete a diskset with Solaris Volume Manager software commands, the cluster framework is automatically notified that it should create or delete a corresponding entry in the Cluster Configuration repository. You can also manually change the preferred node and failback policy with standard cluster interfaces. Using Mediators to Manage Replica Quorum Votes Disksets have their own replicas, which are added to a disk when the disk is put into the diskset, provided that the maximum number of replicas has not been exceeded (50). It is possible to manually administer these replicas through the metadb command, but generally this is not required. The need to do so is discussed in the next section. Replicas should be evenly distributed across the storage enclosures that contain the disks, and they should be evenly distributed across the disks on a per-disk-controller basis. In an ideal environment, this distribution means that any one failure in the storage (disk, controller, or storage enclosure) does not effect the operation of Solaris Volume Manager software. In a physical configuration that has an even number of storage enclosures, the loss of half of the storage enclosures (for example, due to power loss) leaves only 50 percent of the diskset replicas available. While the diskset is owned by a node, this will not create a problem. However, if the diskset is released, on a subsequent take, the replicas will be marked as being stale because the replica quorum of greater than 50 percent will not have been reached. This means that all the data on the diskset will be read-only, and operator intervention will be required. If, at any point, the number of available replicas for either a diskset or the local ones falls below 50 percent, the node will abort itself to maintain data integrity. To enhance this feature, you can configure a set to have mediators. Mediators are hosts that can import [take] a diskset, and, when required, they provide an additional vote when a quorum vote is required (for example, on a diskset import [take]). To assist the replica quorum requirement, mediators also have a quorum requirement that either greater than 50 percent of them are available, or the available mediators are marked as being up to date, this means the mediator is golden and is marked as such. Mediators, whether they are golden or not, are only used when a diskset is taken. If the mediators are golden, and one of the nodes is rebooted, when it starts up, the mediators on it will get the current state from the node that is still in the cluster. However, if all nodes in the cluster are rebooted when the mediators are golden, on startup, the mediators will not be golden and operator intervention will be required to take ownership of the diskset. The actual mediator information is held in the rpc.metamedd(1M) daemon. For example, if there are two hosts (node1 and node2) and two storage enclosures (pack1 and pack2), diskset replicas are distributed evenly between pack1 and pack2, and node1 owns the diskset. If pack1 dies, only 50 percent of diskset replicas are available and the mediators on both hosts are marked as golden. If node1 now dies, node2 can import [take] the diskset because 50 percent of the diskset replicas are available and the mediator on node2 is golden. If mediators were not configured, node2 would not have been able to import [take] the diskset without operator intervention. Mediators do not, however, protect against simultaneous failures. If both pack1 and node1 fail at the same time, the mediator on node2 will not have been marked as golden and there will not be an extra vote for the diskset replica quorum, making operator intervention necessary. Because the nodes should be on an uninterrupted power supply (UPS), which means the mediators should have enough time to be marked as golden, this type of failure is unlikely. Reasons to Manually Change the Replica Allocation Within a Diskset As alluded to in the previous paragraph, it is possible, even with mediators configured, to require administrator intervention under certain failure scenarios. One such scenario is that of a two room cluster. That is, each room has one node and one storage device. If a room fails, then any diskset that was owned by the node in that room will require manual intervention. On the surviving node, the administrator will need to take the set using the metaset or scswitch command and remove the replicas that are marked as errored. When this is done, the diskset needs to be released and retaken so it can gain write access to the configured metadevices. It is possible, by manually moving the replicas about, that the use of manual intervention can be minimized. This can be achieved by "weighting" one room over the other, such that if the non-weighted room fails, then the remaining room would be able to take the diskset. If the "weighted" room fails, manual intervention is required. To "weight" a room, add more replicas to the disks that reside in the room, or delete replicas on the disks that do not reside in that room. Using Soft Partitions as a Basis for File Systems After adding a disk to a diskset, you can modify the partition layout, that is break up the default slice 0 and spread the space between the slices (including slice 0). If slice 7 contains a replica, leave it alone to avoid corrupting the replica on it. Because Solaris Volume Manager software supports soft partitioning, we recommend that you leave slice 0 untouched. Consider a soft partition as a subdivision of a physical Solaris OE slice or as a subdivision of a mirror, redundant array of independent disks (RAID) 5, or striped volume. The number of soft partitions you can create is limited by the size of the underlying device and by the number of possible volumes (nmd, as defined in /kernel/drv/md.conf). The default number of possible volumes is 128. Note that all soft partitions created on a single diskset are part of one diskset and cannot be independently primaried to different nodes. Soft partitions are composed of a series of extents that are located at arbitrary locations on the underlying media. The locations are automatically determined by the software at initialization time. It is possible to manually set these locations, but it is not recommended for general day-to-day administration. Locations should be manually set only during recovery scenarios where the metarecover (1M) command is insufficient. You can create and use soft partitions in two ways: Create them on top of a physical disk slice and use them as building blocks for mirrors or RAID 5 volumes, just as you would use a physical slice. Create them on top of a mirror or RAID 5 volume. In our example, we use the second approach. We consider this the best solution for two reasons: Sizing and resizing soft partitions is limited only by the size of the underlying device. If the underlying device is a Solaris OE slice, it is not always possible to increase the size of the soft partition while keeping the file system on the slice intact. However, it is much easier to grow a Solaris Volume Manager software volume, and then grow the soft partition on top of it. Creating different soft partitions on top of a large mirrored volume allows you to use the Solaris Volume Manager software namespace more efficiently and consistently. Consider the following example: You create one large mirror (d2) on top of two submirrors (d0 and d1). On top of d2, you create soft partitions d10, d11, d12, and so on. On these soft partitions, you create file systems. If you did it the other way around, you would have to create soft partitions d10, d11, d12, and so on, as well as corresponding soft partitions on the other disks d20, d21, d22, and so on. Then, you would have to create the stripes to use as submirrors on top of the soft partitions and finally create the mirrors. In this scenario, you would have used twice as many soft partitions names and, therefore, more of the Solaris Volume Manager software namespace. While we recommend the second approach, keep in mind that a disadvantage of this approach is that you will have to perform a complete disk resync if the disk fails, while the first approach would only require a resync of the defined soft partitions. Using the mdmonitord Daemon to Enable Active Volume Monitoring The mdmonitord daemon quickly fails volumes that have faulty disk components. It does this by probing configured volumes, including volumes in disksets that are currently owned by the node where the daemon runs (note that the daemon runs on all the nodes in a cluster). The probe is a simple open(2) of the top level volume that causes the Solaris Volume Manager software kernel components to open underlying devices. The probe eventually causes the physical disk device to open. If the disk has failed, the probe will fail all the way back up the chain, and the daemon can take the appropriate action. If the volume is a mirror, the mirror must be in use for the submirror's component to be marked as errored. (That is, another application must have it open, for example, if it has a mounted file system on it). If the mirror is not open, the daemon reports an error and performs no other action to prevent unrequired resyncs for unused mirrors. In the case of a RAID5 device, the device fails right away because there is not as much redundancy as there is in a mirror (a second failure in the RAID5 device makes the device inoperable), and it is better to have the cost of the failure immediately. The mdmonitord daemon has two modes of operation: interrupt mode and periodic probing mode. In interrupt mode, the daemon waits for disk failure events. If the daemon detects a failure, it probes the configured volumes as previously described. This is the default behavior. In periodic probing mode, you can specify certain time intervals for the daemon to perform probes by giving the daemon the -t option, followed by the number of seconds between each probe. The daemon also waits for disk failure events. The mdmonitord daemon is useful if your system contains volumes that are accessed infrequently. Without the daemon, a disk failure can go unnoticed for quite some time, unless you manually check the configuration with the metastat -i command. This might not be a problem at first sight, but can be catastrophic if the failed disk is the cluster's quorum disk, or if an entire storage array has failed. These scenarios are described as follows: If a quorum disk fails and, subsequently, a node fails, cluster operation is seriously impaired. We recommend that you put the quorum disk in a diskset and make it part of a submirror so it is monitored by the mdmonitord daemon. Depending on the usage of the mirror, you might want to consider configuring the mdmonitord daemon to do timed probes. If the mirror is well used, that is, if it has plenty of I/O going to it, you might not want this. If mediators are configured, they provide extra votes to guarantee replica quorum. Moreover, if, after an array fails, the remaining replicas are updated, the mediators are set to golden. Now, if a node is lost, the golden status on the remaining node allows Solaris Volume Manager software to continue updating the replicas without intervention. Using the mdmonitord daemon to regularly check the status of volumes increases the possibility of replica updates after a storage array fails. If a host and disk fail at the same time then the mediators are not going to be golden and you will suffer an outage. However if the host is UPS protected (such that it is up for a period of time before power fails) then the mdmonitord could cause an update to the replicas to occur which means a mediator update and if the node then can fail (UPS has gone away) but the mediator will now be golden and we survive the failure, which we may now have done before. This is rather a corner case but does show that the mdmonitord could be used to provide a better uptime.
http://www.informit.com/articles/article.aspx?p=31762&amp;seqNum=4
CC-MAIN-2017-34
refinedweb
3,861
58.72
I have a palindrome set up in the system, and running fine. However, when I type "never odd or even" or "A Man, A Plan, A Canal, Panama", it didn't run properly as if these words in quotation marks are considered palindromes. Where is the loophole on my code re: palindromes esp more than one word //This palindrome project //requires for a determination and provide a better understanding //of such concept in C++ project. #include<iostream> #include<cstring> #include<cstdio> using namespace std; int main() { char word[30],rev[30],chr; cout<<"\t\tMy System.\n"; cout<<"\t\t\tMy Version\n\n"; do { cout<<"\nPlease enter word or number: "; cin>>word; int i, j; for(i = 0, j = strlen(word) - 1; j >= 0; i++, j--) rev[i] = word[j]; rev[i] = 0; if(strcmp(rev,word)==0) cout<<"The word "<<word<<" is considered a Palindrome."; else cout<<"The word "<<word<<" is not considered Palindrome."; cout<<"\n\nDo you want to try again? Please press Y or N: "; cin>>chr; } while(chr=='y'||chr=='Y'); cin.get (); return 0; }
https://www.daniweb.com/programming/software-development/threads/287985/determine-whether-is-palindrome-or-not
CC-MAIN-2017-17
refinedweb
180
72.26
Manages all the rendering at the level of the observer's surroundings. More... #include <LandscapeMgr.hpp> Manages all the rendering at the level of the observer's surroundings. This includes landscape textures, fog, atmosphere and cardinal points. I decided to put all these elements together in a single class because they are inherently linked, especially when we start moving the observer in altitude. Create a new landscape from the files which describe it. Reads a landscape.ini file which is passed as the first parameter, determines the landscape type, and creates a new object for the landscape of the proper type. The load member is then called, passing both parameters. Draw the landscape graphics, cardinal points and atmosphere. Reimplemented from StelModule.. Get the light pollution following the Bortle Scale. Get atmosphere fade duration in s. Get the order in which this module will draw it's objects relative to other modules. Reimplemented from StelModule. Get Cardinals Points color. Return a pseudo HTML formated string with all informations on the current landscape. Get the current landscape ID. Get the current landscape name. Get the default landscape ID. Return a pseudo HTML formated string with information from description or ini file. Get flag for displaying Atmosphere. Get flag for displaying Cardinals Points. Get flag for displaying Fog. Return the value of the flag determining if a change of landscape will update the observer location. Return the global landscape luminance, for being used e.g for setting eye adaptation.. This function searches for a file named "landscape.ini" in the root directory of the archive. If it is not found there, the function searches inside the topmost sub-directories (if any), but no deeper. If a landscape configuration file is found: The landscape identifier is either: The landscape identifier must be unique.. Set the light pollution following the Bortle Scale. Set atmosphere fade duration in s. Set Cardinals Points color. Change the current landscape to the landscape with the ID specified. Change the current landscape to the landscape with the name specified. Change the default landscape to the landscape with the ID specified. Set flag for displaying Atmosphere. Set flag for displaying Cardinals Points. Set flag for displaying Fog. Set the value of the flag determining if a change of landscape will update the observer location. Set the rotation of the landscape about the z-axis. This is intended for special uses such as when the landscape consists of a vehicle which might change orientation over time (e.g. a ship). Update time-dependent state. Includes: Implements StelModule.
http://stellarium.org/doc/0.11.4/classLandscapeMgr.html
CC-MAIN-2015-40
refinedweb
425
61.93
27 January 2010 16:24 [Source: ICIS news] TORONTO (ICIS news)--Germany’s economy should grow by 1.4% in 2010, after a 5.0% decline in 2009 from 2008, the country’s government said on Wednesday in its official economic report and forecast for the year. The 1.4% for 2010 is up by 0.2 percentage points from 1.2% growth the government had forecast in October. Even though capacity utilisation in ?xml:namespace> Exports were expected to increase by 5.1%, after a 14.7% decline in 2009 from 2008, it said. However, even with the increase, exports were not expected to regain their pre-crisis level this year, it added. At the same time, producers would continue to struggle with high costs and were likely to cut more jobs, with the unemployment rate forecast to average 8.9% in 2010, up from 8.2% in 2009, the government said. To help the economy, the government reduced the overall tax burden for families and companies by a total €24bn ($34bn), it said. At the same time, it promised a comprehensive reform to simplify the tax system and to reduce bureaucracy. While But in an economics update last week, Wiesbaden-based chemical employers group BAVC said even with 5% growth in 2010, chemical production would still be below its 2006 level. At the same time, ($1 = €0.71)
http://www.icis.com/Articles/2010/01/27/9329214/germany-boosts-official-2010-growth-forecast-to-1.4.html
CC-MAIN-2014-35
refinedweb
230
67.96
On Oct 15, 2012, at 3:11 PM, Richard Oudkerk shibturn@gmail.com wrote: On 12/10/2012 11:49pm, Guido van Rossum wrote: That said, the idea of a common API architected around async I/O, rather than non-blocking I/O, sounds interesting at least theoretically. (Oh, what a nice distinction.) ... How close would our abstracted reactor interface have to be exactly like IOCP? The actual IOCP API calls have very little to recommend them -- it's the implementation and the architecture that we're after. But we want it to be able to use actual IOCP calls on all systems that have them. One could use IOCP or select/poll/... to implement an API which looks like class AsyncHub: def read(self, fd, nbytes): """Return future which is ready when read is complete""" def write(self, fd, buf): """Return future which is ready when write is complete""" def accept(self, fd): """Return future which is ready when connection is accepted""" def connect(self, fd, address): """Return future which is ready when connection has succeeded""" def wait(self, timeout=None): """Wait till a future is ready; return list of ready futures""" A reactor could then be built on top of such a hub. So in general alle methods are async, even the wait() could be async if it returned a Furure, this way all methods would be of the same concept. I like this as a general API for all types of connections and all underlying OS' /Rene -- Richard Python-ideas mailing list Python-ideas@python.org
https://mail.python.org/archives/list/python-ideas@python.org/message/YGWZSDMBRYJYUIA2IFQ44UKSWS5CNPPT/
CC-MAIN-2022-21
refinedweb
259
64.34
It’s been a long time – New Year, small vacation, etc… Getting back to the blog. By the recommendation of my colleagues I took the Framework Design Guidelines book in the library. This is an interesting book. Unlike some other books where “evangelists” throw at you empty slogans about things they hardly understand, the guys that wrote this book seem to know very well what they are talking about. Even if you don’t agree with everything they say, the book provides an insight into the philosophy behind the .NET framework. Scope of The Book The subtitle of the book is “Conventions, Idioms, and Patterns for Reusable .NET libraries“. This is a little bit misleading. For the authors “reusable .NET libraries” means first and foremost the .NET framework. If you were to design another .NET framework, this would be a perfect book for you. In reality, the .NET framework is already there, and in many aspects it is quite different from the frameworks we, mere mortals, design: - The .NET framework is very, very big - It is designed for the audience of tens if not hundreds of thousands of developers - It has a release cycle measured in years - It is reviewed by the best specialists in the industry - It has hundreds if not thousands of beta testers - It is Microsoft. This carries a lot of weight. If Microsoft says that there is no data structure but array, and insists on calling that “list”, this has a good chance of becoming a new standard. After all, if G-d wanted us to use trees, He would put a tree class in the framework. 🙂 Assorted Comments Introduction p 5: Backward compatibility is not discussed in detail in this book. This is a shame. Backward compatibility is one of the most difficult subjects in framework design. Framework Design Fundamentals p 13: Frameworks must be designed starting from a set of usage scenarios and code samples implementing these scenarios. I totally agree. I’ve seen too many “ad hoc” APIs, that were very difficult, sometimes even impossible to use. If the authors thought about use cases first, these APIs would look much better. p 17: Usability Studies. Before making your API public, the authors suggest to give it a test drive: take a number of average developers not familiar with the API, give them the documentation and ask them to program a simple task. This is wonderful idea, albeit I don’t see how to effectively apply it on a scale much smaller than .NET framework. If I have a “local” framework that serves 15-20, or even 50 overworked developers, the logistics become problematic. You need to finish you work, write all the documentation, then find enough volunteers to do the study, develop a technique to interpret the results, and possibly do another iteration of design, coding and documentation. Good in theory, too much trouble for a small framework. As a side note, they admit Microsoft did not do usability studies for the System.IO namespace, and it turned out somewhat problematic. The stream classes seem to be a particularly tough nut to crack. For whatever reason, stream classes are a weak point not only in .NET, but also in C++, and in Java (of course, this is only my personal opinion; hey, this is my blog after all :-)). p 24: Naming. The simplest, but also often missed opportunity for making frameworks self-documenting is to reserve simple … names for types that developers … instantiate in the most common scenarios. Framework designers often “burn” the best names for less commonly used types, with which most users do not have to be concerned. So true, so true. Further on that on p 54: Another important consideration is that the most easily recognizable names should be used for most commonly used types, even if the name fits some other type better in the purely technical sense, For example, a type used … to submit print jobs to print queue should be named Printer, rather than PrintQueue. p 26: DO involve user education experts early in the design process. User education what?! I am not sure our department even has those. User education experts is not something I can “involve”. Even if I manage to find one, he probably will be too busy to deal with my stuff. In other words, this recommendation is good only for a big framework. p 28: Avoid many abstractions in mainline scenario APIs. While discussing this, the authors scoff at the Object-Oriented Programming, accusing it of making too many abstractions. I don’t think they are doing OOP justice. Having too many abstractions is not a product of the OOP per se, but a product of the violation of the KISS principle. One can produce an overengineered system with or without OOP. As Kent Beck puts it, we want to build the simplest thing that can possibly work (i.e. satisfy all the requirements), but not simpler. In the crusade against complexity, the last part is often forgotten, and “too simple” implementations turn out to be too rigid and difficult to maintain. Naming Guidelines p 39: Capitalization and spelling for common compound words. The authors go to great lengths in discussing capitalization rules. While this is kinda boring, I guess it is a necessary evil. Having all identifiers to follow a common convention is a Good Thing. The problem is, the rules use the term “word”, and for some compound constructs it is not entirely obvious what is a “word”. In fact, it is not obvious to the point that they had to make a table for difficult situations. And yet, this table is still confusing. I could never understand why “hashtable” is one word, whereas “white space” are two words. Here, the spell checker agrees with me: it says there is no such thing as “hashtable” 🙂 p 44: Do not use abbreviations. This looks kinda funny alongside a table that lists “ SByte” and “ ushort“. Why are they calling me short?! 🙂 p 50: Do not use organizational hierarchies as the basis for names … because group names within corporations tend to be short-lived. It’s a very smart thing to say. Furthermore, even names of the corporations themselves change, e.g. when the corporations are bought or merged. From the other hand, it is sometimes not clear what to use instead of the organizational name. p 62: Consider giving a property the same name as its type. This means name collision, and it raises an internal protest in me. From the other hand, sometimes the type name is the best name for the property. p 63: Do use two parameters “sender” and “e” in event handlers. The sender parameter is typically of type object, even if it is possible to employ a more specific type. The pattern is used consistently across the framework. Unfortunately, the authors don’t care to give any reasons for this statement. Why would I want to use object when I know the type? Why would I want to pass an empty structure when there are no any arguments? Why if I want to pass a single argument I have to package it in a structure? This is one of the things the continues to puzzle me. BTW, what is “args” in “EventArgs” anyway? Didn’t they say not to use abbreviations and contractions? p 64: Do not use a prefix for field names. For example do not use “g_” or “s_” to distinguish static versus non-static fields. Why not, may I ask? Prefix “_” works perfectly fine for fields, and I don’t see anything wrong with it. It particularly helps in constructors, when I need to assign parameter to a field. It also helps with property names. If I have a field something and corresponding property Something they would differ only by case. Weren’t we told it’s a bad thing? p 66: This concludes 33 pages of naming guidelines, many of them just in the form of decrees (“do this”) without explanations. That’s a lot of guidelines. From the other hand, naming is important, especially for public stuff, since this is what the users will see. p 69: On the flip side, sometimes types do end up being dumping grounds for various loosely related functions. The .NET Framework offers several types like this, such as Marshal, GC, Console, Math and Application. This is a very honest and very unexpected passage coming from a Microsoft book. My respect to the authors. This actually made me to look who is the publisher. Naturally, it was not Microsoft Press :-). The book is published by Addison-Wesley. p 70: Contrary to popular belief, the main purpose of namespaces is not to help in resolving naming conflicts. No kidding?! Is it really a popular belief? I hope not. p 71: One of the best features of Visual Studio is Intellisense… The benefit of this feature is inversely proportional to the number of options. This is may be true, but I somewhat fear the advent of “design for Intellisense”paradigm. I am not entirely convinced it will produce a higher quality, easy to maintain software. Charles Petzold echoes some of these doubts in his article: “does Visual Studio rot the mind“. I do not 100% agree with everything he says, but there is definitely something to it. p 72: Prior to C# 2.0, distinguishing the to types (same namespace, same type name, different assemblies) was impossible. However, with C# 2.0 it is now possible using the new extern aliases and namespace qualifier features. Using what?! To my astonishment I have no idea what he is talking about. Probably, because I never had such a conflict between two types. I will have to look that up. p 75: Value types that can be changed can be confusing to many users. Therefore, value types should be immutable. Hm… I like this logic. Reference types that can be changed also could be confusing to many users, especially in a multi-threaded applications. Therefore, reference types should be immutable. 🙂 In fact, when I think about it, the C# language can be confusing to many users…
https://ikriv.com/blog/?p=8
CC-MAIN-2019-43
refinedweb
1,695
66.03
Most of the devices TensorFlow Lite for Microcontrollers runs on don’t have file systems, so the model data is typically included by compiling a source file containing an array of bytes into the executable. I recently added a utility to help convert files into nicely-formatted source files and headers, as the convert_bytes_to_c_source() function, but I’ve also had requests to go the other way. If you have a .cc file (like one from the examples) how do you get back to a TensorFlow Lite file that you can feed into other tools (such as the Netron visualizer)? My hacky answer to this is a Python script that does a rough job of parsing an input file, looks for large chunks of numerical data, converts the values into bytes, and writes them into an output file. The live Gist of this is at and will contain the most up to date version, but here’s the code inline: import re output_data = bytearray() with open('tensorflow/tensorflow/lite/micro/examples/magic_wand/magic_wand_model_data.cc', 'r') as file: for line in file: values_match = re.match(r"\W*(0x[0-9a-fA-F,x ]+).*", line) if values_match: list_text = values_match.group(1) values_text = filter(None, list_text.split(",")) values = [int(x, base=16) for x in values_text] output_data.extend(values) with open('converted.tfl', 'wb') as output_file: output_file.write(output_data) You’ll need to replace the input file name with the path of the one you want to convert, but otherwise this should work on most of these embedded model data source files.
https://petewarden.com/2020/02/
CC-MAIN-2021-49
refinedweb
258
54.02
- NAME - VERSION - SYNOPSIS - DESCRIPTION - ATTRIBUTES - CLASS METHODS - OBJECT METHODS - INTERNAL METHODS - TODO - AUTHOR - BUGS - SUPPORT - SEE ALSO - ACKNOWLEDGEMENTS - LICENSE AND COPYRIGHT NAME MongoDBx::Class - Flexible ORM for MongoDB databases VERSION version 1.02 SYNOPSIS Normal usage: use MongoDBx::Class; # create a new instance of the module and load a model schema my $dbx = MongoDBx::Class->new(namespace => 'MyApp::Model::DB'); # if MongoDBx::Class can't find your model schema (possibly because # it exists in some different location), you can do this: my $dbx = MongoDBx::Class->new(namespace => 'MyApp::Model::DB', search_dirs => ['/path/to/model/dir']); # connect to a MongoDB server my $conn = $dbx->connect(host => 'localhost', port => 27017); # be safe by default $conn->safe(1); # we could've also just passed "safe => 1" to $dbx->connect() above # get a MongoDB database my $db = $conn->get_database('people'); # insert a person my $person = $db->insert({ name => 'Some Guy', birth_date => '1984-06-12', _class => 'Person' }); print "Created person ".$person->name." (".$person->id.")\n"; $person->update({ name => 'Some Smart Guy' }); $person->delete; See MongoDBx::Class::ConnectionPool for simple connection pool usage. DESCRIPTION. As opposed to other ORMs (even non-MongoDB ones), MongoDBx::Class attempts to stay as close as possible to MongoDB's non-schematic nature. While most ORMs enforce using a single collection (or table in the SQL world) for every object class, MongoDBx::Class allows you to store documents of different classes in different collections (and even databases). A collection can hold documents of many different classes. Not only that, as MongoDBx::Class is Moose based, you can easily create very flexible schemas by using concepts such as inheritance and roles. For example, say you have a collection called 'people' with documents representing, well, people, but these people can either be teachers or students. Also, students may assume the role "hall monitor". With MongoDBx::Class, you can create a common base class, say "People", and two more classes that extend it - "Teacher" and "Student" with attributes that are only relevant to each one. You also create a role called "HallMonitor", possibly with some methods of its own. You can save all these "people documents" into a single MongoDB collection, and when fetching documents from that collection, they will be properly expanded to their correct classes (though you will have to apply roles yourself - at least for now). COMPARISON WITH OTHER MongoDB ORMs As MongoDB is rather young, there aren't many options out there, though CPAN has some pretty good ones, and will probably have more as MongoDB popularity rises. The first MongoDB ORM in CPAN was Mongoose, and while it's a very good ORM, MongoDBx::Class was mainly written to overcome some limitations of Mongoose. The biggest of these limitations is that in order to provide a more comfortable syntax than MongoDB's native syntax, Mongoose makes the unfortunate decision of being implemented as a singleton, meaning only one instance of a Mongoose-based schema can be used in an application. That essentially kills multithreaded applications. Say you have a Plack-based (doesn't have to be Plack-based though) web application deployed via Starman (or any other web server for that matter), which is a pre-forking web server - you're pretty much doomed. As MongoDB's driver states, it doesn't support connection pooling, so every fork has to have its own connection to the MongoDB server. Mongoose being a singleton means your threads will not have a connection to the server, and you're screwed. MongoDBx::Class does not suffer this limitation. You can start as many connections as you like. If you're running in a pre-forking environment, you don't have to worry about it at all. Other differences from Mongoose include:. is => 'rw'in Moose), otherwise expansion will fail. This is not the case with MongoDBx::Class, your attributes can safely be read-only. Another ORM for MongoDB is Mongrel, which doesn't use Moose and is thus lighter (though as MongoDB is already Moose-based, I see no benefit here). It uses Oogly for data validation (while Moose has its own type validation), and seems to define its own syntax as well. Unfortunately, documentation is currently lacking, and I haven't given it a try, so I can't draw specific comparisons here. Even before Mongoose was born, you could use MongoDB as a backend for KiokuDB, by using KiokuDB::Backend::MongoDB. However, KiokuDB is considered a database of its own and uses some conventions which doesn't fit well with MongoDB. Mongoose::Intro already gives a pretty convincing case when and why you should or shouldn't want to use KiokuDB. ) Initiates a new connection to a MongoDB server running on a certain host and listening to a certain port. %options is the hash of attributes that can be passed to new() in MongoDB::Connection, plus the 'safe' attribute from MongoDBx::Class::Connection. You're mostly expected to provide the 'host' and 'port' options. If a host is not provided, 'localhost' is used. If a port is not provided, 27017 (MongoDB's default port) is used. Returns a MongoDBx::Class::Connection object. NOTE: Since version 0.7, the created connection object isn't saved in the top MongoDBx::Class object, but only returned, in order to be more like how connection is made in MongoDB (and to allow multiple connections). This change breaks backwords compatibility. pool( [ type => $type, max_conns => $max_conns, params => \%params, ... ] ) Creates a new connection pool (see MongoDBx::Class::ConnectionPool for more info) and returns it. type is either 'rotated' or 'backup' (the default). params is a hash-ref of parameters that can be passed to MongoDB::Connection->new() when creating connections in the pool. See "ATTRIBUTES" in MongoDBx::Class::ConnectionPool for a complete list of attributes that can be passed. INTERNAL METHODS The following methods are only to be used internally. BUILD() Automatically called when creating a new instance of this module. This loads the schema and saves a hash-ref of document classes found in the object. Automatic loading courtesy of Module::Pluggable. TODO Improve the tests. Make the isaoption in MongoDBx::Class::Moose's relationship types consistent. Either use the full package names or the short class names. Try to find a way to not require documents to have the _class attribute. 399: Non-ASCII character seen before =encoding in 'Müller,'. Assuming UTF-8
https://metacpan.org/pod/release/IDOPEREL/MongoDBx-Class-1.02/lib/MongoDBx/Class.pm
CC-MAIN-2017-34
refinedweb
1,057
53.41
10 August 2012 17:24 [Source: ICIS news] LONDON (ICIS)--Chemical and pharmaceutical producers in ?xml:namespace> The state’s chemical and pharmaceuticals first-half sales growth compares with a 0.5% year-on-year decline in overall German chemical and pharmaceuticals sales during that period. However, industry association Chemie-Verbande Baden-Wurttemberg said that the state's 2012 full-year sales would be much lower – at about 2% to 3% - because of growing risks from the eurozone debt crisis and the recession in southern In addition, the industry is being challenged by volatile energy and raw material costs, the group said. “Our medium-sized chemical producers are being squeezed as the large raw material suppliers are setting their prices, but firms are finding it hard to pass those higher costs on to their industrial customers,” said the group’s general manager, Thomas Mayer. As for the first half of 2012, Mayer credited in particular higher pharmaceuticals sales – up 7.0% year on year – for the increase in the state’s overall chemicals and pharmaceuticals sales. Domestic chemicals and pharmaceuticals rose 7.3% to €3.9bn in the the first six months while export sales rose 3.0% to €5.4bn, Mayer said. Baden-Wurttemberg’s paint and coatings producers recorded only a 0.6% year-on-year increase in their 2012 first-half sales, he added. (
http://www.icis.com/Articles/2012/08/10/9586124/germany-baden-wurttemberg-records-strong-h1-chem-sales-defies-trend.html
CC-MAIN-2014-35
refinedweb
227
56.86
URI::SmartURI - Subclassable and hostless URIs Version 0.032 my $uri = URI::SmartURI->new( '', { reference => '' } ); my $hostless = $uri->hostless; # '/foo/' $hostless->absolute; # '' $uri->relative; # '../foo/' This is a sort of "subclass" of URI using delegation with some extra methods, all the methods that work for URIs will work on these objects as well. It's similar in spirit to URI::WithBase. It's also completely safe to subclass for your own use. Takes a uri $str and an optional scheme or hashref with a reference uri (for computing relative/absolute URIs) and an optional scheme. my $uri = URI::SmartURI->new(''); my $uri = URI::SmartURI->new('/dev.catalyst.perl.org/new-wiki/', 'http'); my $uri = URI::SmartURI->new( '', { reference => '' } ); The object returned will be blessed into a scheme-specific subclass, based on the class of the underlying $uri->obj (URI object.) For example, URI::SmartURI::http, which derives from URI::SmartURI (or $uri->factory_class if you're subclassing.) Proxy for URI::URL->newlocal Returns the URI with the scheme and host parts stripped. Accessor for the reference URI (for relative/absolute below.) Returns the URI relative to the reference URI. Returns the absolute URI using the reference URI as base. stringification works, just like with URIs and == does as well Explicit equality check to another URI, can be used as URI::SmartURI::eq($uri1, $uri2) as well. Accessor for the URI object methods are delegated to. The class whose constructor was called to create the $uri object, usually URI::SmartURI or your own subclass. This is used to call class (rather than object) methods. These are used internally by SmartURI, and are not interesting for general use, but may be useful for writing subclasses. Returns a hashref of options for the $uri (reference and scheme.) Converts, eg., "URI::http" to "URI::SmartURI::http". Creates a new proxy class class for a URI class, with all exports and constructor intact, and returns its name, which is made using _resolve_uri_class (above). Inflate any URI objects in @rray into URI::SmartURI objects, all other members pass through unharmed. $opts is a hashref of options to include in the objects created. Deflate any URI::SmartURI objects in @rray into the URI objects they are proxies for, all other members pass through unharmed. On import with the -import_uri_mods flag it loads all the URI .pms into your class namespace. This works: use URI::SmartURI '-import_uri_mods'; use URI::SmartURI::WithBase; use URI::SmartURI::URL; my $url = URI::SmartURI::URL->new(...); # URI::URL proxy Even this works: use URI::SmartURI '-import_uri_mods'; use URI::SmartURI::Escape qw(%escapes); It even works with a subclass of URI::SmartURI. I only wrote this functionality so that I could run the URI test suite without much modification, it has no real practical value. Please report any bugs or feature requests to bug-uri::SmartURI You can also look for information at: Catalyst::Plugin::SmartURI, URI, URI::WithBase Thanks to folks on freenode #perl for helping me out when I was getting stuck, Somni, revdiablo, PerlJam and others whose nicks I forget. Rafael Kitover, <rkitover at cpan.org> This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
http://search.cpan.org/~rkitover/URI-SmartURI-0.032/lib/URI/SmartURI.pm
CC-MAIN-2018-05
refinedweb
535
56.45
You don't have to create neither DirectRouter.ashx nor DirectApi.ashx. They are not physical files. These values are used by Ext.Direct.Mvc to define two routes - one to generate API, and one to route Direct requests. DirectHandler.ashx (or whatever value you used in web.config) simply defines URL to be used by Ext.Direct to make AJAX requests against. Just follow the steps in the first post precisely, and you'll be fine. The direct tab still fails I am starting to get a handle on this, but I still haven't set up my project correctly. The project elishnevsky has setup works, but now I am trying to copy concepts from this page to another website, and I am missing something. I need something simpler to start, so I have just deleted out most of the content except for a panel and a "Hello World" button. I have deliberately used different namespaces because this forces me to understand where everything is coming from. I suspect that I have some problems with referring to the correct objects on this line (in Site.Master <%= Html.ActionLink("Direct", "DirectPage", "Direct")%></li> It fails in the following code: protectedoverridevoid ExecuteCore() { if (ControllerContext.RouteData.RouteHandler isDirectMvcRouteHandler) { this.ActionInvoker = newDirectMethodInvoker(); } elseif (IsDirectMethodCall()) { thrownewInvalidOperationException("This controller action can only be executed by Ext.Direct."); } base.ExecuteCore(); } This is the error I most often get:A public action method 'DirectPage' could not be found on controller 'Ext.Direct.Mvc.DirectController'. I have once gotten this error (with a prior edit of the code), but I haven't figured out how to duplicate it: This controller action can only be executed by Ext.Direct I have figured some of this out on my own This new file is now correctly implements "Hello World" on the Direct tab. I was getting confused about namespace names, view names, and so on. Perhaps this example will help others since it is very simple. I am now working on implementing the CustomerOrders tab using ext.direct. As for your previous post, keep in mind, that every action in a controller, that inherits from DirectController, is considered a Direct method, unless marked with [DirectIgnore] attribute. Such controller actions should only be used by Ext.Direct and cannot be executed in any other way, except in a Direct request context. As for your last post, I don't understand your confusion. Can you please describe your problem? I am new to the MVC pattern as well as to ExtJS. So almost everything about this is unfamiliar. So I was getting confused between Ext.Direct actions, view names, controllers, especially since I was renaming everything on purpose so such confusions WOULD happen and I'd have to work them out. I also had to rename the test project namespaces so I'd have more clarity while editing to know which project was the test bed and which was your reference code. I had to restore your original project from the downloaded zip file because I accidently overwrote it with some of my testbed code. I have two more weeks of down time to get my head wrapped around this, and it appears to be a great way to implement my upcoming project which will be converting some very complex asp.net pages that were written very badly in highly repetitive ASP classic and were ported in the most work-intensive but intellectually lazy way possible to ASP.Net 2003 a long time ago. I want to avoid intellectual laziness this time and do modern Web 2.0 coding. Part of that is becoming part of the open source community and ExtJS appears to be very robust and elegantly designed, so this looks like a great place to be. I am reasonably good at Javascript, but the ExtJS style of defining things with functions inside functions, and internal complex nested arrays is not exactly the way I was used to building or using my objects. It is a very compact way of coding but it will take a few more days for me to start doing this with some confidence. Well, all I can say is "good luck" There's many good starting points to learn Ext JS. Check out the links in my signature. As for ASP.NET MVC, there's the official site as well as some blogs, for example this one or this one. elishnevsky Hello elishnevsky, Great contribution works well out of the box. Was wondering, any support for unit testing? Or at a minimum the ability to call the methods directly for testing if they are not attributed with ignore? Cheers, Timothy Code: Test.AddNumbers(10, 33, function(result, response) { console.info(result); }); Thanks elishnevsky -- I was hoping to avoid using the console but hey ... it's better than nothing Again, cheers for the wicked job on the this contribution! Cheers, Timothy Hello elishnevsky, Was just wondering how you would deal with a form that has more than 25 fields to submit to an action, I don't want to have to write a server side action that has 25 parameters for each one. Any recommendations? Thanks again for your help, much appreciated Cheers)
https://www.sencha.com/forum/showthread.php?72245-Ext.Direct-for-ASP.NET-MVC/page5
CC-MAIN-2015-22
refinedweb
867
64.51
Trees. node - a point in the tree. In these pictures, each node includes a label (value at each node) root - the node at the top. Every tree has one root node children - the nodes directly beneath it. Arity is the number of children that node has. leaf - a node that has no children. (Arity of 0!) We're going to use the Tree class from lecture. In your terminal: cp ~cs61a/public_html/sp12/labs/lab9/tree.py . Open the python interpreter: from tree import * Take a moment to study the implementation of Trees. Look at the constructors, selectors, and printing methods. At the bottom, we give you some premade trees that you can work with for each section. Now, after loading the file, the variable kennedy contains the following Tree: Use the correct series of selectors to return the value “Caroline” from the tree. Mutual Recursion occurs when you have a function that will deal with Trees, as well as a function that will deal with Forests (sequences of Trees). Both functions call each other to solve whatever problem is at hand. def square_tree(tree): return Tree(square(tree.label), *square_forest(iter(tree))) def square_forest(forest): new_forest = () for tree in forest: new_forest += (square_tree(tree),) return new_forest The variable t is defined in tree.py and is a Tree of integers that you can use to test your functions. Try out the following to see how it works! >>> print(t) _______________ >>> st = square_tree(t) >>> print(st) _______________ Exercise: Draw your interpretation of this tree on a piece of paper Define the function tree_map which takes a function and a Tree as an argument and returns the equivalent Tree with the function applied to each node’s value. (Hint! This should be a similar but more general form of square tree) >>> print(t) ____________ >>> st = tree_map(square, t) >>> print(st) ____________ Define the function max_of_tree which takes in a Tree as an argument and returns the max of all of the values of each node in the Tree. >>> print(t) ____________ >>> max_of_tree(t) ____________ A set is an unordered collection of distinct objects that supports membership testing, union, intersection, and adjunction. Construction >>> s = {3, 2, 1, 4, 4} >>> s {1, 2, 3, 4} Adjunction >>> s.add(5) >>> s {1, 2, 3, 4, 5} Operations >>> 3 in s True >>> 7 not in s True >>> len(s) 5 >>> s.union({1, 5}) {1, 2, 3, 4, 5} >>> s.intersection({6, 5, 4, 3}) {3, 4} For more detail on Sets you can go to the following link: PythonSets Implement the union function for sets. Union takes in two sets, and returns a new set with elements from the first set, and all other elements that have not already have been seen in the second set. >>> r = {0, 6, 6} >>> s = {1, 2, 3, 4} >>> t = union(s, {1, 6}) {1, 2, 3, 4, 6} >>> union(r, t) {0, 1, 2, 3, 4, 6}
http://www-inst.eecs.berkeley.edu/~cs61a/sp12/labs/lab9/lab9.html
CC-MAIN-2018-09
refinedweb
489
71.24
This post was coauthored by Eugene Yokota and Yifan Xing. This post was coauthored by Eugene Yokota and Yifan Xing. We need to change the culture around tech conferences to improve the inclusion of women (and people from other backgrounds too!). For that, there needs to be clear signaling and communication about two basic issues: These points should be communicated over and over at each conference before the keynote takes place, and before socializing hours. Compile, or compile not. There's no warning. Two of my favorite Scala compiler flags lately are "-Xlint" and "-Xfatal-warnings". Here is an example setting that can be used with subprojects: "-Xlint" "-Xfatal-warnings" ThisBuild / organization := "com.example" ThisBuild / version := "0.1.0-SNAPSHOT" ThisBuild / scalaVersion := "2.12.6" lazy val commonSettings = List( scalacOptions ++= Seq( "-encoding", "utf8", "-deprecation", "-unchecked", "-Xlint", "-feature", "-language:existentials", Whether you want to try using OpenJDK 11-ea, GraalVM, Eclipse OpenJ9, or you are stuck needing to build using OpenJDK 6, jabba has got it all. jabba is a cross-platform Java version manager written by Stanley Shyiko (@shyiko). Here's how we can use jabba on Travis CI to cross build using AdoptOpenJDK 8 and 11: sudo: false dist: trusty group: stable language: scala scala: - 2.12.7 env: global: - JABBA_HOME=/home/travis/.jabba matrix:: Wrote herding cats: day 17 featuring initial and terminal objects, product, duality, and coproduct.. file:/foo/bar Gigahorse 0.3.0 is now released. See documentation on what it is. 0.3.0 adds Square OkHttp support. Gigahorse-OkHttp is availble for Scala 2.10, 2.11, and 2.12. According to the JavaDoc you actually don't have to close the OkHttpClient instance. OkHttpClient scala> import gigahorse._, support.okhttp.Gigahorse import gigahorse._ import support.okhttp.Gigahorse scala> import scala.concurrent._, duration._ import scala.concurrent._ import duration._ Wrote herding cats day 16. Here are a few questions I've been thinking about: The sealed trait and case class is the idiomatic way to represent datatypes in Scala, but it's impossible to add fields in binary compatible way. Take for example a simple case class Greeting, and see how it would expand into a class and a companion object: Greeting
http://eed3si9n.com/category/tags/scala
CC-MAIN-2018-51
refinedweb
372
60.72
How to Read Java Console Input | 3 Ways To Read Java Input. So, let’s start to explore different ways to read input from the java console. 2. Java Console There are three different ways to read the input from Java Console, they are – - Using Java Bufferedreader Class - Scanner Class in Java - Console Class in Java So, let’s study them in detail. Do you know What is Java Character Class Methods? 3. Read Result From Java Console Here, we will cover three ways to read the result from console. a. Java Bufferedreader Class This is the Java traditional technique, introduced in JDK1.0. This strategy is utilized by wrapping the System.in (standard information stream) in an InputStreamReader which is wrapped in a Java BufferedReader, we can read result include from the user in the order line. Pros – The information is cradled for productive perusing. Cons – The wrapping code is difficult to recall. Example of Java Bufferedreader Class– import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Test { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String name = reader.readLine(); System.out.println(name); } } b. Scanner Class in Java This is presumably the most favoured technique to take input. The primary reason for the Scanner class is to parse primitive composes and strings utilizing general expressions, in any case, it can utilize to peruse contribution from the client in the order line. Pros – - Helpful strategies for parsing natives (nextInt(), nextFloat(), … ) from the tokenized input. - General articulations can utilize to discover tokens. Cons – - The reading methods are not synchronized. Let’s Look at Java File Class – java.io.File Class in Java Example of Scanner Class in Java – import java.util.Scanner; class GetInputFromUser { public static void main(String args[]) { Scanner in = new Scanner(System.in); String s = in.nextLine(); System.out.println("You entered string "+s); int a = in.nextInt(); System.out.println("You entered integer "+a); float b = in.nextFloat(); System.out.println("You entered float "+b); } } c. Console Class in Java It has been turning into a favored route for perusing client’s contribution from the command line. In addition, it can utilize for password key like contribution without resounding the characters entered by the client, the configuration string syntax structure can likewise utilize (like System.out.printf()). Pros – - Reading secret word without reverberating the entered characters. - Reading strategies that are synchronized. - Format string sentence structure can utilize. Cons – - Does not work in non-intelligent condition, (for example, in an IDE). Do You Know Difference Between Abstract Class and Interface in Java? Example of Console Class in Java– public class Sample { public static void main(String[] args) { // Using Console to input data from user String name = System.console().readLine(); System.out.println(name); } } 4. Java Console Example String name = null; int number; java.io.BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); name = in.readLine();number = Integer.parseInt(in.readLine()); System.out.println("Name " + name + "\t number " + number); java.util.Scanner sc = new Scanner(System.in).useDelimiter("\\s"); name = sc.next(); number = sc.nextInt();System.out.println("Name " + name + "\t number " + number); java.io.Console cnsl = System.console(); if (cnsl != null) { name = cnsl.readLine("Name: "); System.out.println("Name entered: " + name); } So, this was all about Java Console Tutorial. Hope you like our explanation. Let’s Study Java Comments | Three Types of Comments in Java 5. Conclusion Hence, in this Java console tutorial, we have learned three ways to read input from Java console, using Java bufferedreader class, scanner class in Java, and console class in Java. Moreover, we discussed these ways with console Input examples. At last, we saw the pros and cons of all the 3 ways to read input from console. Furthermore, if you have any query, feel free to ask in the comment section. Related Topic- What is Autoboxing and Unboxing in Java
https://data-flair.training/blogs/read-java-console-input/
CC-MAIN-2019-35
refinedweb
653
52.26
130 Selenium Interview Question & Answer Updated Well, As Software QA Testers Are Searching Online To Get the Latest Interview Question and Answer Which Are Commonly Ask In The Interviews. So I Am Sure, this doc is not going to help you crack that interview, but I know there are many interviewers out there who want to know the answer of one-liner Selenium interview questions. You could use this questionnaire as a resource to tests your Selenium skills once you have gained enough knowledge in the Selenium suite of tools. Most of the questions are derived from the SeleniumHQ Doc and the Google wiki of the Selenium project. Generic Selenium Questions What is Selenium? Answer: Selenium is a browser automation tool that lets you automate operations like – Type, Click, and Selection from a drop-down of a web page. How is Selenium different from commercial browser automation tools? Answer: Selenium is a library that is available in Various languages, i.e. Java, C#, Python, Ruby, PHP, etc. while most commercial tools are limited in their capabilities of being able to use just one language. Moreover, many of those tools have their other Selenium libraries like Remote control [RC] . What is the set of tools available with Selenium? Answer: Selenium has mainly four set of tools – Selenium IDE, Selenium 1.0 (Selenium RC), Selenium 2.0 (WebDriver) and Selenium Grid. Check Also: Common 50 Selenium Interview Questions What is Selenium IDE? Answer: Selenium IDE is a Firefox plugin which is used to record and replay test in firefox browser. Selenium IDE can be used only with the Firefox browser. What is Selenium 1.0? Answer: Selenium 1.0 or Selenium Remote Control (popularly known as Selenium RC) is a library available in a wide variety of languages. The primary reason for the advent of Selenium RC was the incapability of Selenium IDE to execute tests in a browser other than Selenium IDE and the programmatical limitations of language Selenese used in Selenium IDE. What are the element locators available with Selenium, which could be used to locate elements on a web page? Answer: There are mainly 4 locators used with Selenium - Html ID - Html Name - Html Tagname - Html Class Name - XPath locator - CSS locators - Link Text - Partial Link Text What are the two modes of views in Selenium IDE? Answer: Selenium IDE can be opened either in sidebar (View > Sidebar > Selenium IDE) or as a pop up window (Tools > Selenium IDE). While using Selenium IDE in browser sidebar, it cannot record user operations in a pop-up the window opened by an application. Can I control the speed and pause test execution in Selenium IDE? Answer: Selenium IDE provides a slider with Slow and Fast pointers to control the speed of execution. Where do I see the results of Test Execution in Selenium IDE? Answer: Result of test execution can be viewed in a log window in Selenium IDE Where do I see the description of commands used in Selenium IDE? Answer: Commands of description can be seen in the Reference section Can I build a test suite using Selenium IDE? Answer: Yes, you can first record individual test cases and then group all of them in a test suite. Following this entire test suite could be executed instead of executing individual tests. What verification points are available with Selenium? Answer: There are largely three types of verification points available with Selenium - Check for the page title - Check for certain text - Check for the certain element (text box, drop-down, table, etc.) I see two types of the check with Selenium – verification, an assertion, what’s the difference between the two? Answer: A verification check lets test execution continue even in the wake of failure with a check, while assertion stops the test execution. Consider an example of checking the text on a page, and you may like to use the verification point and let test execution continue even if a text is not present. But for a login page, you would like to add an assertion for the presence of text box login as it does not make sense continuing with test execution if the login text box is not present. Read Also: Einfochips Selenium Automation Interview Questions I don’t see checkpoints added to my tests while using Selenium IDE, how do I get them added to my tests? Answer: You need to use the context menu to add checkpoints to your Selenium IDE tests. How do I edit tests in Selenium IDE? Answer: There are two ways to edit tests in Selenium IDE; one is the table view while others are looking into the source code of recorded commands. What is the syntax of the command used in Selenium? Answer: There are three entities associated with a command - Name of Command - Element Locator (also known as Target) - Value (required when using echo, wait, etc.). How do I use HTML id and name while using Selenium IDE Answer: Html id and name can be used as it is in selenium IDE. For example, the Google search box has a name – “q” and id “listb,” and they can be used as a target in Selenium IDE What is XPath? When would I have to use XPath in Selenium IDE? Answer: XPath is a way to navigate in an xml document, and this can be used to identify elements in a web page. You may have to use XPath when there is no name/is associated with the element on the page, or only a partial part of name/ide is constant. - The direct child is denoted with / - The relative child is denoted with // - Id, class, names can also be used with XPath – · //input[@name=’q’] · //input[@id=’lstib’] · //input[@class=’ lst’] - If only part of id/name/class is constant than “contains” can be used as – · //input[contains(@id,’lstib’)] What is the CSS location strategy in Selenium? Answer: CSS location strategy can be used with Selenium to locate elements, it works using cascade style sheet location methods in which Direct child is denoted with – (space) Relative child is denoted with > Id, class, names can also be used with XPath – · css=input[name=’q’] · css=input[id=’lstib’] or input#lstib · css=input[class=’ lst’] or input.lst If only part of id/name/class is constant than “contains” can be used as – · css=input[id*=’ lstib ‘)] Element location strategy using inner text · CSS = a:contains(‘log out’)} I have stored the result of an evaluation; can I print it in IDE to check its value? Answer: You can use echo command as following to check the stored value in Selenium IDE – storeText css=input#s var1 echo ${var1}. Selenium has recorded my test using XPath, how do I change them to CSS locator? Answer: You can use drop-down available next to Find in Selenium to change element locator used by Selenium I have written my element locator, how do I test it? Answer: You can use the Find button of Selenium IDE to test your locator. Once you click on it, you would see element being highlighted on the screen provided your element locator is right Else one error message would be displayed in the log window. I have written one js extension; can I plug it in Selenium and use it? Answer: You could specify you a js extension in “Options” window of Selenium IDE – How do I convert my Selenium IDE tests from Selenese to another language? Answer: You could use the Format option of Selenium IDE to convert tests in another programming language –. I have added one command in the middle of the list of commands, how do I test only this new command? Answer: You can double click on the newly added command, and Selenium IDE would execute only that command in browser. Can I make Selenium IDE tests begin test execution from a certain command and not from the very first command? Answer: You could set a command as a “start” command from the context menu. When a command is set as a start command, then a small green symbol appears before the command. The same context menu can be used to toggle this option. What is an upcoming advancement in Selenium IDE? Answer: The latest advancement in Selenium IDE would be to have capabilities of converting Selenium IDE tests in Webdriver (Selenium 2.0) options. This would help in to generate quick and dirty tests for Selenium 2.0 How can I use the looping option (flow control) is Selenium IDE Answer: Selenese does not provide support for looping, but there is an extension that could be used to achieve the same. Can I use a screen coordinate while using click command? I want to click on a specific part of my element. Answer: You would need to use the clickAT command to achieve. the clickAt command accepts element locator and x, y coordinates as arguments – clickAt(locator, coordString) How do I verify the presence of drop-down options using Selenium? Answer: Use assertSelectOptions as following to check options in a drop-down list. a js file with the following– LocatorBuilders.order = [‘css:name’, ‘CSS:id’, ‘id’, ‘link’, ‘name’, ‘XPath:attributes’]; And add this file under “Selenium IDE Extension” under Selenium Options. My application has dynamic alerts which don’t always appear, how do I handle them? Answer: If you want to simulate clicking “ok “ on alert than use – chooseOkOnNextConfirmation and if you want to simulate clicking “cancel” on alert than use Selenium RC (Selenium 1.0) Questions Can I right-click on a locator? Answer: You can use command contextMenu ( locator) to simulate a right-click on an element on a web page. How do I capture a screenshot of a page using Selenium IDE? Answer: Use command – captureEntirePageScreenshot to take the screenshot of the page. I want to pause my test execution after the certain command. Answer: Use pause command which takes time in milliseconds and would pause test execution for a specified time – pause ( waitTime ) I used the open command to launch my page, but I encountered a timeout error? Answer: This happens because open commands wait for only 30 seconds for the page to load. If your application takes more than 30 sec, then you can use “setTimeout ( timeout )” to make selenium IDE wait for a specified time before proceeding with test execution. What’s the difference between type and typeKeys commands? Answer: type command simulates enter operations at one go while typeKeys simulates keystroke key by key. typeKeys could use when typing data in the text box, which brings options (like Google suggestion list) because such an operation is not usually simulated using type command. 130 Selenium Interview Question Difference Between Assertion and Verification? Answer: Verify command will not stop the execution of the test case if verification fails. It will log an error and proceed with the execution of the rest of the test case. We use verify commands in Selenium IDE when we still want to proceed with the execution of the test case even if the expected output is not matched for a test step. Assert command will stop the execution of the test case if verification fails. It will log an error and will not proceed with the execution of the rest of the test case. We use assertions in scenarios where there is no point proceeding further if the expected output is not matched. It’s pretty simple. Use assertions when you want to stop the execution of a test case if the expected output is not matched and use verification when you still want to proceed execution of a test case if the expected output is not matched. The difference between Set, List, and Map? Set (Interface) - Set is an unordered collection which doesn’t allow duplicate (no duplicate) elements - We can iterate the values by calling the iterator() method Set s = new HashSet(); Iterator iter = s.iterator(); List (Interface) - The list is an ordered collection which allows duplicate elements - We can iterate the values by calling the(); How to Create a Parameterized Test in JUnit Testing Framework? Answer: In this example, we are going to see how to create a parameterized test in JUnit testing framework. Create the Java class to be tested Answer: Create a folder named JUnitParameterized. This is the folder where your classes will be located. Using a text editor, create a Java class named Addition.java. To make sure your file name is Addition.java, (not Addition.java.txt), first choose “Save as > Save as type > All files,” then type in the file name Addition.java. Addition.java public class Addition { public int addNumbers(int a, int b) { int sum = a + b; return sum; } } 2. Create a JUnit test case In the same directory (JUnitParameterized), use a text editor and create a java class named JunitAdditionTest.java with the following code. What are the types of Assertions in JUnit? Answer: Assertions: JUnit provides overloaded assertion methods for all primitive types and Objects and arrays (of primitives or Objects). The parameter order is expected value, followed by an actual value. Optionally the first parameter can be a String message that is output on failure. There is a slightly different assertion, assertThat that has parameters of the optional failure message, the actual value, and a Matcher object. Note that expected and actual are reversed compared to the other assert methods. Examples: A representative of each assert method is shown below. import static org.hamcrest.CoreMatchers.allOf; import static org.hamcrest.CoreMatchers.anyOf; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.CoreMatchers.sameInstance; import static org.hamcrest.CoreMatchers.startsWith; import static org.junit.Assert.assertThat; import static org.junit.matchers.JUnitMatchers.both; import static org.junit.matchers.JUnitMatchers.containsString; import static org.junit.matchers.JUnitMatchers.everyItem; import static org.junit.matchers.JUnitMatchers.hasItems; import java.util.Arrays; import org.hamcrest.core.CombinableMatcher; import org.junit.Test; What is New in TestNG? and Difference Between TestNG and JUNIT? Answer:). - It is.
https://www.softwaretestingo.com/130-selenium-interview-question/
CC-MAIN-2019-47
refinedweb
2,349
54.73
Workflow 1: processing, searching and retrieving observations# This tutorial demonstrates how OpenGHG can be used to process new measurement data, search the data present and to retrieve this for analysis and visualisation. Check installation# This tutorial assumes that you have installed openghg. To ensure install has been successful you can open an ipython console and try to import this module. In a terminal type: $ ipython Then import openghg and print the version string associated with the version you have installed. If you get something like the below openghg is installed correctly. In [1]: import openghg In [2]: openghg.__version__ Out[2]: '0.2.0' If you get an ImportError please go back to the install section of the documentation. Jupyter notebooks# If you haven’t used Jupyter notebooks before please see this introduction. 1. Setting up an object store# The OpenGHG platform uses what’s called an object store to save data. Any saved data has been processed into a standardised format, assigned universally unique identifiers (UUIDs) and stored alongside associated metadata (such as site and species details). Storing data in this way allows for fast retrieval and efficient searching. When using OpenGHG on a local machine the location of the object store is set using an OPENGHG_PATH environment variable (explained below) and this can be any directory on your local system. For this tutorial, we will create a temporary object store which we can add data to. This path is fine for this purpose but as it is a temporary directory it may not survive a reboot of the computer. The OPENGHG_PATH environment variable can be set up in the following way. import os import tempfile tmp_dir = tempfile.TemporaryDirectory() os.environ["OPENGHG_PATH"] = tmp_dir.name # temporary directory When creating your own longer term object store we recommend a path such as ~/openghg_store which will create the object store in your home directory in a directory called openghg_store. If you want this to be a permanent location this can be added to your shell profile. If you’re using bash you could add it to ~/.bashrc or ~/.bash_profile file depending on the system being used. e.g. as export OPENGHG_PATH="$HOME/openghg_store" 2. Adding and standardising data# Data types# Within OpenGHG there are several data types which can be processed and stored within the object store. This includes data from the AGAGE, DECC, NOAA, LondonGHG, BEAC2ON networks. When uploading a new data file, the data type must be specified alongside some additional details so OpenGHG can recognise the format and the correct standardisation can occur. The details needed will vary by the type of data being uploaded but will often include the measurement reference (e.g. a site code) and the name of any network. For the full list of accepted observation inputs and data types, there is a summary function which can be called: from openghg.standardise import summary_data_types summary = summary_data_types() ## UNCOMMENT THIS CODE TO SHOW ALL ENTRIES # import pandas as pd; pd.set_option('display.max_rows', None) summary Note: there may be multiple data types applicable for a give site. This is can be dependent on various factors including the instrument type used to measure the data e.g. for Tacolneston (“TAC”): summary[summary["Site code"] == "TAC"] DECC network# We will start by adding data to the object store from a surface site within the DECC network. Here we have accessed a subset of data from the Tacolneston site (site code “TAC”) in the UK. from openghg.util import retrieve_example_data tac_data = retrieve_example_data(path="timeseries/tac_example.tar.gz") As this data is measured in-situ, this is classed as a surface site and we need to use the ObsSurface class to interpret this data. We can pass our list of files to the read_file method associated within the ObsSurface class, also providing details on: site code - "TAC"for Tacolneston type of data we want to process, known as the data type - "CRDS" network - "DECC" This is shown below: from openghg.client import standardise_surface decc_results = standardise_surface(filepaths=tac_data, data_type="CRDS", site="TAC", network="DECC") print(decc_results) Here this extracts the data (and metadata) from the supplied files, standardises them and adds these to our created object store. The returned decc_results will give us a dictionary of how the data has been stored. The data itself may have been split into different entries, each one stored with a unique ID (UUID). Each entry is known as a Datasource (see below for a note on Datasources). The decc_results output includes details of the processed data and tells us that the data has been stored correctly. This will also tell us if any errors have been encountered when trying to access and standardise this data. AGAGE data# Another data type which can be added is data from the AGAGE network. The functions that process the AGAGE data expect data to have an accompanying precisions file. For each data file we create a tuple with the data filename and the precisions filename. Note: A simpler method of uploading these file types is planned. We can now retrieve the example data for Capegrim as we did above capegrim_data = retrieve_example_data(path="timeseries/capegrim_example.tar.gz") capegrim_data We must create a tuple associated with each data file to link this to a precision file: list_of_tuples = [(data1_filepath, precision1_filepath), (data2_filepath, precision2_filepath), ...] capegrim_data.sort() capegrim_tuple = (capegrim_data[0], capegrim_data[1]) The data being uploaded here is from the Cape Grim station in Australia, site code “CGO”. We can add these files to the object store in the same way as the DECC data by including the right keywords: site code - "CGO"for Cape Grim data type - "GCWERKS" network - "AGAGE" agage_results = standardise_surface(filepaths=capegrim_tuple, data_type="GCWERKS", site="CGO", network="AGAGE", instrument="medusa") When viewing agage_results there will be a large number of Datasource UUIDs shown due to the large number of gases in each data file agage_results A note on Datasources# Datasources are objects that are stored in the object store (++add link to object store notes++) that hold the data and metadata associated with each measurement we upload to the platform. For example, if we upload a file that contains readings for three gas species from a single site at a specific inlet height OpenGHG will assign this data to three different Datasources, one for each species. Metadata such as the site, inlet height, species, network etc are stored alongside the measurements for easy searching. Datasources can also handle multiple versions of data from a single site, so if scales or other factors change multiple versions may be stored for easy future comparison. 3. Searching for data# Visualising the object store# Now that we have added data to our created object store, we can view the objects within it in a simple force graph model. To do this we use the view_store function from the objectstore submodule. Note that the cell may take a few moments to load as the force graph is created. In the force graph the central blue node is the ObsSurface node. Associated with this node are all the data processed by it. The next node in the topology are networks, shown in green. In the graph you will see DECC and AGAGE nodes from the data files we have added. From these you’ll see site nodes in red and then individual datasources in orange. Note: The object store visualisation created by this function is commented out here and won’t be visible in the documentation but can be uncommented and run when you use the notebook version. from openghg.objectstore import visualise_store # visualise_store() Now we know we have this data in the object store we can search it and retrieve data from it. Searching the object store# We can search the object store by property using the search(...) function. For example we can find all sites which have measurements for carbon tetrafluoride (“cf4”) using the species keyword: from openghg.client import search search(species="cfc11") We could also look for details of all the data measured at the Billsdale (“BSD”) site using the site keyword: search(site="tac") For this site you can see this contains details of each of the species as well as the inlet heights these were measured at. Quickly retrieve data# Say we want to retrieve all the co2 data from Tacolneston, we can perform perform a search and expect a SearchResults object to be returned. If no results are found None is returned. results = search(site="tac", species="co2") results We can retrive either some or all of the data easily using the retrieve function. inlet_54m_data = results.retrieve(inlet="54m") inlet_54m_data Or we can retrieve all of the data and get a list of ObsData objects. all_co2_data = results.retrieve_all() all_co2_data 4. Retrieving data# To retrieve the standardised data from the object store there are several functions we can use which depend on the type of data we want to access. To access the surface data we have added so far we can use the get_obs_surface function and pass keywords for the site code, species and inlet height to retrieve our data. In this case we want to extract the carbon dioxide (“co2”) data from the Tacolneston data (“TAC”) site measured at the “185m” inlet: from openghg.client import get_obs_surface co2_data = get_obs_surface(site="tac", species="co2", inlet="185m") If we view our returned obs_data variable this will contain: data- The standardised data (accessed using e.g. obs_data.data). This is returned as an xarray Dataset. metadata- The associated metadata (accessed using e.g. obs_data.metadata). co2_data We can now make a simple plot using the plot_timeseries method of the ObsData object. NOTE: the plot created below may not show up on the online documentation version of this notebook. co2_data.plot_timeseries() You can also pass any of title, xlabel, ylabel and units to the plot_timeseries function to modify the labels. Cleanup#()
https://docs.openghg.org/tutorials/local/1_Adding_observation_data.html
CC-MAIN-2022-33
refinedweb
1,637
51.68
Old Release This documentation relates to an old version of DSpace, version 5.x. Looking for another version? See all documentation. Core Classes The org.dspace.core package provides some basic classes that are used throughout the DSpace code. The Configuration Manager The configuration manager is responsible for reading the main dspace.cfg properties file, managing the 'template' configuration files for other applications such as Apache, and for obtaining the text for e-mail messages. The system is configured by editing the relevant files in [dspace]/config, as described in the configuration section. When editing configuration files for applications that DSpace uses, such as Apache Tomcat, you may want to edit the copy in [dspace-source] and then run ant update or ant overwrite_configs rather than editing the 'live' version directly! This will ensure you have a backup copy of your modified configuration files, so that they are not accidentally overwritten in the future. The ConfigurationManager class can also be invoked as a command line tool: [dspace]/bin/dspace dsprop property.nameThis writes the value of property.name from dspace.cfg to the standard output, so that shell scripts can access the DSpace configuration. If the property has no value, nothing is written. Constants This class contains constants that are used to represent types of object and actions in the database. For example, authorization policies can relate to objects of different types, so the resourcepolicy table has columns resource_id, which is the internal ID of the object, and resource_type_id, which indicates whether the object is an item, collection, bitstream etc. The value of resource_type_id is taken from the Constants class, for example Constants.ITEM. Here are a some of the most commonly used constants you might come across: DSpace types - Bitstream: 0 - Bundle: 1 - Item: 2 - Collection: 3 - Community: 4 - Site: 5 - Group: 6 - Eperson: 7 DSpace actions - Read: 0 - Write: 1 - Delete: 2 - Add: 3 - Remove: 4 Refer to the org.dspace.core.Constants for all of the Constants. Context The Context class is central to the DSpace operation. Any code that wishes to use the any API in the business logic layer must first create itself a Context object. This is akin to opening a connection to a database (which is in fact one of the things that happens.) A context object is involved in most method calls and object constructors, so that the method or object has access to information about the current operation. When the context object is constructed, the following information is automatically initialized: - A connection to the database. This is a transaction-safe connection. i.e. the 'auto-commit' flag is set to false. - A cache of content management API objects. Each time a content object is created (for example Item or Bitstream) it is stored in the Context object. If the object is then requested again, the cached copy is used. Apart from reducing database use, this addresses the problem of having two copies of the same object in memory in different states. The following information is also held in a context object, though it is the responsibility of the application creating the context object to fill it out correctly: - The current authenticated user, if any - Any 'special groups' the user is a member of. For example, a user might automatically be part of a particular group based on the IP address they are accessing DSpace from, even though they don't have an e-person record. Such a group is called a 'special group'. - Any extra information from the application layer that should be added to log messages that are written within this context. For example, the Web UI adds a session ID, so that when the logs are analyzed the actions of a particular user in a particular session can be tracked. - A flag indicating whether authorization should be circumvented. This should only be used in rare, specific circumstances. For example, when first installing the system, there are no authorized administrators who would be able to create an administrator account!As noted above, the public API is trusted, so it is up to applications in the application layer to use this flag responsibly. Typical use of the context object will involve constructing one, and setting the current user if one is authenticated. Several operations may be performed using the context object. If all goes well, complete is called to commit the changes and free up any resources used by the context. If anything has gone wrong, abort is called to roll back any changes and free up the resources. You should always abort a context if any error happens during its lifespan; otherwise the data in the system may be left in an inconsistent state. You can also commit a context, which means that any changes are written to the database, and the context is kept active for further use. Sending e-mails is pretty easy. Just use the configuration manager's getEmail method, set the arguments and recipients, and send. The e-mail texts are stored in [dspace]/config/emails. They are processed by the standard java.text.MessageFormat. At the top of each e-mail are listed the appropriate arguments that should be filled out by the sender. Example usage is shown in the org.dspace.core.Email Javadoc API documentation. LogManager The log manager consists of a method that creates a standard log header, and returns it as a string suitable for logging. Note that this class does not actually write anything to the logs; the log header returned should be logged directly by the sender using an appropriate Log4J call, so that information about where the logging is taking place is also stored. The level of logging can be configured on a per-package or per-class basis by editing [dspace]/config/log4j.properties. You will need to stop and restart Tomcat for the changes to take effect. A typical log entry looks like this: 2002-11-11 08:11:32,903 INFO org.dspace.app.webui.servlet.DSpaceServlet @ anonymous:session_id=BD84E7C194C2CF4BD0EC3A6CAD0142BB:view_item:handle=1721.1/1686 This is breaks down like this: The above format allows the logs to be easily parsed and analyzed. The [dspace]/bin/log-reporter script is a simple tool for analyzing logs. Try: [dspace]/bin/log-reporter --help It's a good idea to 'nice' this log reporter to avoid an impact on server performance. Utils Utils contains miscellaneous utility method that are required in a variety of places throughout the code, and thus have no particular 'home' in a subsystem. Content Management API The content management API package org.dspace.content contains Java classes for reading and manipulating content stored in the DSpace system. This is the API that components in the application layer will probably use most. Classes corresponding to the main elements in the DSpace data model (Community, Collection, Item, Bundle and Bitstream) are sub-classes of the abstract class DSpaceObject. The Item object handles the Dublin Core metadata record. Each class generally has one or more static find methods, which are used to instantiate content objects. Constructors do not have public access and are just used internally. The reasons for this are: "Constructing" an object may be misconstrued as the action of creating an object in the DSpace system, for example one might expect something like: Context dsContent = new Context(); Item myItem = new Item(context, id) to construct a brand new item in the system, rather than simply instantiating an in-memory instance of an object in the system. - find methods may often be called with invalid IDs, and return null in such a case. A constructor would have to throw an exception in this case. A null return value from a static method can in general be dealt with more simply in code. - If an instantiation representing the same underlying archival entity already exists, the find method can simply return that same instantiation to avoid multiple copies and any inconsistencies which might result. Collection, Bundle and Bitstream do not have create methods; rather, one has to create an object using the relevant method on the container. For example, to create a collection, one must invoke createCollection on the community that the collection is to appear in: Context context = new Context(); Community existingCommunity = Community.find(context, 123); Collection myNewCollection = existingCommunity.createCollection(); The primary reason for this is for determining authorization. In order to know whether an e-person may create an object, the system must know which container the object is to be added to. It makes no sense to create a collection outside of a community, and the authorization system does not have a policy for that. Item_s are first created in the form of an implementation of _InProgressSubmission. An InProgressSubmission represents an item under construction; once it is complete, it is installed into the main archive and added to the relevant collection by the InstallItem class. The org.dspace.content package provides an implementation of InProgressSubmission called WorkspaceItem; this is a simple implementation that contains some fields used by the Web submission UI. The org.dspace.workflow also contains an implementation called WorkflowItem which represents a submission undergoing a workflow process. In the previous chapter there is an overview of the item ingest process which should clarify the previous paragraph. Also see the section on the workflow system. Community and BitstreamFormat do have static create methods; one must be a site administrator to have authorization to invoke these. Other Classes Classes whose name begins DC are for manipulating Dublin Core metadata, as explained below. The FormatIdentifier class attempts to guess the bitstream format of a particular bitstream. Presently, it does this simply by looking at any file extension in the bitstream name and matching it up with the file extensions associated with bitstream formats. Hopefully this can be greatly improved in the future! The ItemIterator class allows items to be retrieved from storage one at a time, and is returned by methods that may return a large number of items, more than would be desirable to have in memory at once. The ItemComparator class is an implementation of the standard java.util.Comparator that can be used to compare and order items based on a particular Dublin Core metadata field. Modifications When creating, modifying or for whatever reason removing data with the content management API, it is important to know when changes happen in-memory, and when they occur in the physical DSpace storage. Primarily, one should note that no change made using a particular org.dspace.core.Context object will actually be made in the underlying storage unless complete or commit is invoked on that Context. If anything should go wrong during an operation, the context should always be aborted by invoking abort, to ensure that no inconsistent state is written to the storage. Additionally, some changes made to objects only happen in-memory. In these cases, invoking the update method lines up the in-memory changes to occur in storage when the Context is committed or completed. In general, methods that change any metadata field only make the change in-memory; methods that involve relationships with other objects in the system line up the changes to be committed with the context. See individual methods in the API Javadoc. Some examples to illustrate this are shown below: What's In Memory? Instantiating some content objects also causes other content objects to be loaded into memory. Instantiating a Bitstream object causes the appropriate BitstreamFormat object to be instantiated. Of course the Bitstream object does not load the underlying bits from the bitstream store into memory! Instantiating a Bundle object causes the appropriate Bitstream objects (and hence _BitstreamFormat_s) to be instantiated. Instantiating an Item object causes the appropriate Bundle objects (etc.) and hence _BitstreamFormat_s to be instantiated. All the Dublin Core metadata associated with that item are also loaded into memory. The reasoning behind this is that for the vast majority of cases, anyone instantiating an item object is going to need information about the bundles and bitstreams within it, and this methodology allows that to be done in the most efficient way and is simple for the caller. For example, in the Web UI, the servlet (controller) needs to pass information about an item to the viewer (JSP), which needs to have all the information in-memory to display the item without further accesses to the database which may cause errors mid-display. You do not need to worry about multiple in-memory instantiations of the same object, or any inconsistencies that may result; the Context object keeps a cache of the instantiated objects. The find methods of classes in org.dspace.content will use a cached object if one exists. It may be that in enough cases this automatic instantiation of contained objects reduces performance in situations where it is important; if this proves to be true the API may be changed in the future to include a loadContents method or somesuch, or perhaps a Boolean parameter indicating what to do will be added to the find methods. When a Context object is completed, aborted or garbage-collected, any objects instantiated using that context are invalidated and should not be used (in much the same way an AWT button is invalid if the window containing it is destroyed). Dublin Core Metadata The Metadatum class is a simple container that represents a single Dublin Core-like element, optional qualifier, value and language. Note that since DSpace 1.4 the MetadataValue and associated classes are preferred (see Support for Other Metadata Schemas). The other classes starting with DC are utility classes for handling types of data in Dublin Core, such as people's names and dates. As supplied, the DSpace registry of elements and qualifiers corresponds to the Library Application Profile for Dublin Core. It should be noted that these utility classes assume that the values will be in a certain syntax, which will be true for all data generated within the DSpace system, but since Dublin Core does not always define strict syntax, this may not be true for Dublin Core originating outside DSpace. Below is the specific syntax that DSpace expects various fields to adhere to: Support for Other Metadata Schemas To support additional metadata schemas a new set of metadata classes have been added. These are backwards compatible with the DC classes and should be used rather than the DC specific classes wherever possible. Note that hierarchical metadata schemas are not currently supported, only flat schemas (such as DC) are able to be defined. The MetadataField class describes a metadata field by schema, element and optional qualifier. The value of a MetadataField is described by a MetadataValue which is roughly equivalent to the older Metadatum class. Finally the MetadataSchema class is used to describe supported schemas. The DC schema is supported by default. Refer to the javadoc for method details. Packager Plugins The Packager plugins let you ingest a package to create a new DSpace Object, and disseminate a content Object as a package. A package is simply a data stream; its contents are defined by the packager plugin's implementation. To ingest an object, which is currently only implemented for Items, the sequence of operations is: - Get an instance of the chosen PackageIngester plugin. - Locate a Collection in which to create the new Item. - Call its ingest method, and get back a WorkspaceItem. The packager also takes a PackageParameters object, which is a property list of parameters specific to that packager which might be passed in from the user interface. Here is an example package ingestion code fragment: Collection collection = find target collection InputStream source = ...; PackageParameters params = ...; String license = null; PackageIngester sip = (PackageIngester) PluginManager .getNamedPlugin(PackageIngester.class, packageType); WorkspaceItem wi = sip.ingest(context, collection, source, params, license); Here is an example of a package dissemination: OutputStream destination = ...; PackageParameters params = ...; DSpaceObject dso = ...; PackageIngester dip = (PackageDisseminator) PluginManager .getNamedPlugin(PackageDisseminator.class, packageType); dip.disseminate(context, dso, params, destination); Plugin Manager The PluginManager is a very simple component container. It creates and organizes components (plugins), and helps select a plugin in the cases where there are many possible choices. It also gives some limited control over the life cycle of a plugin. Concepts The following terms are important in understanding the rest of this section: - Plugin Interface A Java interface, the defining characteristic of a plugin. The consumer of a plugin asks for its plugin by interface. - Plugin a.k.a. Component, this is an instance of a class that implements a certain interface. It is interchangeable with other implementations, so that any of them may be "plugged in", hence the name. A Plugin is an instance of any class that implements the plugin interface. - Implementation class The actual class of a plugin. It may implement several plugin interfaces, but must implement at least one. - Name Plugin implementations can be distinguished from each other by name, a short String meant to symbolically represent the implementation class. They are called "named plugins". Plugins only need to be named when the caller has to make an active choice between them. - SelfNamedPlugin class Plugins that extend the SelfNamedPlugin class can take advantage of additional features of the Plugin Manager. Any class can be managed as a plugin, so it is not necessary, just possible. - Reusable Reusable plugins are only instantiated once, and the Plugin Manager returns the same (cached) instance whenever that same plugin is requested again. This behavior can be turned off if desired. Using the Plugin Manager Types of Plugin The Plugin Manager supports three different patterns of usage: - Singleton Plugins There is only one implementation class for the plugin. It is indicated in the configuration. This type of plugin chooses an implementation of a service, for the entire system, at configuration time. Your application just fetches the plugin for that interface and gets the configured-in choice. See the getSinglePlugin() method. - Sequence Plugins You need a sequence or series of plugins, to implement a mechanism like Stackable Authentication or a pipeline, where each plugin is called in order to contribute its implementation of a process to the whole. The Plugin Manager supports this by letting you configure a sequence of plugins for a given interface. See the getPluginSequence() method. - Named Plugins Use a named plugin when the application has to choose one plugin implementation out of many available ones. Each implementation is bound to one or more names (symbolic identifiers) in the configuration. The name is just a string to be associated with the combination of implementation class and interface. It may contain any characters except for comma (,) and equals (=). It may contain embedded spaces. Comma is a special character used to separate names in the configuration entry. Names must be unique within an interface: No plugin classes implementing the same interface may have the same name. Think of plugin names as a controlled vocabulary – for a given plugin interface, there is a set of names for which plugins can be found. The designer of a Named Plugin interface is responsible for deciding what the name means and how to derive it; for example, names of metadata crosswalk plugins may describe the target metadata format. See the getNamedPlugin() method and the getPluginNames() methods. Self-Named Plugins Named plugins can get their names either from the configuration or, for a variant called self-named plugins, from within the plugin itself. Self-named plugins are necessary because one plugin implementation can be configured itself to take on many "personalities", each of which deserves its own plugin name. It is already managing its own configuration for each of these personalities, so it makes sense to allow it to export them to the Plugin Manager rather than expecting the plugin configuration to be kept in sync with it own configuration. An example helps clarify the point: There is a named plugin that does crosswalks, call it CrosswalkPlugin. It has several implementations that crosswalk some kind of metadata. Now we add a new plugin which uses XSL stylesheet transformation (XSLT) to crosswalk many types of metadata – so the single plugin can act like many different plugins, depending on which stylesheet it employs. This XSLT-crosswalk plugin has its own configuration that maps a Plugin Name to a stylesheet – it has to, since of course the Plugin Manager doesn't know anything about stylesheets. It becomes a self-named plugin, so that it reads its configuration data, gets the list of names to which it can respond, and passes those on to the Plugin Manager. When the Plugin Manager creates an instance of the XSLT-crosswalk, it records the Plugin Name that was responsible for that instance. The plugin can look at that Name later in order to configure itself correctly for the Name that created it. This mechanism is all part of the SelfNamedPlugin class which is part of any self-named plugin. Obtaining a Plugin Instance The most common thing you will do with the Plugin Manager is obtain an instance of a plugin. To request a plugin, you must always specify the plugin interface you want. You will also supply a name when asking for a named plugin. A sequence plugin is returned as an array of _Object_s since it is actually an ordered list of plugins. See the getSinglePlugin(), getPluginSequence(), getNamedPlugin() methods. Lifecycle Management When PluginManager fulfills a request for a plugin, it checks whether the implementation class is reusable; if so, it creates one instance of that class and returns it for every subsequent request for that interface and name. If it is not reusable, a new instance is always created. For reasons that will become clear later, the manager actually caches a separate instance of an implementation class for each name under which it can be requested. You can ask the PluginManager to forget about (decache) a plugin instance, by releasing it. See the PluginManager.releasePlugin() method. The manager will drop its reference to the plugin so the garbage collector can reclaim it. The next time that plugin/name combination is requested, it will create a new instance. Getting Meta-Information The PluginManager can list all the names of the Named Plugins which implement an interface. You may need this, for example, to implement a menu in a user interface that presents a choice among all possible plugins. See the getPluginNames() method. Note that it only returns the plugin name, so if you need a more sophisticated or meaningful "label" (i.e. a key into the I18N message catalog) then you should add a method to the plugin itself to return that. Implementation Note: The PluginManager refers to interfaces and classes internally only by their names whenever possible, to avoid loading classes until absolutely necessary (i.e. to create an instance). As you'll see below, self-named classes still have to be loaded to query them for names, but for the most part it can avoid loading classes. This saves a lot of time at start-up and keeps the JVM memory footprint down, too. As the Plugin Manager gets used for more classes, this will become a greater concern. The only downside of "on-demand" loading is that errors in the configuration don't get discovered right away. The solution is to call the checkConfiguration() method after making any changes to the configuration. PluginManager Class The PluginManager class is your main interface to the Plugin Manager. It behaves like a factory class that never gets instantiated, so its public methods are static. Here are the public methods, followed by explanations: static Object getSinglePlugin(Class intface) throws PluginConfigurationError; Returns an instance of the singleton (single) plugin implementing the given interface. There must be exactly one single plugin configured for this interface, otherwise the PluginConfigurationError is thrown. Note that this is the only "get plugin" method which throws an exception. It is typically used at initialization time to set up a permanent part of the system so any failure is fatal. See the plugin.single configuration key for configuration details. static Object[] getPluginSequence(Class intface); Returns instances of all plugins that implement the interface intface, in an Array. Returns an empty array if no there are no matching plugins. The order of the plugins in the array is the same as their class names in the configuration's value field. See the plugin.sequence configuration key for configuration details. static Object getNamedPlugin(Class intface, String name); Returns an instance of a plugin that implements the interface intface and is bound to a name matching name. If there is no matching plugin, it returns null. The names are matched by String.equals(). See the plugin.named and plugin.selfnamed configuration keys for configuration details. static void releasePlugin(Object plugin); Tells the Plugin Manager to let go of any references to a reusable plugin, to prevent it from being given out again and to allow the object to be garbage-collected. Call this when a plugin instance must be taken out of circulation. static String[] getAllPluginNames(Class intface); Returns all of the names under which a named plugin implementing the interface intface can be requested (with getNamedPlugin()). The array is empty if there are no matches. Use this to populate a menu of plugins for interactive selection, or to document what the possible choices are. The names are NOT returned in any predictable order, so you may wish to sort them first. Note: Since a plugin may be bound to more than one name, the list of names this returns does not represent the list of plugins. To get the list of unique implementation classes corresponding to the names, you might have to eliminate duplicates (i.e. create a Set of classes). static void checkConfiguration(); Validates the keys in the DSpace ConfigurationManager pertaining to the Plugin Manager and reports any errors by logging them. This is intended to be used interactively by a DSpace administrator, to check the configuration file after modifying it. See the section about validating configuration for details. SelfNamedPlugin Class A named plugin implementation must extend this class if it wants to supply its own Plugin Name(s). See Self-Named Plugins for why this is sometimes necessary. abstract class SelfNamedPlugin { // Your class must override this: // Return all names by which this plugin should be known. public static String[] getPluginNames(); // Returns the name under which this instance was created. // This is implemented by SelfNamedPlugin and should NOT be overridden. public String getPluginInstanceName(); } Errors and Exceptions public class PluginConfigurationError extends Error { public PluginConfigurationError(String message); } An error of this type means the caller asked for a single plugin, but either there was no single plugin configured matching that interface, or there was more than one. Either case causes a fatal configuration error. public class PluginInstantiationException extends RuntimeException { public PluginInstantiationException(String msg, Throwable cause) } This exception indicates a fatal error when instantiating a plugin class. It should only be thrown when something unexpected happens in the course of instantiating a plugin, e.g. an access error, class not found, etc. Simply not finding a class in the configuration is not an exception. This is a RuntimeException so it doesn't have to be declared, and can be passed all the way up to a generalized fatal exception handler. Configuring Plugins All of the Plugin Manager's configuration comes from the DSpace Configuration Manager, which is a Java Properties map. You can configure these characteristics of each plugin: - Interface: Classname of the Java interface which defines the plugin, including package name. e.g. org.dspace.app.mediafilter.FormatFilter - Implementation Class: Classname of the implementation class, including package. e.g. org.dspace.app.mediafilter.PDFFilter - Names: (Named plugins only) There are two ways to bind names to plugins: listing them in the value of a plugin.named.interface key, or configuring a class in plugin.selfnamed.interface which extends the SelfNamedPlugin class. - Reusable option: (Optional) This is declared in a plugin.reusable configuration line. Plugins are reusable by default, so you only need to configure the non-reusable ones. Configuring Singleton (Single) Plugins This entry configures a Single Plugin for use with getSinglePlugin(): plugin.single.interface = classname For example, this configures the class org.dspace.checker.SimpleDispatcher as the plugin for interface org.dspace.checker.BitstreamDispatcher: plugin.single.org.dspace.checker.BitstreamDispatcher=org.dspace.checker.SimpleDispatcher Configuring Sequence of Plugins This kind of configuration entry defines a Sequence Plugin, which is bound to a sequence of implementation classes. The key identifies the interface, and the value is a comma-separated list of classnames: plugin.sequence.interface = classname, ... The plugins are returned by getPluginSequence() in the same order as their classes are listed in the configuration value. For example, this entry configures Stackable Authentication with three implementation classes: plugin.sequence.org.dspace.eperson.AuthenticationMethod = \ org.dspace.eperson.X509Authentication, \ org.dspace.eperson.PasswordAuthentication, \ edu.mit.dspace.MITSpecialGroup Configuring Named Plugins There are two ways of configuring named plugins: Plugins Named in the Configuration A named plugin which gets its name(s) from the configuration is listed in this kind of entry:_plugin.named.interface = classname = name [ , name.. ] [ classname = name.. ]_The syntax of the configuration value is: classname, followed by an equal-sign and then at least one plugin name. Bind more names to the same implementation class by adding them here, separated by commas. Names may include any character other than comma (,) and equal-sign (=).For example, this entry creates one plugin with the names GIF, JPEG, and image/png, and another with the name TeX: plugin.named.org.dspace.app.mediafilter.MediaFilter = \ org.dspace.app.mediafilter.JPEGFilter = GIF, JPEG, image/png \ org.dspace.app.mediafilter.TeXFilter = TeX This example shows a plugin name with an embedded whitespace character. Since comma (,) is the separator character between plugin names, spaces are legal (between words of a name; leading and trailing spaces are ignored).This plugin is bound to the names "Adobe PDF", "PDF", and "Portable Document Format". plugin.named.org.dspace.app.mediafilter.MediaFilter = \ org.dspace.app.mediafilter.TeXFilter = TeX \ org.dspace.app.mediafilter.PDFFilter = Adobe PDF, PDF, Portable Document Format NOTE: Since there can only be one key with plugin.named. followed by the interface name in the configuration, all of the plugin implementations must be configured in that entry. Self-Named Plugins Since a self-named plugin supplies its own names through a static method call, the configuration only has to include its interface and classname:plugin.selfnamed.interface = classname [ , classname.. ]_The following example first demonstrates how the plugin class, _XsltDisseminationCrosswalk is configured to implement its own names "MODS" and "DublinCore". These come from the keys starting with crosswalk.dissemination.stylesheet.. The value is a stylesheet file. The class is then configured as a self-named plugin: crosswalk.dissemination.stylesheet.DublinCore = xwalk/TESTDIM-2-DC_copy.xsl crosswalk.dissemination.stylesheet.MODS = xwalk/mods.xsl plugin.selfnamed.crosswalk.org.dspace.content.metadata.DisseminationCrosswalk = \ org.dspace.content.metadata.MODSDisseminationCrosswalk, \ org.dspace.content.metadata.XsltDisseminationCrosswalk NOTE: Since there can only be one key with plugin.selfnamed. followed by the interface name in the configuration, all of the plugin implementations must be configured in that entry. The MODSDisseminationCrosswalk class is only shown to illustrate this point. Configuring the Reusable Status of a Plugin Plugins are assumed to be reusable by default, so you only need to configure the ones which you would prefer not to be reusable. The format is as follows: plugin.reusable.classname = ( true | false ) For example, this marks the PDF plugin from the example above as non-reusable: plugin.reusable.org.dspace.app.mediafilter.PDFFilter = false Validating the Configuration The Plugin Manager is very sensitive to mistakes in the DSpace configuration. Subtle errors can have unexpected consequences that are hard to detect: for example, if there are two "plugin.single" entries for the same interface, one of them will be silently ignored. To validate the Plugin Manager configuration, call the PluginManager.checkConfiguration() method. It looks for the following mistakes: - Any duplicate keys starting with "plugin.". - Keys starting plugin.single, plugin.sequence, plugin.named, and plugin.selfnamed that don't include a valid interface. - Classnames in the configuration values that don't exist, or don't implement the plugin interface in the key. - Classes declared in plugin.selfnamed lines that don't extend the SelfNamedPlugin class. - Any name collisions among named plugins for a given interface. - Named plugin configuration entries without any names. - Classnames mentioned in plugin.reusable keys must exist and have been configured as a plugin implementation class. The PluginManager class also has a main() method which simply runs checkConfiguration(), so you can invoke it from the command line to test the validity of plugin configuration changes. Eventually, someone should develop a general configuration-file sanity checker for DSpace, which would just call PluginManager.checkConfiguration(). Use Cases Here are some usage examples to illustrate how the Plugin Manager works. Managing the MediaFilter plugins transparently The existing DSpace 1.3 MediaFilterManager implementation has been largely replaced by the Plugin Manager. The MediaFilter classes become plugins named in the configuration. Refer to the configuration guide for further details. A Singleton Plugin This shows how to configure and access a single anonymous plugin, such as the BitstreamDispatcher plugin: Configuration: plugin.single.org.dspace.checker.BitstreamDispatcher=org.dspace.checker.SimpleDispatcher The following code fragment shows how dispatcher, the service object, is initialized and used: BitstreamDispatcher dispatcher = (BitstreamDispatcher)PluginManager.getSinglePlugin(BitstreamDispatcher .class); int id = dispatcher.next(); while (id != BitstreamDispatcher.SENTINEL) { /* do some processing here */ id = dispatcher.next(); } Plugin that Names Itself This crosswalk plugin acts like many different plugins since it is configured with different XSL translation stylesheets. Since it already gets each of its stylesheets out of the DSpace configuration, it makes sense to have the plugin give PluginManager the names to which it answers instead of forcing someone to configure those names in two places (and try to keep them synchronized). NOTE: Remember how getPlugin() caches a separate instance of an implementation class for every name bound to it? This is why: the instance can look at the name under which it was invoked and configure itself specifically for that name. Since the instance for each name might be different, the Plugin Manager has to cache a separate instance for each name. Here is the configuration file listing both the plugin's own configuration and the PluginManager config line: crosswalk.dissemination.stylesheet.DublinCore = xwalk/TESTDIM-2-DC_copy.xsl crosswalk.dissemination.stylesheet.MODS = xwalk/mods.xsl plugin.selfnamed.org.dspace.content.metadata.DisseminationCrosswalk = \ org.dspace.content.metadata.XsltDisseminationCrosswalk This look into the implementation shows how it finds configuration entries to populate the array of plugin names returned by the getPluginNames() method. Also note, in the getStylesheet() method, how it uses the plugin name that created the current instance (returned by getPluginInstanceName()) to find the correct stylesheet. public class XsltDisseminationCrosswalk extends SelfNamedPlugin { .... private final String prefix = "crosswalk.dissemination.stylesheet."; .... public static String[] getPluginNames() { List aliasList = new ArrayList(); Enumeration pe = ConfigurationManager.propertyNames(); while (pe.hasMoreElements()) { String key = (String)pe.nextElement(); if (key.startsWith(prefix)) aliasList.add(key.substring(prefix.length())); } return (String[])aliasList.toArray(new String[aliasList.size()]); } // get the crosswalk stylesheet for an instance of the plugin: private String getStylesheet() { return ConfigurationManager.getProperty(prefix + getPluginInstanceName()); } } Stackable Authentication The Stackable Authentication mechanism needs to know all of the plugins configured for the interface, in the order of configuration, since order is significant. It gets a Sequence Plugin from the Plugin Manager. Refer to the Configuration Section on Stackable Authentication for further details. Workflow System The primary classes are: The workflow system models the states of an Item in a state machine with 5 states (SUBMIT, STEP_1, STEP_2, STEP_3, ARCHIVE.) These are the three optional steps where the item can be viewed and corrected by different groups of people. Actually, it's more like 8 states, with STEP_1_POOL, STEP_2_POOL, and STEP_3_POOL. These pooled states are when items are waiting to enter the primary states. The WorkflowManager is invoked by events. While an Item is being submitted, it is held by a WorkspaceItem. Calling the start() method in the WorkflowManager converts a WorkspaceItem to a WorkflowItem, and begins processing the WorkflowItem's state. Since all three steps of the workflow are optional, if no steps are defined, then the Item is simply archived. Workflows are set per Collection, and steps are defined by creating corresponding entries in the List named workflowGroup. If you wish the workflow to have a step 1, use the administration tools for Collections to create a workflow Group with members who you want to be able to view and approve the Item, and the workflowGroup[0] becomes set with the ID of that Group. If a step is defined in a Collection's workflow, then the WorkflowItem's state is set to that step_POOL. This pooled state is the WorkflowItem waiting for an EPerson in that group to claim the step's task for that WorkflowItem. The WorkflowManager emails the members of that Group notifying them that there is a task to be performed (the text is defined in config/emails,) and when an EPerson goes to their 'My DSpace' page to claim the task, the WorkflowManager is invoked with a claim event, and the WorkflowItem's state advances from STEP_x_POOL to STEP_x (where x is the corresponding step.) The EPerson can also generate an 'unclaim' event, returning the WorkflowItem to the STEP_x_POOL. Other events the WorkflowManager handles are advance(), which advances the WorkflowItem to the next state. If there are no further states, then the WorkflowItem is removed, and the Item is then archived. An EPerson performing one of the tasks can reject the Item, which stops the workflow, rebuilds the WorkspaceItem for it and sends a rejection note to the submitter. More drastically, an abort() event is generated by the admin tools to cancel a workflow outright. Administration Toolkit The org.dspace.administer package contains some classes for administering a DSpace system that are not generally needed by most applications. The CreateAdministrator class is a simple command-line tool, executed via [dspace]/bin/dspace create-administrator, that creates an administrator e-person with information entered from standard input. This is generally used only once when a DSpace system is initially installed, to create an initial administrator who can then use the Web administration UI to further set up the system. This script does not check for authorization, since it is typically run before there are any e-people to authorize! Since it must be run as a command-line tool on the server machine, generally this shouldn't cause a problem. A possibility is to have the script only operate when there are no e-people in the system already, though in general, someone with access to command-line scripts on your server is probably in a position to do what they want anyway! The DCType class is similar to the org.dspace.content.BitstreamFormat class. It represents an entry in the Dublin Core type registry, that is, a particular element and qualifier, or unqualified element. It is in the administer package because it is only generally required when manipulating the registry itself. Elements and qualifiers are specified as literals in org.dspace.content.Item methods and the org.dspace.content.Metadatum class. Only administrators may modify the Dublin Core type registry. The org.dspace.administer.RegistryLoader class contains methods for initializing the Dublin Core type registry and bitstream format registry with entries in an XML file. Typically this is executed via the command line during the build process (see build.xml in the source.) To see examples of the XML formats, see the files in config/registries in the source directory. There is no XML schema, they aren't validated strictly when loaded in. E-person/Group Manager DSpace keeps track of registered users with the org.dspace.eperson.EPerson class. The class has methods to create and manipulate an EPerson such as get and set methods for first and last names, email, and password. (Actually, there is no getPassword() method‚ an MD5 hash of the password is stored, and can only be verified with the checkPassword() method.) There are find methods to find an EPerson by email (which is assumed to be unique,) or to find all EPeople in the system. The EPerson object should probably be reworked to allow for easy expansion; the current EPerson object tracks pretty much only what MIT was interested in tracking - first and last names, email, phone. The access methods are hardcoded and should probably be replaced with methods to access arbitrary name/value pairs for institutions that wish to customize what EPerson information is stored. Groups are simply lists of EPerson objects. Other than membership, Group objects have only one other attribute: a name. Group names must be unique, so we have adopted naming conventions where the role of the group is its name, such as COLLECTION_100_ADD. Groups add and remove EPerson objects with addMember() and removeMember() methods. One important thing to know about groups is that they store their membership in memory until the update() method is called - so when modifying a group's membership don't forget to invoke update() or your changes will be lost! Since group membership is used heavily by the authorization system a fast isMember() method is also provided. Another kind of Group is also implemented in DSpace‚ special Groups. The Context object for each session carries around a List of Group IDs that the user is also a member of‚ currently the MITUser Group ID is added to the list of a user's special groups if certain IP address or certificate criteria are met. Authorization The primary classes are: The authorization system is based on the classic 'police state' model of security; no action is allowed unless it is expressed in a policy. The policies are attached to resources (hence the name ResourcePolicy,) and detail who can perform that action. The resource can be any of the DSpace object types, listed in org.dspace.core.Constants (BITSTREAM, ITEM, COLLECTION, etc.) The 'who' is made up of EPerson groups. The actions are also in Constants.java (READ, WRITE, ADD, etc.) The only non-obvious actions are ADD and REMOVE, which are authorizations for container objects. To be able to create an Item, you must have ADD permission in a Collection, which contains Items. (Communities, Collections, Items, and Bundles are all container objects.) Currently most of the read policy checking is done with items‚ communities and collections are assumed to be openly readable, but items and their bitstreams are checked. Separate policy checks for items and their bitstreams enables policies that allow publicly readable items, but parts of their content may be restricted to certain groups. Three new attributes have been introduced in the ResourcePolicy class as part of the DSpace 3.0 Embargo Contribution: - rpname: resource policy name - rptype: resource policy type - rpdescription: resource policy description While rpname and rpdescription _are fields manageable by the users the _rptype is a fields managed by the system. It represents a type that a resource policy can assume beteween the following: - TYPE_SUBMISSION: all the policies added automatically during the submission process - TYPE_WORKFLOW: all the policies added automatically during the workflow stage - TYPE_CUSTOM: all the custom policies added by users - TYPE_INHERITED: all the policies inherited by the DSO father. An custom policy, created for the purpose of creating an embargo could look like: policy_id: 4847 resource_type_id: 2 resource_id: 89 action_id: 0 eperson_id: epersongroup_id: 0 start_date: 2013-01-01 end_date: rpname: Embargo Policy rpdescription: Embargoed through 2012 rptype: TYPE_CUSTOM The AuthorizeManager class' authorizeAction(Context, object, action) is the primary source of all authorization in the system. It gets a list of all of the ResourcePolicies in the system that match the object and action. It then iterates through the policies, extracting the EPerson Group from each policy, and checks to see if the EPersonID from the Context is a member of any of those groups. If all of the policies are queried and no permission is found, then an AuthorizeException is thrown. An authorizeAction() method is also supplied that returns a boolean for applications that require higher performance. ResourcePolicies are very simple, and there are quite a lot of them. Each can only list a single group, a single action, and a single object. So each object will likely have several policies, and if multiple groups share permissions for actions on an object, each group will get its own policy. (It's a good thing they're small.) Special Groups All users are assumed to be part of the public group (ID=0.) DSpace admins (ID=1) are automatically part of all groups, much like super-users in the Unix OS. The Context object also carries around a List of special groups, which are also first checked for membership. These special groups are used at MIT to indicate membership in the MIT community, something that is very difficult to enumerate in the database! When a user logs in with an MIT certificate or with an MIT IP address, the login code adds this MIT user group to the user's Context. Miscellaneous Authorization Notes Where do items get their read policies? From the their collection's read policy. There once was a separate item read default policy in each collection, and perhaps there will be again since it appears that administrators are notoriously bad at defining collection's read policies. There is also code in place to enable policies that are timed‚ have a start and end date. However, the admin tools to enable these sorts of policies have not been written. Handle Manager/Handle Plugin The org.dspace.handle package contains two classes; HandleManager is used to create and look up Handles, and HandlePlugin is used to expose and resolve DSpace Handles for the outside world via the CNRI Handle Server code. Handles are stored internally in the handle database table in the form: 1721.123/4567 Typically when they are used outside of the system they are displayed in either URI or "URL proxy" forms: hdl:1721.123/4567 It is the responsibility of the caller to extract the basic form from whichever displayed form is used. The handle table maps these Handles to resource type/resource ID pairs, where resource type is a value from org.dspace.core.Constants and resource ID is the internal identifier (database primary key) of the object. This allows Handles to be assigned to any type of object in the system, though as explained in the functional overview, only communities, collections and items are presently assigned Handles. HandleManager contains static methods for: - Creating a Handle - Finding the Handle for a DSpaceObject, though this is usually only invoked by the object itself, since DSpaceObject has a getHandle method - Retrieving the DSpaceObject identified by a particular Handle - Obtaining displayable forms of the Handle (URI or "proxy URL"). HandlePlugin is a simple implementation of the Handle Server's net.handle.hdllib.HandleStorage interface. It only implements the basic Handle retrieval methods, which get information from the handle database table. The CNRI Handle Server is configured to use this plug-in via its config.dct file. Note that since the Handle server runs as a separate JVM to the DSpace Web applications, it uses a separate 'Log4J' configuration, since Log4J does not support multiple JVMs using the same daily rolling logs. This alternative configuration is located at [dspace]/config/log4j-handle-plugin.properties. The [dspace]/bin/start-handle-server script passes in the appropriate command line parameters so that the Handle server uses this configuration. Search DSpace's search code is a simple API which currently wraps the Lucene search engine. The first half of the search task is indexing, and org.dspace.search.DSIndexer is the indexing class, which contains indexContent() which if passed an Item, Community, or Collection, will add that content's fields to the index. The methods unIndexContent() and reIndexContent() remove and update content's index information. The DSIndexer class also has a main() method which will rebuild the index completely. This can be invoked by the dspace/bin/index-init (complete rebuild) or dspace/bin/index-update (update) script. The intent was for the main() method to be invoked on a regular basis to avoid index corruption, but we have had no problem with that so far. Which fields are indexed by DSIndexer? These fields are defined in dspace.cfg in the section "Fields to index for search" as name-value-pairs. The name must be unique in the form search.index.i (i is an arbitrary positive number). The value on the right side has a unique value again, which can be referenced in search-form (e.g. title, author). Then comes the metadata element which is indexed. '*' is a wildcard which includes all sub elements. For example: search.index.4 = keyword:dc.subject.* tells the indexer to create a keyword index containing all dc.subject element values. Since the wildcard ('*') character was used in place of a qualifier, all subject metadata fields will be indexed (e.g. dc.subject.other, dc.subject.lcsh, etc) By default, the fields shown in the Indexed Fields section below are indexed. These are hardcoded in the DSIndexer class. If any search.index.i items are specified in dspace.cfg these are used rather than these hardcoded fields. The query class DSQuery contains the three flavors of doQuery() methods‚ one searches the DSpace site, and the other two restrict searches to Collections and Communities. The results from a query are returned as three lists of handles; each list represents a type of result. One list is a list of Items with matches, and the other two are Collections and Communities that match. This separation allows the UI to handle the types of results gracefully without resolving all of the handles first to see what kind of content the handle points to. The DSQuery class also has a main() method for debugging via command-line searches. Current Lucene Implementation Currently we have our own Analyzer and Tokenizer classes (DSAnalyzer and DSTokenizer) to customize our indexing. They invoke the stemming and stop word features within Lucene. We create an IndexReader for each query, which we now realize isn't the most efficient use of resources - we seem to run out of filehandles on really heavy loads. (A wildcard query can open many filehandles!) Since Lucene is thread-safe, a better future implementation would be to have a single Lucene IndexReader shared by all queries, and then is invalidated and re-opened when the index changes. Future API growth could include relevance scores (Lucene generates them, but we ignore them,) and abstractions for more advanced search concepts such as booleans. Indexed Fields The DSIndexer class shipped with DSpace indexes the Dublin Core metadata in the following way: Harvesting API The org.dspace.search package also provides a 'harvesting' API. This allows callers to extract information about items modified within a particular timeframe, and within a particular scope (all of DSpace, or a community or collection.) Currently this is used by the Open Archives Initiative metadata harvesting protocol application, and the e-mail subscription code. The Harvest.harvest is invoked with the required scope and start and end dates. Either date can be omitted. The dates should be in the ISO8601, UTC time zone format used elsewhere in the DSpace system. HarvestedItemInfo objects are returned. These objects are simple containers with basic information about the items falling within the given scope and date range. Depending on parameters passed to the harvest method, the containers and item fields may have been filled out with the IDs of communities and collections containing an item, and the corresponding Item object respectively. Electing not to have these fields filled out means the harvest operation executes considerable faster. In case it is required, Harvest also offers a method for creating a single HarvestedItemInfo object, which might make things easier for the caller. Browse API The browse API maintains indexes of dates, authors, titles and subjects, and allows callers to extract parts of these: - Title: Values of the Dublin Core element title (unqualified) are indexed. These are sorted in a case-insensitive fashion, with any leading article removed. For example: "The DSpace System" would appear under 'D' rather than 'T'. - Author: Values of the contributor (any qualifier or unqualified) element are indexed. Since contributor values typically are in the form 'last name, first name', a simple case-insensitive alphanumeric sort is used which orders authors in last name order. Note that this is an index of authors, and not items by author. If four items have the same author, that author will appear in the index only once. Hence, the index of authors may be greater or smaller than the index of titles; items often have more than one author, though the same author may have authored several items. The author indexing in the browse API does have limitations: Ideally, a name that appears as an author for more than one item would appear in the author index only once. For example, 'Doe, John' may be the author of tens of items. However, in practice, author's names often appear in slightly differently forms, for example: Doe, John Doe, John Stewart Doe, John S. Currently, the above three names would all appear as separate entries in the author index even though they may refer to the same author. In order for an author of several papers to be correctly appear once in the index, each item must specify exactly the same form of their name, which doesn't always happen in practice. - Another issue is that two authors may have the same name, even within a single institution. If this is the case they may appear as one author in the index. These issues are typically resolved in libraries with authority control records, in which are kept a 'preferred' form of the author's name, with extra information (such as date of birth/death) in order to distinguish between authors of the same name. Maintaining such records is a huge task with many issues, particularly when metadata is received from faculty directly rather than trained library catalogers. Date of Issue: Items are indexed by date of issue. This may be different from the date that an item appeared in DSpace; many items may have been originally published elsewhere beforehand. The Dublin Core field used is date.issued. The ordering of this index may be reversed so 'earliest first' and 'most recent first' orderings are possible. Note that the index is of items by date, as opposed to an index of dates. If 30 items have the same issue date (say 2002), then those 30 items all appear in the index adjacent to each other, as opposed to a single 2002 entry. Since dates in DSpace Dublin Core are in ISO8601, all in the UTC time zone, a simple alphanumeric sort is sufficient to sort by date, including dealing with varying granularities of date reasonably. For example: 2001-12-10 2002 2002-04 2002-04-05 2002-04-09T15:34:12Z 2002-04-09T19:21:12Z 2002-04-10 - Date Accessioned: In order to determine which items most recently appeared, rather than using the date of issue, an item's accession date is used. This is the Dublin Core field date.accessioned. In other aspects this index is identical to the date of issue index. - Items by a Particular Author: The browse API can perform is to extract items by a particular author. They do not have to be primary author of an item for that item to be extracted. You can specify a scope, too; that is, you can ask for items by author X in collection Y, for example.This particular flavor of browse is slightly simpler than the others. You cannot presently specify a particular subset of results to be returned. The API call will simply return all of the items by a particular author within a certain scope. Note that the author of the item must exactly match the author passed in to the API; see the explanation about the caveats of the author index browsing to see why this is the case. - Subject: Values of the Dublin Core element subject (both unqualified and with any qualifier) are indexed. These are sorted in a case-insensitive fashion. Using the API The API is generally invoked by creating a BrowseScope object, and setting the parameters for which particular part of an index you want to extract. This is then passed to the relevant Browse method call, which returns a BrowseInfo object which contains the results of the operation. The parameters set in the BrowseScope object are: - How many entries from the index you want - Whether you only want entries from a particular community or collection, or from the whole of DSpace - Which part of the index to start from (called the focus of the browse). If you don't specify this, the start of the index is used - How many entries to include before the focus entry To illustrate, here is an example: - We want 7 entries in total - We want entries from collection x - We want the focus to be 'Really' - We want 2 entries included before the focus. The results of invoking Browse.getItemsByTitle with the above parameters might look like this: Rabble-Rousing Rabbis From Sardinia Reality TV: Love It or Hate It? FOCUS> The Really Exciting Research Video Recreational Housework Addicts: Please Visit My House Regional Television Variation Studies Revenue Streams Ridiculous Example Titles: I'm Out of Ideas Note that in the case of title and date browses, Item objects are returned as opposed to actual titles. In these cases, you can specify the 'focus' to be a specific item, or a partial or full literal value. In the case of a literal value, if no entry in the index matches exactly, the closest match is used as the focus. It's quite reasonable to specify a focus of a single letter, for example. Being able to specify a specific item to start at is particularly important with dates, since many items may have the save issue date. Say 30 items in a collection have the issue date 2002. To be able to page through the index 20 items at a time, you need to be able to specify exactly which item's 2002 is the focus of the browse, otherwise each time you invoked the browse code, the results would start at the first item with the issue date 2002. Author browses return String objects with the actual author names. You can only specify the focus as a full or partial literal String. Another important point to note is that presently, the browse indexes contain metadata for all items in the main archive, regardless of authorization policies. This means that all items in the archive will appear to all users when browsing. Of course, should the user attempt to access a non-public item, the usual authorization mechanism will apply. Whether this approach is ideal is under review; implementing the browse API such that the results retrieved reflect a user's level of authorization may be possible, but rather tricky. Index Maintenance The browse API contains calls to add and remove items from the index, and to regenerate the indexes from scratch. In general the content management API invokes the necessary browse API calls to keep the browse indexes in sync with what is in the archive, so most applications will not need to invoke those methods. If the browse index becomes inconsistent for some reason, the InitializeBrowse class is a command line tool (generally invoked using the [dspace]/bin/dspace index-init command) that causes the indexes to be regenerated from scratch. Caveats Presently, the browse API is not tremendously efficient. 'Indexing' takes the form of simply extracting the relevant Dublin Core value, normalizing it (lower-casing and removing any leading article in the case of titles), and inserting that normalized value with the corresponding item ID in the appropriate browse database table. Database views of this table include collection and community IDs for browse operations with a limited scope. When a browse operation is performed, a simple SELECT query is performed, along the lines of: SELECT item_id FROM ItemsByTitle ORDER BY sort_title OFFSET 40 LIMIT 20 There are two main drawbacks to this: Firstly, LIMIT and OFFSET are PostgreSQL-specific keywords. Secondly, the database is still actually performing dynamic sorting of the titles, so the browse code as it stands will not scale particularly well. The code does cache BrowseInfo objects, so that common browse operations are performed quickly, but this is not an ideal solution. Checksum checker Checksum checker is used to verify every item within DSpace. While DSpace calculates and records the checksum of every file submitted to it, the checker can determine whether the file has been changed. The idea being that the earlier you can identify a file has changed, the more likely you would be able to record it (assuming it was not a wanted change). org.dspace.checker.CheckerCommand class, is the class for the checksum checker tool, which calculates checksums for each bitstream whose ID is in the most_recent_checksum table, and compares it against the last calculated checksum for that bitstream. OpenSearch Support DSpace is able to support OpenSearch. For those not acquainted with the standard, a very brief introduction, with emphasis on what possibilities it holds for current use and future development. OpenSearch is a small set of conventions and documents for describing and using 'search engines', meaning any service that returns a set of results for a query. It is nearly ubiquitous‚ but also nearly invisible‚ in modern web sites with search capability. If you look at the page source of Wikipedia, Facebook, CNN, etc you will find buried a link element declaring OpenSearch support. It is very much a lowest-common-denominator abstraction (think Google box), but does provide a means to extend its expressive power. This first implementation for DSpace supports none of these extensions‚ many of which are of potential value‚ so it should be regarded as a foundation, not a finished solution. So the short answer is that DSpace appears as a 'search-engine' to OpenSearch-aware software. Another way to look at OpenSearch is as a RESTful web service for search, very much like SRW/U, but considerably simpler. This comparative loss of power is offset by the fact that it is widely supported by web tools and players: browsers understand it, as do large metasearch tools. How Can It Be Used - Browser IntegrationMany recent browsers (IE7+, FF2+) can detect, or 'autodiscover', links to the document describing the search engine. Thus you can easily add your or other DSpace instances to the drop-down list of search engines in your browser. This list typically appears in the upper right corner of the browser, with a search box. In Firefox, for example, when you visit a site supporting OpenSearch, the color of the drop-down list widget changes color, and if you open it to show the list of search engines, you are offered an opportunity to add the site to the list. IE works nearly the same way but instead labels the web sites 'search providers'. When you select a DSpace instance as the search engine and enter a search, you are simply sent to the regular search results page of the instance. Flexible, interesting RSS FeedsBecause one of the formats that OpenSearch specifies for its results is RSS (or Atom), you can turn any search query into an RSS feed. So if there are keywords highly discriminative of content in a collection or repository, these can be turned into a URL that a feed reader can subscribe to. Taken to the extreme, one could take any search a user makes, and dynamically compose an RSS feed URL for it in the page of returned results. To see an example, if you have a DSpace with OpenSearch enabled, try:<your query> The default format returned is Atom 1.0, so you should see an Atom document containing your search results. You can extend the syntax with a few other parameters, as follows: Multiple parameters may be specified on the query string, using the "&" character as the delimiter, e.g.:<your query>&format=rss&scope=123456789/1 - Cheap metasearchSearch aggregators like A9 (Amazon) recognize OpenSearch-compliant providers, and so can be added to metasearch sets using their UIs. Then you site can be used to aggregate search results with others. Configuration is through the dspace.cfg file. See OpenSearch Support for more details. Embargo Support What is an Embargo? An embargo is a temporary access restriction placed on content, commencing at time of accession. It's or Collections, Bitstreams, etc. The embargo functionally introduced in 1.6, however, includes tools to automate the imposition and removal of restrictions in managed timeframes. Embargo Model and Life-Cycle in your own 'interpreters' to cope with any terms expressions you wish to have. This date that is the result of the interpretation is stored with the item and section on Extending Embargo Functionality removed. This is not an automatic process, however: a 'lifter' must be run periodically to look for items whose 'lift date' is past. Note that this means the effective removal of an embargo is not the lift date,‚ anyone with edit permissions on metadata) to change the lift date, they can do so. Thus, they. it's policies from its owning collection. As with all other parts of the embargo system, you may replace or extend the default behavior of the lifter (see section V., they are indistinguishable from items that were never subject to embargo. 1 Comment Gerrit Hübbers The Dublin Core Metadata table currently gives as an example for language.iso: "_en fr en_US _". I think the text markup is wrong here.
https://wiki.duraspace.org/display/DSDOC5x/Business+Logic+Layer
CC-MAIN-2018-26
refinedweb
10,972
53.81
NAME vga_flip - toggle between text and graphics mode SYNOPSIS #include <vga.h> int vga_flip(void); DESCRIPTION switches between graphics and text mode without destroying the screen contents. This makes it possible for your application to use both text and graphics output. However, This is an old vgalib function. You should really only use it for debugging as it runs extremely unstable because svgalib now does its own virtual console management. If you want to perform a similar action, save the current screen contents with ordinary memory copy operation to the frame buffer or gl_getbox(3), set vga_setmode(TEXT), then call vga_setmode(3) to return to graphics operation and restore the screen contents with memory or gl_putbox(3). One could also use vga_drawscansegment(3) and vga_getscansegment(3) calls. However, avoid any calls to vga_flip() in your applications. The function always returns 0, a fact on which you shouldn’t rely. It might be useful if you are debugging one of your svgalib applications though. If your program reaches a breakpoint while in graphics mode, you can switch to text mode with the gdb command print vga_flip() and later restore the graphics screen contents with the same command. It is useful to define the following alias in gdb: define flip <Return> print vga_flip() <Return> end <Return> SEE ALSO svgalib(7), vgagl(7), libvga.config(5), vga_init(3), vga_setflipchar(3), vga_drawscanline(3), vga_drawscansegment(3), vga_getscansegment(3), gl_getbox(3), gl_putbox.
http://manpages.ubuntu.com/manpages/hardy/man3/vga_flip.3.html
CC-MAIN-2014-10
refinedweb
236
54.52
VCL, which stands for Varnish Configuration Language, is used to define your own caching policies in Varnish Cache and Varnish Enterprise. It is a real programming language whose syntax can in some cases be the same as the C language. The upside of learning VCL is that, once you master it, you are able to define perfect caching policies and ensure that your Varnish Cache instance behaves exactly how you expect in every circumstance and under a variety of conditions. The downside is, of course, that you will have to learn a new programming language. In this blog post we won’t discuss the syntax itself, but most likely I’ll point out some interesting VCL tips and not very well-known VCL rules. - builtin.vcl is always appended to default.vcl When you install Varnish Cache or Varnish Enterprise, other than the binaries you also get two *.vcl files: builtin.vcl: Varnish Cache’s built-in behavior if you don’t define any other .vcl file. A built-in behavior is necessary to avoid wrong or even disruptive caching policies and to give you the ability to start caching immediately. default.vcl: this is the VCL file you can tweak to change the behavior of Varnish Cache. What is not very well-known is that builtin.vcl is, if no “return(action)” is defined, always appended to the default.vcl or any other VCL file you might have defined. For example: if in you default.vcl you define: sub vcl_hash { }your Varnish Cache will instead see: sub vcl_hash { hash_data(req.url); if (req.http.host) { hash_data(req.http.host); } else { hash_data(server.ip); } return (lookup); } This is because the builtin subroutine for vcl_hash will be appended to your empty vcl_hash. As a rule of thumb, we strongly suggest that you let builtin.vcl be appended to your VCL to avoid unhappy situations. If you don’t want the builtin.vcl to be appended to your VCL file, then you need to specify a “return(action)”, which exits one state/subroutine and instructs Varnish to proceed to the next state/subroutine. If you must “return” from any subroutine, please test your VCL extensively before using it in a production environment. (More on Varnishtest). PCRE Varnish Cache and Varnish Enterprise rely on PCRE to process regular expressions. if (bereq.url ~ "\.(aif|aiff|au|avi|bin|bmp|cab|carb|cct|cdf|class|css)$" || bereq.url ~ "\.(dcr|doc|dtd|eps|exe|flv|gcf|gff|gif|grv|hdml|hqx)$" || bereq.url ~ "\.(ico|ini|jpeg|jpg|js|mov|mp3|nc|pct|pdf|png|ppc|pws)$" || bereq.url ~ "\.(swa|swf|tif|txt|vbs|w32|wav|wbmp|wml|wmlc|wmls|wmlsc)$"|| bereq.url ~ "\.(eot|woff|svg|ttf)"|| bereq.url ~ "\.(xml|xsd|xsl|zip)$") PCRE sometimes misbehaves and crashes when heavy recursive regular expressions are used. You can try to simplify as much as possible your regular expressions, breaking them down into smaller expressions. It is also suggested that you increase the thread_pool_stack parameter, which represents the thread stack size. - Strange hashing schemes: sub vcl_hash { hash_data(req.http.Cookie); return(lookup); } This VCL snippet inserts and searches for objects in cache based only on the request Cookie header and here we have at least two problems: - If the request has no Cookie header (very unlikely), no object will be inserted in cache. This is already in conflict with the purpose Varnish Cache serves, which is caching content and making your website faster. If no content is cached, then you can’t really see any performance improvements. - Cookie headers are unique to a user. Therefore when we insert objects in cache based on a Cookie header most likely the objects in cache will be equal one to another, but will be considered as different by Varnish Cache because the Cookie header changes based on the user. This leads to a very fragmented cache that contains more than a single copy of the same content. If you want to change the default Varnish Cache or Varnish Enterprise hashing scheme, do consider every possible scenario and their consequences. Hopefully this blog post will help anyone who is an active VCL writer to define better and more secure caching policies. If you want to learn more about VCL, the Varnish-Book is a great place to start.
https://info.varnish-software.com/blog/varnish-configuration-language-best-practices-3-tips
CC-MAIN-2020-16
refinedweb
715
55.34
15 November 2010 05:16 [Source: ICIS news] SINGAPORE (ICIS)--Shell Chemicals has hiked its December monoethylene glycol (MEG) Asian Contract Price (ACP) by $120/tonne (€88/tonne) from its November nomination, a source with the Anglo-Dutch major said on Monday. “Our December ACP has been proposed at $1,150/tonne CFR (cost and freight) ?xml:namespace> The price hike, however, was not supported by the current MEG market, said a Zhejiang-based end-user. MEG spot prices in Asia had a roller coaster ride last week - prices hit 29-month highs of $1,150-1,180/tonne CFR CMP (China Main Port) on Tuesday, but plunged $150-160/tonne to close at $1,000-1,020/tonne CFR CMP on Friday, according to ICIS. The current weakness was to be expected following recent spectacular gains, said the source from Shell. But in the long run, the Asia MEG values were expected to strengthen as demand continued to grow while supply was steady, the source
http://www.icis.com/Articles/2010/11/15/9410222/shell-raises-december-meg-acp-nomination-by-120tonne.html
CC-MAIN-2014-42
refinedweb
166
55.37
Hello everyone, the main java file that does the upload. Here I am trying to open audio from the gallery. However you can change it to image or video according to your need. The code for upload will not change since we change only the code for opening the gallery. We use only the path of the selected file whether it is image or video or audio to upload. These are for downloading files from the server. 1. If you want to download file using VOLLEY, CHECK HERE. 2. How to Download an image in ANDROID programatically? 3. How to download a file to your android device from a remote server with a custom progressbar showing progress? Layout <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns: <Button android: <Button android: <TextView android: </LinearLayout> MainActivity package file_upload_demo.coderzheaven.com.fileuploaddemo; import android.annotation.SuppressLint; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.provider.DocumentsContract; import android.provider.MediaStore; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.TextView; import java.util.regex.Matcher; import java.util.regex.Pattern; public class MainActivity extends AppCompatActivity implements View.OnClickListener, Handler.Callback { private static final String TAG = MainActivity.class.getSimpleName(); private static final int SELECT_AUDIO = 2; private String selectedPath; private Handler handler; private TextView tvStatus; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViewById(R.id.selectFile).setOnClickListener(this); findViewById(R.id.uploadFile).setOnClickListener(this); tvStatus = findViewById(R.id.tvStatus); handler = new Handler(this); } public void openGallery() { Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, "Select Image "), SELECT_AUDIO); } public void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_OK) { if (requestCode == SELECT_AUDIO) { Uri selectedImageUri = data.getData(); selectedImageUri = handleImageUri(selectedImageUri); selectedPath = getRealPathFromURI(selectedImageUri); tvStatus.setText("Selected Path :: " + selectedPath); Log.i(TAG, " Path :: " + selectedPath); } } } public static Uri handleImageUri(Uri uri) { if (uri.getPath().contains("content")) { Pattern pattern = Pattern.compile("(content://media/.*\\d)"); Matcher matcher = pattern.matcher(uri.getPath()); if (matcher.find()) return Uri.parse(matcher.group(1)); else throw new IllegalArgumentException("Cannot handle this URI"); } return uri; } @SuppressLint("NewApi") public String getRealPathFromURI(Uri uri) { String filePath = ""; String wholeID = DocumentsContract.getDocumentId(uri); // Split at colon, use second item in the array String id = wholeID.split(":")[1]; String[] column = {MediaStore.Images.Media.DATA}; // where id is equal to String sel = MediaStore.Images.Media._ID + "=?"; Cursor cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, column, sel, new String[]{id}, null); int columnIndex = cursor.getColumnIndex(column[0]); if (cursor.moveToFirst()) { filePath = cursor.getString(columnIndex); } cursor.close(); return filePath; } @Override public void onClick(View v) { if (v.getId() == R.id.selectFile) { openGallery(); } if (v.getId() == R.id.uploadFile) { if (null != selectedPath && !selectedPath.isEmpty()) { tvStatus.setText("Uploading..." + selectedPath); FileUploadUtility.doFileUpload(selectedPath, handler); } } } @Override public boolean handleMessage(Message msg) { Log.i("File Upload", "Response :: " + msg.obj); String success = 1 == msg.arg1 ? "File Upload Success" : "File Upload Error"; Log.i(TAG, success); tvStatus.setText(success); return false; } } Fie Upload Utility package file_upload_demo.coderzheaven.com.fileuploaddemo; import android.os.Handler; import android.os.Message; import android.util.Log; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; public class FileUploadUtility { static String SERVER_PATH = ""; public static void doFileUpload(final String selectedPath, final Handler handler) { new Thread(new Runnable() { @Override public void run() { HttpURLConnection conn = null; DataOutputStream dos = null; DataInputStream inStream = null; String lineEnd = "rn"; String twoHyphens = "--"; String boundary = "*****"; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1 * 1024 * 1024; String responseFromServer = ""; try { //------------------ CLIENT REQUEST FileInputStream fileInputStream = new FileInputStream(new File(selectedPath)); // open a URL connection to the Servlet URL url = new URL(SERVER_PATH); // Open a HTTP connection to the URL conn = (HttpURLConnection) url.openConnection(); // Allow Inputs conn.setDoInput(true); // Allow Outputs conn.setDoOutput(true); // Don't use a cached copy. conn.setUseCaches(false); // Use a post method. conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); dos = new DataOutputStream(conn.getOutputStream()); dos.writeBytes(twoHyphens + boundary + lineEnd); dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + selectedPath + "\"" + lineEnd); dos.writeBytes(lineEnd); // create a buffer of maximum size bytesAvailable = fileInputStream.available();); // close streams Log.e("Debug", "File is written"); fileInputStream.close(); dos.flush(); dos.close(); } catch (MalformedURLException ex) { Log.e("Debug", "error: " + ex.getMessage(), ex); sendMessageBack(responseFromServer, 0, handler); return; } catch (IOException ioe) { Log.e("Debug", "error: " + ioe.getMessage(), ioe); sendMessageBack(responseFromServer, 0, handler); return; } responseFromServer = processResponse(conn, responseFromServer); sendMessageBack(responseFromServer, 1, handler); } }).start(); } private static String processResponse(HttpURLConnection conn, String responseFromServer) { DataInputStream inStream; try { inStream = new DataInputStream(conn.getInputStream()); String str; while ((str = inStream.readLine()) != null) { responseFromServer = str; } inStream.close(); } catch (IOException ioex) { Log.e("Debug", "error: " + ioex.getMessage(), ioex); } return responseFromServer; } static void sendMessageBack(String responseFromServer, int success, Handler handler) { Message message = new Message(); message.obj = responseFromServer; message.arg1 = success; handler.sendMessage(message); } } Server Side Now the server side , the code is written in Php. <?php // Where the file is going to be placed $target_path = "uploads/"; /* Add the original filename to our target path. Result is "uploads/filename.extension" */ $target_path = $target_path . basename( $_FILES['uploadedfile']['name']); if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) { echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded"; } else{ echo "There was an error uploading the file, please try again!"; echo "filename: " . basename( $_FILES['uploadedfile']['name']); echo "target_path: " .$target_path; } ?> Things to keep in mind 1. Make sure your server is running. 2. Your server file path should be right. 3. Check your folder write permission in the server. Please leave your valuable comments. Enjoy. Source Code You can download Android Studio source code from here. Pingback: How to Upload Multiple files in one request along with other string parameters in android? | Coderz Heaven Hi Thanks for this tutorial.. Can you tell me how to store images in the emulator database and retrieve images from the database on to the emulator.. example: doctor list with their images on the emulator.. Waiting for your reply… Its not good to store images in the database. instead copy it into a folder in your Sdcard or application sandbox and save the path of that file in your database. For example if you have a number of images, copy it to drawable folder and store their names in the database and load it using that name. if you are downloading the images then download it to your application sandbox or sdcard and then load it from there. and how to view the uploaded files on Android in the form of a gallery? how do we take it from server to Android? @agatha:- I can’t understand the que actually. Do you want to see the uploaded files in your server in your android phone or what? You can download the image from your server to your android device. check this post to how to download the images () Thanks for such nice tutorial. It is really help me. Thank you very much!! Its good thanks but when i m trying to upload a file having size more than 100KB it fails, without showing any error after some time it jumps to another file for uploading. Can you suggest me for this … Hey…check your php.ini file and check your parameters such as ‘upload_max_filesize’, ‘post_max_size’, ‘max_input_time’, ‘max_execution_time’…once you set them up make sure you restart your apache service Hey I tried my best to compile this code. but it gives many more errors. So can you please send me a link to download a course code to this function as soon as possible. Thanks and Best Regards, Shehan. Hi thanks for your tutorial,it’s awesome i try it in windows and it’s work but when i try in linux it’s doesn’t work what should i do??if trouble with folder permission i am not sure because i have modified the permission please help me..thank you 🙂 @Baskoro :- Check what is the error message coming and paste it here. Hi, Thanks for this valuable post. It helps me a lot. I have 2 doubts before implementing this solution in my app. 1. Will this program supports uploading files greater than 10MB 2. My PHP webserver is hosted on a shared hosting server where the PHP upload limit is defined as 2 MB. In this case will this program upload files greater than 10MB? Answers 1. Yes 2. Yes, if Your server allows it. I dont understand what do you mean by “if Your server allows it”. Do you mean the PHP.INI variable “post_max_size” I checked out your code. I have a doubt.. Is this code allows user to send a very large file ie., greater than 20 MB.. Bcoz i tried many ways, i can upload 5MB of file sucessfully but wen i try to upload 20MB iam getting “OUT OF MEMORY” Exception.. Plz help Try increasing the buffersize. Hi,thanks for the nice post.But i have a doubt in this.After the file was written to the server it takes more than to two minutes to get the response from the server.So i want to know that does the reading of response depends upon the device internet speed? Yes,of course. Iam using 3G connection to upload file to the server.Will exception rise does the 3G connection disabled while uploading the video? Pingback: Uploading and Downloading of files - Popular and Useful posts. hi thanks for nice post. i want to send some more parameters with the video. how to add that parameters to this code. like name,about the video etc can send to the service how to add parameter to this code? I am gettng “There was an error uploading the file, please try again!” all the times. also i am not getting the name of my file from the server. Help me out. hey Dhaval, please check your internet connection, server path and the file name variables. Also add the internet permission in the Android Manifest file. I got it. The “\” were missing in the code above, the line: String lineEnd = “rn”; should be String line End = “\r\n”; actually. Also the line “dos.writeBytes(“Content-Disposition…” had same issue. Placed “\”s and all set. Thanks for you reply Hey nice post . It worked form me please provide the code to send parameters with this file . Like if i want to send “key” with this file . Please reply ASAP Check this post Hi, can you help me with this. the code is correct yet i can’t upload the file. it was force close. “the application has stopped unexpectedly.please try again later. what should be the solution for this? i got error in php file i tried to generate service in server it shows as follows( i am new to php please help me….. thank you) Warning: fopen(uploaded_image.jpg) [function.fopen]: failed to open stream: Permission denied in /home/inspirei/public_html/bramara/upload/img.php on line 5 Warning: fclose(): supplied argument is not a valid stream resource in /home/inspirei/public_html/bramara/upload/img.php on line 7 Image upload complete!!, Please check your php file directory…… ¦ Check your permissions in the PHP Server directory. You should set a write permission for the image to be uploaded in the server. thx for code..but i have error like this.. Notice: Undefined index: uploads in C:\xampp\htdocs\upload_test\upload_media_test.php on line 5 what’s wrong?? please help me..thx dos.writeBytes(“Content-Disposition: form-data; name=”uploadedfile”;filename=”” + selectedPath + “”” + lineEnd); dos.writeBytes(lineEnd); getting error on this lines plz help me out What is the error? can you please paste it here. To resolve syntax error in Vikrant post dos.writeBytes(“Content-Disposition: form-data; name=\”uploaded_file\”;filename=\””+ selectedPath + “\”” + lineEnd); dos.writeBytes(“Content-Disposition: form-data; name=”uploadedfile”;filename=”” + selectedPath + “”” + lineEnd); dos.writeBytes(lineEnd); getting error on this lines plz help me out Error : Syntax error on Tokens, delete this tokens Use: dos.writeBytes(“Content-Disposition: form-data; name=’uploaded_file’;filename='” + fileName + “‘” + lineEnd); I’ve used the next line to try and handle the code error – dos.writeBytes(“Content-Disposition: form-data; name=’uploaded_file’;filename='”+ fileName + “‘” + lineEnd); But now only – fileName – is being an error – anyone knows why is that? There is a “semicolon” in between your code in param “writeBytes”… remove that… Can you exactly give the line because still i am getting error. Hi i need to upload audio file to a online server and download it. please help. You just need to follow this tutorial for uploading and this link for downloading. 09-28 03:46:14.554: E/Debug(10081): Server Response 09-28 03:46:14.584: E/Debug(10081): Server Response Notice: Undefined index: uploadedfile in C:\xampp\htdocs\android\audio.php on line 5 09-28 03:46:14.594: E/Debug(10081): Server Response 09-28 03:46:14.604: E/Debug(10081): Server Response Notice: Undefined index: uploadedfile in C:\xampp\htdocs\android\audio.php on line 10 09-28 03:46:14.604: E/Debug(10081): Server Response 09-28 03:46:14.604: E/Debug(10081): Server Response Notice: Undefined index: uploadedfile in C:\xampp\htdocs\android\audio.php on line 12 09-28 03:46:14.604: E/Debug(10081): Server Response There was an error uploading the file, please try again! 09-28 03:46:14.614: E/Debug(10081): Server Response Notice: Undefined index: uploadedfile in C:\xampp\htdocs\android\audio.php on line 17 09-28 03:46:14.614: E/Debug(10081): Server Response filename: target_path: uploads/ same problem here Thanks!! Its Working. But how can i implement progress bar with calculating uploaded bytes with this Example? Add this line before loop otherwise zero kb data is uploaded on server. // Read file bytesRead = fileInputStream.read(buffer, 0, bufferSize); while (bytesRead > 0) { System.out.println(“Inside while loop”); outputStream.write(buffer, 0, bufferSize); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } Thanks Thanks for the information. Hi very nice post. But this code failed when uploading file size greater than 20MB i.e it throws exception OutOfMemory. How do I increase the buffer size? or any other way to resolve this. thanks should we follow these ” How to create a new Virtual SD card in emulator in ANDROID? How to start emulator with the created SDCard?” and “How to add files like images inside your emulator in ANDROID?” tutorials to open the emulator? thanks I always get 03-15 19:48:59.414: E/Debug(32243): Server Response There was an error uploading the file, please try again!filename: target_path: Upload/ Why? When I am running your code, filename is known but it looks like it is not forwarded with the code Did you check the file path? it is correct? Did you check for null before uploading the file? Nice post. Thanks a lot for these genius posts. Hi I have tried your code for client and server both, and I am getting below response Server Response There was an error uploading the file, please try again!filename: target_path: upload/ Please help me out ..how to solve this and what is the issue ? Did you check your server folder permission where you are uploading the file. getting same error… and gave permissions of server folder also Try uploading the image to the server folder from a Client like Filezilla. It should work with the above code. this code not works on android kitkat any solution? Hy, I want to upload large file About 50MB, but I was got error of out of memory. I convert video file in to bytearray then is getting error. I upload video like this. record video and then convert in bytearry for encode base64 and getting string value from encoding file and post data in to our server. please have a solution of that issue then help me. Thank you in advance. i got error, Error converting result java.io.IOException: Attempted read on closed stream. My LOG cant show before dos = new DataOutputStream(conn.getOutputStream()); hllo sr where we place php code in android?? tell me In Your server… I want to upload image, video and audio together. How can i do that with this code ? /* Add the original filename to our target path. Result is “uploads/filename.extension” */ $target_path = $target_path . basename( $_FILES[‘uploadedfile’][‘name’]); i m not getting that what would be the uploadedfile name bcos user can select any file from gallery uploadedfile is the one selected by the user from the gallery. how to Handle Breakdown while uploading and how to Resumable uploading like google play store in android. For resuming you server should support it. No get any response from server shailesh, What error are you getting? php codeignator not work pls help Hello, Running this code, I am getting: HTTP Response: Bad Gateway 502. How can i resolve this issue? Kayode, It would be better to check your server. “The server was acting as a gateway or proxy and received an invalid response from the upstream server.” There are many other 5xx server error messages, all of which boil down to: “The server failed to fulfill an apparently valid request.” is it work of pdf and doc files also It will work on any file, but depends on the server side code. cannot resolve symbol uploadfile? dos.writeBytes(“Content-Disposition: form-data; name=”uploadedfile”;filename=”” + selectedPath + “”” + lineEnd); cannot resolve symbol uploadfile? how resolve it? use ( \ ) before ( each ” ) Thanks For tutorial, but now I Want to upload image with some parameters like name,Description to save mysql database from where i can pass these parameters?? Thanks for the great tutorial Pingback: Загрузите большое видео на PHP-сервер из прил
http://www.coderzheaven.com/2012/03/29/uploading-audio-video-or-image-files-from-android-to-server/?replytocom=1867
CC-MAIN-2019-43
refinedweb
2,987
53.58
I created a little "hello world" type project and added an extra GUI component called "TestComponent" to it. The component has a TextButton and two ToggleButtons in it. I prefer to make all my code very explicit about what it's doing, which means I prefer to make "using namespace" statements rarely, and only in very localized code blocks. I saw in one of the JUCE main headers that you can set the DONT_SET_USING_JUCE_NAMESPACE preprocessor directive to disable the global "using namespace juce;" declaration in that header. Sure enough, when I add DONT_SET_USING_JUCE_NAMESPACE=1 to my global preprocessor directives in the IntroJucer, my compilers don't recognize juce objects without juce:: in front of them. So far, so good. The problem is that when I save the project, all the "juce::" statements that I added to the TestComponent unit in order to make it compile get removed.
https://forum.juce.com/t/dont-set-using-juce-namespace-and-auto-generated-code/15525
CC-MAIN-2022-33
refinedweb
147
59.03
You don't need to copy the jar-file to your webapps/lib in Eclipse. Instead,you can add a external jar-file(which has been copied to tomcat/lib) for the project in Eclipse. On Mon, 18 Jun 2007 15:58:55 +0200 "Kevin Wilhelm" <KevinWilhelm@gmx.net> wrote: > It works! Thanks! > > The problem has been that each webapp had its own shared-lib jar-file, because I am developing in Eclipse. So Eclipse needs to know which classes I am accessing :/ At the end there were 3 times the same jar-file: 1st webapp, 2nd webapp, tomcat/lib. > > Removing the jars from the webapps and leaving the one in tomcat/lib solved the problem. > > However this is very disgusting. Every time I am deploying the 2 webapps to Tomcat, the jars are copied as well. I have to delete them manually, so that only the jar in Tomcat/lib is used. Is there some workaround for this? Should I use Ant for deploying then? But I won't be able to debug the webapps from within my IDE anymore since I am avoiding Eclipse's deployment mechanisms. > > > -------- Original-Nachricht -------- > Datum: Mon, 18 Jun 2007 15:40:36 +0200 > Von: "Johnny Kewl" <john@kewlstuff.co.za> > An: "Tomcat Users List" <users@tomcat.apache.org> > Betreff: Re: Share one singleton across webapps > > > > > The typical form is like this > > > > public class SingletonObject > > { > > private SingletonObject(){} > > > > public static SingletonObject getSingletonObject() > > { > > if (ref == null) > > // it's ok, we can call this constructor > > ref = new SingletonObject(); > > return ref; > > } > > > > private static SingletonObject ref; > > } > > > > If thats in Tomcat/lib.... it should share > > Notice the use of static.... ie there is only one, no matter how many > > times > > its started. > > ...and the check for null.... which is how it determines it needs to make > > one instance if there is non... > > > > Thats the trick.... a normal class which is what I imagine you trying, > > will > > load once..... but instance many times. > > > > Hope that helps... try not use them unless you really have to. > > > > > > > > > > ----- Original Message ----- > > From: "Kevin Wilhelm" <KevinWilhelm@gmx.net> > > To: <users@tomcat.apache.org> > > Sent: Monday, June 18, 2007 3:12 PM > > Subject: Share one singleton across webapps > > > > > > >I managed to get a jar file shared across two webapps in my Tomcat 6. > > > Inside there is a class that represents a Singleton. > > > > > > The problem: the singleton class is instantiated by the first webapp and > > > then again instantiated in the second webapp. So there are 2 > > > representations of the class and it is not really shared. > > > > > > There has to be a way to let the first webapp instantiate the singleton > > > and set some property so that the second webapp can use the singleton > > > and read the property. How do I achieve this? > > > -- > > > Ist Ihr Browser Vista-kompatibel? Jetzt die neuesten > > > Browser-Versionen download > > -- > GMX FreeMail: 1 GB Postfach, 5 E-Mail-Adressen, 10 Free SMS. > Alle Infos und kostenlose Anmeldung: > > --------------------------------------------------------------------- > To start a new topic, e-mail: users@tomcat.apache.org > To unsubscribe, e-mail: users-unsubscribe@tomcat.apache.org > For additional commands, e-mail: users-help@tomcat.apache.org ----------------------------
http://mail-archives.apache.org/mod_mbox/tomcat-users/200706.mbox/%3C20070619135511.17DC.XWU@ublearning.com%3E
CC-MAIN-2015-22
refinedweb
512
67.65
Issues Window does not get focus on OS X with Python 3 A pygame window created using the code below on OS X using the latest pygame source: import pygame pygame.init() screen = pygame.display.set_mode((640, 480)) done = False while not done: pygame.event.pump() keys = pygame.key.get_pressed() if keys[pygame.K_ESCAPE]: done = True if keys[pygame.K_SPACE]: print("got here") events = pygame.event.get() for event in events: if event.type == pygame.MOUSEBUTTONDOWN: print("mouse at ", event.pos) does not receive any keyboard input. It is not possible to trigger the "got here" message nor cause it to terminate using Escape; instead all keypresses show up in the terminal window from which the script was run. This happens even though the window appears to have focus. Additionally, based on the mouse event handling, the window exhibits some combination of the incorrect mouse behavior described in these two issues: viz. all subsequent clicks register with the same position as the first one, and the only way to update its position is to click and drag to a new location. Just wanted to mention that I ran into this issue as well. I got around it by installing the MacPorts version (py27-game) which is an earlier version (1.9.1_8). It only addressed the keyboard input issue...I have not tried the mouse yet. I have the same issue. I couldnt build the 1.9.1 release, i tried a lot of versions between 1.9.1 and the most recent version in the repo but I found no version that worked. The latest version that compiled was 3019:252da58b4 i used: gcc 4.2 python 3.4 (the official dmg) Mac OS X 10.6.8 I cannot use a different python version because my project depends on asyncio. It works perfectly under linux, this is probably a OS X specific issue. Please tell me what i could do to help. "I cannot use a different python version because my project depends on asyncio." Think about using virtualenv, which aims to separate out the dependencies for multiple Python projects. It really makes a huge difference. Any workarounds on this (without using python 2.7)? After some debugging, I found that I was only affected by this if inside a virtualenv. Installing pygame systemwide works fine on OS X 10.10.3 with python3, both from python.org or homebrew. If one can cope without all the SDL-features, one can get pygame working inside virtualenv by using pygame_sdl2. More detail is found in this thread: We have found a workaround, described in this thread. It means substituting the system Framework Python for the virtualenv one that can't handle windowing properly on a Mac. Thanks Arve Seljebu and Rob Collins for investigating this. Is there any hope of fixing it within pygame? I'm not familiar with OSX, but it seems weird that a Python virtualenv can affect window management. If we don't know of a fix, is there a way we can detect it and warn/error about it? This is likely to do with which SDL was used inside different python environments. We likely need to redo the way this is handled on OSX. Since installing system wide Frameworks is really not a good idea in modern OSX (and probably never was). Issue #244was marked as a duplicate of this issue. I think this is the same issue as noticed by matplotlib : The problem is to do with the difference between framework and not-framework builds on OSX. That's good to know. If it is the same and mpl hasn't fixed it, I suspect there's not much we can do other than documenting workarounds. The docs you linked to suggest that python3 -m venvworks for mpl where virtualenvdoesn't. Does using venvalso make Pygame behave properly? Yes it does: What should I do if I use conda? Mentioned article says Anaconda is framework build. I successfully installed it with pip being inside my conda environment. And code starts, but with now visible window. Have you tried it in conda? If our suspicions are correct, and those docs are right that Anaconda is a framework build, it should work. I have Python 3.5 conda environment. Installed pygame: When run aliens (or anything else) console says: And nothing opens up. When swipe see all the windows: I've also tried 1.9.2b12 version. didn't help. From your screenshot it looks like it's opening but not getting focussed. If you switch to it before you die, can you move the car with the left/right arrows? Thomas Kluyver yes, window is created, but when I select it I see it for a split-second and then I see my console again. So, no, I can't move a car. Other people: does Aleksandr's description match what you see? Is there a way to check if Python is a framework build? Also when I Cmd+Tab through windows - it's not there. That's why I have to swipe up to see to four-finger-swipe-up (Mission control is the name in system pref.) I've tried different example now. Since aliens closes itself too quickly. With other example I was able to get focus. Here is how: Using same trick I've got focus on aliens. Should arrow keys work? Because they don't. Pressing any key while being "focused" doesn't change anything (car doesn't move)
https://bitbucket.org/pygame/pygame/issues/203/window-does-not-get-focus-on-os-x-with
CC-MAIN-2017-04
refinedweb
920
77.13
Retrieve the current value of the specified event property of type char. #include <screen/screen.h> int screen_get_event_property_cv(screen_event_t ev, int pname, int len, char *param) The handle of the event: Immediate Execution This function stores the current value of an event property in a user-provided buffer. No more than len bytes of the specified type will be written. The list of properties that can be queried per event type are listed as follows: 0 if a query was successful and the value(s) of the property are stored in param, or -1 if an error occurred (errno is set; refer to /usr/include/errno.h for more details).
http://www.qnx.com/developers/docs/6.6.0.update/com.qnx.doc.screen/topic/screen_get_event_property_cv.html
CC-MAIN-2018-13
refinedweb
110
59.23
ISBN:1584502878 Table of Contents Object-Oriented ProgrammingFrom Problem Solving to Java Preface Chapter 1 - Computer Systems Chapter 2 - Program Development Chapter 3 Chapter 4 - Object-Oriented Programs Chapter 5 Chapter 6 Chapter 7 - Selection Chapter 8 - Repetition Chapter 9 - Arrays Chapter 10 - Strings Chapter 11 - Basic Object-Oriented Modeling Chapter 12 - Inheritance Chapter 13 - Abstract Classes, Interfaces, and Polymorphism Chapter 14 - Basic Graphical User Interfaces Chapter 15 - Exceptions and I/O Chapter 16 - Recursion Chapter 17 - Threads Appendix A Appendix B Index List of Figures List of Tables CD Content 07:20:54 005.1'17--dc21 2003053204 Printed in the United States of America 03 7 6 5 4 3 2 First Edition CHARLES RIVER MEDIA titles are available for site license or bulk purchase by institutions, user groups, corporations, etc. For additional information, please contact the Special Sales Department at 781-740-0400. Requests for replacement of a defective CD-ROM must be accompanied by the original disc, your mailing address, telephone number, date of purchase and purchase price. Please state the nature of the problem, and send the information to CHARLES RIVER MEDIA, INC., 10 Downer Avenue, Hingham, Massachusetts 02043. CRM's sole obligation to the purchaser is to replace the disc, based on defective materials or faulty workmanship, but not on the operation or functionality of the product. I dedicate this book to my wife Gisela and my two sons, Maximiliano and Constantino, for their love and support. Preface Preface The main goal of this book is to present the basic concepts and techniques for object-oriented modeling and objectoriented programming principles. Because solution design is a creative activity, this book attempts to exploit the creative and critical thinking capacity of students in finding solutions to problems and implementing the solutions applying high-level, object-oriented programming principles. The fundamental principles of problem solving techniques and illustrations of these principles are introduced with simple problems and their solutions, which are initially described mainly in pseudo-code. In the first few chapters, emphasis is on modeling and design. The principles of object-oriented modeling and programming are gradually introduced in solving problems. From a modeling point of view, objects are introduced early and represented in UML diagrams. This book avoids stressing the syntax of the programming language from the beginning. This helps students in dealing with the difficulty of understanding the underlying concepts in problem solution and later programming. The main conceptual tools used are modeling diagrams, pseudo-code, and some flowcharts that are applied to simplify the understanding of the design structures. The overall goal is to provide an easier way to understand problem solving by developing solutions in pseudo-code and implementing them as working programs. This also enhances the learning process as the approach allows one to isolate the problem solving and programming principle aspects from the programming language (Java) to be used for final implementation of the problem solution. When implementing problem solutions, students can construct working programs using the Kennesaw Java Preprocessor (KJP) programming language, and then convert to Java with the KJP translator. Compilation and execution of Java programs is carried out with the standard SDK Java software from Sun Microsystems. All Java classes can be used with KJP. This helps the students in their transition from object-oriented modeling and design to implementation with Java. Standard pseudo-code constructs are explained and applied to the solution design of various case studies. General descriptions of the data structures needed in problem solutions are also discussed. The KJP language is introduced, which is a slightly enhanced pseudo-code notation. The KJP translator tool is used to convert (translate) a problem solution described in pseudo-code into Java. The assumption here is that, even after they learn Java, students will always use pseudo-code in the design phase of software development. KJP is a high-level, programming language that facilitates the teaching and learning of the programming principles in an object-oriented context. The notation includes conventional pseudo-code syntax and is much easier to read, understand, and maintain than standard object-oriented programming languages. The KJP translator tool carries out syntax checking and automatically generates an equivalent Java program. The KJP language has the same semantics as Java, so the transition from KJP to Java is, hopefully, very smooth and straightforward. The main motivation for designing the KJP language and developing the KJP translator was the quest for a higher-level language to teach programming principles, and at the same time, to take advantage of the Java programming language for all the functionality and capabilities offered. The overall goal is to help students reason about the problem at hand, design the possible solutions to the problem, and write programs that are: Easy to write Easy to read Easy to understand Easy to modify For most of the topics discussed, one or more complete case studies are presented and explained with the corresponding case study in pseudocode. The KJP software tool used for converting a problem solution to Java is Preface applied in the lab exercises. Appendix A explains the usage of the KJP translator and the jGRASP development environment (Auburn University); Appendix B briefly lists the contents of the included CD-ROM. The most recent version of the KJP software and the various case studies are available from the following Web page: The important features of the book that readers can expect are: The emphasis on starting with modeling and design of problem solution and not programming with Java. The syntax details are not initially emphasized. The use of pseudo-code to describe problem solution, KJP as the high-level programming language, and Java as the ultimate implementation language. Java is chosen as the implementation language because it is one of the most important programming language today. When used as a teaching tool, the facilitation of understanding large and complex problems and their solutions, and gives the gives guidance on how to approach the implementation to these problems. The practical use of object-oriented concepts to model and solve real problems. A good practical source of material to understand the complexities of problem solving and programming, and their applications. Instead of presenting examples in a cookbook manner that students blindly follow, this book attempts to stimulate and challenge the reasoning capacity and imagination of the students. Some of the problems presented at the end of the chapters make it necessary for students to look for possible solution(s) elsewhere. It also prepares students to become good programmers with the Java programming language. I benefitted from the long discussions with my colleagues who are involved directly or indirectly in teaching the various sections of CSIS 2301 (Programming Principles I), CSIS 2302 (Programming Principles II), and related courses in the Department of Computer Science and Information Systems at Kennesaw State University. I am thankful to Mushtaq Ahmed, Ray Cobb, Richard Gayler, Hisham Haddad, Ben Setzer, Chong-Wei Xu, and Richard Schlesinger. I am especially thankful to Mushtaq Ahmed for his help with the chapter on recursion, and to Chong-Wei Xu for his help with the chapter on threads. I am also thankful to the students in the pilot section of CSIS 2300 (Introduction to Computing) who have used the first six chapters of the book. The graduate students in the course IS 8020 (ObjectOriented Software Development) applied and reviewed most of the material in the book. I want to thank David Pallai and Bryan Davidson of Charles River Media for their help in producing the book. J. M. Garrido Kennesaw, GA 07:20:55 Hardware components, which are the electronic and electromechanical devices, such as the processor, memory, disk unit, keyboard, screen, and others Software components, such as the operating system and user programs All computer systems have the fundamental functions: processing, input, and output. Processing executes the instructions in memory to perform some transformation and/or computation on the data also in memory. This emphasizes the fact that the instructions and data must be located in memory in order for processing to proceed. Input involves entering data into the computer for processing. Data is entered into the computer with an input device (for example, the keyboard). Output involves transferring data from the computer to an output device such as the video screen. Other devices 1.2.1.1 CPU The CPU is capable of executing the instructions that are stored in memory, carrying out arithmetic operations, and performing data transfers. Larger computers have several processors (CPUs). Note In order for the CPU to execute an instruction, the program must be specified in a special form called machine language. This is a notation that is specifically dependent on the type of CPU. To execute a program, the source program is translated from its original text form into a machine language program. An important parameter of the computer is the speed of the CPU, usually measured in MHz or GHz. This is the number of machine cycles that the CPU can handle. Roughly, it indicates the time the CPU takes to perform an instruction. On small systems such as small servers and personal computers, the CPU is constructed on a tiny electronic chip (integrated circuit) called a microprocessor. This chip is placed on a circuit board that contains other electronic components, including the memory chips. Two typical CPUs found in today's personal computers are the Intel PentiumTM 4 with 2.4 GHz and the AMD Athlon XPTM 2400. (s). In most applications, the input and output devices mentioned are used when the program maintains a dialog with the user while executing. This computer-user dialog is called user interaction. The input and output devices are connected to the communication ports in the computer (see Figure 1.1). For graphic applications, a video display device is connected to the graphic controller, which is a unit for connecting one or more video units and/or graphic devices. Data descriptions, which define all the data to be manipulated and transformed by the instructions A sequence of instructions, which defines all the transformations to be carried out on the data in order to produce the desired results System software Application software The system software is a collection of programs that control the activities and functions of the various hardware components. An example of system software is the operating system, such as Unix, Windows, MacOS, OS/2, and others. Application software consists of those programs that solve specific problems for the users. These programs execute under control of the system software. Application programs are developed by individuals and organizations for solving specific problems. High-level languages allow more readable programs, and are easier to write and maintain. Examples of these languages are Pascal, C, Cobol, FORTRAN, Algol, Ada, Smalltalk, C++, Eiffel, and Java. These last four high-level programming languages are object-oriented programming languages. These are considered slightly higher level than the other high-level languages. The first object-oriented language, Simula, was developed in the mid-sixties. It was used mainly to write simulation models. The language is an extension of Algol. In a similar manner, C++ was developed as an extension to C in the early eighties. Java was developed by Sun Microsystems in the mid-nineties, as an improved object-oriented programming language compared to C++. Java has far more capabilities than any other object-oriented programming language to date. Languages like C++ and Java can require considerable effort to learn and master. There are several experimental, higher-level, object-oriented programming languages. Each one has a particular goal. One such language is KJP (Kennesaw Java Preprocessor); its main purpose is to make it easier to learn object-oriented programming principles and help students transition to Java. 1.3.4 Compilation The solution to a problem is implemented in an appropriate programming language. This becomes the source (1 von 3)09.11.2006 07:20:56 program written in a high-level programming language, such as C++, Eiffel, Java, or others. After a source program is written, it is translated to an equivalent program in machine language, which is the only programming language that the computer can understand. The computer can only execute instructions that are in machine language. The translation of the source program to machine language is called compilation. The step after compilation is called linking and it generates an executable program in machine language. For some other languages, like Java, the user carries out two steps: compilation and interpretation. This last step involves direct execution of the compiled program. Figure 1.5 shows what is involved in compilation of a source program in Java. The Java compiler checks for syntax errors in the source program and then translates it into a program in bytecode, which is the program in an intermediate form. The Java bytecode is not dependent on any particular platform or computer system. This makes the bytecode very portable from one machine to another. Figure 1.6 shows how to execute a program in bytecode. The Java virtual machine (JVM), which is another software tool from Sun Microsystems, carries out the interpretation of the program in bytecode. The conversion is illustrated in Figure 1.7. Appendix A explains in further detail how to use the KJP translator. Before a program starts to execute in the computer, it must be loaded into the memory of the computer. The program executing in the computer usually reads input data from the input device and after carrying out some computations, it writes results to the output device(s). When executing in a computer, a program reads data from the input device (the keyboard), then carries out some transformation on the data, and writes the results on the output device (the video screen). The transformation also 1.4 Summary 1.4 Summary A computer system consists of several hardware and software components. The I/O devices are necessary to read or write data to and from memory to the appropriate external device. Application software is a related set of programs that the user interacts with to solve particular problems. System software is a set of programs that control the hardware and the application software. Compilation is the task of translating a program from its source language to an equivalent program in binary code (possibly machine language). When the program executes in a computer, it reads the input data, carries out some computations, and writes the output data (results). To fully understand the development process, it is necessary to have some knowledge about the general structure of a computer system. 07:20:56 hardware software CPU RAM byte memory location devices input output system software application software instructions programming language Java C++ Eiffel KJP compilation JVM program execution MHz GHz MB bytecode Source code 07:20:57 1.6 Exercises 1.6 Exercises 1. Explain the relevant differences between hardware and software components. Give examples. 2. List and explain the hardware parameters that affect the performance of a computer system. 3. Why is the unit of capacity for memory and for the storage devices the same? Explain with an example. 4. Which is the main input device in a personal computer (PC)? What other devices are normally used as input devices? 5. Which is the main output device in a personal computer? What other devices are normally used as output devices? 6. Can a disk device be used as an input device? Explain. Can it be used as an output device? Explain. 7. What is a programming language? Why do we need one? Why are there so many programming languages? 8. Explain the purpose of compilation. How many compilers are necessary for a given application? What is the difference between program compilation and program execution? Explain. 9. What is the real purpose of developing a program? Can we just use a spreadsheet program such as MS Excel to solve numerical problems? Explain. 07:20:57 07:20:57 The necessary transformation to be carried out on the given data to produce the final results 2.2.2 Algorithm In a broad sense, the transformation on the data is described as a sequence of operations that are to be carried out on the given data in order to produce the desired results. Figure 2.1 illustrates the notion of transformation. This is a clear, detailed, precise, and complete description of the sequence of operations. The transformation of the data is also called an algorithm. The algorithm is a formal description of how to solve the problem. 07:20:58 For large programs, it is necessary to follow the life cycle as a process. This allows for the program construction to be accomplished in an organized and disciplined manner. Even for small programs, it is good practice to carry out these activities in a well-defined development process. For the design task, the strategy called design refinement has proven very useful. You start with a general, high-level and incomplete design (no details); it provides a big picture view of the solution. Next, work through a sequence of improvements or refinements of the design, each with more detail, until a final design that reflects a complete solution to the problem is obtained. For the implementation task, a similar strategy is followed. This is sometimes called incremental development. This captures the importance of the modular decomposition of the software system. At each step, a single module is implemented (and tested). This practice is sometimes called continuous integration. 2.4 Summary 2.4 Summary Program development involves finding a solution to a problem and then writing the problem solution in a programming language to produce a computer program. The program development process is a well-defined sequence of activities carried out by the programmer. The outcome of this process is a correct and good-quality program. The software development process can be considered as part of the software life cycle. Two important and widely known models for the software life cycle are the waterfall and the spiral models. The software development process is a well-defined sequence of tasks that are carried out to produce a program that is a computer solution to the given problem. It is strongly recommended to follow a software development process even for small programs. 07:20:59 problem solving development process requirements analysis design decomposition implementation testing maintenance retirement algorithm waterfall model spiral model 07:20:59 2.6 Exercises 2.6 Exercises 1. Give valid reasons why the first phase of the program development process needs to be strict with respect to ambiguity, clarity, and completeness in describing the problem. 2. In very simple terms, what is the difference between the algorithm and the program? 3. Give valid reasons why the design phase of the program development process is needed. Can you write the program without a design? 4. Explain when the analysis phase ends and the design phase starts. Is there a clear division? Is any overlapping possible? 5. Is there a clear difference between the software development process and the software life cycle? Explain. 6. Is the goal for using a development process in developing a small program valid? Explain. What are the main advantages in using a process? What are the disadvantages? 07:20:59 07:21:00 3.3.1 Models Note The concept of abstraction is applied in describing the objects of a problem. This involves the elimination of unessential characteristics. A model includes only the relevant aspects of the real world pertaining to the problem to solve. As mentioned previously, modeling is the task of designing and building a model. The result of modeling is that only the relevant objects and only the essential characteristics of these objects are included in the model. There are several levels of abstraction and these correspond to the different levels of detail needed to completely define objects and the collections of objects in a model. An important and early task of the modeling process is to identify real-world objects and collections of similar objects within the boundaries of the problem. Three basic issues in modeling are: 1. Identifying the objects to include in the model 2. Describing these objects 3. Grouping similar objects into collections Physical objects, which are tangible objects, such as persons, animals, cars, balls, traffic lights, and so on Nontangible objects, which are not directly visible, such as contracts, accounts, and so on Conceptual objects, which do not clearly exist but are used to represent part of the components or part of the behavior of the problem. For example, the environment that surrounds the problem and that affects the entities of the problem An object is a dynamic concept because objects exhibit independent behavior and interact with one another. They communicate by sending messages to each other; this way all objects collaborate for a common goal. Every object has: State, represented by the set of properties (or attributes) and their associated values A simple example of an object is an object of class Ball. Its identity is an object of class Ball. The attributes of this object are color, size, and move_status. Figure 3.3 shows the UML diagram for two Ball objects and illustrates their structure. The diagram is basically a rectangle divided into three sections. The top section indicates the class of the object, the middle section includes the list of the attributes and their current values, and the bottom section includes the list of operations in the object. Suppose there is a scenario in which a child called Mike plays with two balls of the same size, one red and the other blue. The child is represented by an object of class Person. The balls are represented by two objects of class Ball. When the object of class Person needs to interact with the two objects of class Ball, the object of class Person invokes the move operation of each object of class Ball. Another possible interaction is the object of class Person invoking the show_color operation of an object of class Ball. Note Objects interact by sending messages to each other. The object that sends the message is the requestor of a service that can be provided by the receiver object. A message represents a request for service, which is provided by the object receiving the message. The sender object is known as the client of a service, and the receiver object is known as the supplier of the service. The purpose of sending a message is the request for some operation of the receiver object to be carried out; in other words, the request is a call to one of the operations of the supplier object. Objects carry out operations in response to messages. These operations are object-specific; a message is always sent to a specific object. This is also known as method invocation. A message contains three parts: The operation to be invoked or started, which is the service requested and must be an accessible operation The input data required by the operation to perform, which is known as the arguments The output data, which is the reply to the message and is the actual result of the request To describe the general interaction between two or more objects (the sending of messages between objects), a UML diagram known as a collaboration diagram is used to describe the interaction. For example, to describe the interaction among an object of class Person with the two objects of class Ball, a simple collaboration diagram is drawn. Figure 3.5 shows a collaboration diagram with these three objects. In this example, the Person object invokes the move operation of the Ball object by sending a message to the first Ball object, and as a result of this message, that object (of class Ball) performs its move operation. 3.4 Classes 3.4 Classes In the real-world problem, a class describes a collection of real-world entities or objects with similar characteristics. The abstract descriptions of the collections of objects are called classes (or class models). Figure 3.6 illustrates the identifying of two collections of real-world objects, the modeling of the classes, and the software implementation of these classes. Each class model describes a collection of similar real-world objects. Collections of such objects are used to distinguish one type of object from another. The model of a class is represented graphically in UML as a class diagram. Collections of objects are modeled as classes. An object belongs to a collection or class, and any object of the class is an instance of the class. Every class defines: A complete object-oriented model of an application consists of a description of all the classes and their relationships, the objects and their interactions, and a complete documentation of these. A class defines the attributes and behavior for all the objects of the class. Figure 3.7 shows the diagram for class Person. Figure 3.8 shows the UML diagram for class Ball. 3.4 Classes 3.4.1 Encapsulation The encapsulation principle suggests that an object be described as the integration of attributes and behavior in a single unit. There is an imaginary wall surrounding the object to protect it from another object. This is considered an encapsulation protection mechanism. To protect the features of an object, an access mode is specified for every feature. When access to some of the attributes and some operations is not allowed, the access mode of the feature is specified to be private; otherwise, the access mode is public. If an operation of an object is public, it is accessible from other objects. Figure 3.9 illustrates the notion of an object as an encapsulation unit. 3.4 Classes level of abstraction. The external view implies that information about an object is limited to that only necessary for the object's features to be invoked by another object. The rest of the knowledge about the object is not revealed. As mentioned earlier, this principle is called information hiding or data hiding. Note In the class definition, the external view of the objects should be kept separate from the internal view. The internal view of properties and operations of an object are hidden from other objects. The object presents its external view to other objects and shows what features (operations and attributes) are accessible. The public features of an object are accessible to other objects, but the implementation details of these features are kept hidden. In general, only the headers, that is, the specification, of the operations are known. Similarly, only the public attributes are the ones accessible from other objects. The models of objects are represented using the Unified Modeling Language (UML), the standard graphical notation introduced previously in this chapter. A basic part of this notation is used in this book to describe objectoriented models. Because every object belongs to a class, the complete description of the objects is included in the corresponding class definitions. 07:21:01 3.6 Summary 3.6 Summary In modeling object-oriented applications, one of the first tasks is to identify the objects and collections of similar objects in the problem domain. An object has properties and behaviors. The class is a definition of objects with the same characteristics. A model is an abstract representation of a real system. Modeling is the process of constructing representations of objects and defining the common characteristics into classes. Modeling involves what objects and relevant characteristics of these objects are to be included in the model. Objects collaborate by sending messages to each other. A message is request to to carry out a certain operation by an object. Information hiding emphasizes the separation of the list of operations that an object offers to other objects from the implementation details that are hidden to other objects. 07:21:02 abstraction objects collections real-world entities object state object behavior messages attributes operations methods functions UML diagram interactions method invocation classes encapsulation information hiding private public responsibilities delegations collaboration 07:21:02 3.8 Exercises 3.8 Exercises 1. Explain and give examples of the difference between classes and objects. Why is the object considered a dynamic concept? Why is the class considered a static concept? Explain. 2. Explain why the UML class and object diagrams are very similar. What do these diagrams actually describe about an object and about a class? Explain. 3. Explain and give examples of object behavior. Is object interaction the same as object behavior? Explain and give examples. What UML diagram describes this? If an object-oriented application has only one object, is there any object interaction? Explain. 4. What are the differences between encapsulation and information hiding? How are these two concepts related? Explain. 5. From the principle of information hiding, why are the two views of an object at different levels of abstraction? Explain. How useful can this principle be in software development? 6. Consider an automobile rental office. A customer can rent an automobile for a number of days and with a finite number of miles (or kilometers). Identify the type and number of objects involved. For every type of object, list the properties and operations. Draw the class and object diagrams for this problem. As a starting point, use class Automobile described in this chapter. 7. For the automobile rental office, describe the object interactions necessary. Draw the corresponding collaboration diagrams. 8. Consider a movie rental shop. Identify the various objects. How many objects of each type are there? List the properties and the necessary operations of the objects. Draw the corresponding UML diagrams for this problem. 9. For the two problems described in Exercises 7 and 8, list the private and public characteristics (properties and operations) for every type of object. Why do you need to make this distinction? Explain. 07:21:02 07:21:03 The static view describes the structure of the program. Programs are composed of one or more modules called classes. The dynamic view describes the behavior of the program while it executes. This behavior consists of the set of objects, each one exhibiting individual behavior and its interaction with other objects. 07:21:03 4.3 Modules 4.3 Modules A problem is often too complex to deal with as a single unit. A general approach is to divide the problem into smaller problems that are easier to solve. The partitioning of a problem into smaller parts is known as decomposition. These small parts are called modules, which are easier to manage. Program design usually emphasizes modular structuring, also called modular decomposition. A problem is divided into smaller problems (or subproblems), and a solution is designed for each subproblem. Therefore, the solution to a problem consists of several smaller solutions corresponding to each of the subproblems. This approach is called modular design. Object-oriented design enhances modular design by providing classes as the most important decomposition (modular) unit. As an example, Figure 4.2 shows a program that consists of four modules. 07:21:03 Descriptions of the data, which are the attribute declarations of the class Note The most important decomposition unit in an application is the class, which can be considered a module that can be reused in another application. Data descriptions represent the declarations of the attributes for the objects of the class. Descriptions of the operations represent the behavior for the objects of the class. Figure 4.3 illustrates the structure of a class named Class_A. This class consists of the declarations of the attributes and the definitions of three operations: Operation1, Operation2, and Operation3. Each of these operations consists of its local data declarations and its instructions. Simple variables are those of simple or primitive types; these store small and simple data items like integer values, floating-point values, and others. Object variables (or object references) are variables that can store the reference to objects when they are created. The only way to manipulate objects is by using their references, because in Java and KJP objects do not have an identifier directly associated with them. 07:21:04 4.6 Algorithms 4.6 Algorithms The basic definition of an algorithm is a detailed and precise description of the sequence of steps for the behavioral aspect of a problem solution. This algorithm is normally broken down into smaller tasks, each carried out by an object and defined in the classes. In the design phase of software development, the detailed design of the classes includes descriptions of these smaller algorithms. In an object-oriented program, every object carries out some particular task. The collaboration of all the objects in a program will accomplish the complete solution to the problem. As mentioned in previous chapters, the overall design involves detailed design of the classes in the problem. The design of a class describes the data and the tasks that the objects of the class will carry out. Because the class is the main decomposition unit in a program, the overall algorithm for a problem has been decomposed into smaller algorithms, each described in the design of the class. The algorithm of a class is further decomposed into each operation in the class. This is the second level of decomposition for algorithms. In object-oriented design and programming, the algorithms are described at the level of the operation. At this level, traditional structured design and programming techniques can be applied. Note 07:21:04 Class definitions Definition of functions Creation of objects Manipulation of the objects created by calling (or invoking) the functions that belong to these objects Note In Java and KJP, the functions or operations are known as methods. Objects do not directly have names, instead, object reference variables are used to reference objects when they are created. constants . . . variables . . . objects . . . public . . . endclass class_name The name of a data item is an identifier and is given by the programmer; it must be different from any keyword in KJP (or in Java). The type defines: The set of possible values that the data item may have The set of possible operations that can be applied to the data item The data items named x and y are called variables because their values change when operations are applied on them. Those data items that do not change their values are called constants, for example, Max_period, PI, and so on. These data items are given an initial value that will never change. When a program executes, all the data items used by the various operations are stored in memory, each data item occupying a different memory location. The names of these data items represent symbolic memory locations. Classes Numeric Text Boolean The numeric types are further divided into three types, integer, float, and double. The noninteger types are also known as fractional, which means that the numerical values have a fractional part. Values of integer type are those that are countable to a finite value, for example, age, number of automobiles, number of pages in a book, and so on. Values of type float have a decimal point; for example, cost of an item, the height of a building, current temperature in a room, a time interval (period). These values cannot be expressed as integers. Values of type double provide more precision than type float, for example, the value of the total assets of a corporation. Text data items are of two basic types: character and type string. Data items of type string consist of a sequence of characters. The values for these two types of data items are textual values. A third type of variables is the one in which the values of the variables can take a truth-value (true or false); these variables are of type boolean. Classes are more complex types that appear as types of object variables in all object-oriented programs. Data entities declared (and created) with classes are called objects. Elementary Note Object-oriented programming is mainly about defining classes as types for object variables (references), and then declaring and creating objects of these classes. The type of an object reference is a class. For example, consider a program that includes two class definitions, Employee and Ball. The declarations of an object reference called emp_obj of class Employee, and an object reference ball1 of class Ball are: objects object emp_obj of class Employee object ball1 of class Ball (2 von 3)09.11.2006 07:21:06 The scope of a data item is that portion of a program in which statements can reference that data item The persistence of a data item is the interval of time that the data item existsthe lifetime of the data item 07:21:07 show_status, which displays the values of the attributes color and move_status get_color, which reads the value of attribute color from the console get_size, which reads the value of attribute size from the console The program has two classes: Ball and Mball. The second class (Mball) is the class with function main. This function is defined to carry out the following sequence of activities: 1. Declare two object variables, obj_1 and obj_2, of class Ball. 2. Create the two objects. 3. Invoke functions get_color and get_size for each object. 4. Invoke function show_status for each object. 5. Invoke functions move and then show_status for each object. 6. Terminate execution of the entire program. On the CD The complete definition of class Ball in KJP follows and is stored in the file the CD-ROM that accompanies this book. description Ball.kpl on On the CD description This program illustrates the general structure Mball. Figures 4.6 and 4.7 show the console input and output produced during execution of the program. The KJP code for class Salary1 follows and is stored in the file description This program computes the salary increase for an employee. If his/her salary is greater than $45,000 the salary increase is 4.5%; otherwise, Salary1.kpl. 4.12 Summary 4.12 Summary The static view of a program describes the program as an assembly of classes. A class is a decomposition unita basic modular unit that allows breaking a problem into smaller subproblems. A class is also a type for object reference variables. It is also a collection of objects with similar characteristics. A class is a reusable unit; it can be reused in other applications. An algorithm is a complete, precise, detailed description of the method of solution to a problem. Because a problem is broken down into subproblems, the solution is sought for each of the subproblems. In practice, the algorithm for the complete problem is broken down and designed in each class and in each function. The general structure of a class consists of data definitions and function definitions. A class is decomposed into data definitions and functions. Data declarations exist in the class to define the attributes; data declarations also appear in the functions to define the function's local data. A function includes data definitions and instructions. Data definitions consist of the declarations of constants, simple variables, and object variables (references). The data declarations require the type and name of the constant, variable, and object reference. After object references are declared, the corresponding objects can be created. The definition of classes in KJP and other object-oriented programming languages is accomplished by writing the program using the language statements and following a few rules on how to structure the program. Two complete programs were presented in this chapter. The first program consists of two class definitions (Ball and Mball). Two objects of class Ball are created and function main sends several messages to each object. 07:21:08 dynamic view decomposition modules units class reuse package devices data declaration variables constants simple types algorithms structured programming object references class description local data initial value data types scope persistence 07:21:08 4.14 Exercises 4.14 Exercises 1. Explain the reason why a class is an appropriate decomposition unit. What other units are possible to consider? 2. Explain why object-oriented programs need a control function such as main. 3. The entire algorithm for a problem is decomposed into classes and functions. Explain this decomposition structure. Why is there a need to decompose a problem into subproblems? 4. KJP programs do not allow public attribute definitions in classes. Explain the reason for this. What are the advantages and disadvantages? Hint: review the concepts of encapsulation and information hiding. 5. The dynamic view of a program involves the objects of the problem collaborating to accomplish the overall solution to the problem. Where are these objects created and started? Explain. 6. Consider the first complete program presented in this chapter. Add two more functions to class Ball. Include the corresponding function calls from class Mball. For example, add another attribute weight in class Ball. The additional functions would be get_weight and show_weight. 7. Analyze the second KJP program presented in this chapter, which calculates the salary increase for employees. Follow the same pattern to write another program to compute the grade average per student. The data for each student is student name, grade1, grade2, grade3, and grade4. 8. Restructure the second program, and convert it to an object-oriented program, similar to the first program presented. 9. What are the main limitations of the programs with a single class and a single function? Explain. 07:21:09 07:21:09 5.2 Classes 5.2 Classes In Chapter 3, the model of an object is described as an encapsulation of the attributes and behavior into a single unit. When access to some of the attributes and some operations is not allowed, the access is said to be private; otherwise, the access mode is public. This is considered an encapsulation protection mechanism. A class defines the attributes and behavior of the objects in a collection. In other words, every collection of entities is defined by describing the attributes and behavior of these entities. The attributes are defined as data declarations, and the behavior is defined as one or more operations (methods or functions). As an example, Figure 5.1 shows the general structure of a class. 5.2 Classes 5.3 Methods 5.3 Methods As mentioned in Chapter 4, a program is normally decomposed into classes, and classes are divided into methods or functions. Methods are the smallest decomposition units. A function represents a small subtask in the class. Figure 5.2 illustrates the general structure of a function. This structure consists of: A sequence of instructions 5.3 Methods . . . variables . . . objects . . . begin . . . endfun function_name In the structure shown, the keywords are in boldface. The first line defines the name of the function at the top of the construct. In the second line, the description paragraph includes the documentation of the function. The data declarations define local data in the function. These are divided into constant declarations, variable declarations, and object declarations. This is similar to the data declarations in the class. The local data declarations are optional. The instructions of the function appear between the keywords begin and endfun. The following KJP code shows a simple function for displaying two text messages on the screen. description This function displays the initial message for the program on the screen. */ function display_message is begin print "Starting program." print "Computing standard deviation of rainfall data" endfun display_message The function (operation) to be invoked or started, which is the service requested; this must be a public function if invoked by another object The input data required in order for the operation to start; this data is known as the arguments The output data, which is the reply to the message; this is the actual result of the request To describe the general interaction between two or more objects (the sending of messages between objects), one of the UML diagrams used is the collaboration diagram; see Figure 5.3 as an example. Another UML diagram used to describe object interaction is the sequence diagram. 1. Simple (or void) functions do not return any value when they are invoked. The previous example, function display_message, is a simple or void function because it does not return any value to the function that invoked it. 2. Value-returning functions return a single value after completion. 3. Functions with parameters require one or more data items as input values when invoked. The most general category of functions is one that combines the last two categories just listedfunctions that return a value and that have parameters. Another important criterion for describing categories of functions depends on the purpose of the function. There are two such categories of functions: Accessor functions return the value of an attribute of the object without changing the value of any attribute(s) of the object. For example, the following are accessor functions: get_color, get_size, and show_status of class Ball in Section 4.11.1. Mutator functions change the state of the object in some way by altering the value of one or more attributes in the object. Normally, these functions do not return any value. For example, the following functions are mutator functions: move and stop of class Ball in Section 4.11.1. It is good programming practice to define the functions in a class as being either accessor or mutator. Note One difference of the value-returning function with a simple (or void) function is that the type of the value returned is indicated in the function statement. Another difference is that a return statement is necessary with the value to return. In a simple assignment, the value returned by the called function is used by the calling function by assigning this returned value to another variable. For example, suppose function main calls function get_val of an object referenced by myobj. Suppose then that function main assigns the value returned to variable y. The KJP code statement for this call is: set y = call get_val of myobj This call statement is included in an assignment statement. When the call is executed, the sequence of activities that are carried out is: 1. Function main calls function get_val in object referenced by myobj. 2. Function get_val executes when called and returns the value of variable local_var. 3. Function main receives the value returned from function get_val. 4. Function main assigns this value to variable y. Using the value returned in an assignment with an arithmetic expression is straightforward after calling the function. For example, after calling function get_val of the object referenced by myobj, the value returned is assigned to variable y. This variable is then used in an arithmetic expression that multiplies y by variable x and adds 3. The value that results from evaluating this expression is assigned to variable zz. This assignment statement is: set zz = x * y + 3 Note The difference with the previous function call is that the name of the object reference is followed by the keyword using and this is followed by the list of arguments, which are values or names of the data items. endfun function_name The following example uses this syntax structure with a function named min_1. The complete definition of function min_1 in KJP is: description This function calculates the minimum value of parameters a and b, it then prints the result on the screen. */ function min_1 parameters real a, real b is variables real min // local variable begin if a < b then set min = a else set min = b endif display "Minimum value is: ", min return endfun min_1 The definition of function min_1 declares the parameters a and b. These parameters are used as placeholders for the corresponding argument values transferred from the calling function. Figure 5.5 illustrates the calling of function min_1 with the transfer of argument values from the calling function to the called function. The call to function min_2 should be in an assignment statement, for example, to call min_2 with two constant arguments, a and b, and assign the return value to variable y: set y = call min_2 of obj_a using a, b Note If no initializer function is defined in the class, the default values set by the compiler are used for all the attributes. If no initializer function is included in the class definition, the default values are set by the Java compiler (zero and empty) for the two attributes. It is good programming practice to define at least a default initializer function. For example, in class Person the default values for the two attributes are set to 21 for age and "None" for obj_name. This function is defined as: description This is the default initializer method. */ function initializer is begin set age = 21 set obj_name = "None" endfun initializer Recall that the general structure of the statement to create an object is: create object_ref_name of class class_name This statement implicitly uses the default initializer function in the class. A complete initializer function sets the value of all the attributes to the values given when called. These values are given as arguments in the statement that creates the object. The general statement to create an object with given values for the attributes is: create object_ref_name of class class_name using argument_list A second initializer function is included in class Person to set given initial values to the attributes of the object when created. For example, suppose there is an object reference person_obj of class Person declared, to create an object referenced by person_obj with initial value of 32 for age and " J. K. Hunt" for the obj_name: create person_obj of class Person using 32, "J. K. Hunt" The definition of this complete initializer function in class Person includes parameter definitions for each attribute: description This is a complete initializer, it sets the attributes to the values given when an object is created. */ Note The definition of two or more functions with the same name is known as overloading. This facility of the programming language allows any function in a class to be overloaded. In other words, it is a redefinition of a function with another function with the same name, but with a different number of and types of parameters. It is very useful in a class to define more than one initializer function. This way, there is more than one way to initialize an object of the class. When a class defines two initializer functions, the compiler differentiates them by the number of and the type of parameters. // description This access On the CD Person.kpl. The instructions in function main start and control the execution of the entire program. The following KJP code (in file Mperson.kpl) implements class Mperson that contains function main for the creation and manipulation of two objects of class Person. description This is the main class in the program. It creates objects of class Person and then manipulates these objects. */ class Mperson is public description This is the control function. */ function main is variables // data declarations integer lage string lname objects object person_a of class Person object person_b of class Person begin display "Creating two objects of class Person" create person_a of class Person create person_b of class Person using 37, "James Bond" call change_name of person_a using "Agent 008" set lname = call get_name of person_a set lage = call get_age of person_a display "First object: ", lname, " age: ", lage set lname = call get_name of person_b set lage = call get_age of person_b display "Second object: ", lname, " age: ", lage call change_name of person_a using "Agent 009" set lage = call get_age of person_a On the CD Person.java and Mperson. After translating and compiling both classes (Person and Mperson) of the problem, the execution of class Mperson gives the following output: Creating two objects of class Person First object: Agent 008 age: 21 Second object: James Bond age: 37 First object: Agent 009 age: 21 The Java implementation of class Person, generated by the KJP translator from following: // /** This is the complete definition of class Person. The attributes are age and name. */ public class Person { // attributes // variable data declarations private int age; private String obj_name; /** This is the default initializer method. */ public Person() { age = 21; obj_name = "None"; } // end constructor /** This is a complete initializer function, it sets the attributes to the values given on object creation. */ public Person(int iage, String iname) { age = iage; obj_name = iname; } // end constructor /** This accessor function returns the name of the object. */ public String get_name() { return obj_name; } // end get_name /** This mutator function changes the name of the object to the name in variable new_name. This function has type void. Person.kpl, is the */ public void change_name(String new_name) { obj_name = new_name; } // end change_name /** This accessor function returns the age of the Person object. */ public int get_age() { return age; } // end get_age /** This mutator function increases the age of the person when called. */ public void increase_age() { age++; } // end increase_age } // end Person On the CD The Java implementation of class Mperson, generated by the KJP translator from Mperson. kpl, is stored in the file For every declaration of a static variable, there is only one copy of its value shared by all objects of the class. A static method cannot reference nonstatic variables and cannot include calls to nonstatic methods. The basic reason for this is that nonstatic variables and methods belong to an object, static variables and methods do not. Often, static variables are also known as class variables, and static methods as class methods. 07:21:12 5.9 Summary 5.9 Summary Two levels of program decomposition are discussed in this chapter, classes and functions. Classes are modular units that can be reused (in other applications), whereas functions are internal decomposition units. Most often, the function call depends on the manner in which messages are sent among objects. Simple functions do not involve data transfer between the calling function and the called function. Value-returning functions return a value to the calling function; these functions have an associated type that corresponds to the return value. The third type of function is the one that defines one or more parameters. These are values sent by the calling function and used as input in the called function. Other categories of functions group functions as accessor and mutator functions. The first group of functions access and return the value of some attribute of the object. The second group changes some of the attributes of the object. Initializer functions are also known as constructors and are special functions that set the attributes to appropriate values when an object is created. A default initializer function sets the value of the attributes of an object to default values. A complete program is included in this chapter. The program consists of two classes, Person and Mperson. Two objects of class Person are created, and then these are manipulated by invoking their functions. Static variables and methods are associated with the class that defined them and not with its objects. The value of a static variable is shared by all objects of the class. 07:21:13 operations methods function call messages object reference object creation object manipulation local declaration return value assignment parameters arguments local data default values initializer constructor 07:21:13 5.11 Exercises 5.11 Exercises 1. Explain the reason why a function is a complete decomposition unit. What is the purpose of a function? 2. Explain why function main is a special function. 3. Why is it necessary to carry out data transfer among functions? How is this accomplished? 4. Design and write a function definition in KJP that includes two parameters and returns a value. 5. Explain the reason why more than one initializer function (constructor) is normally necessary in class. 6. In the complete program presented in this chapter, add two attributes, salary and address, and two or more functions to class Person. Include the corresponding function calls from class Mperson. 7. Modify the program that computes the salary increase of employees presented in Chapter 4. Design and write two classes, Employee and Memployee. All the computations should be done in class Employee, and function main should be defined in class Memployee. 8. Design and write a program that consists of three classes: Person, Ball, and Mperson. An object of class Person interacts with two objects of class Ball, as briefly explained in Chapter 3. Redesign of these classes is needed. 07:21:14 07:21:14 For every computation, there is one or more associated data items (or entities) that are to be manipulated or transformed by the computations (computer operations). Data descriptions are necessary, because the algorithm manipulates the data and produces the results of the problem. A type The software developer defines the name of a data item and it must be different than the keywords used in the programming language statements. Classes Numeric Text Boolean The numeric types are further divided into three types integer, real, and double. The second type is also called fractional, which means that the numerical values have a fractional part. Type real is also called float. Type double provides more precision than type real. Text data items are of two basic types: character and type string. Data items of type string consist of a sequence of characters. The values for these data items are textual values. A third type of variables is type boolean, in which the values of the variables can take a truth-value (true or false). Classes are more complex types that appear in all object-oriented programs. Data entities declared with classes are called object variables or object references. Aggregates are more advanced types that define data structures as collections of data items of any other type, for example, an array of 20 integer values. The data items usually change their values when they are manipulated by the various operations. For example, assume that there are two data items named x and y; the following sequence of instructions in pseudo-code first gets the value of x, and then adds the value x to y: read value of x from input device add x to y The data items named x and y are called variables, because their values may change when operations are applied on them. Those data items that do not change their values are called constants, and their names are usually denoted in uppercase, for example, MAX_PERIOD, PI, so on. These data items are given an initial value that will never change. In every program that executes, all the data items used by the various operations are stored in memory, each data item occupying a different memory location. The names of these data items represent symbolic memory locations. Elementary Object references Elementary (or simple) variables are those whose type is elementary (also called primitive). Variables x and y defined previously are examples of elementary variables. Object-oriented programming is mainly about defining classes as types for object references, and then declaring and creating objects of these classes. The type of an object is a class. Aggregate variables are declared as arrays of elementary types or declared as arrays of object reference variables of some class type. The following are examples of data declarations in KJP of two constants of types integer and double, followed by three elementary variables of type integer, float, and boolean. constants integer MAX_PERIOD = 24 double PI = 3.1416 variables integer count real salary boolean active The following is an example of a data declaration of an object reference. Assume that there is a class definition called Employee with two object references, one called emp_obj and the other called new_emp; the declaration is: objects object emp_obj of class Employee object new_emp of class Employee 5. Compute area = 6. Print value of area to the output device (video screen). Note that the algorithm is written in a very informal notation, and the value of the sides of a triangle must represent a well-defined triangle. This description of the algorithm is written in an informal pseudo-code notation. 07:21:15 Flowcharts Pseudo-code 6.4.1 Flowcharts A flowchart is a visual notation for describing a sequence of instructions, in a precise manner. Flowcharts consist of a set of symbols connected by arrows. These arrows show the order in which the instructions are to be carried out. The arrows also show the flow of data. Figure 6.1 shows some of the basic symbols used in a flowchart, and the arrows that connect these symbols. A flowchart that describes a problem solution always begins with a start symbol, and always ends with a stop symbol. The start symbol always has an arrow pointing out of it, and the stop symbol always has one arrow pointing into it. A well-defined flowchart must have a starting point represented by a start symbol and a terminating point represented by a stop symbol. 6.4.2 Pseudo-code Pseudo-code is structured notation that can be very informal; it uses an English description of the set of transformations that define a problem solution. It is a natural language description of an algorithm. Note Pseudo-code is much easier to understand and use than an actual programming language. It can be used to describe relatively large and complex algorithms. If a few design rules are followed, another advantage is that it is almost straightforward to convert the pseudo-code to a programming language like KJP. The notation used in a programming language is much more formal and allows the programmer to clearly and precisely describe the algorithm in detail. Various levels of algorithm descriptions are normally necessary, from a very general level for describing a preliminary design, to a much more detailed description for describing a final design. Thus, the first level of description is very informal, and the last level is formal. Sequence, which essentially means a sequential ordering of execution for the blocks of instructions Selection, also called alternation or conditional branch; the algorithm must select one of the alternate paths to Repetition, also called loops, which is a set (or block) of instructions that are executed zero, one, or more times Input-output, which means the values of indicated variables are taken from an input device (keyword) or the values of the variables (results) are written to an output device (screen) Note All problem solutions include some or all of these structures, each appearing one or more times. To design problem solutions (algorithms) and programs, it is necessary to learn how to use these structures in flowcharts and in pseudo-code. 6.5.1 Sequence Figure 6.3 illustrates the first structure, a simple sequence of three blocks of instructions. This is the most common and basic structure. The problem for calculating the area of a triangle is solved using only the sequence and inputoutput structures. The simple salary problem, which is discussed at the end of this chapter, also uses only these structures. 6.5.2 Selection Figure 6.4 illustrates the selection structure. In this case, one of two alternate paths will be followed based on the evaluation of the condition. The instructions in Block1 are executed when the condition is true. The instructions in Block2 are executed when the condition is false. Figure 6.4: Flowchart segment that shows alternate flow of execution for the instructions in Block1 and Block2. An example of a condition is x > 10. A variation of the selection structure is shown in Figure 6.5. If the condition is false, no instructions are executed, so the flow of control continues normally. 6.5.3 Repetition Figure 6.7 shows the repetition structure. The execution of the instructions in Block1 is repeated while the condition is true. Figure 6.7: A flowchart segment that shows a structure for repeating the instructions in Block1. Another form for this structure is shown in Figure 6.8. The instructions in Block1 are repeated until the condition becomes true. Figure 6.8: Flowchart segment that shows another structure for repeating the instructions in Block1. The data list consists of the list of data items separated by commas. For example, to print the value of variable x on the video screen unit, the statement is: display x A more practical output statement that includes a string literal and the value of variable x is: display "value of x is: ", x Class Math is a predefined class and is part of the class library supplied with the Java compiler. This class provides several mathematical functions, such as square root, exponentiation, trigonometric, and other mathematical functions. Figure 6.9: Flowchart that shows the transformations for the simple salary problem. The solution is decomposed into two classes, Employee and Memployee. Class Employee defines the complete algorithm in one or more of its operations. Class Memployee contains function main, which declares and creates an object of class Employee and invokes operation compute_increase of that object. The data description for the attributes of class Employee consists of two variables, salary and name. These attributes have access mode private, which is always enforced in KJP. The algorithm is implemented in function compute_increase. This function computes the salary increase and updates the salary of the object. On the CD The complete KJP code for class Employee follows and is stored in the file kpl. description This program computes the salary increase for an employee at the rate of 4.5%. This is the class for employees. The main attributes are salary and name. */ Employee. class Employee is private variables // variable data declarations real salary string name public // description This is the constructor, it initializes an object on creation. */ function initializer parameters real isalary, string iname is begin set salary = isalary set name = iname endfun initializer // description This function gets the salary of the employee object. */ function get_salary of type real is begin return salary endfun get_salary // description This function returns the name of the employee object. */ function get_name of type string is begin return name endfun get_name // description This function computes the salary increase and updates the salary of an employee. It returns the increase. */ function compute_increase of type real is constants real percent = 0.045 // % increase variables real increase begin // body of function set increase = salary * percent add increase to salary // update salary return increase endfun compute_increase endclass Employee Class Memployee contains function main. The name and salary of the employee are read from the console, and then an object of class Employee is created with these initial values for the attributes. Function main invokes function compute_increase of the object. On the CD The complete KJP implementation of class Memployee follows. The code for this class is stored in the file Memployee.kpl. description This program computes the salary increase for an employee. This class creates and manipulates the employee objects. */ class Memployee is public description This is the main function of the application. */ function main is variables real increase real obj_salary string obj_name objects object emp_obj of class Employee begin display "Enter salary: " read obj_salary display "Enter name: " read obj_name create emp_obj of class Employee using obj_salary, obj_name set increase = call compute_increase of emp_obj set obj_salary = get_salary() of emp_obj display "Employee name: ", obj_name display "increase: ", increase, " new salary: ", obj_salary endfun main endclass Memployee On the CD The Java code generated by the KJP translator for class Employee follows and is stored in the file Employee.java. /** This function returns the name of the employee object. */ public String get_name() { return name; } // end get_name /** This function computes the salary increase and updates the salary of an employee. It returns the increase. */ public float compute_increase() { // constant data declarations final float percent = 0.045F; // increase float increase; // body of function starts here increase = (salary) * (percent); salary += increase; // update salary return increase; } // end compute_increase } // end Employee Figure 6.10 shows the results of executing the salary program for the indicated input data. 5. Compute area = 6.8 Summary 6.8 Summary Data descriptions involve identifying, assigning a name, and assigning a type to every data item used in the problem solution. Data items are variables and constants. The names for the data items must be unique, because they reference a particular data item. The general data types are numeric and string. The numeric types can be integer or real. An algorithm is a precise, detailed, and complete description of a solution to a problem. The basic design notations to describe algorithms are flowcharts and pseudo-code. Flowcharts are a visual representation of the execution flow of the various instructions in the algorithm. Pseudo-code is more convenient to describe small to large algorithms; it is closer to writing an actual program. The building blocks for designing and writing an algorithm are called design structures. These are sequence, selection, repetition, and input-output. Several pseudo-code statements are introduced in this chapter, the assignment statements, arithmetic statements, and input/output statements. 07:21:17 data type identifier pseudo-code variables constants declarations flowchart structure sequence block of instructions process selection repetition Input/Output statements KJP 07:21:18 6.10 Exercises 6.10 Exercises 1. Write an algorithm in informal pseudo-code to compute the perimeter of a triangle. 2. Write the flowchart description for the problem to compute the perimeter of a triangle. 3. Write a complete KJP program for computing the area of a triangle. Use only two classes. 4. Write a complete algorithm in pseudo-code that computes the average of grades for students. 5. Write the complete KJP program for the problem that computes the grades of students. 6. Write an algorithm in informal pseudo-code that calculates a bonus for employees; the bonus is calculated to be 1.75% of the current salary. 7. Write the complete program in KJP for the problem that calculates a bonus for employees. Use only assignment and input/output statements. 8. Write an algorithm in flowchart and in informal pseudo-code to compute the conversion from inches to centimeters. 9. Write an algorithm in flowchart and in informal pseudo-code to compute the conversion from centimeters to inches. 10. Write an algorithm in flowchart and in informal pseudo-code to compute the conversion from a temperature reading in degrees Fahrenheit to Centigrade. 11. Write a complete algorithm in form of a flowchart and informal pseudo-code to compute the conversion from a temperature reading in degrees Centigrade to Fahrenheit. 12. Write a complete program in KJP to compute the conversion from inches to centimeters. 13. Write a complete program in KJP to compute the conversion from centimeters to inches. 14. Write a complete program in KJP to compute the conversion from a temperature reading in degrees Fahrenheit to Centigrade. 15. Write a complete program in KJP to compute the conversion from a temperature reading in degrees Centigrade to Fahrenheit. 16. Write a complete program in KJP that combines the conversions from inches to centimeters and from centimeters to inches. 17. Write a complete program in KJP that combines the two types of temperature conversion. 18. Write a complete program in KJP that combines the calculation of the perimeter and the area of a triangle. 07:21:18 Chapter 7: Selection Chapter 7: Selection 7.1 Introduction The previous chapter presented the techniques and notations used for describing algorithms. Four design structures are used for the detailed description of algorithms. These are sequence, selection, repetition, and input/ output. This chapter explains the selection design structure in algorithms and its application to simple problem solutions. Two statements are discussed, the if and the case statements. These statements include conditions, which are Boolean expressions that evaluate to a truth-value (true or false). Simple conditions are formed with relational operators for comparing two data items. Compound conditions are formed by joining two or more simple conditions with the logical operators. Two examples are discussed: the solution of a quadratic equation and the solution to a modified version of the salary problem (introduced in the previous chapter). 07:21:18 Note All the instructions in Block1 are said to be in the then section of the if statement. In a similar manner, all the instructions in Block2 are said to be in the else section of the if statement. When the if statement executes, the condition is evaluated and only one of the two alternatives will be carried out: the one with the statements in Block1 or the one with the statements in Block2. Equal, == Not equal, != Examples of simple conditions that can be expressed with the relational operators in KJP are: x >= y time ! = Note start_t Instead of applying the mathematical symbols shown previously for the relational operators, additional keywords can be used for the operators in KJP. For example: x greater or equal to y time not equal start_t a greater than b Note that the flowchart shown for the salary problem is not complete, the start and the end symbols are not shown. The flowchart is only slightly more complicated than the one for the previous version of the salary problem. On the CD The code of the KJP implementation for this class is stored in the file Employee_m.kpl. The following class, Comp_salary_m includes the function main, which creates and manipulates objects of class Employee_m. description This program computes the salary increase for an employee. If his/her salary is greater than $45,000, the salary increase is 4.5%; otherwise, the salary increase is 5%. This class creates and manipulates the objects of class Employee_m. */ class Comp_salary_m is public description This is the main function of the application. */ function main is variables real increase real salary integer age string oname objects On the CD The following is the code for the Java implementation of class Employee_m. // KJP v 1.1 File: Employee_m.java, Thu Dec 12 20:09:35 2002 /** This program computes the salary increase for an employee. If his/her salary is greater than $45,000, the salary increase is 4.5%; otherwise, the salary increase is 5%. This is the class for employees. The main attributes are salary, age, and name. */ public class Employee_m { // variable data declarations private float salary; private int age; private String obj_name; private // salary increase float increase; /** This is the initializer function (constructor), it initializes an object on creation. */ public Employee_m(String iname, float isalary, int iage) { salary = isalary; age = iage; obj_name = iname; } // end constructor /** This function gets the salary of the employee object. */ public float get_salary() { return salary; } // end get_salary /** This function returns the name of the employee object. Comp_salary_m.kpl. */ public String get_name() { return obj_name; } // end get_name /** This function computes the salary increase and updates the salary of an employee. */ public void sal_increase() { // constant data declarations final float percent1 = 0.045F; // increase final float percent2 = 0.05F; // body of function starts here if ( salary > 45000) { increase = (salary) * (percent1); } else { increase = (salary) * (percent2); } // endif salary += increase; // update salary } // end sal_increase /** This function returns the salary increase for the object. */ public float get_increase() { return increase; } // end get_increase } // end Employee_m On the CD Employee_m.java. The output of the execution of this program is shown in Figure 7.4. This program uses class Comp_salary_m as the main class that includes the two classes. Two runs are shown, the first with a salary less than $45,000.00, and the second with a salary higher than $45,000.00. The expression inside the square root is called the discriminant. It is defined as: b2 - 4ac. If the discriminant is negative, the solution will involve complex roots. The solution discussed here only considers the case for real roots of the equation. Figure 7.5 shows the flowchart for the general solution. endif Print values of the roots: x1 and x2 The algorithm is implemented in function main of class Quadra. It implements the data description and final design of the algorithm in KJP for the solution of the quadratic equation. On the CD The code for the KJP implementation follows and is stored in the file Quadra.kpl. description This program computes the solution for a quadratic equation; this is also called a second-degree equation. The program reads the three coefficients a, b, and c of type double; the program assumes a > 0. This is the main and the only class of this program. */ class Quadra is public description The control function for the program. */ function main is variables // coefficients: a, b, and c double a double b double c double disc // discriminant double x1 // roots for the equation double x2 begin display "Enter value of a" read a display "Enter value of b" read b display "Enter value of c" read c // Compute discriminant set disc = Math.pow(b,2) - (4*a*c) // Check if discriminant is less than zero if disc less than 0.0 then // not solved in this program display "Roots are complex" else // ok, compute both roots display "Roots are real" set x1 = ( -b + Math.sqrt(disc)) / (2.0 * a) set x2 = ( -b - Math.sqrt(disc)) / (2.0 * a) print "x1: ", x1 print "x2: ", x2 endif endfun main endclass Quadra The KJP translator generates a Java file from a KJP file. In this case, the file generated is following code is the Java implementation of class Quadra. // KJP v 1.1 File: Quadra.java, Fri Dec 06 19:47:10 2002 Quadra.java. The /** This program computes the solution for a quadratic equation; this is also called a second-degree equation. The program reads the three coefficients a, b, and c of type double; the program assumes a > 0. This is the main and the only class of this program. */ public class Quadra { /** The control function for the program. */ public static void main(String[] args) { // coefficients: a, b, and c double a; double b; double c; double disc; // discriminant // roots for the equation double x1; double x2; System.out.println("Enter value of a"); a = Conio.input_Double(); System.out.println("Enter value of b"); b = Conio.input_Double(); System.out.println("Enter value of c"); // // Compute discriminant c = Conio.input_Double(); // Check if discriminant is less than zero disc = Math.pow(b, 2) - (4 * a * c); if ( disc < 0.0) { // not solved in this program System.out.println("Roots are complex"); // ok, compute both roots } else { System.out.println("Roots are real"); x1 = - b + Math.sqrt(disc) /( 2.0 * a); x2 = - b - Math.sqrt(disc) /( 2.0 * a); System.out.println("x1: "+ x1); System.out.println("x2: "+ x2); } // endif } // end main } // end Quadra On the CD Quadra.java. The execution of class Quadra is shown in Figure 7.6. The values for the coefficients are 2, 5, and 3 for a, b, and c, respectively. 07:21:21 = = = = = 4 3 2 1 0 The example assumes that the variables involved have an appropriate declaration, such as: variables integer num_grade character letter-grade ... For the next example, consider the types of tickets for the passengers on a ferry. The type of ticket determines the passenger class. Assume that there are five types of tickets, 1, 2, 3, 4, and 5. The following case statement displays the passenger class according to the type of ticket, in variable ticket-type. variables integer ticket_type ... case ticket-type of value 1: print "Class value 2: print "Class value 3: print "Class value 4: print "Class value 5: print "Class endcase A" B" C" D" E" The case statement supports compound statements, that is, multiple statements instead of a single statement in one or more of the selection options. Another optional feature of the case statement is the default option. The keywords default or otherwise can be used for the last case of the selector variable. For example, the previous example only took into account tickets of type 1, 2, 3, 4, and 5. This problem solution can be enhanced by including the default option in the case statement: case ticket_type of value 1: print "Class A" value 2: print "Class B" 7.7 Summary 7.7 Summary The selection design structure, also known as alternation, is very useful to construct algorithms for simple problems. The two statements in pseudocode explained are the if and case statements. The first one is applied when there are two possible paths in the algorithm, depending on how the condition evaluates. The case statement is applied when the value of a variable is tested, and there are multiple possible values; one path is used for every value selected. The condition in the if statement consists of a Boolean expression, which evaluates to a truth-value (true or false). It is constructed with relational operators between two data items. Conditions that are more complex are formed from simple ones using logical operators. The KJP language (as other programming languages) includes equivalent statements for the selection structures. 07:21:21 alternation condition truth-value if statement relational operators logical operators then else endif case statement value endcase otherwise 07:21:22 7.9 Exercises 7.9 Exercises 1. Write a complete algorithm in flowchart and pseudo-code to compute the distance between two points. Each point, P, is defined by a pair of values (x, y). The algorithm must check that the point values are different than zero, and that the two points are not the same. The distance, d, between two points, P1(x1,y1) and P2 (x2,y2) is given by the expression: 2. Given four numbers, find the largest one. Write a complete algorithm in pseudo-code that reads the four numbers and prints the largest one. 3. Given four numbers, find the smallest one. Write a complete algorithm in pseudo-code that reads the four numbers and prints the smallest one. 4. A car rental agency charges $34.50 per day for a particular vehicle. This amount includes up to 75 miles free. For every additional mile, the customer must pay $0.25. Write an algorithm in pseudo-code to compute the total amount to pay. Use the numbers of days and the total miles driven by the customer as input values. 5. Extend the salary problem to include an additional restriction, a salary increase of 5% can only be assigned to an employee if the salary is less than $45,000 and if the number of years of service is at least 5 years. 6. Write a more complete algorithm to solve the quadratic equation that includes the possibility of complex roots. In other words, include the part of the solution when the discriminant is negative. 7. Passengers with motor vehicles taken on the ferry pay an extra fare based on the vehicle's weight. Use the following data: vehicles with weight up to 800 lb pay $75.00, up to 1200 lb pay $115.55, and up to 2300 lb pay $190.25. From the data on the weight of the vehicle, calculate the fare for the vehicle. 8. Develop an algorithm in pseudo-code that reads four letter grades and calculates the average grade. Use the case statement as explained previously. 9. Expand the ferry problem to calculate the cost of the ticket per passenger. Use the following values: class A ticket costs $150.45, class B costs $110.00, class C costs 82.50, class D costs $64.00, and Class E costs $45.50. Write a complete algorithm in pseudo-code to calculate the cost of the passenger's ticket. 07:21:22 Chapter 8: Repetition Chapter 8: Repetition 8.1 Introduction Most practical algorithms require a group of operations to be carried out several times. The repetition design structure is a looping structure in which a specified condition determines the number of times the group of operations will be carried out. This group of operations is called a repetition group. There are three variations of the repetition structure, and most programming languages include them. This chapter explains three constructs to apply the three variations of the repetition structure. The constructs for repetition are: 1. While loop 2. Loop until 3. For loop The first construct, the while loop, is the most general one. The other two repetition constructs can be expressed with the while loop. 07:21:22 A counter variable has the purpose of storing the number of times (iterations) that some condition occurs in a function. The counter variable is of type integer and is incremented every time some specific condition occurs. The variable must be initialized to a given value. Note A loop counter is an integer variable that is incremented every time the operations in the repeat group are carried out. Before starting the loop, this counter variable must be initialized to some particular value. The following portion of code has a while statement with a counter variable called loop_counter. This counter variable is used to control the number of times the repeat group will be carried out. The counter variable is initially set to 1, and every time through the loop, its value is incremented. constants integer Max_Num = 15 ... variables integer loop_counter // counter variable ... begin set loop_counter = 1 // initial value of counter while loop_counter < Max_Num do increment loop_counter display "Value of counter: ", loop_counter endwhile ... The first time the operations in the repeat group are carried out, the loop counter variable loop_counter has a value equal to 1. The second time through the loop, variable loop_counter has a value equal to 2. The third time through the loop, it has a value of 3, and so on. Eventually, the counter variable will have a value equal to the value of Max_Num. When this occurs, the loop terminates. Variable Num_emp denotes how many times to repeat the block of instructions in Block1. For example, if the value of Num_emp is 10, this means that there are 10 employees, and the block of instructions will be repeated 10 times, once for each employee. The condition for the repetition (loop) is: counter less or equal to Num_emp. The last instruction in the loop increments the value of variable counter. The flowchart in Figure 8.2 shows only the repeat structure of the algorithm and Block1 contain all the instructions that are repeated. This is a simple way to modularize a program, in other words, group instructions into small modules. This also helps reduce the size of the flowchart. The corresponding code in KJP for the algorithm is: integer Num_emp // number of employees to process integer counter . . . read Num_emp // read number of employees set counter = 1 while counter <= Num_emp do // instructions in Block1 increment counter endwhile . . . A complete implementation of the algorithm for the salary problem is implemented in classes Employee_m and Salarym. The operations for calculating the salary increase and updating the salary for every employee are implemented in class Employee_m, which is the same as discussed previously. On the CD The code for the KJP implementation of class Salarym follows; it is stored in the file Salarym.kpl. description This program computes the salary increase for a number of employees. If the employee's salary is greater than $45,000, the salary increase is 4.5%; otherwise, the salary increase is 5%. The program also calculates the number of employees with a salary greater than $45,000 and the total amount of salary increase. */ class Salarym is public // description This function creates objects to compute the salary increase and update the salary. This calculates the number of employees with salary greater than $45,000 and the total salary increase. */ function main is variables integer num_emp // number of employees integer loop_counter real salary string name integer age real increase real total_increase = 0.0 integer num_high_sal = 0 // number employees // with salary greater than 45000 objects object emp_obj of class Employee_m begin // body of function display "enter number employees to process: " read num_emp set loop_counter = 1 // initial value while loop_counter <= num_emp do display "enter employee name: " read name display "enter salary: " read salary display "enter age: " read age create emp_obj of class Employee_m using name, salary, age if salary > 45000 then increment num_high_sal endif call sal_increase of emp_obj set increase = call get_increase of emp_obj // updated salary set salary = call get_salary of emp_obj display "Employee: ", name, " increase: ", increase, " salary: ", salary increment loop_counter add increase to total_increase // accumulate endwhile print "Number employees with salary > 45000: ", num_high_sal print "Total amount of salary increase: ", total_increase endfun main endclass Salarym On the CD The code for Java implementation of class Salarym follows and is stored in the file Salarym.java. This file was generated by the KJP translator. int age; float increase; float total_increase = 0.0F; // accumulator int num_high_sal = 0; // number employees with // salary greater than 45000 Employee_m emp_obj; // body of function starts here System.out.println( "enter number of employees to process: "); num_emp = Conio.input_Int(); loop_counter = 1; // initial value while ( loop_counter <= num_emp ) { System.out.println("enter employee name: "); name = Conio.input_String(); System.out.println("enter salary: "); salary = Conio.input_Float(); System.out.println("enter age: "); age = Conio.input_Int(); emp_obj = new Employee_m(name, salary, age); if ( salary > 45000) { num_high_sal++; } // endif emp_obj.sal_increase(); increase = emp_obj.get_increase(); // get updated salary salary = emp_obj.get_salary(); System.out.println("Employee: "+ name+ " increase: "+increase+" salary: "+ salary); loop_counter++; total_increase += increase; // accumulate } // endwhile System.out.println( "Number of employees with salary > 45000: "+ num_high_sal); System.out.println( "Total amount of salary increase: "+ total_increase); } // end main } // end Salarym 8.4.1 Counters A counter variable has the purpose of storing the number of times that some condition occurs in the algorithm. Note A counter variable is of type integer and is incremented every time some specific condition occurs. The variable must be initialized to a given value, which is usually zero. Suppose that in the salary problem, there is a need to count the number of employees with salary greater than $45,000. The name of the variable is num_high_sal and its initial value is zero. The variable declaration is: integer num_high_sal = 0 Within the while loop, if the salary of the employee is greater than $45,000.00, the counter variable is incremented. The pseudo-code statement is: increment num_high_sal This counter variable is included in the implementation for class Salarym, as described previously. After the while loop, the following KJP statement prints the value of the counter variable num_sal: display "Employees with salary > 45000: ", num_sal 8.4.2 Accumulators An accumulator variable stores partial results of repeated additions to it. The value added is normally that of another variable. The type of an accumulator variable depends of the type of the variable being added. The initial value of an accumulator variable is normally set to zero. For example, assume the salary problem requires the total salary increase for all employees. A new variable of type real is declared, the name of this variable is total_increase. The data declaration for this variable is: real total_increase = 0.0 // accumulator The algorithm calculates the summation of salary increases for every employee. The following statement is included in the while loop to accumulate the salary increase in variable total_increase: add increase to total_increase After the endwhile statement, the value of the accumulator variable total_increase is printed. The pseudo-code statement to print the string "Total amount of salary increase" and the value of total_increase is: display "Total salary increase: ", total_increase The KJP implementation for class Salarym for the salary problem includes the calculation of the total amount of salary increase. 07:21:24 Independent of the initial evaluation of the condition, the operations in the loop will be carried out at least once. If the condition is true, the operations in the repeat group will be carried out only once. The KJP code for the loop-until construct is written with the repeat compound statement, which uses the keywords repeat, until, and endrepeat. The repeat group consists of all operations after the repeat keyword and before the until keyword. The general concepts of loop counters and loop conditions also apply to the loop-until construct. The following portion of code shows the general structure for the loop-until statement. repeat statements in Block1 until condition endrepeat As a simple example, consider a mathematical problem of calculating the summation of a series of integer numbers. These start with some given initial number, with the constraint that the total number of values added is below the maximum number of values given; for example, the summation of integer numbers starting with 10 in increments of 5 for a total of 2000 numbers. For this problem, a counter variable, numbers, is used to store how many of these numbers are counted. An accumulator variable is used for storing the value of the intermediate sums. Every time through the loop, the value of the increment is added to the accumulator variable called sum. Class Sum computes the summation of a series of numbers. The KJP implementation of this class follows. On the CD The KJP code that implements class Sum is stored in the file description This class calculates summation for a series of (1 von 3)09.11.2006 07:21:24 Sum.kpl. numbers. */ class Sum is public description This is the main function in the program. */ function main is variables integer sum // accumulates summations integer numbers // number of values to sum integer svalue // starting value integer maxnum // maximum number of values integer inc_value // increment value begin // body of function starts display "Enter starting value: " read svalue display "Enter number of values: " read maxnum display "Enter increment: " read inc_value set sum = svalue set numbers = 0 repeat add inc_value to sum increment numbers until numbers >= maxnum endrepeat display "Summation is: ", sum, " for ", numbers, " values" endfun main endclass Sum On the CD The code for the Java implementation of class Sum follows. This code is stored in the file Sum.java and was generated by the KJP translator. On the CD Max.kpl. On the CD Figure 8.5 shows the output for the execution of the program with class Max. 8.7 Summary 8.7 Summary The repetition structure is an extremely powerful design structure. A group of instructions can be placed in a loop in order to be carried out repeatedly; this group of operations is called the repetition group. The number of times the repetition group is carried out depends on the condition of the loop. There are three loop constructs: while loop, loop until, and for loop. In the while and for loops, the loop condition is tested first, and then the repetition group is carried out if the condition is true. The loop terminates when the condition is false. In the loop-until construct, the repetition group is carried out first, and then the loop condition is tested. If the loop condition is true, the loop terminates; otherwise, the repetition group is executed again. 07:21:25 loop while loop condition repeat group loop termination loop counter do endwhile accumulator repeat-until endrepeat for to downto endfor 07:21:26 8.9 Exercises 8.9 Exercises 1. Rewrite the KJP code that implements class Sum, which computes the summation of a series of numbers. The program should consist of at least two classes. 2. Rewrite the KJP program that includes class Max, which computes the maximum value of a list of numbers. The program should consist of at least two classes. 3. Write the algorithm in informal pseudo-code and KJP code for a program that is to calculate the average of a series of input values. 4. Write the complete algorithm and the KJP code for a program that finds the minimum value from a series of input values. 5. Rewrite the KJP code for Exercise 1, with a different loop statement. 6. Modify the algorithm and the KJP program of the salary problem. The algorithm should compute the average increase using 5.5% and 6% salary increases. 7. Write the algorithm and KJP code for a program that reads the grade for every student, determines his letter grade, and calculates the overall group average, maximum, and minimum grade. 8. Write the algorithm in informal pseudo-code and the KJP implementation of a program that reads rainfall data in inches for yearly quarters, for the last five years. The program should compute the average rainfall per quarter (for the last five years), the average rainfall per year, and the maximum rainfall per quarter and for each year. 9. Write the algorithm in informal pseudo-code and the KJP implementation. 10. Write the algorithm in informal pseudo-code and the KJP implementation of a program that reads data for every inventory item code and calculates the total value (in dollars) for the item code. The program should also calculate the grand total of amount for the unit value. 07:21:26 Chapter 9: Arrays Chapter 9: Arrays 9.1 Introduction There is often the need to declare and use a large number of variables of the same type and carry out the same calculations on each of these variables. Most programming languages provide a mechanism to handle large number of values in a single collection and to refer to each value with an index. An array is a data structure that can store multiple values of the same type. These values are stored using contiguous memory locations under the same name. The values in the array are known as elements. To access an element in a particular location or slot of the array, an integer value known as index is used. This index represents the relative position of the element in the array; the values of the index start from zero. Figure 9.1 illustrates the structure of an array with 10 elements. 07:21:26 The declaration of an array of object references is similar to the declaration of object references. The general KJP statement for declaring arrays of object references is: object array_name array [ capacity ] of class class_name Arrays of object references must be declared in the objects section for data definitions. For example, the KJP declaration of array employees of class Employee and with 50 elements of capacity is: objects object employees array [50] of class Employee . . . A more convenient and recommended manner to declare an array is to use an identifier constant with the value of the capacity of the array. For example, assume the constant MAX_TEMP has a value 10 and NUM_OBJECTS a value of 25; the declaration of the array temp and array employees is: constants integer MAX_TEMP = 10 integer NUM_OBJECTS = 25 variables float temp array [MAX_TEMP] objects object employees array [NUM_OBJETS] of class Employee . . . The declaration of an array indicates the type of value that the elements of the array can hold. It also indicates the name and total number of elements of the array. In most practical problems, the number of elements manipulated in the array is less than the total number of elements. For example, an array is declared with a capacity of 50 elements, but only the first 20 elements of the array are used. Because the array is a static data structure, elements cannot be inserted or deleted from the array, only the values of the elements can be updated. 07:21:27 07:21:27 return jmax endfun maxtemp // result The minimum value can be found in a similar manner; the only change is the comparison in the if statement. The average is calculated simply as sum/n. Function average_temp in class Temp implements the algorithm discussed. The function uses array temp, which is declared in class Temp as an array of type float and that has num_temp_values elements. The function returns the average value calculated. The KJP code for the function follows. description This function computes the average value of the array temp. The accumulator variable sum stores the summation of the element values. */ function average_temp of type float is variables float sum // variable for summation float ave // average value integer j begin set sum = 0 for j = 0 to num_temp_values - 1 do add temp[j] to sum endfor set ave = sum / num_temp_values return ave endfun average_temp 9.4.3 Searching When the elements of an array have been assigned values, one of the problems is to search the array for an element with a particular value. This is known as searching. Not all the elements of the array need to be examined; the search ends when and if an element of the array has a value equal to the requested value. Two important techniques for searching are linear search and binary search. The binary search technique can only be applied to a sorted array. The values to be searched have to be sorted in ascending order. The part of the array elements to include in the search is split into two partitions of about the same size. The middle element is compared with the requested value. If the value is not found, the search is continues on only one partition. This partition is again split into two smaller partitions until the element is found or until no more splits are possible (not found). Class Temp declares an array of temperatures named temp. One of the functions reads the element values from the console, another function reads the value of temperature to search, and a third function searches the array for the requested temperature value and returns the index value or a negative integer value. The description of the algorithm, as a sequence of steps, is: 1. Set the lower and upper bounds of the array to search. 2. Continue the search while the lower index value is less than the upper index value. a. Split the section of the array into two partitions. Compare the middle element with the requested value. b. If the value of the middle element is the requested value, the result is the index of this element-search no more. c. If the requested value is less than the middle element, change the upper bound to the index of the middle element minus 1. The search will continue on the lower partition. d. If the requested value is greater or equal to the middle element, change the lower bound to the index of the middle element plus 1. The search will continue on the upper partition. 3. If the value is not found, the result is a negative value. Function bsearchtemp in class Temp implements the binary search algorithm using array temp. The code for the KJP implementation for this function follows. description This function carries out a binary search of the array of temperature for the temperature value in parameter temp_val. It sets the index value of the element found, or -1 if not found. */ function bsearchtemp parameters float temp_val is variables boolean found = false integer lower // index lower bound element integer upper // index upper bound element integer middle // index of middle element begin set lower = 0 set upper = num_temp_values while lower < upper and found not equal true do set middle = (lower + upper) / 2 if temp_val == temp[middle] then set found = true set t_index = middle else if temp_val < temp [middle] then set upper = middle -1 else set lower = middle + 1 endif endif endwhile if found not equal true then set t_index = -1 endif endfun searchtemp On the CD Temp.java. 9.4.4 Sorting Sorting an array consists of rearranging the elements of the array in some order according to the requirements of the problem. For numerical values, the two possible sorting orders are ascending and descending. There are several sorting algorithms; however, some are more efficient than others. Some of the most widely known sorting algorithms are: Selection sort Insertion sort Merge sort Bubble sort Shell sort Selection sort is the only one explained here; it is a very simple and inefficient sorting algorithm. Assume there is an array of a numerical type of size N; the algorithm performs several steps. First, it finds the index value of the smallest element value in the array. Second, it swaps this element with the element with index 0 (the first element). This step actually places the smallest element to the first position. Third, the first step is repeated for the part of the array with index 1 to N - 1; this excludes the element with index 0, which is at the proper position. The smallest element found is swapped with the element at position with index 1. This is repeated until all the elements are located in ascending order. A more precise description of the algorithm, as a sequence of steps, is: 1. For all elements with index J = 0 to N-2, carry out steps 2 and 3. 2. Search for the smallest element from index J to N-1. 3. Swap the smallest element found with element with index J, if the smallest element is not the one with index J. Class Temp declares an array temp of type float. The array declaration is: float temp array [NUM_TEMP] Function selectionsort in class Temp implements the algorithm for the selection sort. The code for the KJP implementation for this function follows. description This function carries out a selection sort of the array of temperature. */ function selectionsort is variables integer N // elements in array integer Jmin // smallest element integer j integer k float t_temp // intermediate temp begin set N = num_temp_values for j = 0 to N - 2 do // in the index range from j to N-1 set Jmin = j for k = j+1 to N - 1 do if temp[k] < temp [Jmin] then set Jmin = k endif endfor if Jmin != j then // swap elements with index J and Jmin set t_temp = temp[j] set temp[j] = temp [Jmin] set temp[Jmin] = t_temp endif endfor endfun selectionsort The selection sort is not a very efficient algorithm. The number of element comparisons with an array size of N is N2/2 - N/2. The first term (N2/2) in this expression is the dominant one; the order of growth of this algorithm is N2. This is formally expressed as O(N2). 07:21:29 07:21:29 9.8 Summary 9.8 Summary Arrays are data structures capable of storing a number of different values of the same type. Each of these values is known as an element. The type of an array can be a simple type or can be a class. To refer to an individual element, an integer value, known as the index, is used to indicate the relative position of the element in the array. Arrays are static data structures; after the array has been declared, the capacity of the array cannot be changed. Various practical problems can be solved using arrays. Searching involves finding an element in the array with a target value. Two important search algorithms are linear search and binary search. Sorting involves rearranging the elements of an array in some particular order of their values. In Java, arrays are considered objects; they need to be declared and created. 07:21:30 array capacity index array element element reference searching linear search binary search algorithm efficiency sorting Selection sort matrix 07:21:30 9.10 Exercises 9.10 Exercises 1. Design and implement a function named mintemp for class Temp. This function should find the element of array temp with the minimum value. The function must return the index value of the corresponding element. 2. Design and implement a function that computes the standard deviation of the temperature values in array temp. The standard deviation measures the spread, or dispersion, of the values in the array with respect to the average value. The standard deviation of array X with N elements is defined as: where 3. Design and implement a function for class Temp that sorts the array of temperature values using insertion sort. This divides the array into two parts. The first is initially empty; it is the part of the array with the elements in order. The second part of the array has the elements in the array that still need to be sorted. The algorithm takes the element from the second part and determines the position for it in the first part. To insert this element in a particular position of the first part, the elements to the right of this position need to be shifted one position to the right. Note: insertion sort is not explained in this book; look it up on the Web. 4. Design and implement a problem that provides the rainfall data for the last five years. For every year, four quarters of rainfall are provided measured in inches. Class Rainfall includes attributes such as the precipitation (in inches), the year, and the quarter. Class Mrainfall declares an array of object references of class Rainfall. The problem should compute the average, minimum, and maximum rainfall per year and per quarter (for the last five years). Hint: use a matrix. 5. Redesign and reimplement the solution for Exercise 1 with an array parameter definition in the function. Use the appropriate call to the function. 6. Redesign and reimplement the solution for Exercise 2 with an array parameter definition in the function. Use the appropriate call to the function. 7. Redesign and reimplement the solution for Exercise 3 with an array parameter definition in the function. Use the appropriate call to the function. 8. Design and implement a problem that provides the rainfall data for the last five years. For every year, twelve months of rainfall are provided measured in inches. Class Rainfall2 includes attributes such as the precipitation (in inches), the year, and the month. Class Mrainfall2 declares an array of object references of class Rainfall2. The problem should compute the average, minimum, maximum, and standard deviation of rainfall per year and per month (for the last five years). Hint: use a matrix. 07:21:30 07:21:31 A value of type string is a string constant enclosed in quotes. For example, the following statement assigns a string value to the string variable message. set message = "Hello, world!" A string variable can be declared with a value; the following declares string variable s2 with the string constant "Hi, everyone!". string s2 = "Hi, everyone" The two string variables just declared can be displayed on the console with the following statements: display message display s2 When executing the program that includes these two statements, the following message will appear on the screen: Hello, world! Hi, everyone 07:21:31 For example, to get the index value in string variable message for the character 'r' and assign this to integer variable num, the complete statement is: variable integer num ... set num = indexof 'r' of message When this statement executes, the value of variable num becomes 9. If the starting index value is known, it can be included after the character in the assignment statement. If the character indicated does not exist in the string, then the value assigned is - 1. When this statement executes, the value of variable yystr becomes "World!" Two index values are used for substrings that have start and end index positions. For example, to retrieve the substring located at index positions 8 to 10 of string variable message, the portion of code with the assignment statement should be as follows. variable character yystr integer num1 = 8 integer num2 = 10 ... set yystr = substring num1 num2 of message When this statement executes, the value of variable yystr becomes "orl". When this statement executes, the value of variable num becomes 9. If the starting index value is known, it can be included after the substring in the assignment statement. If the substring indicated does not exist in the string, then the value assigned is - 1. 07:21:32 07:21:33 Another operator for string comparison is the compareto operator, which compares two strings and evaluates to an integer value. If this integer value is zero, operator is used in an assignment statement. The general structure of an assignment statement with this operator follows. set int_var = str_var1 compareto str_var2 For example, the following KJP code compares string variables s1 and s2 in an assignment statement with integer variable test. This integer variable is then tested in an if statement for various possible sets of instructions. variables string s1 string s2 integer test // result of string comparison . . . begin . . . set test = s1 compareto s2 if test == 0 then . . . if test > 0 then . . . else . . . In the example, variable test holds the integer values with the result of the string comparison of s1 and s2. Variable test is subsequently evaluated in an if statement for further processing. 07:21:33 class Person // body of function starts here begin display "Type number of objects to process: " read n for j = 0 to n - 1 do display "Type age of person: " read lage display "Type name of person: " read lname create parray[j] of class Person using lage, lname endfor display "Type target name: " read target_name // // linear search for target name // result is index of array element with // object with the name found, or -1 // set j = 0 while j < n and found not equal true do set tname = call get_name of parray[j] if target_name equals tname then set result_ind = j set found = true else increment j endif endwhile if found not equal true then set result_ind = -1 // name not found endif endfun main endclass Marrayperson On the CD The KJP implementation for this application is stored in several files. Class Marrayperson is stored in the file Person.kpl. indexOf(...) gets the index position of the first occurrence in the string object of the character in the argument. For example, int intvar = ss.inexOf(mychar); tries to find the first occurrence of character variable mychar in string object ss, and assigns the value to integer variable intvar. If the character cannot be found, this method returns - 1. This method can also be invoked with a substring in the argument; it gets the index position of the first character in the matching substring argument. substring(...) gets the substring in the string object that starts at the given index position. For example, String mysubstr = ss.substring(8); gets the substring that starts at index position 8 in the string referenced by ss and the substring takes the object reference mysubstr. When two arguments are used with this method, the substring has the first argument as the starting index position, and the second argument as the end index position. toLowerCase() gets a copy of the string in lowercase. For example, String mylcstr = ss. toLowerCase(); converts a copy of the string referenced by ss to lowercase and this new string is referenced by mylcstr. toUpperCase() gets a copy of the string in uppercase. For example, String mylcstr = ss. toUppperCase(); converts a copy of the string referenced by ss to uppercase and this new string is referenced by mylcstr. the two strings. It compares if the two variables are referencing the same string object. The equals function of the first string is invoked with the second string as the argument. This function compares two strings and evaluates to a truth-value, so it can be used with an if statement. For example, the following Java statement tests if the string referenced by s1 is equal to the string referenced by s2: String s1; String s2; . . . if (s1.equals(s2)) . . . This string comparison only tests if two strings are equal; it is useful in carrying out linear searches. For a binary search of strings, these need to be in alphabetical order. For this search, the comparison needed is more complete in the sense that if the strings are not equal, the order of the first string with respect to the second string needs to be known. Function compareTo defined in class String compares two strings and evaluates to an integer value. If this integer value is equal, function of the first string is invoked with the second string as the argument. This function is invoked in an assignment statement. For example, the comparison of strings s1 and s2 is: String s1; String s2; int test; // result of string comparison . . . test = s1.compareTo(s2); if (test == 0) . . . if (test > 0) . . . else . . . In the example, variable test holds the integer values with the result of the string comparison of s1 and s2. Variable test is subsequently evaluated in an if statement for further processing. Caution Because string objects cannot be modified, Java provides class StringBuffer. This library class can be instantiated by creating string objects that can be modified. Several methods of class StringBuffer are similar to the ones in class String. Other methods, such as insert (...), allow a character or a substring to be inserted at a specified index position. 10.9 Summary 10.9 Summary Strings are sequences of characters. Because each character has an index position in the string, this is similar to an array of characters. String variables are not variables of a primitive type. String variables have a set of operators that enable the manipulation of strings. In Java, strings are considered objects of class String. This class is available in the Java class library. To manipulate strings in Java, various methods of class String are used. Strings cannot be modified, Java provides the StringBuffer, another library class that can be instantiated to create modifiable strings. By using the various methods of this class, strings can be manipulated and modified. 07:21:35 string variable string constant concatenation string comparison string searching string length index position substring class String class Stringbuffer 07:21:35 10.11 Exercises 10.11 Exercises 1. Design and implement a class that inputs a string and creates a copy of the input string with the characters in reverse order. 2. Design and implement a class that inputs a long string and counts the number of times that the word "and" appears; the class should display this number on the console. 3. Design and implement a class that inputs a string and checks if the string is a palindrome; if so, it displays the message "is a palindrome" on the console. A palindrome is a string that does not change when the characters are changed to reverse order. 4. Design and implement a class that inputs a string and checks if the string starts with the substring "Mr. " or with the string "Mrs. ". Note the space after the dot. If the input string does not include any one of these substrings, the class should display a message. 5. Design and implement the solution to a problem that sets up an array of objects of class Person. The solution should carry out a binary search of the name of the objects looking for a specific string value (the target string). Hint: modify class Marrayperson in Chapter 9. 6. Design and implement a solution to a problem that rearranges an array of objects of class Person. For this, use selection sort. Hint: modify class Marrayperson in Chapter 9. 7. Redesign and reimplement the solution for Exercise 6 with an array parameter definition in the function. Use the appropriate call to the function. 07:21:35 07:21:36 Sequence diagrams Collaboration diagrams 4. State diagrams State diagrams Activity diagrams 5. Implementation diagrams Package diagrams Component diagrams Deployment diagrams Often, only a subset of these diagrams is needed to completely model an application. The most relevant UML diagrams are described in this chapter. The UML stereotype provides an extension mechanism to the UML that allows users to extend the modeling language according to their needs. Two examples of stereotypes are actor and active, which are used in the following subsections. The name of the class of the object is underlined. For example, :Person denotes an object of class Person. The attributes of the object include their current values. This defines the current state of the object. The types of the attributes are not included because these are defined in the class. The operations of the object are included. When these are left out, they are defined in the corresponding class. 11.3.2 Associations An association is a relationship between two or more classes. The simplest association is the binary association, which is represented by a solid line connecting two classes in the corresponding UML diagram. The name of the association may be included just above the line. The association name may also include a solid small triangle to indicate the direction in which to read the association name. The associations can also include roles, which are shown at the ends of the line, close to the corresponding classes. A binary association is shown in Figure 11.4. It shows a binary relation between class Person and class Ball. The name of the association here is plays_with, and the roles are customer and provider. the other class. A range of numbers can be specified for each class in the diagram. If l denotes the lower bound in a range, and if u denotes the upper bound in the range, then the notation l..u corresponds to the range. When a star is used, it indicates an unlimited upper bound. The star at the side of class Ball in Figure 11.4 denotes that there can be zero or many objects of this class in the association with class Person. There is only one object of class Person. 11.3.4 Aggregation An n-ary association is a relationship that involves more than two classes. When a relationship exists among classes where some classes are contained within other classes, the relationship is known as aggregation, or partwhole relationship or containment. In simple aggregation, the larger class is called the owner class; the smaller classes are called component classes. Often, classes are not contained in other classes but are organized in the communication mechanism through the class representing the whole. With UML aggregation diagrams, this relationship is denoted with a diamond at the owner class side of the association. Figure 11.5 shows an owner class Computer, in associations with three component classes, CPU, Memory, and Input/Output. 11.3.5 Inheritance Inheritance is a vertical relationship among classes. It allows for enhanced class reuse, that is, the ability to develop a new class using a predefined and previously developed class. This allows the sharing of some classes across several different applications. The new class inherits the characteristics of the existing and more general class, to incorporate the characteristics into the new class. In most practical applications, classes are arranged in hierarchies, with the most general class at the top of the hierarchy. A parent class is also called the super class (or the base class). A derived class inherits the characteristics (all attributes and operations) of its parent class. A derived class can be further inherited to lowerlevel classes. In the UML class diagram, an arrow with an empty head points from a subclass (the derived class) to its parent class. A subclass can be: An extension of the parent class, if it includes its own attributes and operations, in addition to the derived characteristics it inherits from the parent class A specialized version of the parent class, if it overrides (redefines) one or more of the derived characteristics inherited from its parent class This is the basic idea of class reuse with inheritance, which has as its main advantage that the definition and development of a class takes much less time than if the class were developed from scratch. This is the reason why class reuse is important. In UML terminology, generalization is the association between a general class and a more specialized class (or extended class). This association is also called inheritance, and it is an important relationship between classes. Therefore, in modeling, it is useful to show this in the class diagrams. In the UML class diagram, an arrow points from a class (the derived class) to its parent class. Caution When a class inherits the characteristics from more than one parent class, the mechanism is called multiple inheritance. Most object-oriented programming languages support multiple inheritance (KJP and Java do not). Figure 11.6 illustrates a simple class hierarchy with inheritance. The parent class is Polygon and the subclasses are: Triangle, Rectangle, and Parallelogram that inherit the features from the parent class. 11.5 Summary 11.5 Summary The UML notation is a standard semigraphical notation for modeling a problem with various types of diagrams. These diagrams are grouped into two categories. The first group describes the static aspects of the model, and the second group describes the dynamic aspects of the model. The class diagrams are one of the most basic and important diagrams. They show the structure of the classes in the model and the relationship among these classes. Other static modeling diagrams are object diagrams and use cases. The UML dynamic modeling diagrams show the behavior of objects and their interactions. These are collaboration, sequence, and state diagrams. 07:21:38 static modeling dynamic modeling class diagrams object diagrams use cases collaboration diagrams sequence diagrams state diagrams actor role multiplicity cardinality association generalization inheritance aggregation composition extension specialization transition 07:21:38 11.7 Exercises 11.7 Exercises 1. Explain the difference between the class diagram and the object diagram. What are the similarities? 2. Explain the differences and similarities between the collaboration diagram and the sequence diagram. 3. Construct more detailed and complete UML diagrams (static and dynamic modeling) for the movies rental problem. This application must control the inventory of movies in a movie rental shop. 4. Construct the relevant UML diagrams (static and dynamic modeling) for the problem of the child playing with two balls. Explain the diagrams used in this application. 5. Construct the relevant UML diagrams (static and dynamic modeling) of a program that reads rainfall data in inches for yearly quarters, for the last five years. The program should compute the average rainfall per quarter (for the last five years), the average rainfall per year, and the maximum rainfall per quarter and for each year. 6. Construct the relevant UML diagrams (static and dynamic modeling). 7. Construct the relevant UML diagrams (static and dynamic modeling) of a program that reads data for every inventory item code and calculates the total value (in dollars) for the item code. The program also calculates the grand total unit value. 8. Consider an automobile rental office. A customer can rent an automobile for a number of days and with a finite number of miles (or kilometers). Identify the type and number of objects involved. For every type of object, list the properties and operations. Construct static and dynamic modeling diagrams for this problem. 07:21:38 07:21:39 12.2 Classification 12.2 Classification Classification is a modeling concept, and for a given application, it refers to the grouping of the objects with common characteristics. In this activity, the classes and their relationships are identified. Some classes of an application are completely independentonly the class with function main has a relationship with them. The other classes in the application are related in some manner and they form a hierarchy of classes. In a class hierarchy, the most general class is placed at the top. This is the parent class and is also known as the super class (or the base class). A derived class inherits the characteristics (all attributes and operations) of its parent class. A derived class can be further inherited to lower-level classes. In the UML class diagram, an arrow with an empty head points from a subclass (the derived class) to its base class to show that it is inheriting the features of its base class. Because in the UML diagram, the arrow showing this relationship points from the subclass up to the base class, inheritance is seen as a vertical relationship between two classes (see Figure 12.1). 07:21:39 12.3 Inheritance 12.3 Inheritance Inheritance is a mechanism by which a new class acquires all the nonprivate features of an existing class. This mechanism is provided by object-oriented programming languages. The existing class is known as the parent class, the base class, or the super class. The new class being defined, which inherits the nonprivate features of the base class, is known as the derived class or subclass. The new class acquires all the features of the existing base class, which is a more general class. This new class can be tailored in several ways by the programmer by adding more features or modifying some of the inherited features. The main advantage of inheritance is that the definition and development of a class takes much less time than if the class were developed from scratch. Another advantage of inheritance is that it enhances class reuse. A subclass can be: An extension of the base class, if it includes its own attributes and operations, in addition to the derived characteristics it inherits from the base class A specialized version of the base class, if it overrides (redefines) one or more of the characteristics inherited from its parent class A combination of an extension and a specialization of the base class When a class inherits the characteristics from more than one parent class, the mechanism is called multiple inheritance. Most object-oriented programming languages support multiple inheritance; however, Java and KJP support only single inheritance. Therefore, in modeling, it is useful to show this in the class diagrams. In UML terminology, generalization is the association between a general class and a more specialized class or extended class. This association is also known as inheritance, and it is an important relationship between classes. In the UML class diagram, the arrow that represents this relationship points from a class (the derived class) to its parent class. Figure 12.1 illustrates a simple class hierarchy with inheritance. The parent class is Polygon and the subclasses are: Triangle, Rectangle, and Parallelogram that inherit the features from the parent class. The idea of a subclass and a subtype is important. All objects of class Parallelogram are also objects of class Polygon, because this is the base class for the other classes. On the contrary, not all objects of class Polygon are objects of class Parallelogram. 12.3 Inheritance Because a subclass can also be inherited by another class, it often includes protected features in addition to the private and public ones. In UML class diagrams, a feature of the class is indicated with a plus (+) sign if it is public, with a minus (-) sign if it is private, and with a pound (#) sign if it is protected. Initializer (constructor) functions are not inherited. A derived class must provide its own initializer functions. These are the only public features that are not inherited by the subclass. The KJP statement to call or invoke an initializer function of the base class from the subclass is: call super using argument_list If the argument list is absent in the call, the initializer function invoked is the default initializer of the base class. Suppose a new class, Toyball, is being defined that inherits the features of an existing (base) class Ball. The attributes of class Ball are color and size. The color attribute is coded as integer values (white is 0, blue is 2, yellow is 3, red is 4, black is 5). Class Ball includes an initializer function that sets initial values to these two attributes. The subclass Toyball has one other attribute, weight. The initializer function of this class needs to set initial values to the three attributes, two attributes of the base class and the one attribute of the subclass. The two attributes of the base class (Ball) are set by invoking the function super in the initializer function of the subclass, Toyball. class Toyball inherits Ball is private // attributes variables real weight // no private methods in this class public // public methods description This is the constructor, it initializes an object on creation. */ function initializer parameters real iweight, integer icolor, real isize is begin // call the initializer of the base class call super using icolor, isize set weight = iweight endfun initializer . . . endclass Toyball The attributes of a class are private, so the only way to set the initial values for the attributes of base class is to invoke its initializer function of the base class. In the previous KJP code, this is accomplished with the statement: call super using icolor, isize 12.3 Inheritance The code for the KJP implementation of base class Person follows; this is stored in the file Person.kpl. description This is the complete definition of class Person. The attributes are age and name. */ class Person is private // attributes variables // variable data declarations integer age string obj_name // no private methods in this class public description This is the default initializer method. */ function initializer is begin set age = 21 set obj_name = "None" endfun initializer // description This is a complete initializer function, it sets the attributes to the values given on object creation. */ function initializer parameters integer iage, string iname is begin set age = iage set obj_name = iname endfun initializer description This accessor function returns the name of the object. 12.3 Inheritance */ function get_name of type string is begin return obj_name endfun get_name description This mutator function changes the name of the object to the name in 'new_name'. This function is void. */ function change_name parameters string new_name is begin set obj_name = new_name endfun change_name description The following KJP code implements class Employeec, which is a subclass of class Person. Class Employeec computes the salary increase. description This class computes the salary increase for an employee. If his/her salary is greater than $45,000, the salary increase is 4.5%; otherwise, the salary increase is 5%. This is the class for employees. The main attributes are salary, age, and name. */ class Employeec inherits Person is private variables integer years_service real salary public description This is the initializer function (constructor), it initializes an object on creation. */ function initializer parameters real isalary, integer iage, string iname is begin // call the initializer in the base class call super using iage, iname set salary = isalary set years_service = 0 endfun initializer description This function gets the salary of the employee object. */ (4 von 9)09.11.2006 07:21:40 12.3 Inheritance On the CD import Conio // Library class for console I/O description This program computes the salary increase for an employee. This class creates and (5 von 9)09.11.2006 07:21:40 12.3 Inheritance On the CD The Java implementation of class Employeec is shown next, and is stored in the file Employeec.java. 12.3 Inheritance 12.3 Inheritance Manager.kpl and is Class Manager is a specialized version of class Employeec. Class Manager inherits class Employeec and overrides function sal_increase. description This class computes the salary increase for a manager; the salary increase is 2.5% of the salary plus $2700.00. */ class Manager inherits Employeec is public description This is the initializer function (constructor), it initializes an object on creation. */ function initializer parameters real isalary, integer iage, string iname is begin // call the initializer of the base class call super using isalary, iage, iname endfun initializer description This function computes the salary increase and updates the salary of a manager object. It returns the increase. */ function sal_increase of type real is constants real MAN_PERCENT = 0.025 variables real increase real salary begin // body of function set salary = call get_salary 12.3 Inheritance Class Mmanager includes the definition of function main, which creates and manipulates objects of class Manager. Class Mmanager is stored in file Mmanager.kpl. 12.4 Summary 12.4 Summary Inheritance is a vertical relationship among classes. This relationship enhances class reuse. A subclass (derived class) inherits all the features of its base (parent) class. Only the public and protected features can directly be accessed by the base class. The initializer (constructor) functions of the base class are not inherited; all classes are responsible for defining their initializer functions. A subclass can be an extension and/or a specialization of the base class. If a subclass defines new features in addition to the ones that it inherits from the base class, then the subclass is said to be an extension to the base class. If a subclass redefines (overrides) one or more functions of the base class, then the subclass is said to be a specialization of the base class. The UML class diagrams show the inheritance relationships. 07:21:41 parent class super class base class subclass derived class horizontal relationship vertical relationship class hierarchy inherit extension specialization class reuse association generalization inheritance reuse overiding 07:21:41 12.6 Exercises 12.6 Exercises 1. Explain the difference between horizontal and vertical relationships. How can these be illustrated in UML diagrams? 2. In what way does inheritance enhance class reuse? Why is this important? 3. Because attributes are private in KJP, explain the limitations in dealing with inheritance. 4. One of the examples discussed in this chapter is class Toyball as a subclass of class Ball. Draw UML diagrams, and design and write a complete KJP program for a sport using specialized objects of class Ball. Choose tennis or volleyball (or any other sport of your preference). 5. Repeat the previous problem with the subclass being a specialization and an extension of the base class. 6. Draw the corresponding UML diagrams, redesign, and rewrite class Manager for the salary problem. Provide a class that includes function main and that creates and manipulates objects of class Manager and objects of class Employeec. Class Manager should be an extension and a specialization of class Employeec. Explain how class reuse is being applied in this problem. 7. Refer to Figure 12.1. Design and write the class definitions for the four classes. Class Polygon is the base class, the most simple and general class in the hierarchy. The other three classes are specializations and/or extensions of the base class. These three classes should provide functions to compute the perimeter and the area for the corresponding objects. 8. How would you include classes Circle and Sphere in the class hierarchy of the previous problem? Write the KJP program with the class implementations for these two classes. 9. A complex number has two attributes, the real part and the imaginary part. The two basic operations on complex numbers are complex addition and complex subtraction. Design and implement a KJP program for simple complex numbers. A slightly more advanced pair of operations are complex multiplication and complex division. Design and write the KJP program that includes an extension to the basic complex numbers. Hint: in addition to the rectangular representation of complex numbers (x,y), it might be useful to include attributes for the polar representation of complex numbers (module, angle). 10. Consider a class hierarchy involving motor vehicles. At the top of the hierarchy, class Motor_vehicle represents the most basic and general type of vehicles. Automobiles, Trucks, and Motorcycles are three types of vehicles that are extensions and specializations of the base class. Sport_automobiles are included in the class hierarchy as a subclass of Automobile. Design and implement a KJP program with all these classes. Include attributes such as horse power, maximum speed, passenger capacity, load capacity, and weight. Include the relevant functions. 07:21:42 07:21:42 An abstract class cannot be instantiated; it is generally used as a base class. The subclasses override the abstract methods inherited from the abstract base class. A base class is an abstract class when it does not provide the implementation for one or more functions. Such base classes provide single general descriptions for the common functionality and structure of its subclasses. An abstract class is a foundation on which to define subclasses. Classes that are not abstract classes are known as concrete classes. The base class Gfigures is an abstract class because it does not provide the implementation of the functions area and perimeter. The KJP code with the definition of class Gfigures follows. description This abstract class has two functions. */ abstract class Gfigures is public description This function computes and returns the area of the geometric figure. */ abstract function area of type double description This function computes and returns the perimeter of the geometric figure. */ abstract function perimeter of type double endclass Gfigures On the CD The KJP code with the implementation of this class is stored in the file The Java code for class Gfigures is stored in the file Caution Gfigures.kpl. Gfigures.java. Because the abstract class Gfigures does not include the body of the functions area and perimeter, objects of this class cannot be created. In other words, class Gfigures cannot be instantiated. In Java, the structure of the abstract class is very similar. The definition of this abstract class follows. // KJP v 1.1 File: Gfigures.java, Sat Jan 04 19:03:07 2003 /** This abstract class with two functions. */ public abstract class Gfigures { /** This function computes and returns the area of the geometric figure. */ abstract public double area(); /** This function computes and returns the perimeter of the geometric figure. */ abstract public double perimeter(); } // end class Gfigures The following KJP code includes the complete definition of class Triangle. This inherits the function from class Gfigures and redefines functions area and perimeter. The code for this class is stored in the file description (2 von 4)09.11.2006 07:21:43 Triangle.kpl. double y // second side double z // third side double area double perim objects object my_triangle of class Triangle begin display "This program computes the area" display " of a triangle" display "enter value of first side: " read x display "enter value of second side: " read y display "enter value of third side: " read z create my_triangle of class Triangle using x, y, z set area = call area of my_triangle display "Area of triangle is: ", area set perim = call perimeter of my_triangle display "Perimeter of triangle is: ", perim endfun main endclass Mtriangle After translating the classes Triangle and Mtriangle and compiling them with the Java compiler, class Mtriangle can be executed. The output produced on the console is: This program computes the area of a triangle enter value of first side: 2 enter value of second side: 4 enter value of third side: 5 Area of triangle is: 3.799671038392666 Perimeter of triangle is: 11.0 13.3 Interfaces 13.3 Interfaces An interface is similar to a pure abstract class. It does not include attribute definitions and all its methods are abstract methods. Constant definitions are allowed. An interface does not include constructors and cannot be instantiated. 13.3 Interfaces A class makes use of an interface by implementing it. All methods declared in the interface must be implemented in the class that implements it. This class can define additional features. The class that implements an interface must use KJP statement implements. The header for the class definition that uses this KJP statement has the following general structure: description . . . class cls_name implements interface_name is . . . endclass cls_name On the CD For example, class Nball implements interface Iball, which was defined earlier. The KJP code for this class follows and is stored in the file Nball.kpl. 13.3 Interfaces 13.4 Subtypes 13.4 Subtypes Although an interface and an abstract class cannot be instantiated, both can be used as super types for object references. This implies that interfaces and abstract classes are useful for declaring object references. For example, refer again to Figure 13.1. Class Gfigures is an abstract class and the other classes are subclasses. An object reference can be declared of type Gfigures. objects object gen_figure of class Gfigures ... In a similar manner, objects of the subclasses can be declared of each of their classes. The subclasses are considered subtypes of type Gfigures. For example, the following declaration defines three object references, triangle_obj, circle_obj, and rect_obj. objects object triangle_obj of class Triangle object circle_obj of class Circle object rect_obj of class Rectangle ... The types of these object references declared are considered subtypes in the problem domain because of the original class hierarchy represented in Figure 13.1. For this organizational structure of the problem, the object reference triangle_obj is declared of type Triangle, but is also of type Gfigures. In fact, any object reference of type Triangle is also of type Gfigures. The same principle applies to the object references declared with the types Circle and Rectangle. Of course, the opposite is not true; any object reference of type Gfigures is not also of type Rectangle, Circle, or Triangle. An interface can also be used as a super type, and all the classes that implement the interface are considered subtypes. 07:21:43 13.5 Polymorphism 13.5 Polymorphism An object reference of a super type can refer to objects of different subtypes. This is possible from the subtyping principle explained before. To illustrate this concept, the following code creates objects for the object references triangle_obj, circle_obj, and rect_obj. Assume there is a declaration for variables x, y, z, and r. create triangle_obj of class Triangle using x, y, z create circle_obj of class Circle using r create rect_obj of class Rectangle using x, y The object reference gen_figure of class Gfigures can be assigned to refer to any of the three objects, triangle_obj, circle_obj, and rect_obj, created previously. For example, the following link implements such an assignment. set gen_figure = triangle_obj This is perfectly legal, because the type of object reference triangle_obj is a subtype of the type of object gen_figure. After this assignment, it is possible to invoke a function of the abstract class Gfigures that is implemented in the subclass Triangle. For example, the following code invokes function perimeter: call perimeter of gen_figure The actual function invoked is the one implemented in class Triangle, because it is the type of object reference triangle_obj. At some other point in the program (possibly in function main), another similar assignment could be included. The following code assigns the object reference circle_obj to the object reference gen_figure. set gen_figure = circle_obj The call to function perimeter is the same as before, because the three subtypes represented by the three subclasses Rectangle, Circle, and Triangle implement function perimeter. Because the implementation for this function is different in the three classes, the runtime system of the Java compiler selects the right version of the function. Polymorphism is a runtime mechanism of the language that allows the selection of the right version of a function to be executed depending on the actual type of the object. Only one among several possible functions is really called. This function selection is based on late binding because it occurs at execution time. 07:21:44 endfor endfun main endclass Mgfigures Note that only three elements of the array are actually used, although the array has 15 elements. The Java code for class Mgfigures follows. On the CD The KJP code with the implementation of class Mgfigures is stored in the file Mgfigures.kpl, and the Java code implementation is stored in the file Mgfigures. java. x = Conio.input_Double(); System.out.println( "enter value second side: "); y = Conio.input_Double(); // create rectangle object rect_obj = new Rectangle(x, y); fig_list [2] = rect_obj; for (i = 0 ; i <= 2; i++) { area = fig_list [i].area(); System.out.println( "Area of geometric fig is: "+area); perim = fig_list [i].perimeter(); System.out.println( "Perimeter of geometric fig is: "+ perim); } // endfor } // end main } // end Mgfigures The output for an execution run of this class is shown next. The input values are shown in the text file as shown. Note that the values of the sides of the triangle correspond to a well-defined triangle. enter value of first side of triangle: 2 enter value of second side: 4 enter value of third side: 5 enter value radius of circle: 3.5 Enter value of first side of rectangle: 4.5 enter value of second side: 7.25 Area of geometric fig is: 3.799671038392666 Perimeter of geometric fig is: 11.0 Area of geometric fig is: 38.4844775 Perimeter of geometric fig is: 21.99113 Area of geometric fig is: 32.625 Perimeter of geometric fig is: 23.5 13.7 Summary 13.7 Summary Abstract classes have one or more abstract methods. An abstract method does not include its implementation, only the function declaration, also known as the function specification. These classes cannot be instantiated; they can only be used as base classes. The subclasses redefine (override) the functions that are abstract in the base class. A pure abstract class has only abstract methods. An interface is similar to a pure abstract class, but it cannot declare attributes. An interface may include constant declarations and may inherit another interface. A class can implement several interfaces. A base class can be used as a super type, and the subclasses as subtypes. An abstract class can be used as a type of an object variable (object reference). This object variable can be assigned object variables of a subtype. There are normally several object variables of each subtype. It is then possible to invoke a function of an object variable of a subtype. Polymorphism is a language mechanism that selects the appropriate function to execute. This selection is based on late binding. Polymorphism uses the type of the actual object and not the type of the object variable. 07:21:45 concrete class abstract method function overriding interface super type subtype polymorphism late binding heterogeneous array 07:21:45 13.9 Exercises 13.9 Exercises 1. Explain the differences and similarities between interfaces and abstract classes. Give two examples. 2. Explain the differences and similarities between polymorphism and overloading. Give examples. 3. Explain the differences between implementing an interface and overriding the methods of an abstract class. Give two examples. 4. Explain the differences between function overriding and polymorphism. Give two examples. 5. Does function overriding imply polymorphism? Is it possible to override one or more functions without using polymorphism? Explain and give an example. 6. Is it possible to define an abstract base class and one or more subclasses without using polymorphism? Explain and give an example. 7. Which is the most straightforward way to overcome the Java (and KJP) limitation of only supporting single inheritance? Give an example. 8. Enhance the problem with base class Gfigures discussed in Section 13.2.1 and illustrated in Figure 13.1. Add the capability to the geometric figures to draw themselves on the screen using dots and dashes. Define an interface at the top of the hierarchy. Write the complete program. 9. A company has several groups of employees, executives, managers, regular staff, hourly paid staff, and others. The company needs to maintain the data for all employees in a list. Design a solution to this problem that uses a heterogeneous array of employee objects. Use an abstract base class and apply polymorphism to process the list (array). Write the complete program. 10. Repeat the previous problem defining an interface instead of an abstract base class. Compare the two solutions to the problem. 11. Design a hierarchy for animals. Find some behavior in all animals that is carried out in different manners (eat, move, reproduce, or others). Define the top-level animal category with an abstract base class and one or more interfaces. Define and implement the subclasses. Write the complete program. 07:21:45 07:21:46 Containers Components Events Listeners Several precompiled Java classes are provided in various packages with the Java compiler. Other library packages are provided by third parties. The import statement is required by any class definition that needs access to one or more classes in a library package. Most programs that include GUI, need to access the two Java class packages, AWT and Swing. In the programs, an import statement must be included at the top of a class definition. The following two lines of code are the ones normally required by programs that access the graphical libraries AWT and Swing. The import statements shown give access to all the classes in the two packages. import all java.awt import all javax.swing 14.3 Frames 14.3 Frames The largest type of container is a frame. This container can be created simply as an object of class JFrame of the Swing library. An empty frame window can be built by creating an object of class JFrame with a specified title and setting the size for it. Figure 14.2 shows an empty frame (window). The relevant properties of this frame are its title, color, and size. The KJP code that implements class Frame_sample follows. It is stored in the file Frame_sample.kpl. The Java implementation of the class is stored in the file Frame_sample.java. 14.3 Frames Note The size of the graphical object on the screen is measured in pixels. A pixel is the smallest unit of space that can be displayed on the video screen. The total number of pixels on the screen defines the resolution of the screen. High-resolution screens have a larger number of pixels, and the pixels are much smaller. // text label When the objects of class JLabel are created, their text titles are defined. The following KJP statements create the two text objects and define their associated text titles. create blabel1 of class JLabel using "Kennesaw Java Preprocessor" create blabel2 of class JLabel using "The Language for OOP" Labels can also display pictures by indicating icons for the pictures. Image labels display a picture by indicating the corresponding icon. In classes using Swing, a picture is set up into an icon in a label, so that the classes can position the label in a container and display it. The pictures are normally in a standard format, such as JPEG or GIF. Note A picture is defined as an icon, which is an object of class ImageIcon. The icon is then defined as part of the label. The following statements declare an object variable of class ImageIcon and an object of class JLabel. object kjpimage of class ImageIcon object kjplabel of class JLabel On the CD // image // for image The icon object is created with a picture stored in a specified picture file. The following statement creates the icon object kjpimage with a picture in the file kjplogo.gif. create kjpimage of class ImageIcon using "kjplogo2.gif" Finally, with the icon object created, it can be defined as part of a label. The following statement creates the label object with the icon defined in object variable kjpimage. create kjplabel of class JLabel using kjpimage Border, which arranges the components in the north, east, west, center, and south positions in the container Flow, which arranges the components in the container from left to right Grid, which arranges the components in a matrix with row and column positions 14.3 Frames Card, which arranges the components in a similar manner as the stack of cards Gridbag, which arranges the components in a similar manner as the grid but with variable size cells The most common layout managers are the first three: border, flow, and grid. Figure 14.3 shows the positioning of components using the border layout manager. The following class, Kjplogo, sets up a window (an object of class JFrame) with three components: two text labels and an image label. The KJP code for class Kjplogo is implemented and stored in file Kjplogo.kpl. 14.3 Frames "KJP logo" create blabel1 of class JLabel using "Kennesaw Java Preprocessor" create blabel2 of class JLabel using "The Language for OOP" create kjpimage of class ImageIcon using "kjplogo2.gif" create kjplabel of class JLabel using kjpimage create lmanager of class BorderLayout set cpane = call getContentPane of frame_obj call setLayout of cpane using lmanager // add the text image label and text label // components // to the content pane of the window call add of cpane using kjplabel, BorderLayout.CENTER call add of cpane using blabel1, BorderLayout.NORTH call add of cpane using blabel2, BorderLayout.SOUTH call setSize of frame_obj using WIDTH, HEIGHT call setVisible of frame_obj using true endfun main endclass Kjplogo Figure 14.4 shows the window that appears on the screen when the program in class Kjplogo executes. The size of the frame object is normally set before displaying it on the screen. As mentioned before, the units for size are in pixels. The previous example used two named constants: WIDTH and HEIGHT. This is the recommended manner to set the values for the size. The size is set by invoking method setSize with the values in 14.3 Frames pixels for width and height of the frame. For example, to set the size of the frame referenced by frame_obj, the statement is: call setSize of frame_obj using WIDTH, HEIGHT The third attribute of a frame is the color. This attribute is normally set to a container in the frame, such as the content pane of the frame or the panels defined and contained in the content pane. In other words, the color of any of these containers can directly be set. The most common method to invoke for a container is setBackground. The argument is normally a predefined constant in class Color, which is available in the AWT package. These constants represent various colors to apply as background color to the container. The most common constants for the colors are listed in Table 14.1. Table 14.1: Common colors in a frame Color.blue Color.orange Color.green Color.gray Color.magenta Color.pink Color.red Color.white Color.yellow Color.darkGray Color.lightGray To set the background color of a container in a frame object, method setBackground is invoked with the selected color. This method is defined in class JFrame. The following statement sets the background color to pink in frame frame_obj of the previous example. Recall that cpane is the content pane of frame_obj. call setBackground of cpane using Color.pink Each of these actions generates a specific type of event. A program that is dependent on events while it executes is called event-driven, because the behavior of the program depends on the events generated by user actions. A listener is an object that waits for a specific event to occur and that responds to the event in some manner. Each listener has a relationship with an event or with a group of similar events. Listener objects must be carefully designed to respond to its type of events. The AWT and Swing packages provide several classes and interfaces for defining listener objects. For action events, the interface ActionListener must be implemented by the class that defines the behavior of the listener object. Figure 14.6 shows the UML collaboration diagram for an object of class JButton and a listener object of class Bquithandler (defined in this next section). The button object generates an action event that it sends to the listener object by invoking method actionPerformed. The interaction among these objects occurs automatically (behind the scenes). Figure 14.6: The UML collaboration diagram for a button and listener objects. The KJP code that implements class Kjplogbutton is stored in the file kpl, and the Java implementation is stored in the file Kjplogbutton. Kjplogbutton.java. Kjplogbutton. import all javax.swing // Library for graphics import all java.awt.event description This class defines the behavior of listener objects for the button. When the user clicks the button, the program terminates. */ class Bquithandler implements ActionListener is public description The only function in the class. */ function actionPerformed parameters object myev of class ActionEvent is begin call System.exit using 0 endfun actionPerformed endclass Bquithandler On the CD The KJP code that implements class Bquithandler is stored in the file kpl, and the Java implementation is stored in the file Bquithandler. Bquithandler.java. Figure 14.7 shows the window that appears on the screen when the program, which consists of the two classes defined previously, executes. When the user clicks the button, the program terminates. . . . create text1 of class JTextField using 20 To register a listener object with a text field is similar to registering a listener object to a button. The following statements declare and create a listener object, register an action event listener object with the text field object text1, and include the text field in the content pane. object tfieldlistener of class Tlistener create tfieldlistener of class Tlistener . . . call addActionListener of text1 using tfieldlistener call add of cpane using text1 All data is entered and displayed as strings, so proper conversion needs to be carried out for entering and displaying numerical data. To get string data entered by a user into a text field, method getText of the text field object is used. To display string data in a text field, the method setText is used with the string as the argument. The following statement gets the string data entered by the user in the text field text1, and assigns the string value to variable ss. string ss . . . set ss = call getText of text1 In a similar manner, the following statement displays string yy on the text field object text1. string yy . . . call setText of text1 using yy To convert the string value entered in a text field to numeric of type double, method Double.parseDouble is used with the string value as the argument. This is actually a static method parseDouble in class Double, which is a Java library class. The following statement converts the string ss to a numeric (of type double) variable dd. double dd . . . set dd = call Double.parseDouble using ss To display numeric data (of type double) to a text field, it must first be converted to a string value. Method String. valueOf (static method valueOf of class String) must be invoked with the numeric value as the argument. The following statement converts variable dd of type double to a string and assigns it to string variable ss. set ss = call String.valueOf using dd In this example, the two numeric variables of type double: dincrease and dsalary, are formatted with the same pattern, which allows only two decimal digits (after the decimal point). The resulting numeric value is normally rounded to the specified decimal digits. Note Formatting includes an implied conversion of the noninteger numeric value to a string. This string data can be shown in a text field in the relevant container. object object object object begin create On the CD The complete KJP code that implements class Csalarygui is stored in the file Csalarygui.kpl. The corresponding Java implementation is stored in the file Csalarygui.java. Class Sal_listener implements the behavior of the listener object, which responds to the buttons. Part of the code in this class calculates the salary increase and updates the salary. The KJP code that implements this class follows. import all javax.swing import all java.awt.event On the CD Sal_listener.kpl. Sal_listener.java. When the program executes, the user directly interacts with the GUI presented. The data entered by the user is: "Chris D. Hunt" for attribute name, 45 for age, and 36748.50 for salary. The final data, after the program computes the salary increase and updates the salary, is shown in Figure 14.8. 14.5 Applets 14.5 Applets In addition to console and graphical applications, Java and KJP support applets. These are not standalone programs, because they require a Web browser to run. The code of the compiled class for an applet is placed in an HTML file with the appropriate tags. When a user uses his Web browser to start an applet, the compiled classes of the applet in the HTML file are downloaded from the server and execute. Suppose the class for an applet is named Akjplogo, the appropriate tags in the HTML file with the compiled class are as follows: <applet code = "Akjplogo.class" width=300 height=400> </applet> An applet normally includes graphical components in addition to any computation that may appear in a program. A Web browser displays the complete Web page, including the GUI for the applet. A small and complete HTML file with an applet embedded in it is shown next. <HTML> <HEAD> <TITLE> The KJP Applet </TITLE> </HEAD> <BODY BGCOLOR=blue TEXT=white> This is a simple applet showing the KJP logo. Any text included here in the HTML document. <CENTER> <H1> The KJP Applet </H1> <P> <APPLET CODE="Akjplogo.class" WIDTH=250 HEIGHT=150> </APPLET> </CENTER> </BODY> </HTML> There are various aspects of an applet to consider when defining the corresponding class, and that differentiates it from a conventional class. In an applet, the class definition must inherit class JApplet from the Swing library, or the Applet class from the AWT library. As mentioned before, applets are not standalone programs, so function main is not used. Instead, function init is included. A frame for a window is not defined because the applet automatically constructs a window. The size of the applet window is set in the HTML file. The Web browser makes the applet visible. Class Akjplogo defines an applet that displays the KJP logo. It defines three graphical components that are labels, in a similar manner to class Kjplogo. The KJP code with the implementation of the applet class Akjplogo is presented as follows. import all javax.swing // Library for graphics import all java.awt description This applet creates and displays a frame window with an image and a text label. */ class Akjplogo inherits JApplet is public description This is the main function of the application. */ function init is objects object cpane of class Container 14.5 Applets On the CD The KJP code with the implementation for class Akjplogo is stored in the file kpl. The Java implementation is stored in the file Akjplogo.java. Akjplogo. To execute the applet, a Web browser is used to run the applet class. To test the applet the appletviewer utility can be used. When the applet class Akjplogo executes with the appletviewer, the GUI shown in Figure 14.9 appears on the screen. The KJP code with the implementation of class Psalarygui is stored in the file Psalarygui.kpl, and the Java implementation in the file Psalarygui.java. When the program that consists of classes Psalarygui and Sal_listener executes, the window shown is similar to the program discussed in Section 14.4.5. Figure 14.10 shows the window for class Psalarygui. startang = 0 finalang = 45 ... call drawArc of graph_obj using x, y, width, height, startang, finalang Other drawing functions defined in class Graphics are listed in Table 14.2. Table 14.2: Common drawing functions in class Graphics drawOval draw2DRect drawPolygon drawRoundRect fillArc fillOval fillPolygon fillRect fillRoundRect fill3Drect "Drawing example" set cpane = call getContentPane of dframe create mdrawing of class MydrawE create quitbutt of class JButton using "Quit" create bordermanager of class BorderLayout call setLayout of cpane using bordermanager create butthandler of class Bquithandler call add of cpane using mdrawing, BorderLayout.CENTER call add of cpane using quitbutt, BorderLayout.SOUTH // register the listener object with the // button object call addActionListener of quitbutt using butthandler call setSize of dframe using WIDTH, HEIGHT call setVisible of dframe using true endfun main endclass DrawExample Class MydrawE inherits class JComponent, and the relevant function is paint. This function draws 15 circles of different sizes and at different locations. The KJP code for class MydrawE is listed as follows. import all java.awt import all javax.swing description This class draws several ovals. */ class MydrawE inherits JComponent is public description Paint where the actual drawings are. */ function paint parameters object gobj of class Graphics is constants integer TIMES = 15 // number of circles variables // position in drawing area integer x integer y // width and height integer w integer h integer j // loop counter begin set x = 50 set y = 20 set w = 170 set h = 170 set j = 0 for j = 0 to TIMES - 1 do // draw a circle call drawOval of gobj using x, y, w, h add 5 to x add 5 to y subtract 5 from w subtract 5 from h endfor endfun paint endclass MydrawE Figure 14.12 shows the top part of the frame that contains the drawing area with several circles of different sizes and the bottom part of the frame that contains a single button for exiting the program when the user clicks it. The KJP code that implement classes DrawExample and MydrawE are stored in the files DrawExample.kpl and DrawExample.java and Another way to organize the program is to define a single class that inherits class JFrame and include a constructor, function main, and function paint. This is a single-class application. 14.8 Summary 14.8 Summary For graphical applications, KJP and Java make extensive use of the Java packages AWT and Swing. These packages have a large number of predefined component and container classes for graphical user interfaces. The purpose of a graphical user interface is to give the user a clear and attractive representation of relevant data, guide the user in the operation of the application, and facilitate his interaction with the program, and also provide some level of checking and verification of the input data. A window is defined as a frame, which is the largest type of container. Graphical components and smaller containers are added to a frame in various manners, depending on the layout manager. Components and containers cannot be directly added to a frame; the content pane of the frame has to be used to add the graphical elements. Typical graphical elements are labels, buttons, text fields, and drawing areas. Types of containers are frames and panels. Various components are defined with listener objects that respond to the user in different ways. Buttons and text fields are components that generate events when the user clicks a button. These components can have object listeners attached. Listener objects handle the events that are generated by buttons and/or text fields. This is why the programs with graphical user interfaces (GUIs) are also called event-driven applications. More detailed documentation of the various classes in the AWT and Swing packages for constructing graphical applications can be found on the Sun Microsystems Web pages. The following Web page has links to the various documentation pages for the Java packages as well as pages for tutorials. 07:21:50 frame AWT Swing container content pane component listener pixel layout manager border grid flow card action event picture label text field applet panel drawing coordinate system origin 07:21:50 14.10 Exercises 14.10 Exercises 1. Design and implement a program that carries out conversion from inches to centimeters and from centimeters to inches. The program must include a GUI for the user to select which conversion will be calculated, and then the user inputs data and gets the result on the frame. 2. Modify the salary problem with GUI, presented in this chapter. The calculations of the salary increase and updating the salary should be done in class Csalarygui, instead of in class Sal_listener. 3. Redesign the GUI for the salary problem presented. Use several panels and different layout managers and colors for the buttons than the ones included in the problem presented in this chapter. 4. Design and implement a program with two or more classes that draws a toy house and a few trees. Use lines, rectangles, ovals, and arcs. 5. Design and implement a program that converts temperature from degrees Fahrenheit to Celsius and vice versa. The program should present the appropriate GUI with the selection using two buttons, one for each type of conversion. 6. Search the appropriate Web pages for additional graphical elements. Design and implement a program that uses a GUI that includes a combo box to solve the temperature conversion problem. 7. Search the appropriate Web pages for additional graphical elements. Design and implement a program that uses a GUI that includes a combo box to solve the problem for conversion from inches to centimeters and vice versa. 8. Design and implement a program that includes a GUI for inventory data. This consists of item code, description, cost, quantity in stock, and other data. Use labels, text fields, and buttons to calculate the total inventory value for each item. 9. Redesign the previous program and implement it using text areas. Search the Web for information on these graphical elements. 10. Search the appropriate Web pages for additional graphical elements. Design and implement a program that uses a GUI that includes a slider to solve the problem for conversion from inches to centimeters and vice versa. 11. Search the appropriate Web pages for additional graphical elements. Design and implement a program that uses a GUI that includes a slider to solve the temperature conversion problem. 07:21:51 07:21:51 description This program checks for an exception in the value of age. */ class TestException is public description This is the main function of the application. If the age is zero or negative, an exception is thrown and caught. */ function main is variables integer obj_age real increase real obj_salary string obj_name string lmessage // message for exception objects object emp_obj of class Employeec object lexecep_obj of class Exception begin display "Enter set increase = call sal_increase of emp_obj set obj_salary = get_salary() of emp_obj display "Employee name: ", obj_name display "increase: ", increase, " new salary: ", obj_salary endfun main endclass TestException In the program discussed, handling of the exception is carried by displaying information about the exception object, lexcep_obj, by invoking its method getMessage, and by executing the instructions that reread the value of age. All these statements appear in the catch block. If no exception occurs, the catch block does not execute, and the program proceeds normally. (2 von 3)09.11.2006 07:21:52 On the CD The KJP code that implements class TestException is stored in the file TestException.kpl, and the Java implementation is stored in the file TestException.java. When the user types a zero or negative value for the age, an exception is thrown. The exception is detected in the try block. To handle the exception, the statements in the catch block are executed. These statements display the message that explains and identifies the exception and allows the user to reenter the value for the age. When the program executes and the user enters a "bad" value for the age, the program stops, displays the message, and resumes to let the user reenter the value for the age. Figure 15.1 shows the values used to test this program. 15.3 Files 15.3 Files A disk file organizes data on a massive storage device such as a disk device. The main advantage of a disk file is that it provides permanent data storage; a second advantage is that it can support a large amount of data. A third advantage of a disk file is that the data can be interchangeable among several computers, depending on the type of storage device used. On the same computer, disk files can be used by one or more different programs. A disk file can be set up as the source of a data stream or as the destination of the data stream. In other words, the file can be associated with an input stream or with an output stream. Figure 15.2 illustrates the flow of data and the difference between an input and an output stream. A binary file is not human-readable. Its data is stored in the same way as represented in memory. Especially for numeric data, the representation in memory is just ones and zeroes. A compiled program is stored in a binary file. Binary files take less storage space and are more efficient to process. When reading or writing numeric data, there is no conversion from or to string format. 15.3 Files . . . try begin create myoutfile of class FileOutputStream using "mydata.txt" create myoutstream of class PrintWriter using myoutfile endtry The previous statements have connected the disk file to an output stream, myoutstream. This opening of the file could generate an exception if the file cannot be created. For this reason, the statements must appear in a try block. To handle the exception, a catch block must immediately follow. catch parameters object e of class FileNotFoundException begin display "Error creating file mydata.txt" terminate endcatch If the output file cannot be created, an exception is raised (thrown) and statements in the catch block display an error message related to the exception and terminate the program. The output stream created is used for all output statements in the program with methods print and println of object reference myoutstream. After the output file has been created, it can be used to write string data. The numeric data must first be converted to string. For example, to convert an integer value to a string value, function valueOf of the class String is invoked. The following statements declare a variable of type integer, int_val, declare a variable of type string, str_val, convert the value of the integer variable to a string, and assign the value to the string variable, str_val. variables integer int_val string str_val . . . set str_val = call String.valueOf(int_val) 15.3 Files real obj_salary string obj_name string str_age string str_inc string str_sal string file_name string lmessage // message for exception objects object emp_obj of class Employeec object myoutfile of class FileOutputStream object myoutstream of class PrintWriter // exception for negative age object lexecep_obj of class Exception begin set myoutstream = null display "Enter name for output file: " read file_name // open ouput file try begin create myoutfile of class FileOutputStream using file_name create myoutstream of class PrintWriter using myoutfile endtry catch parameters object e of class FileNotFoundException begin display "Error creating file mydata.txt" terminate endcatch set more_data = 'Y' while more_data equal 'Y' do display "Enter person 15.3 Files On the CD The KJP code that implements class Fileproc is stored in the file the Java code is stored in the file Fileproc.kpl, and Fileproc.java. The program, composed of class Fileproc and class Employeec, displays the following input/output when it executes with the data shown: ----jGRASP exec: java Fileproc Enter name for output file: mydata.txt Enter person name: James Bond Enter age: 54 Enter salary: 51800.75 Employee name: James Bond increase: 2331.034 new salary: 54131.785 More data? (Yy/Nn): y Enter person name: Jose M. Garrido Enter age: 48 Enter salary: 46767.50 Employee name: Jose M. Garrido increase: 2104.5376 new salary: 48872.04 More data? (Yy/Nn): y Enter person name: 15.3 Files John B. Hunt Enter age: 38 Enter salary: 39605.65 Employee name: John B. Hunt increase: 1980.2825 new salary: 41585.93 More data? (Yy/Nn): n ----jGRASP: operation complete. The output file, mytest.txt, was created and written by the program and has one data item per line with the following structure: James Bond 54 2331.034 54131.785 Jose M. Garrido 48 2104.5376 48872.04 John B. Hunt 38 1980.2825 41585.93 15.3 Files After opening the file for input, the program can read input streams from the file, line by line. The Java method readLine, which is defined in class BufferedReader, is invoked to read a line of text data. This data is assigned to a string variable. The statement to read a line of data must be placed in a try block because a reading error might occur. The exception is thrown by method readLine. One additional complication, compared to writing a text file, is that it is necessary to check whether the file still has data; otherwise, there would be an attempt to read data even if there is no more data in the file. When there is no more data in the file, the value of the text read is null. The following statements define a try block with a while loop, which repeatedly reads lines of text from the text file. try begin // Read text line from input file set indata = call readLine of myinfile while indata not equal null do // get name set obj_name = indata . . . // read next line set indata = call readLine of myinfile endwhile endtry The first statement in the try block reads a text line from the file. All subsequent reading is placed in the while loop. Because the text file can only store string values, conversion is needed for numeric variables. For example, obj_salary and increase are variables of type double, so the string value read from the text file has to be converted to type double. The following statements read the text line (a string) from the file, and then convert the string value to a value of type double with method Double.parseDouble. // get salary set indata = call readLine of myinfile set obj_salary = call Double.parseDouble using indata // get increase set indata = call readLine of myinfile set increase = call Double.parseDouble using indata Method Integer.parseInt would be invoked if conversion were needed for an integer variable. 15.3 Files 15.3 Files On the CD The KJP code with the implementation of class Rfileproc is stored in the file Rfileproc. kpl. The corresponding Java code is stored in the file Rfileproc.java. When the program executes, it reads data from the text file "mydata.txt." The program gets the values for the individual data items (name, age, salary, and increase) and computes the total salary and increase. The following listing is the one displayed on the screen. ----jGRASP exec: java Rfileproc Enter name for input file: mydata.txt Employee name: James Bond age: 54 increase: 54131.785 salary: 2331.034 Employee name: Jose M. Garrido age: 48 increase: 48872.04 salary: 2104.5376 Employee name: John B. Hunt age: 38 increase: 41585.93 salary: 1980.2825 -----------------------------------Total salary: 6415.8541000000005 Total increase: 144589.755 ----jGRASP: operation complete. 15.3 Files from the text file. The following text file has three lines, each with various values, some string values and some numeric values. James_Bond 54 2331.034 54131.785 Jose_M._Garrido 48 2104.5376 48872.04 John_B._Hunt 38 1980.2825 41585.93 The Java class StringTokenizer facilitates separating the individual strings from a text line. The following statements declare and create an object of class StringTokenizer, read a line from the text file, and get two string variables, var1 and var2, from the line. // declare object ref for tokenizer object tokenizer of class StringTokenizer // // read line from text file set line = call readLine of input_file // // create tokenizer object create tokenizer of class StringTokenizer using line // // get a string variable from line set var1 = call nextToken of tokenizer // // get another string variable from line set var2 = call nextToken of tokenizer To get the number of substrings remaining on a line, the Java method countTokens can be invoked with the tokenizer object. This function returns a value of type integer. A similar function, hasMoreTokens, returns true if there are substrings on the line; otherwise, it returns false. Class Lfileproc is similar to class Rfileproc, but it reads a line from the text file and separates the individual string variables for name, age, increase, and salary. On the CD [1]In The KJP code that implements class Lfileproc is stored in the file The Java code is stored in the file Lfileproc.java. Lfileproc.kpl. 15.4 Summary 15.4 Summary This chapter explains how to detect and handle exceptions. These errors indicate abnormal conditions during the execution of the program. An exception is detected in a try block, which encloses a sequence of statements that might throw an exception. The exception is handled in a catch block, which encloses the sequence of statements that implement some action in response to the exception. The simplest way to handle an exception is to display information about the exception and terminate the program. An I/O stream is a sequence of bytes in the input direction or in the output direction, which is treated as a source of data or a destination of data. I/O streams are normally connected with files. The two general types of files are text and binary files. Only text files are explained. Most of the statements for opening, reading, and writing files throw exceptions. Therefore, these statements must be placed in a try block. The input and output with text files are carried out to or from a text line, which is a string. If the data is numeric, then conversion to or from the appropriate numeric type is necessary. 07:21:53 exception detection exception handling checked exception unchecked exception try block catch block throw exception disk storage device type conversion input stream output stream text file binary file open read line write line 07:21:53 15.6 Exercises 15.6 Exercises 1. Explain the purpose of using exceptions in any program. If a program can be implemented without exceptions, what are the trade-offs? 2. Explain the differences between throwing an exception and catching an exception. Give examples. 3. What is the difference between detecting an exception and throwing an exception? Explain and give examples. Why do most Java classes for input/output throw exceptions? 4. Redesign and reimplement class Fileproc by adding exception handling for an empty name and age less than 18. 5. Redesign and reimplement class Fileproc. The new class must declare and create an array of objects of class Employeec and compute the lowest, highest, and average salary. 6. Design and implement a program with at least two classes that stores the inventory parts for a warehouse. Each inventory part has the following attributes: description, unit code, number of items in stock, and the unit cost. The program should store the data in a text file. The program should also compute the total investment per item. 7. Design and implement a program with at least two classes that reads the inventory data from the text file written by the program in the previous exercise. The program should display the individual data on each inventory item, and print the total investment and revenue. 8. Redesign and reimplement the program in the previous exercise by adding exception handling for a negative number of parts in stock, a zero or negative unit cost, and negative unit price. 9. Redesign and reimplement the program in the previous exercise by adding exception handling for a unit price equal to or less than the unit cost. 10. Design and implement a GUI for inventory data in the inventory program in Exercise 6. 07:21:54 07:21:54 07:21:54 The base case in this recursive definition is the value of 1 for the function if the argument has value zero, that is yn = 1 for n = 0. The recursive case is yn = y yn-1, if the value of the argument is greater than zero. 2 23 2expon(2, 3) 23 2 22 2expon(2, 2) 22 2 21 2expon(2, 1) 21 2 20 2expon(2, 0) 20 // base case if n == 0 then set result = 1.0 else // recursive case if n greater than 0 then set result = y * expon(y, n-1) display "y = ", y, " n = ", n, " expon ", result else // exceptional case display "Negative power" set result = 1.0 endif endif return result endfun expon On the CD The KJP code that implements class Rectest is stored in the file Java implementation is stored in the file Rectest.kpl. The Rectest.java. When the program implemented in class Rectest executes, with a value 3.0 for y and value 4 for n, the intermediate and final results are shown as follows: ----jGRASP exec: java Rectest Enter value for n: 4 type value for y: 3.0 expon 3.0 power 4 expon 3.0 power 3 expon 3.0 power 2 expon 3.0 power 1 expon 3.0 power 0 y = 3.0 n = 1 expon 3.0 y = 3.0 n = 2 expon 9.0 y = 3.0 n = 3 expon 27.0 y = 3.0 n = 4 expon 81.0 Expon 3.0 power 4 is 81.0 ----jGRASP: operation complete. When analyzing the intermediate results for the computation of the recursive function expon, it is clear those successive calls to the function continue until it reaches the base case. After this simple calculation of the base, the function starts calculating the exponentiation of y with power 1, 2, 3, and then 4. There are actually two phases in the calculation using a recursive function: 1. The recursive calls up to the base case. This represents the sequence of calls to the function; it is known as the winding phase. 2. The unwinding phase returns the values from the base case to each of the previous calls. If the main method is the only method involved in processing, there is only one frame in the stack with storage for all the variables, locals and constants. If method main invokes another method, A, then the stack grows only by one frame. After the method A completes execution, the memory block allocated to its frame is released and returned to the system. 16.5 Summary 16.5 Summary A recursive method definition contains one or more calls to the function being defined. In many cases, the recursive method is very powerful and compact in defining the solution to complex problems. The main disadvantages are that it demands a relatively large amount of memory and time to build stack. As there is a choice between using iterative and recursive algorithms, so programmers must evaluate the individual situation and make a good decision for their use. 07:21:56 base case recursive case terminating condition recursive solution iterative solution winding phase unwinding phase stack LIFO push operation pop operation frame activation record runtime stack 07:21:56 16.7 Exercises 16.7 Exercises 1. Write a recursive method to print the square of n natural numbers. 2. Write a recursive method to print n natural numbers that are even. 3. Write a recursive method to print all letters in a string in reverse order, that is, if the string is "Java," it will print "avaJ." 4. Write a recursive method that will reverse a given string, that is, it will convert "hello" to "olleh." 5. Write a recursive method that will compute the factorial of n natural numbers. 6. A palindrome is a string that does not change when it is reversed. For example: "madam," "radar," and so on. Write a recursive method that checks whether a given string is a palindrome. 7. Design and implement a program that includes a recursive method for a linear search in an array of integer values. For a review on the principles of linear searches, see Section 9.4.3.1. 8. Design and implement a program that includes a recursive method for a binary search in an array of integer values. For a review on the principles of binary searches, see Section 9.4.3.2. 07:21:56 07:21:57 07:21:57 07:21:57 The advantage of the second technique is that there is no need to inherit class Thread. To create a thread and start its execution, the following portion of code is included in the main class of an application program: objects object ms of class MyThreadb object myth of class Thread (1 von 2)09.11.2006 07:21:58 ... begin ... create ms of class MyThreadb create myth of class Thread using ms call start of myth 17.5 Summary 17.5 Summary This chapter presented a very simple introduction to threads and basic principles of thread programming. The thread supports concurrency inside one program. It is a necessary mechanism for event-driven programming and network programming. 07:21:58 multithreading processes tasks control sequence preempt animation lightweight process concurrent execution 07:21:59 17.7 Exercises 17.7 Exercises 1. Describe and explain an application with multiple threads. 2. Why are threads important? 3. Explain and give an example of concurrency. 4. What are the similarities and differences between processes and threads? 5. Investigate why is the use of threads some times necessary in event-driven programming. 07:21:59 Appendix A Appendix A: A.1 Introduction This appendix introduces and explains the use of the KJP translator and the jGRASP software development environment. There are two general procedures to follow for developing programs and using the KJP translator. These procedures are: 1. Working in a DOS window 2. Working with an integrated development environment (IDE), such as jGRASP This appendix first explains how to set up and use the KJP translator in a DOS window. The latest information, sample files, and version of the KJP translator is available from the following Web page: In the second part of this appendix, an explanation is presented on how to configure and use the jGRASP environment, which is available from Auburn University. The Web page is: The KJP translator consists of a program that provides the following functions: 1. Syntax checking of a source program in KJP; a list of errors is displayed and written to an error file with the same name as the source program 2. Conversion of the source program in KJP to an equivalent program in Java 07:21:59 These files can be copied from the CD-ROM or downloaded from the KJP Web page. Most versions of Windows have the Windows Explorer located in the Accessories system folder. To start Windows Explorer, from the Windows Desktop, click the Start button, select Programs, select Accessories, and then select Windows Explorer. Figure A.1 shows the Windows Explorer window. To use Windows Explorer to create a new directory (or folder), first position the mouse on the home (root) directory; this could be the drive A or drive C. Next, click the File menu, select New, and then select Folder. Type the name of the new folder in the small box that appears. 07:22:00 This file has the same name as the source program but with an err extension; for example, Cat.err. 7. The second file contains the Java program; the file has the same name but with the java extension. For example, if your source program is Cat.kpl, then the Java program created is Cat.java. 8. Use the Java compiler to compile the Java program (e.g. Cat.java) generated by the KJP translator. 9. Use the Java virtual machine (JVM) to execute the compiled program. When starting execution, enter the input data to the program, if needed. 10. Return to the Windows desktop by typing exit while in DOS. In step 2 (DOS window), to change the directory to the one where you have the source programs in KJP, type the following command: cd\, and then press the Enter key. If the directory with your source programs is called my_files, on the next line type cd my_files and then press the Enter key; this changes to the directory called my_files. To get a list of the files in the current directory, type dir and then press Enter. To start the DOS editor, type edit at the command prompt then press the Enter key. After the editor starts and if you are typing a new source program, start typing line by line; press the Enter key at the end of every line. When you have completed entering the text, click on the File menu and select the Save as option. Type the name of the Tarea.kpl. file (program name). It must start with a capital letter, and have a .kpl extension. For example, Figure A.2 shows the DOS editor with some text lines already entered. To exit the DOS editor, click the File menu, and then select Exit. To compile (step 5 above) a source program in KJP called Salary. press the Enter key. After a few seconds, you will see a message on the screen. In this case, File kpl, no syntax errors, lines processed: 45. The window in Figure A.3 shows these commands. The KJP translator produces two new files with the same name as the original source program in KJP. The first file is the corresponding Java program. The other file created contains the syntax errors that the KJP compiler detected. The name of this file is the same as the source file but with the err extension. For example, after compiling the The error file generated by the KJP compiler shows all the syntax errors detected in the source program. These are indicated with the line number and column number where they appear. If there are no errors detected, then the last line of this text file includes the message no syntax errors. The total number of lines read is also shown In summary, after invoking the KJP compiler, the new files that appear on the current directory are Salary. Salary.java, and Salary.err. You can check this with the dir command in DOS. You can also kpl, check the date with Windows Explorer. Salary.java, type javac Salary.java in DOS. After To invoke the Java compiler and compile the file a few seconds, the Java compiler completes and displays error messages, if any. Take note of the error messages and go back to the DOS editor to correct them, by changing the source program in KJP. If there are no error messages, run the program by invoking the Java Virtual Machine (JVM), and then type java Salary at the DOS prompt. Notice that you don't need the file extension. After a few seconds, your program starts execution. 2. The jGRASP main window appears on the screen, as shown in Figure A.4. On the left pane, select the folder where the KJP program files are located. 3. Click the File menu, and select Open. Figure A.7 shows the Open File window. Appendix B Appendix B: B.1 About the CD-ROM CD Content The CD-ROM included with this book contains all the files that are used as source programs in KJP and in Java. It also includes the program file necessary for using the KJP translator and the binary file for console input/output. 07:22:01 B.2 CD Folders B.2 CD Folders The CD-ROM contains the following folders: KJP_source: This folder contains all of the KJP sample programs from within the book. These files are set up by chapter. These files are all in text format that can be read by most text editors. Java_source: This folder contains all of the Java files that correspond to the examples presented in the book. These files are all in text format that can be read by most text editors. KJP_translator: This folder includes the KJP translator program file, which is an executable file, and the Conio class. 07:22:02 At least 32 MB of RAM 07:22:02 B.4 Installation B.4 Installation To use this CD-ROM, you just need to make sure that your system matches at least the minimum system requirements. Detailed instructions for the installation are explained in Appendix A of this book. 07:22:02 Index Index A Abnormal condition, 304 Abstract description, 25 Abstract methods, 240 Abstraction, 27, 35 Access mode, 34 Access private, 63 public, 63 Accumulator, 155 Action, 272 Activation record, 332 Aggregation, 213 Algorithm, 18, 43, 46, 92, 95, 123, 155, 177 Alternation, 120 Analysis phase, 21 Analysis, 21 Applets, 287 Application software, 8 Arguments, 73, 76 Arithmetic, 107 Array, 167, 252 declaration, 169 element, 170 name, 170 of objects, 171 Assignment, 103, 197 Associations, 212 Attributes, 29, 45 Average, 173 AWT, 261, 263 07:22:03 Index_B Index B Base cases, 328 Base class, 222 Binary, 176 Border, 267 Box, 267 Buttons, 261, 272 Byte, 4 07:22:03 Index_C Index C Call, 67, 72 Card, 267 Case statement, 139140 CD-ROM, 5 Character, 189, 192 Characteristics, 222 Class, 2728, 32, 40, 4445, 60, 107, 177, 222, 239 abstract, 239 base, 236, 241 concrete, 239, 254 derived, 214, 222, 241 extended, 223 general, 223 hierarchy, 222 parent, 223 relationship, 223 relationships, 212 specialized, 223 Classes, 50 Coding, 22 Collaboration diagram, 31 Collections, 27, 32 Color, 264 Comparing, 196 Compiling. 10, 83 Components, 2, 28, 262, 267 Composition, 213 Computer architecture, 1 Computer, 1 Concatenation, 195 Concurrency, 335 Condition, 120, 122, 138, 146147 Console, 105 Constants, 47, 190 Constructor, 77 Containers, 264, 267 Contiguous, 167 Conversion, 323 Index_C Index_D Index D Data, 23, 42, 48, 50, 6566 declarations, 42, 49, 169 definitions, 43 descriptions, 8 items, 46 local, 65 structure, 167 transfer, 70 types, 93 Declarations, 42, 45, 52, 60 Decomposition, 21, 40, 44 Delegations, 35 Deployment, 21 Derived, 222 Design refinement, 22 Design structure, 91, 101, 120, 146 Design, 21 Detailed design, 22 Development process, 39 Diagrams, 210 Dialog boxes, 261 Dimension, 183 Disk file, 308 Disks, 4 Drawing, 295 Dynamic model, 215 07:22:04 Index_E Index E Electronic, 2 Elements, 175, 254 Encapsulation, 33, 64 Entities, 26 Events, 217, 272, 277 Exception, 303, 323 checked, 304 detecting, 303 generate, 305 handling, 303 occurrence, 307 throw, 316 unchecked, 304 Expressions, 107, 122 External view, 34 07:22:05 Index_F Index F Field, 278 Files, 308 binary, 309 input, 316 output, 310 text, 309 Flow, 267 Flowchart, 97, 108, 125 For loop, 160 Formatting, 280 Frame, 262 Functions, 50, 68 accessor, 69 call, 73 mutator, 69 value-returning, 69 void, 69 with parameters, 69 07:22:05 Index_G Index G Generalization, 214, 223 Grid, 267, 281 Gridbag, 267 GUI, 261 07:22:05 Index_H Index H HTML, 287 Hypertext, 7 07:22:06 Index_I Index I I/O streams, 303, 309, 323 I/O, 2 Icons, 266 Identifiers, 45 If-then-else, 120 Immutable, 191 Implementation, 21, 35, 239 Import, 263 Incremental development, 23 Index, 167, 170, 184, 192 Information hiding, 34, 36, 64 Inheritance, 213214, 221223, 240 Inherited features, 222 Initial value, 92 Initializer, 77, 79, 224 default, 78 Input, 2, 105, 278 Input-output, 100 Instructions, 3, 8, 66 Interface, 239, 246, 251, 259, 261262, 277 Internal view, 34 Internet, 6 Iterations, 147, 327 Iterative approach, 22 07:22:06 Index_J Index J Java, 11, 57 07:22:06 Index_K Index K Keyboard, 5 KJP translator, 12 KJP, 10, 57 07:22:07 Index_L Index L Labels, 265 LAN, 6 Languages, 44 Layout, 267, 281 Life cycle, 19 Listener, 272, 277 Loop-until, 156 07:22:07 Index_M Index M Maximum, 172 Mechanism, 221 Menus, 261 Message, 30, 67, 217 Method, 50, 201 invocation, 31, 67 overriding, 234 Minimum, 172, 181 Model, 25, 132 Modeling, 27 Modules, 3941 Mouse click, 262, 272 07:22:08 Index_N Index N Notation, 99 Numeric, 93 07:22:08 Index_O Index O Object, 26, 29, 40, 52, 67, 94, 169, 184 behavior, 28, 36, 42 interaction, 30, 40, 273 properties, 29, 36 receiver, 67 reference, 43, 49, 94, 250 sender, 67 structure, 29 Object-oriented, 26 Operating system, 2 Operations, 29, 42 Operators, 138, 189, 191 Output, 2, 13, 98, 100, 105 07:22:08 Index_P Index P Package, 41, 263 Pane, 267, 290 Panels, 262, 290 Parameters, 74, 79, 181 Persistence, 50 Pictures, 266 Pixels, 271 Point, 262 Polymorphism, 239 Position, 192 Private, 34, 45 attributes, 45 operations, 45 Problem solving, 18 Problems, 1 Process, 19, 21, 335 execution, 336 lightweight, 336 Processing, 2 Program, 40 behavior, 40 dynamic view, 40 static view, 40 Programming language, 9, 19 Programming, 239 generic, 239 Programs, 2, 7 Protection, 33 Pseudo-code, 96, 120 Public, 3435, 45, 224 operations, 45 07:22:09 Index_R Index R RAM, 23 Real-world problem, 26 Rearranging, 179 Recursion, 327 Recursive cases, 328 Recursive, 327, 333 Referencing, 184 Register, 279 Relationships, 32, 213 Repeatedly, 327 Repetition, 100, 145 Responsibilities, 35 Runtime, 333 07:22:09 Index_S Index S Scope, 50 Screen, 5 Search, 198 Searching, 175 Selection, 100, 120 Semigraphical, 207 Sequence, 100, 190 Sequential, 175 Signal, 272 Size, 264 Software, 1, 19 components, 2 development process, 17 engineering, 19 life cycle, 20 maintenance, 20 Solution, 108 Sorted, 177 Sorting, 179 Source program, 3 Specialization, 234 Specifications, 239 Spiral model, 22 Stack, 331 State diagram, 217 transition, 217 Statement, 146 Statements, 4445, 9192, 103, 106, 119 Static model, 210 Static, 86, 167 Storage, 2 Strings, 93, 189, 196 Subclass, 222, 224, 243, 250, 259 Subproblem, 40 Substring, 193 Subtypes, 251, 254, 259 Index_S Index_T Index T Tasks, 335 Terminating, 328 Testing, 21 Text, 48, 93, 272 Thread, 336 definition, 337 implementation, 338 Title, 264 Transformation, 18 Translation, 10, 44 Type conversion, 318 Types, 48 07:22:10 Index_U Index U UML, 25, 31, 35, 207 actors, 208 diagrams, 207 state, 217 stereotype, 208209 use case, 208 User interaction, 261 07:22:11 Index_V Index V Values, 47 Variables, 43, 47 07:22:11 Index_W Index W WAN, 6 Waterfall model, 20 Web browser, 289 Web page, 287 While loop, 145 Window, 264, 281, 288 07:22:11 List of Figures List of Figures Chapter 1: Computer Systems Figure 1.1: Basic hardware structure of a computer system. Figure 1.2: Basic structure of a local area network. Figure 1.3: A LAN connected to the Internet. Figure 1.4: General structure of a program. Figure 1.5: Compiling a Java source program. Figure 1.6: Executing a Java program. Figure 1.7: Conversion from pseudo-code to Java. Figure 1.8: An executing program. List of Figures Chapter 7: Selection Figure 7.1: Flowchart segment general selection structure. Figure 7.2: Example of selection structure. Figure 7.3: Application of the selection structure. Figure 7.4: Execution of class Comp_salary_m for the salary problem. Figure 7.5: High-level flowchart for the quadratic equation. Figure 7.6: Execution of class Quadra for the quadratic equation. (2 von 5)09.11.2006 07:22:12 List of Figures Chapter 8: Repetition Figure 8.1: A flowchart segment with the while-loop construct. Figure 8.2: Salary problem with repetition. Figure 8.3: Flowchart segment for the loop-until construct. Figure 8.4: Execution of program with class Sum. Figure 8.5: Execution of program with class Max. Chapter 9: Arrays Figure 9.1: An array named temp with 10 elements. List of Figures Appendix A Figure A.1: Windows Explorer. Figure A.2: The DOS editor. Figure A.3: The DOS window with commands. Figure A.4: The jGRASP main window. Figure A.5: User Compiler Environment. Figure A.6: The jGRASP Global Settings window. List of Figures List of Tables List of Tables Chapter 14: Basic Graphical User Interfaces Table 14.1: Common colors in a frame Table 14.2: Common drawing functions in class Graphics 07:22:12 CD Content CD Content Following are select files from this book's Companion CD-ROM. These files are copyright protected by the publisher, author, and/or other third parties. Unauthorized use, reproduction, or distribution is strictly prohibited. For more information about this content see 'About the CD-ROM'. File All CD Content Description Object-Oriented Programming: From Problem Solving to Java 07:22:13 Size 77,688
https://www.scribd.com/document/324442777/Jose-M-Garrido-Object-Oriented-Programming-Fro-BookSee-org
CC-MAIN-2019-35
refinedweb
34,426
55.54
Equalling a just declared matrix to a submatrix does not give a newly allocated matrix (modifying the new matrix modifies the old matrix). I mean: // it just creates a random (gaussian) matrix LaGenMatDouble A = StatUtil::RandnMatrix(2,3,0.0,1.0); LaGenMatDouble B = A(LaIndex(0,1),LaIndex(1,2)); cout << "A is" << endl << A << "B is" << endl << B; B(0,0) = 10; cout << "A is" << endl << A << "B is" << endl << B; A is -0.531466 -1.82688 0.302208 0.849202 -0.983648 -0.00441152 B is -1.82688 0.302208 -0.983648 -0.00441152 A is -0.531466 10 0.302208 0.849202 -0.983648 -0.00441152 B is 10 0.302208 -0.983648 -0.00441152 I don't know if that's the behavior you were looking for, but it's not what I expected. Regards, Manuel A. Vázquez (mani001@terra.es) Christian Stimming 2007-07-09 Logged In: YES user_id=531034 Originator: NO Thanks for reporting this issue. As you can see in the example program below, the unwanted reference copy is created only when writing LaGenMatDouble B = A(LaIndex,LaIndex); i.e. only when assigning directly at declaration. It does not appear when assigning later, C=A(LaIndex,LaIndex), where a deep copy as expected is created. I'm actually a bit at a loss as to why this happens - the constructor and operator= of that class clearly will create a deep copy . Maybe I can think of a solution, but so far I don't have an idea. For the record, providing full example programs for such bugs would make bugfixing much easier. // Compile as follows: gcc bla.cpp -o bla -I/usr/include/lapackpp -llapackpp using namespace std; int main(int argc, char* argv[]){ // Just an example matrix LaGenMatDouble A(2,3); A(0,0)=0; A(0,1)=1; A(0,2)=2; A(1,0)=3; A(1,1)=4; A(1,2)=5; A.debug(1); LaGenMatDouble B = A(LaIndex(0,1),LaIndex(1,2)); // huh? Is a reference to A LaGenMatDouble C; C = A(LaIndex(0,1),LaIndex(1,2)); // correctly creates a copy of A cout << "A is" << endl << A << "B is" << endl << B << "C is" << endl << C; B(0,0) = 10; cout << "A is" << endl << A << "B is" << endl << B << "C is" << endl << C; return 0; } Christian Stimming 2007-07-14 Logged In: YES user_id=531034 Originator: NO Thanks for reporting this issue. It turns out this is caused by an unexpected optimization of C++, and this cannot easily be fixed in the current lapackpp structure. A workaround is explained in the updated documentation here ; basically, you must write LaGenMatDouble B; B = A(LaIndex(0,1),LaIndex(1,2)); All other possibilities will not work with the current lapackpp matrix classes. Sorry for that. This bug will stay open until someone can come up with a permanent solution. Anonymous
http://sourceforge.net/p/lapackpp/bugs/18/
CC-MAIN-2015-35
refinedweb
483
63.7
Your browser does not seem to support JavaScript. As a result, your viewing experience will be diminished, and you have been placed in read-only mode. Please download a browser that supports JavaScript, or enable it if it's disabled (i.e. NoScript). Thanks to the help of @m_adam I have the simplest code that allows you to get the MoGraph Selection data from a MoGraph Generator with a MoGraph Selection. In the attached project, I have a Matrix Object with a MoGraph Selection Tag and the Python effector that prints the selection data to the console. This implementation requires you drag the Selection Tag into the "Selection" link (Effector Tab->Selection). Because the method is based on the Tag Name, make sure the Selection Tag has a nice unique name to avoid any confusion. The code is fully Commented for your convenience (or inconvenience for that matter)... import c4d from c4d import gui from c4d.modules import mograph as mo def main(): moData = mo.GeGetMoData(op) #Get MoGraph Data moSelTagName = op[c4d.ID_MG_BASEEFFECTOR_SELECTION] #Get the MoGraph Selection Tag Name from the Effector's "Selection" Link # Retrieve the first tag attached to the generator (the Matrix) matching the name moSelTag = None # initialize the "moSelTag" Variable for tag in gen.GetTags(): # Go through All tags on the MoGraph Generator... # "gen" is a Global Variable holding the MoGraph Generator (e.g. the cloner object which executes the Python Effector) if not tag.IsInstanceOf(c4d.Tmgselection): # if the tag is NOT a MoGraph Selection, try the next tag continue # if the previous is FALSE, then the Tag is a MoGraph Selection if tag.GetName() == moSelTagName: # Does the Tag found above have the same name as the Linked Selection Tag? moSelTag = tag # If the above is true, then set the Variable to that Tag and Break the Original Loop to continue down break if moSelTag: # If after all of the above we have a valid tag in the Variable, then do the following: sel = mo.GeGetMoDataSelection(moSelTag) #Get the Mograph Selection from the Tag selData = sel.GetAll(moData.GetCount()) #Get the Data from the Mograph Selection print(selData) # Print the Data # Execute main() if __name__=='__main__': main() Get Mograph Selection data 01A.c4d
https://plugincafe.maxon.net/topic/14085/how-to-get-a-mograph-selection-using-a-python-effector
CC-MAIN-2022-27
refinedweb
369
53.92
Closed Bug 648979 (ccrework) Opened 11 years ago Closed 4 years ago Rework comm-central to build underneath mozilla-central Categories (MailNews Core :: Build Config, defect) Tracking (Not tracked) People (Reporter: standard8, Assigned: jcranmer) Details Attachments (4 files, 4 obsolete files) Since it was set up, the comm-central build system has served us well. However the primary issue we have with it is that it requires us to constantly port across build system changes from mozilla-central. If we can make direct use of the mozilla-central build system, then we don't need to copy it for the comm-central apps all the time. Therefore the proposal is that we move comm-central to be underneath mozilla-central (this does not mean that we will be inside mozilla-central). So the directory structure we have now is: /comm-central/mailnews /comm-central/mail /comm-central/mozilla/accessible /comm-central/mozilla/toolkit etc. where /mozilla/ is the directory where the hg clone of mozilla-central is held. Under the new system we'd have: /mozilla-central/accessible /mozilla-central/toolkit /mozilla-central/comm/mailnews /mozilla-central/comm/mail etc. We'd need mozilla-central's configure and a few other items to have some additional hooks so that we could still specify options for comm-central (e.g. building with ldap), however ted and khuey agreed that it'd be a reasonable addition to do. I have a first draft for this. I'm currently looking at getting the patches or repo published somewhere. I can now post the said patches. Some notes before I do that: - I currently assume that comm-central is in a sub-directory of mozilla called 'comm'. - I've written a script which does the main bulk of replacements that are necessary. It isn't optimised and the regexps could probably be better, but it works. - I've got an additional patch which starts getting things working - with both the script and the patch I can get Thunderbird building and running on my mac (in 64 bit mode only), and it also passes at least some of the xpcshell-tests. - There's much more work to do, including getting SeaMonkey and Lightning building & running. - We'll also need the hooks for configure.in options. So far the things I know that we'll need some kind of hooks for are: ** Running LDAP sub-configures and getting variables passed in. ** Getting MOZ_STATIC_MAIL_BUILD and MOZ_COMPOSER defined in the build system. ** Properly getting things like MOZ_MAIL_NEWS defined in the build system. (oh and the builds are currently without LDAP due to the sub-configures issues). This is the script to do all the replacements. cd into the comm-central directory and sh ./translatescript.sh This is the patch that is generated as a result of running the replacement script. This is the first round of manual changes. Note: to get everything to compile, I also add the following to the mozilla-central autoconf.mk.in: MOZ_STATIC_MAIL_BUILD = 1 MOZ_COMPOSER = 1. (In reply to comment #7) >. That's covered in the last point of comment 8. (In reply to comment #8) >?). Having review of the principles should be good, though I'm not sure if review on every single line is needed, and to some degree, even review-after-the-fact works nice if a project branch is so confined to a specific purpose and the actual changes should be easy to sort out. > That's covered in the last point of comment 8. This is comment 8, I guess you mean comment 2, actually ;-) Comment on attachment 526800 [details] Replacement script ># Replace '(/mail' with '(/comm/mail' in jar.mn files >find . -name 'jar.mn' -exec sed -i backup -E 's/(.*)\(\/mail(.*)/\1\(\/comm\/mail\2/' {} \; Merely looking at this script, shouldn't we do this step for suite, and similar steps for calendar? Probably, I just wasn't concentrating on getting them working at the time. Still hoping to set up a test repo for this, just working on fixing another bug first. Hm, sorry, I am new to this bug, and this discussion is interesting, but just a hair's width above my head. Does all this mean that if and when this bug gets FIXED, the mozilla-central client.py will (at least when the mozconfig says we're building the suite) pull all six of the mozilla-central, comm-central, chatzilla, venkman, LDAP SDK and DOMi repositories (like the comm-central client.py does now)? Or will there still be a comm-central client.py, which will (among other things) pull mozilla-central a directory level or so above itself? Undetermined. So far, it seems like we'll make m-c client.py do most of what c-c client.py does. Ted was -- in theory -- ok with that plan. But first we want to get this setup working before we delve to the client.py side. I've now created a repository where we can work on this and try and get things running correctly. As I think it would be useful to have some easy co-ordination on this, I've created an etherpad here: with notes on how to build, what work needs doing etc. Please keep up to date. I'm proposing that build config peers can land changes without review at this time. If non-peers wish to land, then please get a general once-over from a peer so that we can check things are heading in the right direction. Alias: ccrework Flags: in-testsuite- Version: unspecified → Trunk I've successfully built a version of Thunderbird that uses the m-c build system by doing the following things: 1. Introduce lots of symlinks everywhere, to avoid sed path changes. Basically: c-c/mozilla/comm -> c-c c-c/mozilla/mozilla -> c-c/mozilla c-c/mozilla/{mail,mailnews,chat} - c-c/* c-c/mozilla/editor/ui -> c-c/editor/ui 2. Fix paths in bridge/bridge.mozbuild, mail/app.mozbuild, and mail/configure.in 3. Flatten everything in mail/app.mozbuild 4. Disable mozbuild-migration checks in the m-c build system, as well as the xpccheck stuff 5. s/$(DIR_INSTALL)/$(INSTALL)/g in comm-central. 6. Added MOZDEPTH/MOZILLA_SRCDIR to mozilla-central/config/baseconfig.mk From the results of this, after bug 846540 lands, the following things would need to be done: 1. Change DIR_INSTALL to INSTALL in the c-c build system (this can be done before) 2. Find some way to make xpcshell and mozmill tests work again. For xpcshell, we may have to push on making a non-broken global manifest system (bug 844655 disavows fixing that as a goal right now). For mozmill, we at least need to integrate it into top-level make/mach, and make package-tests as well. 3. Fix mail/app.mozbuild and suite/app.mozbuild, as well as the respective configure.ins, to get paths right and eliminate the COMM_BUILD duality. We can probably eliminate bridge/bridge.mozbuild at that time too, but it's not a big deal. 4. Complete all pending mozbuild migration work. 5. Break out a sed script and rewrite all critical pseudo-absolute paths. 6. Change all the builders and release engineering scripts. I've done no testing other than make, make package-tests, and running thunderbird to see if it keels over dead so far, so it's quite possible we will have issues with things like l10n-repacks or packaging scripts. I'll let someone who knows that stuff better than I worry about those changes. Status update for people following along at home: My current patch-queue is capable of making TB (without Lightning) build under mozilla-central. The main patches that can be done before the move have been uploaded and awaiting review (basically, more moz.build migration and some makefile cleanup). The stuff that can't be done before the move are the massive path-rewriting, which is this: find -name Makefile.in | grep -v mozilla | grep -v ldap/sdks | xargs sed -e '/include/!s+$(topsrcdir)+$(topsrcdir)/comm+g' -i find -name Makefile.in | grep -v mozilla | grep -v ldap/sdks | xargs sed -e 's+$(topsrcdir)/comm/mozilla+$(topsrcdir)+g' -i find -name Makefile.in | grep -v mozilla | grep -v ldap/sdks | xargs sed -e '/config\/autoconf.mk/!s+$(DEPTH)/\([^$]\)+$(DEPTH)/comm/\1+g' -i find -name Makefile.in | grep -v mozilla | grep -v ldap/sdks | xargs sed -e 's+$(MOZDEPTH)+$(DEPTH)+g' -i find -name Makefile.in | grep -v mozilla | grep -v ldap/sdks | xargs sed -e 's+$(MOZILLA_SRCDIR)+$(topsrcdir)+g' -i find -name jar.mn | grep -v mozilla | grep -v ldap/sdks | xargs sed -e 's+(/+(/comm/+' -i find -name jar.mn | grep -v mozilla | grep -v ldap/sdks | xargs sed -e 's+(/comm/mozilla+(/mozilla+' -i find -name moz.build | grep -v mozilla | xargs sed -e 's+$(topsrcdir)+$(topsrcdir)/comm+g' -i Then there are several manual path changes to account for things not easily findable (like configure.in and bridge.mozbuild changes). The final step is to kill COMM_BUILD. As of right now, Thunderbird builds, but package-tests and l10n-check break, as do all of the comm-central specific test files. Any relative obj dirs, e.g. MOZ_OBJDIR=@TOPSRCDIR@/../opt/ or just /opt/, are broken for me. Folks on #maildev told me that this bug fixes it. Workaround: absolute paths work, but they are cumbersome when you have many trees. Severity: normal → blocker This is the final script I'll be using (minus applying any patches named temp-*.diff). Several of the steps are autogenerated by running commands instead of manually writing patches that will tend to get obsolete. I've separated out each step into different commits so that it's clear what all the changes have in common, but this does break pretty severely the rule that individual patches should work on their own. Assignee: nobody → Pidgeot18 Status: NEW → ASSIGNED Attachment #8376275 - Flags: review?(mbanner) This is the file named rewrite-paths.diff mentioned in the merge script. It contains the manual changes not covered by the automatic rewrite, as well as moving the bridge.mozbuild file to mailnews.mozbuild to eliminate a useless and potentially confusing top-level directory. Something else that could be done is to move the mork logic under mailnews/db, but since m-c already has a top-level db/ directory, I don't think it's quite so necessary for the merge work. Attachment #526800 - Attachment is obsolete: true Attachment #526803 - Attachment is obsolete: true Attachment #526805 - Attachment is obsolete: true Attachment #8376652 - Flags: review?(mbanner) This is the package-tests.diff file, which mostly contains manual fixes to get packaging to work properly, most of which cannot be applied prior to this bug because it breaks under the current build system. Attachment #8376653 - Flags: review?(mbanner) This is m-c-post.diff, the changes we need to mozilla-central to make this work. I'm not asking for review yet because I'm not sure whom to ask, and I also expect this code to be more likely to bitrot than the other files. Effectively, we need a dependency to make the pseudo-derecurse work--this is the default in m-c and will I believe eventually be the only supported mode; it was never ported to c-c because both glandium and I gave up trying to figure out why it wasn't working. The OS X universal build changes are ugly, but after discussing with Ted in #build, we came to the conclusion that adding yet-another-directory to the list was the way to go. In terms of testing: The Thunderbird code is tested by periodic pushes to Alder acting as a try server for this bug. This also confirms the buildability of Lightning for TB, although we don't run any Lightning tests on buildbot. I've manually built SeaMonkey on one of the attempted heads (after dropping inspector, venkman, and chatzilla in their appropriate places), and that worked, and I've built it on the latest change without the three extensions, and that worked as well. Instantbird doesn't build for me on Linux with comm-central, but it builds just as well on the merged repository, so I'll take that as a sign that it should work. The manual builds are done as regular ./mach builds only on Linux. My experience with build system work is that mailnews, calendar, and mail are all far nastier in stressing the build system than chat, im, and suite, so I feel safe in assuming that works-on-Linux for SM and IB means works-on-all-platforms. I'm not so confident that packaging works properly for SM and IB, but I assume that packaging issues are not quite so high a priority with both IB and SM's buildbots being down and they don't preclude people working on code locally. I'll be happy to work with people to fix build errors introduced by this change. I haven't tried Firefox on it yet, but I will be sure to do a real try run before getting review on m-c-post.diff and certainly before pushing anything to m-c. :-) Comment on attachment 8376654 [details] [diff] [review] m-c-post.diff I think you should ask gps for review on the m-c bit as he is the build system owner. Comment on attachment 8376654 [details] [diff] [review] m-c-post.diff Review of attachment 8376654 [details] [diff] [review]: ----------------------------------------------------------------- ::: Makefile.in @@ +294,5 @@ > ifdef ENABLE_CLANG_PLUGIN > js/src/export config/export: build/clang-plugin/export > endif > +ifdef MOZ_LDAP_XPCOM > +ldap/export: config/export This shouldn't be needed. The backend makes */export depend on config/export already. Comment on attachment 8376275 [details] merge-script.sh I've not tested it, but it looks fine. Attachment #8376275 - Flags: review?(standard8) → review+ Patches look good, though obviously we need to move forward with the discussions about when we can land this etc. This is an updated version of the m-c-post.diff patch taking into account glandium's prior comment. I'm also considering this review a chance to have m-c build system people weigh on the patches here. It passes both alder and try ( Attachment #8376654 - Attachment is obsolete: true Attachment #8383181 - Flags: review?(mh+mozilla) Attachment #8383181 - Flags: feedback?(gps) Status: ASSIGNED → RESOLVED Closed: 4 years ago Resolution: --- → FIXED So in what way is this fixed? This was fixed in Bug 1366607. Resolution: FIXED → DUPLICATE
https://bugzilla.mozilla.org/show_bug.cgi?id=648979
CC-MAIN-2022-21
refinedweb
2,427
65.22
Serverless Projects The AWS Toolkit for Eclipse includes a project creation wizard that you can use to quickly configure and create serverless projects that deploy on AWS CloudFormation and run Lambda functions in response to RESTful web requests. Creating a Serverless Project To create a serverless project Select the AWS icon in the toolbar, and choose New AWS serverless project... from the menu that appears. Enter a Project name. Enter a Package namespace for your project. This will be used as the prefix for the source namespaces created for your project. Choose either to Select a blueprint or to Select a serverless template file: - Select a Blueprint Choose a pre-defined project blueprint to use for your serverless project. - Select a Serverless Template File Choose a JSON-formatted Serverless Application Model (SAM) .templatefile on your filesystem to fully customize your serverless project. Note For information about the structure and contents of a .templatefile, view the current version of the specification on GitHub. Press the Finish button to create your new serverless project. Serverless Project Blueprints The following serverless project blueprints are available to use: - article This blueprint creates a S3 Bucket for storing article content, and a DynamoDB Table for article metadata. It contains Lambda functions for retrieving ( GetArticle) and storing ( PutArticle) articles, which are triggered by API Gateway events. - hello-world A simple blueprint that creates a Lambda function which takes a single string. Its output is Hello, value, where value is the string that was passed in, or Worldif no string is passed to the function. Serverless Project Structure The serverless project wizard will create a new Eclipse project for you, consisting of the following parts: The srcdirectory contains two sub-directories, each prefaced with your chosen Package namespace: - mynamespace.function Contains class files for the Lambda functions that are defined by your serverless template. - mynamespace.model Contains generic ServerlessInputand ServerlessOutputclasses that define the input and output model for your Lambda functions. Note For more information about the input and output formats used in the model classes, see the Configure Proxy Integration for a Proxy Resource page in the API Gateway Developer Guide. The serverless.templatefile defines the AWS resources and Lambda functions (a resource of type "AWS::Serverless:Function") used by your project. Deploying a Serverless Project To deploy your serverless project In Eclipse's Project Explorer window, select your project and open the context menu (right-click or long press). Choose Amazon Web Services ‣ Deploy Serverless Project... on the context menu. This will bring up the Deploy Serverless to AWS CloudFormation dialog. Select the AWS Regions to use. This determines where the AWS CloudFormation stack that you deploy is located. Choose an S3 Bucket to use to store your Lambda function code, or select the Create button to create a new S3 bucket to store your code. Choose a name for your AWS CloudFormation stack. Press the Finish button to upload your Lambda functions to Amazon S3 and deploy your project template to AWS CloudFormation. When your project is deployed, a AWS CloudFormation stack detail window will appear that provides information about your deployment and its current status. It will initially show its status as CREATE_IN_PROGRESS. When the status is CREATE_COMPLETE, your deployment is active. To return to this window at any time, open the AWS Explorer, select the AWS CloudFormation node, and then select the name of the AWS CloudFormation stack you specified. Note If there was an error during deployment, your stack may be rolled back. See Troubleshooting in the AWS CloudFormation User Guide for information about how to diagnose stack deployment errors.
https://docs.aws.amazon.com/toolkit-for-eclipse/v1/user-guide/serverless-projects.html
CC-MAIN-2018-13
refinedweb
599
63.39
Java programmers are often confused about the difference between AWT and Swing components, the features of AWT and Swing, and the functionalities of both. While Swing is a collection of program components that possess the ability to develop graphical user interface (GUI) objects independent of the platform being used, AWT components are platform-dependent and perform differently on varying platforms. As this article progresses, readers would understand the definition of Swing and AWT as well as the key differences between the two in the form of a comparison chart and points alike. AWT vs. Swing What is AWT in JAVA Abstract Window Toolkit (AWT) refers to a collection of application program interfaces (API s) that are utilized by Java programmers for the creation of graphical user interface (GUI) objects. These objects are in the form of scroll bars, windows, buttons, etc. This toolkit is an essential component of Java Foundation Classes (JFC) belonging to Sun Microsystems, which is the company responsible for the origin of Java. Simple Java AWT Example //Swaping two Number using Java AWT package swap; import java.awt.*; import java.awt.event.*; public class swap { public static void main(String args[]) { Frame f = new Frame("My Frame"); Label l1 = new Label ("First"); Label l2 = new Label ("Second"); TextField t1 = new TextField(20); TextField t2 = new TextField(20); Button b = new Button("OK"); f.add(l1); f.add(t1); f.add(l2); f.add(t2); f.add(b); b.addActionListener(new ActionListener () { public void actionPerformed(ActionEvent ae) { String temp = t1.getText(); t1.setText(t2.getText()); t2.setText(temp); } }); f.layout(new FlowLayout()); f.setSize(300,300); f.setVisible(true); } } What is Swing in JAVA Swing in Java refers to a graphical user interface (GUI) in the form of a lightweight widget toolkit; the toolkit is packaged with widgets with rich functionality. Swing forms an integral part of the Java Foundation Classes (JFC) and provides coders with several useful packages for the development of rich desktop-friendly applications in Java. The built-in controls in Swing comprise of image buttons, trees, tabbed panes, color choosers, sliders, toolbars, tables, etc. Swing also enables the creation of text areas for displaying rich text format (RTF) or HTTP objects. Swing components are written purely in java and are therefore independent of the platform they work on. Simple Java Swing Example //SWAPing import javax.swing.*; import java.awt.event.*; public class swap implements ActionListener{ JTextField tf1,tf2; JButton b1; swap(){ JFrame f= new JFrame(); tf1=new JTextField(); tf1.setBounds(50,50,150,20); tf2=new JTextField(); tf2.setBounds(50,100,150,20); b1=new JButton("Ok"); b1.setBounds(50,200,50,50); b1.addActionListener(this); f.add(tf1);f.add(tf2);f.add(b1); f.setSize(300,300); f.setLayout(null); f.setVisible(true); } public void actionPerformed(ActionEvent e) { String temp = t1.getText(); t1.setText(t2.getText()); t2.setText(temp); } public static void main(String[] args) { new swap(); } } A key difference between Swing and AWT - An understanding of the key differences between Java AWT and Swing goes a long way in helping coders use the most appropriate components as and when needed. - Swing presents a more-or-less Java GUI. Swing components utilize AWT for creating an operating system window. After that, Swing draws buttons, labels, checkboxes, text boxes, etc. directly on to the window. These Swing objects are designed to respond to key entries and mouse-clicks alike. Here, users can decide upon what they would like to do rather than allow the OS to handle the features and functionalities to be put to use. On the other hand, AWT being a cross-platform interface uses the OS or native GUI toolkit to enable its functionality. - An essential difference between AWT and Swing is that AWT is heavyweight while Swing components are lightweight. - In the case of AWT components, native codes are utilized for the generation of view components as provided by the OS. This is the reason behind the look and feel of AWT components changing from one platform to another. In comparison, in the case of Swing components in Java, the JVM is responsible for generating the view for parts. Conclusion This tutorial helps users understand the functionality and features of both for better utilization of their components. Swing offers richer functionality, is lightweight, and much more extensive than AWT. Java programmers desirous of accessing built-in functions rather than creating them on their own should opt for Swing rather than AWT. Additionally, in case the work on hand is GUI intensive, then AWT components would give off a very first look and feel in comparison to their Swing counterparts. This is because Swing implements the GUI functionality on its own rather than depend on the host OS platform for the same – so, choose between these java components accordingly to attain the best results.
https://www.stechies.com/difference-between-awt-swing/
CC-MAIN-2021-39
refinedweb
804
51.89
Results 1 to 1 of 1 Thread: slmodem with kernel 2.6.19 - Join Date - Dec 2006 - 3 slmodem with kernel 2.6.19 one was a .patch file that i personally could not get to work After stairing at the patch file and the other things i ran accross on the net i came up with a fix this was done with slmodem-2.9.11-20061021 after unpacking cd into slmodem-2.9.11-20061021/drivers edit amrmo_init.c remove this line: #include <linux/config.h> save and exit cd .. back to slmodem-2.9.11-20061021 make like normal this fixes the errors that look like this /path/to/slmodem-2.9.11-20061021/drivers/amrmo_init.c:589: warning: passing arg 2 of `request_irq' from incompatible pointer type make[4]: *** [/path/to/slmodem-2.9.11-20061021/drivers/amrmo_init.o] Error 1 hope this saves someone else a headache after upgrading to the new kernel.
http://www.linuxforums.org/forum/hardware-peripherals/80058-slmodem-kernel-2-6-19-a.html
CC-MAIN-2017-51
refinedweb
158
69.99
Edit 2 I assumed you meant that your integer was an int and not an Integer. Reply Submitted by Anonymous (not verified) on September 30, 2009 - 10:42am Permalink Thanks man Thanks man Reply Submitted by Anonymous (not verified) on November 2, 2009 - 2:47am Permalink Simple In a company crossing multiple timezones, is it rude to send a co-worker a work email in the middle of the night? Reply Submitted by Anonymous (not verified) on November 2, 2012 - 5:23am Permalink works great.. have a peek at this web-site Thanks, you are really right. Also, if performance is a concern, it seems slower (more below, as well as in other answers). To convert an integer to string use: String.valueOf(integer), or Integer.toString(integer) for primitive, or Integer.toString() for the object. Also, the exception is thrown when the null value is entered or if an empty string is given as input.To “catch” errors and perform error checking for invalid characters, the following works great.. The technique is simple and quick to type. lol, English is by far more difficult to parse then Java! The other seems like a 'trick" to fool the compiler, bad mojo when different versions of Javac made by other manufacturers or from other platforms are considered if the code ever Often, these numeric values have to be used as a part of set of characters. share|improve this answer edited Jan 23 '12 at 15:00 answered Jan 23 '12 at 14:46 Jonathan 4,77321835 OP is starting with an Integer object. I don't want to append an integer to an (empty) string. Java.lang.string Cannot Be Cast To Java.lang.integer Hibernate Integer i = 33; String s = i.toString(); //or s = String.valueOf(i); //or s = "" + i; Casting. up vote 522 down vote favorite 122 I'm working on a project where all conversions from int to String are done like this: int i = 5; String strI = "" Java.lang.string Cannot Be Cast To Java.lang.integer In Java Is "she don't" sometimes considered correct form? StringBuffer class is mutable class and can be appended.Learn Java programming from scratch through Udemy.comFor performing calculations, double and float values are used in Java. Why do I never get a mention at work? You ask for concatenation; 3. Cast Integer To String C I'm deleting my comment and upvoting this answer. –Ted Hopp Jan 23 '12 at 14:59 1 Similar (but not duplicate) issue: an 'int' cannot be cast to a String because Not the answer you're looking for? I don't want to get fanatic about micro-optimization, but I don't want to be pointlessly wasteful either. Antu Tunga 654,120 views 3:19:09 CA Exercise 1 - Java Tutorials Arrays Strings Scanner Integer - Duration: 12:39. more stack exchange communities company blog Stack Exchange Inbox Reputation and Badges sign up log in tour help Tour Start here for a quick overview of the site Help Center Detailed Cast Integer To String Java Watch Queue Queue __count__/__total__ Find out whyClose How to Convert INT to STRING in JAVA Copper Fish SubscribeSubscribedUnsubscribe9494 Loading... Int Cannot Be Dereferenced Is adding the ‘tbl’ prefix to table names really a problem? Casting an object means that object already is what you're casting it to, and you're just telling the compiler about it. Interconnectivity One Very Odd Email more hot questions question feed lang-java about us tour help blog chat data legal privacy policy work here advertising info mobile contact us feedback Technology Life Resolution Either we should assign element the string literal public class Test { private static int element1; String element2 = "Hello"; private void method1(){ element2 = "0"; } } or change share|improve this answer answered Jan 23 '12 at 14:49 yshavit 27.7k44274 add a comment| up vote 0 down vote Use String.valueOf(integer). Cast To String Java What does the Hindu religion think of apostasy? Enter your email address: Delivered by FeedBurner Subscribe to Java News and Posts. This will interpret the int as an ASCII character code and give you that char. Source Thanks, you are really right. So using something like String.valueOf(…) would confuse students. Cast To String C++ share|improve this answer answered Jan 23 '12 at 14:46 millimoose 27.4k54889 add a comment| up vote 1 down vote Casting is different than converting in Java, to use informal terminology. Integer i = 33; String s = i.toString(); //or s = String.valueOf(i); //or s = "" + i; Casting. If the function is unable to parse the input integer value, then the compiler throws “IllegalFormatException”. As for the choice between Integer.toString or String.valueOf, it's all a matter of taste. How safe is 48V DC? Cast To String C# The String class is immutable and cannot be changed. if you just desire to print, simply make the return type void and remove the "return" at the bottom. It is not the most efficient, but it is the clearest IMHO and that is usually more important. Questions Search Legacy Tests Repository DashBoard IBM WCS Quick Reference / Cheat Sheet Data Models Important SQL and Config WCS Shout Box WCS Interview Questions WCS List on Stumbleupon Java Java have a peek here StringBuilder has its own logic for turning a the primitive int i into a String. –Mark Peters Nov 5 '10 at 14:44 4 The part about the code smell is Not the answer you're looking for? Object / / A / / B In this case, (A) objB or (Object) objB or (Object) objA will work. I changed my post. –Dmitry Sokolyuk Oct 27 at 15:16 add a comment| Your Answer draft saved draft discarded Sign up or log in Sign up using Google Sign up Branded Logo Design 2,506 views 5:59 Java Programming Ep. 3: Strings & Scanner Input - Duration: 14:44. Linked 0 Why primitive types can not be casted? 2 This method of type casting is not working 3 Problems converting Integer to String 0 getting the hidden field value of Back to top Summary I hope this Java String to int example has been helpful. mathtutordvd 19,646 views 11:39 Core Java With OCJP/SCJP: java.lang.package Part-5 || Strings class - Duration: 1:16:07. In it, you'll get: The week's top questions and answers Important community announcements Questions that need answers see an example newsletter By subscribing, you agree to the privacy policy and terms Were the Smurfs the first to smurf their smurfs? "PermitRootLogin no" in sshd config doesn't prevent `su -` What is really curved, spacetime, or simply the coordinate lines? You can search for more duplicates here. –Anderson Green Jul 19 '13 at 2:32 25 The "silly, easy" way is string = "" + integer; –Joe Blow May 20 '14 If you're interested in converting a String to an Integer object, use the valueOf() method of the Integer class instead of the parseInt() method. You ask for the empty string; 2. For casting to work, the object must actually be of the type you're casting to. It's much more efficient to just do myIntegerObject.toString(). –Ted Hopp Jan 23 '12 at 16:21 add a comment| up vote 4 down vote You should call myIntegerObject.toString() if you want the share|improve this answer answered Jan 23 '12 at 14:45 Petar Minchev 32.6k870102 1 @Ted Hopp - which one? Since no no instance of Integer can ever be a String, you can't cast Integer to String.
http://hiflytech.com/to-string/cannot-convert-int-to-string-java.html
CC-MAIN-2018-13
refinedweb
1,265
64.41
table of contents NAME¶ setgroups— LIBRARY¶Standard C Library (libc, -lc) SYNOPSIS¶ #include <sys/param.h> #include <unistd.h> int setgroups(int ngroups, const gid_t *gidset); DESCRIPTION¶The setgroups() system call sets the group access list of the current user process according to the array gidset. The ngroups argument indicates the number of entries in the array and must be no more than {NGROUPS_MAX}+1. Only the super-user may set a new group list. The first entry of the group array (gidset[0]) is used as the effective group-ID for the process. This entry is over-written when a setgid program is run. To avoid losing access to the privileges of the gidset[0] entry, it should be duplicated later in the group array. By convention, this happens because the group value indicated in the password file also appears in /etc/group. The group value in the password file is placed in gidset[0] and that value then gets added a second time when the /etc/group file is scanned to create the group set. RETURN VALUES¶The setgroups() function returns the value 0 if successful; otherwise the value -1 is returned and the global variable errno is set to indicate the error. ERRORS¶The setgroups() system call will fail if: SEE ALSO¶getgroups(2), initgroups(3) HISTORY¶The setgroups() system call appeared in 4.2BSD.
https://manpages.debian.org/buster/freebsd-manpages/setgroups.2freebsd.en.html
CC-MAIN-2022-05
refinedweb
228
54.02
[U]ntil. Jacob Bronowski in Magic, Science and Civilization, published in 1978 by the Columbia University Press One of the grim spectacles created by the recent tribal war in Rwanda was the plight of the Hutu refugees who, during a few chaotic days in July, fled from Rwanda into northeastern Zaire. More than a million Hutus swarmed to a makeshift camp near the Zairian town of Goma -- and there they were overrun by a fierce epidemic of cholera. Cholera is a bacterial infection. Its effects include severe, continual diarrhea, which entails such a massive loss of water that a typical victim soon suffers fatal dehydration. For as long as the victim survives, however, he discharges copious feces that are laden with cholera bacteria; and if such feces get into a source of drinking water, the bacteria can spread rapidly and can infect many new victims. This is how most cholera epidemics arise, and this is what happened, with fearsome results, in the Goma refugee camp. At its peak, the Goma epidemic -- which was aggravated by outbreaks of measles -- took hundreds of lives each day. The United Nations, several national governments, and some private organizations quickly began efforts to stop the spread of diseases at the camp, and those efforts involved various tactics. To control the propagation of cholera, relief workers built latrines that would sequester the feces of infected individuals and keep the feces out of local water supplies; they also used reverse-osmosis equipment to provide drinking water that was free of bacteria. To treat individual victims of cholera, they used oral or intravenous rehydration. And to control measles, they administered vaccines. All of that was straightforward and comprehensible, because all of it was based on knowledge of the relevant organisms (i.e., humans, cholera bacteria, and measles viruses) and on physical, chemical and biological methods of dealing with those organisms. In short, all of it was based on natural science, an intellectual enterprise, developed in Europe during the 1500s and 1600s, that is quite unique: Natural science is the one and only intellectual system that lets us understand nature, make reliable predictions about nature, and use the laws of nature in attaining our own goals. All educated persons are aware of natural science, aware of its unique status, and aware of how the practical use of scientific information has changed much of human life during the past 500 years or so. Hence no educated observer could have been surprised to learn that the disease-control campaign at Goma was a multifaceted application of science, and no educated observer could have been surprised to see the particular things that were done as that campaign took shape. Similarly, no educated observer could have been surprised to see that a lot of things were not done. The relief agencies did not import any squads of shamans, witch doctors, faith healers or mojo men. There were no global appeals for chiropractors, acupuncturists, homeopaths, naturopaths, Eddyists, crystal mystics, or practitioners of "color therapy." There were no airborne deliveries of magical herbs, magical magnets, magical candles, magical pictures or magical crucifixes. And there was no international attempt to thwart the cholera epidemic by singing mystical chants or by manipulating some desiccated scraps of departed holy men. That, too, was straightforward. The notion of promoting health or curing disease by using magic and mumbo jumbo is a relic from the distant past, when the prevalent approach to dealing with nature was to seek formulas that would override or reverse nature's laws. It was tried for millennia, in countless forms, and it is still employed by ignorant people today, but to no avail. The only approach that has worked is medicine based on science -- and science is the very antithesis of magic. I have been appalled and disgusted, therefore, to find that a high-school "health" book issued by Holt, Rinehart and Winston teaches the student that science and magic are interchangeable. The book -- Holt Health, dated in 1994 -- explicitly endorses superstitions and magical rubbish, and it depicts magic as an equivalent alternative to scientific medicine. I consider this to be a grave matter indeed, for I believe that Holt's claptrap is dangerous not only to the student's intellectual development but to his health as well.. These efforts are embodied in two feature articles printed under the rubric "Cultural Diversity." One of the articles appears on pages 6 and 7, the other on pages 578 and 579. In both cases, Holt's writers promote ignorant fallacies, cast superstition in the guise of fact, and pointedly refuse to tell what they really are talking about. They load their prose with bafflegab and unexplained terms, including quackish words and phrases that are entirely meaningless, and they lead the student to think that such inane stuff should be taken as information about "health." Their essential message to the student is this: Don't think, don't try to understand, don't ask -- just swallow. The student who learns that lesson, I assert, will be prey for quacks of every sort. Now the writers start to use "cultural" nonsense for endorsing magic and tricking the student: A bank clerk in Milwaukee who hears voices makes an appointment with a mental health therapist, but an Inuit shaman expects to hear voices and relies on sage advice from the invisible world. That comparison is bogus. The clerk's hallucinations are presumably spontaneous and pathological; the shaman's are induced, by well established techniques, during the shaman's magical doings. But what is more important here is that the writers don't define shaman and don't disclose that they are talking about magic. They present the "invisible world" as if it were a matter of fact rather than superstition, and they leave the student to imagine that claims about "sage advice" from "the invisible world" should be accepted as information. This is unconscionable, but there is worse to come. Turning their attention to something relatively mundane, the writers of Holt's "health" text tell the student that garlic has been "relied upon as a medicine" and that the use of garlic as a "medical remedy" spans many cultures. A "medical remedy" for what? -- and to what effect? Is there any evidence that garlic serves any therapeutic purpose? The writers refuse to say; they evidently want the student to imagine that garlic must be a valuable, universal curative agent simply because many people believe in it. Here the writers are promoting one of the grand fallacies on which superstition thrives: the notion that if something is widely believed, it must be valid (or "there must be something to it"). That is nonsense, of course, and health textbooks should take pains to refute it. Holt Health does the opposite. The writers' attack on rationality is well under way now. As the attack continues, the writers begin the outright promotion of magical quackery: They present the use of "ginseng root" as an alternative to taking vitamins or to consulting a physician. They do not, however, tell what "ginseng root" is. They don't even give a hint; nor do they disclose that ginseng root is medically worthless, or that belief in the therapeutic powers of ginseng root is based on a long-discredited superstition. I can't imagine that this performance is due to mere ignorance and incompetence. I conclude that the writers are engaging in calculated deception, and I decline to let them get away with it. In Part 2 of this article, therefore, I'll quote their entire passage about ginseng, analyze it, and give essential information about ginseng quackery. Next, Holt's writers take a stab at promoting acupuncture. Acupuncture is a kind of Oriental nonsense that involves sticking needles into a person's body to influence his "life force" -- but the writers don't mention any of that. They dispense bunkum, and they try to boost acupuncture by making bogus claims, but they never say what acupuncture is. Again, they simply refuse to say what they are talking about. What they are talking about is quackery; this too will be explained in Part 2, where I'll quote their entire acupuncture passage and show how deceptive it is. After peddling their Oriental magic, the writers uncork a long paragraph that can properly be described as a quack's delight. Here is the paragraph, in full: Good health is a matter of mind, body, and spirit working together in balance and harmony. Hozro, or harmony, is the aim of the Navajo hataali. The Blessing Way ceremony to bring patients back into balance using chants and meditation. Harmony is also the aim of holistic healing methods, in which all levels of an individual are brought into balance. Thus, health becomes a connecting flow of vitality throughout all parts of an individual's life and thought. "Mind, body, and spirit working together in balance and harmony"? What does that mean? The answer is: Nothing at all. The words "balance" and "harmony" have no meaning in medicine or biology, and claims dealing with "balance" and "harmony" are pure mumbo jumbo -- a style of mumbo jumbo that turns up regularly in advertisements used by quacks. By putting such stuff into a schoolbook, and by treating it as if it were meaningful information, Holt's writers are setting the student up for crystal-peddlers, "psychic healers" and all of the other quacks who invoke "balance" and "harmony" in promotions for useless products and services. The rest of Holt's paragraph is more of the same: ". . . . Hozro, or harmony, is the aim of the Navajo hataali." [Whether it's called "hozro" or "harmony," it's still mumbo jumbo. And why don't the writers tell that a "hataali" is a Navajo witch doctor?] ". . . . The Blessing Way ceremony to bring patients back into balance using chants and meditation." [A verb isn't the only thing that's missing from that pseudosentence. Just what is this ceremony that brings patients "back into balance"? And how can we observe this "balance"? Again, the writers tell nothing. Again, they require the student to accept goofy bafflegab as if it were information.] ". . . . Harmony is also the aim of holistic healing methods, in which all levels of an individual are brought into balance." [That word "holistic" is another favorite of quacks, and another that shows up often in quacks' advertisements. It is meaningless.] ". . . . Thus, health becomes a connecting flow of vitality throughout all parts of an individual's life and thought." [That is pure quacktalk, of course. If it means anything at all, it means that Holt is promoting vitalism -- a moldy doctrine which asserts that living things have preternatural properties and faculties, transcending the laws of physics and chemistry. There has never been any evidence to support that notion, but there is a huge body of knowledge, including the entire discipline of organic chemistry, to refute it. Vitalism was definitively rejected by science during the 19th century. Today it persists only among the ignorant.] The article on pages 6 and 7 ends in utter absurdity: Cultural diversity can add a rich, new dimension to your view of health and wellness. But you must remain open to new ideas. "New ideas"? There is nothing new about the grubby magic that the Holt writers are peddling, and there is nothing new about deceiving students and teaching them to be dupes. To promote such fanciful stuff in their "health" book, Holt's writers drag out some unspecified American Indians (whom they call "Native Americans," in accordance with a fashionable pretension). They use these nameless Indians as the focus for an astonishing exhibition of bafflegab, complete with witch doctors, "harmony," mysterious "power" and animism! Here it is: Native American cultures are examples of cultures that provide alternative health systems for their people.. An "imbalance among the elements" indeed! I needn't point out that the writers have again presented superstition as if it were fact, but I must note that the whole passage is rather unfair to the Indians. The writers haven't told that purveyors of "alternative" treatments can be found as easily in urban shopping centers as in Indian communities. In most big cities you can take your pick of from a veritable regiment of quacks who will offer to tweak your "elements" and correct your "imbalance" (though they won't be able to tell you how the "elements" can be detected, or how the "imbalance" can be measured). You can even find magic-makers who will promise to adjust your "life energy" and fix your "aura"! The nadir of Holt's article on "alternative" health-care comes as the writers make their final, outrageous attempt to convince the student that magic-makers and practitioners of scientific medicine are comparable: "Like medical doctors," they say, "Native American healers must undergo years of special training. . . ." Of all the writers' efforts to delude the student through false analogies and false implications, that one may be the worst. When I recited it to a physician friend of mine, she commented: "Pianists have to undergo lengthy training, too. I guess that means that when you are sick, you should just have somebody play Chopin at you." Responsible educators will never lead students to believe that magic is interchangeable with scientific medicine, nor will they promote the superstitions and fallacies that are endorsed in Holt Health. On the contrary, responsible educators will try to ensure that students can see through the very kinds of nonsense that the Holt hacks are promoting. Here are some basic points that students should understand: An accountant in Arizona might buy a bottle of vitamin tablets or make an appointment with her doctor for a checkup if she is feeling run-down, while her Chinese counterpart might rely solely on ginseng root as a tonic. A housewife in West Virginia has her choice of these, but might choose the ginseng because her mother and grandmother both dug the roots themselves and prepared them for use by relying on an old family recipe. Now here are the facts that health educators should know: The word ginseng has two meanings: It is the common name for any of several herbs that belong to the genus Panax, and it is the commercial name for the root of any such herb. Panax roots are used in making solutions and powders that are sold as magical remedies, and various species of Panax are cultivated, in various parts of the world, to supply roots for the remedy trade. The idea that a ginseng root has magical, therapeutic powers is one of many beliefs based on the old notion that there are mystical correspondences among parts of the cosmos. This notion has given rise to a superstition called the doctrine of "signatures" or "signs," which holds that there is a correspondence between an object's physical appearance and the object's usefulness in curing disease: If a plant (or some part of the plant) resembles a human liver, it can be used for relieving liver disorders; if a plant (or some part of the plant) looks like a human stomach, it can be used for curing stomach trouble; and so on. According to this superstition, ginseng root is a sort of cure-all, because the root resembles (to some extent) an entire human body. A typical root has ramifications that can be interpreted as arms or legs, and it may even have excrescences that can be interpreted as a head and a penis. Ginseng roots play a prominent role in "Oriental medicine," and a root that looks especially man-like can command an exceptionally high price. Oriental quacks dispense ginseng concoctions as remedies for specific illnesses, as aphrodisiacs, and as panaceas that allegedly improve overall health. The commercial use of ginseng is not limited to the Orient, however, for ginseng products are promoted to superstitious customers in other parts of the world as well. In the United States, such products are sold widely in "health food" stores and are advertised on radio, on television, and in mass-market "health" magazines. There is no evidence that ginseng concoctions have any therapeutic value. At best, a ginseng extract may act as a mild stimulant, comparable to coffee or tea. If the sale or promotion of a ginseng product involves a claim that the product can produce a specific therapeutic result, such sale or promotion constitutes quackery. Because ginseng products have no therapeutic value, the writers of Holt Health are engaging in gross deception when they lead the student to believe that taking a ginseng "tonic" is similar to taking vitamins. Ginseng products are medically worthless. Vitamins, on the other hand, are known to be necessary to health, and specific vitamins are known to have specific preventive and therapeutic effects. (Laymen, of course, may use vitamins in frivolous, superstitious, and even harmful ways, but that is another matter.) When Holt's hacks depict the use of a ginseng "tonic" as an alternative to consulting a physician, they further deceive the student and they promote a hideous misperception that can directly endanger the student's health and life. Any person who imagines that ginseng is a substitute for a medical checkup is entertaining a dangerous fantasy, whether the person is a superstitious Chinese accountant, an ignorant housewife in West Virginia, or an unfortunate student who has believed the tommyrot in Holt Health. The ancient Chinese healing art of acupuncture is now being used in the West to relieve pain. Many western physicians and scientists refused to accept acupuncture as anything more than mind over matter until first-hand observations of the results changed their opinions. Now several kinds of treatment apply the meridians and pressure points of acupuncture for pain relief. And here is what health educators should know about that ancient "healing art": Acupuncture is a Chinese craft whose practitioners allege that they can manipulate a person's physiology by sticking needles into various sites on the person's body. These sites, or "acupuncture points," are said to lie along pathways, called "meridians," that carry a "life force." Acupuncturists claim that their needles alter the flow of the "life force" and produce various physiological effects, from anesthesia to the curing of specific diseases. The whole thing is, and always has been, nonsense. Acupuncture arose as an outgrowth of astrology, and it originally recognized 365 acupuncture points -- a point for each day in the year. Since then, many new ones have been dreamed up, and there are now more than 2,000 sites that supposedly can be jabbed to influence the "life force." That "life force" is completely imaginary. Belief in such a force is a vestige of vitalism, a doctrine that was discredited long ago. (See Part 1 of this article.) Of course, the "meridians" that bear the "life force" are imaginary too. They were contrived by people who knew nothing about internal anatomy, who did not try to study internal anatomy, and who relied on utterly fanciful conceptions of how the human body worked. When we view the meridians in the light of our modern knowledge of anatomy and physiology, we find that the meridians have no anatomical or physiological basis whatsoever. Along with many other absurd, traditional practices that figure in "Oriental medicine," acupuncture lost favor in China when the Chinese learned about scientific medical and surgical techniques developed in the West. The traditional practices were revived, however, for political and economic reasons, under the Communist regime led by Mao Zedong. This revival included some bizarre "demonstrations" that were staged during the 1960s and 1970s to convince visitors from the West that acupuncture could be used to anesthetize patients during surgery. We now know that the demonstrations were shams: In typical cases the patients were decorated with acupuncture needles but were anesthetized, secretly, by chemical methods. When gullible Western observers went home and told about the demonstrations, acupuncture gained a specious credibility and became a prominent and fashionable form of quackery in the United States and some other Western countries. All of that information is useful in analyzing the deceptive passage about acupuncture in Holt Health. Consider Holt's last claim first: "Now several kinds of treatment apply the meridians and pressure points [i.e., acupuncture points] . . . for pain relief." Horseflop! No one can "apply" the meridians, because the meridians are fictions; no one can "apply" the pressure points either, because they too are fictions -- as Holt's hacks surely know, if they have looked into acupuncture at all. Next, consider Holt's claim that "Many western physicians and scientists refused to accept acupuncture as anything more than mind over matter until first-hand observations of the results changed their opinions." I assume that "many western physicians and scientists" is Holt's name for those gullible persons whom the Chinese fooled with phony demonstrations, and I hasten to report what Holt's hacks have concealed: No study of acupuncture has shown that acupuncture produces any medical result other than a placebo effect. This brings me to Holt's opening claim, the claim that "acupuncture is now being used in the West to relieve pain." To the extent that acupuncture may function at all in the relief of pain, it merely functions as a placebo. I have been interested in quackery for some years, and my files contain various articles that deal with acupuncture in one way or another. Among my favorites is a story that appeared in the Los Angeles Times for 14 January 1989. Written by a reporter named Ashley Dunn, it was a pathetically credulous account of how two California acupuncturists, Cho Sheng-gung and Wu Li-hsia, claimed to have used acupuncture to cure a skin infection that afflicted some goldfish! Ashley Dunn swallowed their nonsense whole. He informed his readers that "Acupuncture involves harmonizing life forces in the body through the insertion of needles at strategic points," and then he recounted the tale of how Wu Li-hsia was able to "stimulate" each goldfish's immune system: In human beings, the treatment to stimulate the body's immune system involves three points . . . . The first, on the shin, about three inches below the kneecap, is called zu san li, or "three measures of the leg." The problem, of course, is that fish have no shins. So, Wu picked a spot near the fish's tail and hoped for the best. So much for all those notions about meridians and precisely located insertion points! To top his story off, Dunn quoted a comment by one Hwang San-hong, president of something called the Acupuncture Medicine Association of Southern California. This luminary said there was no reason why acupuncture shouldn't work on fishes, and he explained this by invoking his deep knowledge of biology: "Most animals," he said, "have a spine and nerves and a blood system. They're almost the same as humans." Maybe Hwang San-hong really believed that. But even if he didn't, his silly pronouncement was no worse than the rest of the twaddle that acupuncturists serve up. To learn more about acupuncture, and to read about some of the dangers that it entails, educators may consult Arthur Taub's essay "Acupuncture: Nonsense with Needles." The essay appears in The Health Robbers: A Close Look at Quackery in America, issued in 1993 by Prometheus Books (Buffalo, New York)..
http://www.textbookleague.org/53quak.htm
crawl-001
refinedweb
3,895
57.4
Fl_Group | +----Fl_Text_Display----Fl_Text_Buffer | +----Fl_Text_Editor #include <FL/Fl_Text_Display.H> This is the FLTK text display widget. It allows the user to view multiple lines of text and supports highlighting and scrolling. The buffer that is displayed in the widget is managed by the Fl_Text_Buffer class. Creates a new text display widget. Destroys a text display widget. Sets or gets the current text buffer associated with the text widget. Multiple text widgets can be associated with the same text buffer. Sets or gets the text cursor color. Sets the text cursor style to one of the following: Fl_Text_Display::NORMAL_CURSOR- Shows an I beam. Fl_Text_Display::CARET_CURSOR- Shows a caret under the text. Fl_Text_Display::DIM_CURSOR- Shows a dimmed I beam. Fl_Text_Display::BLOCK_CURSOR- Shows an unfilled box around the current character. Fl_Text_Display::HEAVY_CURSOR- Shows a thick I beam. Hides the text cursor. Sets the text buffer, text styles, and callbacks to use when displaying text in the widget. Style buffers cannot be shared between widgets and are often used to do syntax highlighting. The editor example from Chapter 4 shows how to use the highlight_data() method. Returns non-zero if the specified mouse position is inside the current selection. Inserts text at the current insert position. Sets or gets the current insert position. Moves the current insert position down one line. Moves the current insert position left one character. Moves the current insert position right one character. Moves the current insert position up one line. Moves the current insert position right one word. Replaces text at the current insert position. Returns the style associated with the character at position lineStartPos + lineIndex. Moves the current insert position left one word. Marks text from start to end as needing a redraw. Sets or gets where scrollbars are attached to the widget - FL_ALIGN_LEFT and FL_ALIGN_RIGHT for the vertical scrollbar and FL_ALIGN_TOP and FL_ALIGN_BOTTOM for the horizontal scrollbar. Sets or gets the width/height of the scrollbars. Scrolls the current buffer to start at the specified line and column. Shows or hides the text cursor. Scrolls the text buffer to show the current insert position. Sets or gets the default color of text in the widget. Sets or gets the default font used when drawing text in the widget. Sets or gets the default size of text in the widget. Moves the insert position to the end of the current word. Moves the insert position to the beginning of the current word. If mode is not zero, this call enables automatic word wrapping at column pos. Word-wrapping does not change the text buffer itself, only the way that the text is displayed.
http://www.fltk.org/doc-1.1/Fl_Text_Display.html
crawl-001
refinedweb
434
69.68