text
stringlengths
454
608k
url
stringlengths
17
896
dump
stringclasses
91 values
source
stringclasses
1 value
word_count
int64
101
114k
flesch_reading_ease
float64
50
104
in reply to Re^2: Parse multiple xml tags with different names to an arrayin thread Parse multiple xml tags with different names to an array Hi, Thank you, but I am unable to figure out my exact requirement from a huge pool of info there in "state of web spidering in perl". Can you specify exactly which matches my req ? Thanks, Bala. Well, I only link examples in one post, so that one :) and they all match your spec, they're all about extracting "tags" from xml ... As Corion says, LibXML is one of the best choices available, use xpather.pl on your xml file to get a list of xpaths you can use to extract data you want (or url, but its better to download url to file for testing/development/until you figure stuff out ) examples of extracting "tags" are at Re: Stepping up from XML::Simple to XML::LibXML, Re^5: Parsing xml using libXML, Re: Nested XML Question, Re^2: How to make use of dynamic namespace registration to replace the values of elements and attributes using XML::LibXML::XPathContext xml module Re: Perl XML Search, Re: Filter for XML elements, Re: hi i want to retrieve the element and values from xml document, Re: XML::Simple XML / XMLin / XMLout? or something else?, Re: Struggling with XML, Re: XML Parsing, Re^6: Is there any XML reader like this? (XML::Simple beats LibXML hands down in the speed stakes!), Re^5: XML::LibXML problem,,, With all your help , I am able to get the child nodes as an array using the code below : my $parser = XML::LibXML->new(); my $doc = $parser->parse_string($string); my @nodes = $doc->findnodes("//ROOT_TAG/*"); Is there any possible ways to do this ? [download] The resultant array elements of @nodes are all XML::LibXML::Elements object. I need this to be hash for my processing. Is there any way to do this ? Thanks, Bala. Yes No Results (278 votes). Check out past polls.
http://www.perlmonks.org/?node_id=1055255
CC-MAIN-2017-13
refinedweb
331
66.17
What is the best way to choose a random file from a directory in Python? Edit: Here is what I am doing: import os import random import dircache dir="some/directory" filename = random.choice(dircache.listdir(dir)) path = os.path.join(dir, filename) Is this particularly bad, or is there a particularly better way? import os, random random.choice(os.listdir("C:\")) #change dir name to whatever Regarding your edited question: first, I assume you know the risks of using a dircache, as well as the fact that it is deprecated since 2.6, and removed in 3.0. Second of all, I don’t see where any race condition exists here. Your dircache object is basically immutable (after directory listing is cached, it is never read again), so no harm in concurrent reads from it. Other than that, I do not understand why you see any problem with this solution. It is fine. If you want directories included, Yuval A’s answer. Otherwise: import os, random random.choice([x for x in os.listdir("C:\") if os.path.isfile(os.path.join("C:\", x))]) The problem with most of the solutions given is you load all your input into memory, which can become a problem for large inputs/hierarchies. Here’s a solution adapted from The Perl Cookbook by Tom Christiansen and Nat Torkington. To get a random file anywhere beneath a directory: #! /usr/bin/env python import os, random n=0 random.seed(); for root, dirs, files in os.walk('/tmp/foo'): for name in files: n += 1 if random.uniform(0, n) < 1: rfile=os.path.join(root, name) print rfile Generalizing a bit makes a handy script: $ cat /tmp/randy.py #! /usr/bin/env python import sys, random random.seed() n = 1 for line in sys.stdin: if random.uniform(0, n) < 1: rline=line n += 1 sys.stdout.write(rline) $ /tmp/randy.py < /usr/share/dict/words chrysochlore $ find /tmp/foo -type f | /tmp/randy.py /tmp/foo/bar The simplest solution is to make use of os.listdir & random.choice methods random_file=random.choice(os.listdir("Folder_Destination")) Let’s take a look at it step by step :- 1} os.listdir method returns the list containing the name of entries (files) in the path specified. 2} This list is then passed as a parameter to random.choice method which returns a random file name from the list. 3} The file name is stored in random_file variable. Considering a real time application Here’s a sample python code which will move random files from one directory to another import os, random, shutil #Prompting user to enter number of files to select randomly along with directory source=input("Enter the Source Directory : ") dest=input("Enter the Destination Directory : ") no_of_files=int(input("Enter The Number of Files To Select : ")) print("%"*25+"{ Details Of Transfer }"+"%"*25) print("nnList of Files Moved to %s :-"%(dest)) #Using for loop to randomly choose multiple files for i in range(no_of_files): #Variable random_file stores the name of the random file chosen random_file=random.choice(os.listdir(source)) print("%d} %s"%(i+1,random_file)) source_file="%s%s"%(source,random_file) dest_file=dest #"shutil.move" function moves file from one directory to another shutil.move(source_file,dest_file) print("nn"+"$"*33+"[ Files Moved Successfully ]"+"$"*33) You can check out the whole project on github Random File Picker For addition reference about os.listdir & random.choice method you can refer to tutorialspoint learn python os.listdir :- Python listdir() method random.choice :- Python choice() method Language agnostic solution: 1) Get the total no. of files in specified directory. 2) Pick a random number from 0 to [total no. of files – 1]. 3) Get the list of filenames as a suitably indexed collection or such. 4) Pick the nth element, where n is the random number. Independant from the language used, you can read all references to the files in a directory into a datastructure like an array (something like ‘listFiles’), get the length of the array. calculate a random number in the range of ‘0’ to ‘arrayLength-1’ and access the file at the certain index. This should work, not only in python. If you don’t know before hand what files are there, you will need to get a list, then just pick a random index in the list. Here’s one attempt: import os import random def getRandomFile(path): """ Returns a random filename, chosen among the files of the given path. """ files = os.listdir(path) index = random.randrange(0, len(files)) return files[index] EDIT: The question now mentions a fear of a “race condition”, which I can only assume is the typical problem of files being added/removed while you are in the process of trying to pick a random file. I don’t believe there is a way around that, other than keeping in mind that any I/O operation is inherently “unsafe”, i.e. it can fail. So, the algorithm to open a randomly chosen file in a given directory should: - Actually open()the file selected, and handle a failure, since the file might no longer be there - Probably limit itself to a set number of tries, so it doesn’t die if the directory is empty or if none of the files are readable Python 3 has the pathlib module, which can be used to reason about files and directories in a more object oriented fashion: from random import choice from pathlib import Path path: Path = Path() # The Path.iterdir method returns a generator, so we must convert it to a list # before passing it to random.choice, which expects an iterable. random_path = choice(list(path.iterdir()))
https://codeutility.org/best-way-to-choose-a-random-file-from-a-directory/
CC-MAIN-2021-43
refinedweb
944
65.93
CodePlexProject Hosting for Open Source Software Hello everyone, I haven't been using Composite C1 for that long, and I haven't launched my first website (but it's on its way), never the less i feel that I have a few ideas that could improve the overall experience of the CMS. Here goes: 1) Creating a functions requires way to may mouse clicks. Changing a control type takes way to many clicks. It would ease my day if the trees automaticly expanded to the first "folder/namespace" which has anything else but a single folder inside. The first 2-3 clicks are just a waste, Since you always need to expand "All functions" and in most cases "Composite" aswell. 2) On the Media tab i'd like to have preview function. it's hard to figure out which files are what only by filename. not every use is a genious at naming files :-P Having used for instance Dynamicweb, the filearchieve there is pretty good, all images are listed with a thumbnail and filename, and that works very well 3) Where is the save and publish button? Again this is to cut down on all the clicking ;-) That's all for now, but i basicly love everything else about this CMS :-D Best regards Martin Thanks Martin. I loved the idea of "Save & Publish" also, the preview of media files can be a very useful thing. I also need a refresh button when editing a XSLT function. It happens that I am editing a function in VS2010 and I want to see the preview in C1 Console. Each time I have to close the function in C1 Console and reopen it for it to understand the changes I've made in VS2010 IDE. I think it should be possible to make the "Save & Publish" button yourself... will look into that, a small midnight project for tonight :) The media library for sure needs a big touchup. Go and vote here for improved uploading as well :) Btw, im working on making something similar to the Universal Media Picker () for Composite C1. Let me now if its something you would be interested in seeing released into the wild, or if you have suggestions/ideas for such a project. @burningice: Would be awesome if you could make a Save & publich button, I'd install it :-) I've had a look at UMP and it's really nice, and adds a lot of value to the UX of handeling files in Umbraco, so a port for Composite C1 would be appreciated :-) IMO the Media library is a major weak point in Composite C1 now. But i personaly don't like the extra layer added to the filemanagement that's in Umbraco, Composite, Synkronv VIA and many other CMS. I prefer to work directly with the files and folders and not some database object, which prevent me from FTP'ing my files and folders :-) @Aboo, Yes, a refresh button for XSLT would be awesome, working in VS2010 and the likes is just a lot easier that the CMS editor. I agree with @boedlen - too many mouse clicks in general. Other stuff I'd like to see added/changed are - 9 issues, top of mind, not in any way prioritized: 1) Easy lightweight tool to query data with no need to create files on server. When solutions are live, I often don't have the luxery of Visual Studio or direct interaction with file system. 2) Instead of hooking metadata field to page types then vice versa hooking page types to metadata fields. 3) Create overall rules for depth and inheritance on page meta types. These rules are sort of hidden now (i.e. right clicking on pages adding page meta types) 4) Sitemap dependant on language parameter (i.e. forcing to see the english sitemap XML when viewing a german page) 5) Widgets for selecting file system folders, files, and scope (i.e. setting filters to a specific folder). 6) Setting a value to specify if an XSLT function should or should not be selectable in the WYSIWYG editor. 7) Some basic editor functions such as searching pages/media files, and copying pages/data/functions/templates etc. 8) Effective and effecient handling of large amounts of data - not as concrete as description could be - but it could be something like publishing all pages in a tree with one mouse click. I.e. the "go-live" moment of x pages made ready for publication. 9) Switching language and automatically saving any open C1 pages (open = pages being edited) - the saving part with the change-language action is not something you'd expect. 10) More to come... :) Some issues might already be fixed as I have'nt had the chance to work with C1 version 2.0 just yet. @boedlen: hear, hear, hear - all super ideas! Right now we are tied up working on starter sites, Azure and ASP.NET dev features but you are not the only one looking forward to those features. Hopefully we can address them in the beginning of 2011. Perhaps the community will beat us to it ;-) @aboo: also an excellent idea, but this is a wee complex if we are to sync up between client/server. Perhaps some "auto ignore posted XSLT code if server file is newer" could do the trick? This would be fairly easy to introduce, but it could also introduce some ultra annoying issues. Is you can "see" the solution which take multi dev environments into accounts, fire away. @boedlen I'm not a super fan of a "Refresh XSLT" button, cause it's the kind of button that - if you forget clicking it can have a 'doooooh' effect - we would need something devs can simply trust to always help them, if at all possible. @Approxright Hi Marcus, Thank you for your descriptive response mate. You can consider a simple scenario when a developer is editing an XSLT function using Visual Studio IDE (Or any other IDE) and testing it using Composite C1 console's preview tab. Both (C1 Console & IDE) are having the same file opened. Each time I do a modification in XSLT file I have to close it in C1 console and re-open it and it can be a great waste of time when you need too many back and forth while testing. Instead of closing the function, double clicking it, clicking the preview tab (four clicks at least), I could do that with a simple refresh button which will act as if it is closing and reopening the function. VS IDE will take care of the backward way scenario. When you edit an XSLT file in C1 console and save it VS has a file watcher which watches for the changes and will show the popular re-load dialog. Of course the ideal way is to have a file watcher for the opened files in C1 console and then push a notification to the client when there has been a change but I am aware of consequences when having a web-based application and I guess this is not necessary at this stage. @Aboo I added the feature you requested - it's in the source version now. The XSLT edit workflow will now check the physical XSLT file on save and preview events - if the file have been updated by another program, this new version is used for preview (and not overwritten by save). I worked with it and it seems to support editing XSLT in a program like VS2010 just fine. On Save events - if the file was changed - the XSLT shown in the C1 Console will sync. Not so on preview though, here the C1 Consoles XSLT will stay untouched, but the new version of the file will be used. If you have a chance to download the source version and play around with it, let me know if it works for you. I don't think a Save & Publish button is needed. Rather, the Publish Button should appear if the page is dirty. When If you hit SAVE. it just saves it... and doesn't publish. If you hit PUBLISH and the page is dirty... it asks you if want to SAVE and then PUBLISHES. The number one request/complaint from our clients are related to mouse clicks, particularly when inserting an image. In my experience, most users can not organize their own desktops (neither the wooden nor digital versions); Forcing them to do so only makes them resent C1 (particularly for small web sites). I would suggest assuming the user wants to upload a new image to a default upload directory so that users can choose between three work flows: * upload quickly, organize later (or never) or * upload and organize now or * select extant image Use cases: (1) on content editing page, user clicks "Insert Image" (one click). The user is immediately presented with the ability to upload (optionally select an extant image in the media gallery). The default destination directory is pre-selected. The user selects "OK". (2) on content editing page, user clicks "Insert Image" (one click). The user is immediately presented with the ability to upload. The user selects a destination directory or creates a new one. The user selects "OK". (3) on content editing page, user clicks "Insert Image" (one click). Rather than upload, the user instead chooses to open the media gallery. The user navigates to the appropriate directory and selects the desired image. The user selects "OK". @alexgenaud Thx for the input!! This is recorded here:. If you want you can go and upvote this feature request :) Are you sure you want to delete this post? You will not be able to recover it later. Are you sure you want to delete this thread? You will not be able to recover it later.
http://c1cms.codeplex.com/discussions/237929
CC-MAIN-2017-22
refinedweb
1,641
69.82
hi everyone. I'm a novice Ruby on Rails developer and i want to make a cross-platform native app. I'm trying to get a gem working. That gem is Savon -> savon has about 6 dependencies so i'm trying to get it all squared away. There are two pieces that are native ruby code but don't seem to be included with rhomobile's ruby version. logger - Class: Logger (Ruby 1.9.3) rack/utils - Module: Rack::Utils i tried adding them to the extensions on build.yml but its not working. extensions: - net-http - thread - timeout - uri - digest - digest-md5 - digest-sha1 - logger - openssl - openssl.so - rack/utils - akami - builder - gyoku - httpi - nokogiri - nori - savon - wasabi can anyone give me some headway on how to get these two pieces working? also, any idea when Ruby 2.0.0 will be supported? Hi Kendrick, Integrating savon is not easy as the gem dependency chain is too big. What is the purpose of integrating it? If you want to consume SOAP, you may refer Visnupriya R Kutir Mobility yikes... well that kinda blows. I'm dealing with a very complex SOAP installation. So complex, I can't even figure it out with SoapUI. Thanks for the answer though. if anyone feels like helping my cause... you can read more here: Ruby and SOAP creating a web service proxy and namespace - Stack Overflow
https://developer.zebra.com/thread/4404
CC-MAIN-2017-34
refinedweb
233
77.53
Download Go Official binary distributions are available for the FreeBSD (release 10-STABLE and above), Linux, macOS (10.10 and above), and Windows operating systems and the 32-bit (386) and 64-bit (amd64) x86 processor architectures. 386 amd64. cgo †A C compiler: /usr/local /usr/local/go. go1.2.1.linux-amd64.tar.gz (Typically these commands must be run as root or through sudo.) sudo Add /usr/local/go/bin to the PATH environment variable. You can do this by adding this line to your /etc/profile (for a system-wide installation) or $HOME/.profile: /usr/local/go/bin PATH /etc/profile . profile source $HOME/.profile. c:\Go The installer should put the c:\Go\bin directory in your PATH environment variable. You may need to restart any open command prompts for the change to take effect. c:\Go\bin Download the zip file and extract it into the directory of your choice (we suggest c:\Go). Add the bin subdirectory of your Go root (for example, c:\Go\bin) to your PATH environment variable. bin your workspace directory, $HOME/go%USERPROFILE%\go. (If you'd like to use a different directory, you will need to set the GOPATH environment variable.) $HOME/go %USERPROFILE%\go GOPATH Next, make the directory src/hellosrc\hello inside your workspace, and in that directory create a file named hello.go that looks like: src/hello src\hello hello.go package main import "fmt" func main() { fmt.Printf("hello, world\n") } Then build it with the go tool: go $ cd $HOME/go/src/hello $ go build C:\> cd %USERPROFILE%\go\src\hello C:\Users\Gopher\go\src\hello> go build The command above will build an executable named hellohello.exe in the directory alongside your source code. Execute it to see the greeting: hello hello.exe $ ./hello hello, world C:\Users\Gopher\go\src\hello> hello hello, world If you see the "hello, world" message then your Go installation is working. You can run go install to install the binary into your workspace's bin directory or go clean -i to remove it. install clean -i Before rushing off to write Go code please read the How to Write Go Code document, which describes some essential concepts about using the Go tools. It may be useful to have multiple Go versions installed on the same machine, for example, to ensure that a package's tests pass on multiple Go versions. Once you have one Go version installed, you can install another (such as 1.10.7) as follows: $ go get golang.org/dl/go1.10.7 $ go1.10.7 download The newly downloaded version can be used like go: $ go1.10.7 version go version go1.10.7 linux/amd64 All Go versions available via this method are listed on the download page. You can find where each of these extra Go versions is installed by looking at its GOROOT; for example, go1.10.7 env GOROOT. To uninstall a downloaded version, just remove its GOROOT directory and the goX.Y.Z binary. GOROOT go1.10.7 env GOROOT goX.Y.Z To remove an existing Go installation from your system delete the go directory. This is usually /usr/local/go under Linux, macOS, and FreeBSD or c:\Go under Windows. You should also remove the Go bin directory from your PATH environment variable. Under Linux and FreeBSD you should edit /etc/profile or $HOME/.profile. If you installed Go with the macOS package then you should remove the /etc/paths.d/go file. Windows users should read the section about setting environment variables under Windows. /etc/paths.d/go For help, see the list of Go mailing lists, forums, and places to chat. Report bugs either by running “go bug”, or manually at the Go issue tracker. bug
https://golang.org/doc/install?download=go1.8.linux-amd64.tar.gz
CC-MAIN-2019-47
refinedweb
636
58.18
Receives messages from connected sockets. Standard C Library (libc.a) #include <sys/types.h> #include <sys/socket.h> #include <sys/socketvar.h> int recv (Socket, Buffer, Length, Flags) int Socket; void *Buffer; size_t Length; int Flags; The recv subroutine receives messages from a connected socket. The recvfrom and recvmsg subroutines receive messages from both connected and unconnected sockets. However, they are usually used for unconnected sockets only. The recv subroutine returns the length of the message. If a message is too long to fit in the supplied buffer, excess bytes may be truncated depending on the type of socket that issued the message. If no messages are available at the socket, the recv subroutine waits for a message to arrive, unless the socket is nonblocking. If a socket is nonblocking, the system returns an error. Use the select subroutine to determine when more data arrives. Upon successful completion, the recv subroutine returns the length of the message in bytes. If the recv subroutine is unsuccessful, the subroutine handler performs the following functions: The recv subroutine is unsuccessful if any of the following errors occurs: The recvfrom.
http://ps-2.kev009.com/tl/techlib/manuals/adoclib/libs/commtrf2/recv.htm
CC-MAIN-2022-33
refinedweb
186
59.4
I'm writing a program that asks the user how many numbers they would like to input, then proceeds to ask the user to enter the said amount of numbers. At the end, the program computes the sum, average, largest number and smallest number. I've got the entire program figured out, but I've been sitting here for hours trying to figure out how to compute the smallest number and it's driving me crazy. Can someone please tell me how to do this? I feel like i've tried everything. (Probably not, though, seeing as I'm new to C++ lol) Here's what I have for code. #include <iostream> #include <conio.h> using namespace std; int main() { int UserInput, number, i; int sum = 0; float average = 0; int largest = 0; int smallest = 0; cout << "How many numbers do you wish to enter? "; cin >> UserInput; for (i = 0; i < UserInput; i++) { cout << "Enter a number: "; cin >> number; sum = sum + number; average = float(sum)/UserInput; if (number > largest) largest = number; if (number > smallest && number < largest) smallest = number; } cout << "The sum is: " << sum << endl; cout << "The average is: " << average << endl; cout << "The largest is: " << largest << endl; cout << "The smallest is: " << smallest << endl; getch(); return 0; }
https://www.daniweb.com/programming/software-development/threads/313926/smallest-number-from-user-input
CC-MAIN-2018-22
refinedweb
205
66.37
Please see link for more details (...), but basically, if I have multiple selection islands, I would like to create fills for those islands based on the average color within each selection island. If just select and blur (large), you just get a single color. That's not what I want. Hopefully someone here (RobA?) can help me. :) selection islands More generally, you want to apply a filter to each island (component that is a closed region) of a selection separately? You want to fill one island with its average color, the next island with its average color, ...? The Gimp library doesn't appear to have a way to access components of the selection. I think it could be done by converting the selection to a path, then accessing components of the path (which are strokes?) For each stroke (that is closed), create a new path from the stroke, create a new selection from the path, apply the filter. End by restoring the original selection. It might be slow, but that doesn't matter. The details might be devilish. For example, would a selection component at the edge of the image return a closed stroke? Does the Gimp library tell you whether a stroke is closed? Yes, it is a slow process, Yes, it is a slow process, but Saul created a cool Script-fu for me at GIMPTalk (for some reason, I get spam filter trigger when I link again; see link in first thread). The no save history version is about 3 times faster (at least on my machine). :) apply to selection islands I began another way to do this. For now, it is a draft that so far, seems to work. It needs more work and testing. For example, it leaves the progress bar weird. When I have more time.... #!/usr/bin/env python ''' Test apply filter to selection parts Apply a filter to selection parts. This might be used when a filter would treat each selection part differently because of the content or context of the selection part. If a filter output does not depend on the selection, e.g. a filter that renders, creates new content, de novo, from scratch ...., then don't use this plugin, instead filter the entire selection. In computer programming 'apply a function' means 'iteratively invoke' on say a list. Which is what this does. In computer GUI design, an 'Apply' button means 'do it.' But for the general public, use the long 'Apply filter to selection parts' to say more clearly what will happen. Test cases: doesn't alter existing paths doesn't alter the selection doesn't alter the context doesn't alter layers or channels ''' ''' Notes about types and terminology. This can be very confusing. The below might not be correct: probably a PDB stroke is a SVG polygon. These contexts of discussion: Gimp user PDB type SVG Pygimp type this program Gimp PDB PDB type SVG Pygimp type this program Path vectors VECTORS file? vector object a set of strokes NA strokes int array NA tuple a sequence of stroke items NA stroke int polyline int (position) a set of lines NA NA NA polygon NA a closed set of connected lines ''' from gimpfu import * def apply_filter_to_stroke(image, drawable, vectors, stroke): ''' For the given stroke of the given vectors, apply filter to a selection made from stroke. Doesn't appear to be a gimp_vectors_add_stroke(). There is gimp_vectors_stroke_new_from_points but is only a bezier (for now.) So we can't use the strategy: add current stroke to a new vectors. (See a draft of that strategy below.) Instead, we remove all but the current stroke from a copy of vectors. ''' workingvectors = gimp.pdb.gimp_vectors_copy(vectors) gimp.pdb.gimp_image_add_vectors(image, workingvectors, -1) count, strokes = gimp.pdb.gimp_vectors_get_strokes(workingvectors) # Remove all but the given stroke. # !!! Note these are stroke positions, we assume they remain constant among copies. for strokecopy in strokes: if not strokecopy == stroke: print "Removing stroke", strokecopy gimp.pdb.gimp_vectors_remove_stroke(workingvectors, strokecopy) # assert workingvectors now has one) ''' This is a draft of another strategy, but nonworking. workingvectors = gimp.pdb.gimp_vectors_new(image, 'working') gimp.pdb.gimp_image_add_vectors(workingvectors) gimp.pdb.gimp_vectors_add_stroke(workingvectors,) ''' def plugin_main(image, drawable): savedselection = gimp.pdb.gimp_selection_save(image) # save the original selection gimp.pdb.plug_in_sel2path(image, drawable, run_mode=RUN_NONINTERACTIVE) # Note the new path is now active, but there might be other paths ''' count, vectors = gimp.pdb.gimp_image_get_vectors(image) Returns a tuple of integer ID's, not vector objects. There is no PDB proc to get a vector object by ID ??? ''' vectors = gimp.pdb.gimp_image_get_active_vectors(image) # print vectors, type(vectors) # vectors is a single object. Not a Python list, not iterable. count, strokes = gimp.pdb.gimp_vectors_get_strokes(vectors) # strokes is a tuple of items of type "stroke positions" i.e. integers # A stroke is a list of lines, connected in the graph theory sense (shared end points) ?? # Here, I assume a stroke from a path from a selection is closed in the graph theory sense. # TBD test whether any strokes are NOT closed. print "Strokes", strokes, type(strokes) for stroke in strokes: print stroke, type(stroke) apply_filter_to_stroke(image, drawable, vectors, stroke) # Cleanup gimp.pdb.gimp_image_remove_vectors(image, vectors) # Remove path we created from selection gimp.pdb.gimp_selection_load(savedselection) # restore the original selection "python_fu_apply", "Apply", "This plugin applies a filter to components of a multipart selection", "Lloyd Konneker (bootch nc.rr.com)", "2010", "/Filters/_Apply", "*", # image types, !!! TBD But test the filter has compatible image types [], # TBD Should be a choice of filters here [], plugin_main, ) if __name__ == "__main__": # if invoked from Gimp app as a plugin print "Starting apply" main() Use code tags, please. It would probably be helpful to wrap your code within "[pre]" and "[/pre]" tags (substitute "<" and ">" for the brackets); this will preserve Python's invisible syntax. code tags, thanks Sorry, I was in a hurry, didn't preview, didn't know code tags. If you disable selection view If you disable selection view (thanks for the tip from RobA), the Script-fu runs even faster. Maybe Saul will post it here too. It's works fantastic. It's like having the Mosaic filter and you can decide the panel design (not limited to Voronoi outline or the few other shapes that it supports). :) Saul updated the Script-fu; Saul updated the Script-fu; runs on steroids now. Hope he posts it here at the Registry. Really makes fantastic colored mosaics of any type shape for the tiles you can image. Extremely grateful I am to Saul and many thanks to Rob too. If only I had half your talents. :) Wow! On steroids, is the correct way to put it. Works way faster than before. Good job, Saul & Rob A.! Thanks for pointing it out, Lyle. Hey Saul, First, again I Hey Saul, First, again I do appreciate what you did for me on this cool Script. The big issue is when you have a huge number of islands to fill. I wonder if there could be a way to speed things up by just selecting the color at the center of the selection island as opposed to getting the average color within a selection island. Maybe add this as a user option (either average or center color). Not sure how hard it would be to implement though. Just wondering. :)
http://registry.gimp.org/comment/7792
CC-MAIN-2014-52
refinedweb
1,210
66.44
Library for performing speech recognition with the Google Speech Recognition API. Project description Library for performing speech recognition with the Google Speech Recognition API. Links: Quickstart: pip install SpeechRecognition. See the “Installing” section for more details. How to cite this library (APA style): Zhang, A. (2015). Speech Recognition (Version 1.3) [Software]. Available from How to cite this library (Chicago style): Zhang, Anthony. 2015. Speech Recognition (version 1() r.listen_in_background(sr.Microphone(), callback) import time while True: time.sleep(0.1) # we're still listening even though the main thread is blocked Calibrate the recognizer energy threshold (see recognizer_instance.energy_threshold) for ambient noise levels: import speech_recognition as sr r = sr.Recognizer() with sr.Microphone() as source: # use the default microphone as the audio source audio = the thread (a threading.Thread instance) immediately, while the background thread continues to run in parallel..
https://pypi.org/project/SpeechRecognition/1.3.1/
CC-MAIN-2022-21
refinedweb
141
53.68
Just to elaborate a little more, I think I'm in agreement with a lot of Pythoneers that it's more than just a computer language, this glue cohering our various Python-using communities (partially overlapping). It's a webspace (docs, PEPs), a shared namespace, an in-common history, players, characters (benevolent dictator)... the usual stuff of ethnography. I could also mention rituals: lightning talks, sprints, meetups, Zopefests. And then there's the language itself, with its many __ribs__. Part of that shared ethnography is Monty Python the comedy troupe, and I make a big deal out of explaining that at the start of my Python courses in part because it's a good segue into the whole idea of what a "namespace" is (a concept with currency in the XML community as well). However, Monty Python, though still a Broadway phenomenon ('Spamalot' on the marquee last time I was through, which was late last year, Eric Idle of IDLE fame in the credits), is not common knowledge among OLPC kids. Which is *not* to say I think we should drop it. On the contrary, with YouTube and the like, these allusions will become easier and more fun to explain (in the form of short clips, streaming media). Nevertheless, those kids in Cambodia just getting their laptops and cranking up to "learn programming" or whatever they're expected to do, aren't going to have this shared context of British comedy, at least not right away. All an OLPC kid might know, from cursory English, Amerish or perhaps some Caribbean brew, is that Pythons are a kind of snake (constrictors more specifically, not venemous). And a Ruby is a gemstone (usually red), like an emerald (green). A Perl is a valuable thing too (from oysters), but look how it's spelled (some won't notice or care about the difference though, leading to like Perl Divers in Panama -- a group of coders). Java is of course the legal drug. Geekdom more generally has experimented with martial arts metaphors, like kung fu (there was some TV show where the one geek had to admit the other geek had more of it -- was that a Buffy episode? Yes, I think it was). A reason there is many people, males often more overtly, like to display rank, often by means of costume (white, yellow, brown and black belts are just the beginning -- wait'll you see epaulets). I'm not posing as the only answer man here, but I don't mind remaining a font of suggestions, as many others of us are. Lots of good suggestions come from edu-sig IMO, from many corners. My suggestion is to embrace the snake imagery whole heartedly and not just in the form of permuting and punning on Py. In my case, I actually have a constrictor in my office (my daughter will be buying a mouse for it on the way home from school today). It's not a Python though, but a baby Corn. Here's its picture: Not every culture is intrinsically snake friendly, depending on local myth and so on. But kids are typically open minded to fairy tales from other traditions, and that's what they see on satellite TV: mythologies from around the world, some rather alien-seeming. Rather than try to accommodate and "water down" the snake associations, for "marketing reasons", I think core Python culture should be unabashedly willing to help the snake world preserve itself and thrive. We respect and enjoy snakes. We don't teach mindless fear and panic ala 'Snakes on a Plane'. There's a link here to the word "geek" which implies "circus performer" if you study the etymology. Circus kids are likewise open minded and by definition friendly with animals (elephants, horses...), even if some freaks bite the heads off chickens on occasion (more geek etymology). This helps close the loop with comedy *troupe* and *flying circus.* Another suggestion. Snakes naturally bridge to dragons in all kinds of lore, much of it in the Fantasy section. A pro snake attitude translates to a pro dragon attitude. I won't try to unpack all the consequences in this post. I go into more depth in my talk proposal to Europython, which I'll eventually put at my website. Kirby
https://mail.python.org/pipermail/edu-sig/2007-June/007962.html
CC-MAIN-2016-40
refinedweb
717
68.3
qbutton.3qt man page QButton — The abstract base class of button widgets, providing functionality common to buttons Synopsis #include <qbutton.h> Inherits QWidget. Inherited by QCheckBox, QPushButton, QRadioButton, and QToolButton. Public Members QButton ( QWidget * parent = 0, const char * name = 0, WFlags f = 0 ) ~QButton () QString text () const virtual void setText ( const QString & ) const QPixmap * pixmap () const virtual void setPixmap ( const QPixmap & ) QKeySequence accel () const virtual void setAccel ( const QKeySequence & ) bool isToggleButton () const enum ToggleType { SingleShot, Toggle, Tristate } ToggleType toggleType () const virtual void setDown ( bool ) bool isDown () const bool isOn () const enum ToggleState { Off, NoChange, On } ToggleState state () const bool autoResize () const (obsolete) void setAutoResize ( bool ) (obsolete) bool autoRepeat () const virtual void setAutoRepeat ( bool ) bool isExclusiveToggle () const QButtonGroup * group () const Public Slots void animateClick () void toggle () Signals void pressed () void released () void clicked () void toggled ( bool on ) void stateChanged ( int state ) Properties QKeySequence accel - the accelerator associated with the button bool autoRepeat - whether autoRepeat is enabled bool autoResize - whether autoResize is enabled (obsolete) bool down - whether the button is pressed bool exclusiveToggle - whether the button is an exclusive toggle (read only) bool on - whether the button is toggled (read only) QPixmap pixmap - the pixmap shown on the button QString text - the text shown on the button bool toggleButton - whether the button is a toggle button (read only) ToggleState toggleState - the state of the toggle button (read only) ToggleType toggleType - the type of toggle on the button (read only) Protected Members void setToggleButton ( bool b ) virtual void setToggleType ( ToggleType type ) void setOn ( bool on ) virtual void setState ( ToggleState s ) virtual bool hitButton ( const QPoint & pos ) const virtual void drawButton ( QPainter * ) virtual void drawButtonLabel ( QPainter * ) virtual void paintEvent ( QPaintEvent * ) Description The QButton class is the abstract base class of button widgets, providing functionality common to buttons.:.. Member Type Documentation QButton::ToggleState This enum defines the state of a toggle button. QButton::Off - the button is in the "off" state QButton::NoChange - the button is in the default/unchanged state QButton::On - the button is in the "on" state QButton::ToggleType This enum type defines what a button can do in response to a mouse/keyboard press: QButton::SingleShot - pressing the button causes an action, then the button returns to the unpressed state. QButton::Toggle - pressing the button toggles it between an On and an Off state. QButton::Tristate - pressing the button cycles between the three states On, Off and NoChange Member Function Documentation QButton::QButton ( QWidget * parent = 0, const char * name = 0, WFlags f = 0 ) Constructs a standard button called name with parent parent, using the widget flags f. If parent is a QButtonGroup, this constructor calls QButtonGroup::insert(). QButton::~QButton () Destroys the button. QKeySequence QButton::accel () const Returns the accelerator associated with the button. See the "accel" property for details. void QButton::animateClick () [slot] Performs an animated click: the button is pressed and released a short while later. The pressed(), released(), clicked(), toggled(), and stateChanged() signals are emitted as appropriate. This function does nothing if the button is disabled. See also accel. bool QButton::autoRepeat () const Returns TRUE if autoRepeat is enabled; otherwise returns FALSE. See the "autoRepeat" property for details. bool QButton::autoResize () const Returns TRUE if autoResize is enabled; otherwise returns FALSE. See the "autoResize" property for details. void QButton::clicked () [signal] This signal is emitted when the button is activated (i.e. first pressed down and then released when the mouse cursor is inside the button), when the accelerator key is typed or when animateClick() is called. This signal is not emitted if you call setDown().. Examples: void QButton::drawButton ( QPainter * ) [virtual protected] Draws the button. The default implementation does nothing. This virtual function is reimplemented by subclasses to draw real buttons. At some point, these reimplementations should call drawButtonLabel(). See also drawButtonLabel() and paintEvent(). void QButton::drawButtonLabel ( QPainter * ) [virtual protected] Draws the button text or pixmap. This virtual function is reimplemented by subclasses to draw real buttons. It is invoked by drawButton(). See also drawButton() and paintEvent(). QButtonGroup * QButton::group () const Returns the group that this button belongs to. If the button is not a member of any QButtonGroup, this function returns 0. See also QButtonGroup. bool QButton::hitButton ( const QPoint & pos ) const [virtual protected] Returns TRUE if pos is inside the clickable button rectangle; otherwise returns FALSE. By default, the clickable area is the entire widget. Subclasses may reimplement it, though. bool QButton::isDown () const Returns TRUE if the button is pressed; otherwise returns FALSE. See the "down" property for details. bool QButton::isExclusiveToggle () const Returns TRUE if the button is an exclusive toggle; otherwise returns FALSE. See the "exclusiveToggle" property for details. bool QButton::isOn () const Returns TRUE if the button is toggled; otherwise returns FALSE. See the "on" property for details. bool QButton::isToggleButton () const Returns TRUE if the button is a toggle button; otherwise returns FALSE. See the "toggleButton" property for details. void QButton::paintEvent ( QPaintEvent * ) [virtual protected] Handles paint events for buttons. Small and typically complex buttons are painted double-buffered to reduce flicker. The actually drawing is done in the virtual functions drawButton() and drawButtonLabel(). See also drawButton() and drawButtonLabel(). Reimplemented from QWidget. const QPixmap * QButton::pixmap () const Returns the pixmap shown on the button. See the "pixmap" property for details. void QButton::pressed () [signal] This signal is emitted when the button is pressed down. See also released() and clicked(). Examples: void QButton::released () [signal] This signal is emitted when the button is released. See also pressed(), clicked(), and toggled(). void QButton::setAccel ( const QKeySequence & ) [virtual] Sets the accelerator associated with the button. See the "accel" property for details. void QButton::setAutoRepeat ( bool ) [virtual] Sets whether autoRepeat is enabled. See the "autoRepeat" property for details. void QButton::setAutoResize ( bool ) Sets whether autoResize is enabled. See the "autoResize" property for details. void QButton::setDown ( bool ) [virtual] Sets whether the button is pressed. See the "down" property for details. void QButton::setOn ( bool on ) [protected] Sets the state of this button to On if on is TRUE; otherwise to Off. See also toggleState. void QButton::setPixmap ( const QPixmap & ) [virtual] Sets the pixmap shown on the button. See the "pixmap" property for details. void QButton::setState ( ToggleState s ) [virtual protected] Sets the toggle state of the button to s. s can be Off, NoChange or On. void QButton::setText ( const QString & ) [virtual] Sets the text shown on the button. See the "text" property for details. void QButton::setToggleButton ( bool b ) [protected] If b is TRUE, this button becomes a toggle button; if b is FALSE, this button becomes a command button. See also toggleButton. void QButton::setToggleType ( ToggleType type ) [virtual protected] Sets the toggle type of the button to type. type can be set to SingleShot, Toggle and Tristate. ToggleState QButton::state () const Returns the state of the toggle button. See the "toggleState" property for details. void QButton::stateChanged ( int state ) [signal] This signal is emitted whenever a toggle button changes state. state is On if the button is on, NoChange if it is in the" no change" state or Off if the button is off. This may be the result of a user action, toggle() slot activation, setState(), or because setOn() was called. See also clicked() and QButton::ToggleState. QString QButton::text () const Returns the text shown on the button. See the "text" property for details. void QButton::toggle () [slot] Toggles the state of a toggle button. See also on, setOn(), toggled(), and toggleButton. ToggleType QButton::toggleType () const Returns the type of toggle on the button. See the "toggleType" property for details. void QButton::toggled ( bool on ) [signal] This signal is emitted whenever a toggle button changes status. on is TRUE if the button is on, or FALSE if the button is off. This may be the result of a user action, toggle() slot activation, or because setOn() was called. See also clicked(). Example: listbox/listbox.cpp. Property Documentation QKeySequence accel This property holds the accelerator associated with the button. This property is 0 if there is no accelerator set. If you set this property to 0 then any current accelerator is removed. Set this property's value with setAccel() and get this property's value with accel(). bool autoRepeat This property holds whether autoRepeat is enabled.(). bool autoResize This property holds whether autoResize is enabled.(). bool down This property holds whether the button is pressed. If this property is TRUE, the button is pressed down. The signals pressed() and clicked() are not emitted if you set this property to TRUE. The default is FALSE. Set this property's value with setDown() and get this property's value with isDown(). bool exclusiveToggle This property holds whether the button is an exclusive toggle. If this property is TRUE and the button is in a QButtonGroup, the button can only be toggled off by another one being toggled on. The default is FALSE. Get this property's value with isExclusiveToggle(). bool on This property holds whether the button is toggled. This property should only be set for toggle buttons. Get this property's value with isOn(). QPixmap pixmap This property holds the pixmap shown on the button.(). QString text This property holds the text shown on the button.(). bool toggleButton This property holds whether the button is a toggle button. The default value is FALSE. Get this property's value with isToggleButton(). ToggleState toggleState This property holds the state of the toggle button. If this property is changed then it does not cause the button to be repainted. Get this property's value with state(). ToggleType toggleType This property holds the type of toggle on the button. The default toggle type is SingleShot. See also QButton::ToggleType. Get this property's value with toggleType().button.3qt) and the Qt version (3.3.8). Referenced By The man page QButton.3qt(3) is an alias of qbutton.3qt(3).
https://www.mankier.com/3/qbutton.3qt
CC-MAIN-2017-47
refinedweb
1,632
50.43
Hello, I was trying to apply transfer learning on the MNIST dataset from keras.datasets. The mnist dataset is grayscale with only single channel (28,28,1). But, as large networks like VGG or inception need input images in size (224,224,3), I was trying to resize the whole training data to that particular size. - To convert the images from grayscale to RGB I used cv2.COLOR_GRAY2RGB. I was successful in transforming the whole dataset. code snippet for reference: def fixColor(image): return(cv2.cvtColor(image, cv2.COLOR_GRAY2RGB)) new_train = [] for i in range(len(input_train)): new_train.append(fixColor(input_train[i])) Now, the next function takes input in numpy array format, so I had to convert this list(new_train) to numpy. This was successful with: from numpy import array a = array( new_train ) - Now, to change the height and width from (28,28) to (224,224) I decided to use image.smart_resize (from tensorflow.keras.preprocessing.image). It worked well when I trying to experiment with small examples. But when I tried transforming the whole training dataset, the kernal crashes, as the RAM being used shoots up. I tried both on local system and google colab to no avail. code snippet: new_train2 = [] # a new list as the append operation is more efficient in list compared to numpy array for i in range(len(a)): new_train2.append(image.smart_resize(a[i],(224,224))) I tried many different hacks but nothing worked completely. Could anyone kindly help me with this issue? Entire code : import tensorflow as tf from tensorflow import keras from keras.datasets import mnist import numpy as np import cv2 from tensorflow.keras.preprocessing import image (input_train, target_train), (input_test, target_test) = mnist.load_data() def fixColor(image): return(cv2.cvtColor(image, cv2.COLOR_GRAY2RGB)) new_train = [] for i in range(len(input_train)): new_train.append(fixColor(input_train[i])) from numpy import array a = array( new_train ) new_train2 = [] for i in range(len(a)): new_train2.append(image.smart_resize(a[i],(224,224))) Thank you.
https://discuss.cloudxlab.com/t/transfer-learning-on-mnist/7011
CC-MAIN-2021-10
refinedweb
326
51.14
This will be our first hardware tutorial so far. Setting up the Pi will not be part of this tutorial. The. Background In this experiment, we will use Pulse Width Modulation, or PWM, to control the brightness of RGB. PWM is a technique for getting analog results with digital means. Digital control is used to create a square wave, a signal switched between on and off with no intermediary state. This on-off pattern can simulate voltages in between full on 3v controlling the brightness of the LED. Please note that we will connect VCC to 3.3V and not to 5V. The oscillogram above shows that the amplitude of DC voltage output is 3.3V. However, the actual voltage output is only 1.65V through PWM, for the high level only takes up 50% of the total voltage within a period (3.3V*0.5 = 1.65V). The three basic parameters of PWM are easier to understand when visualized: - Duty cycle – proportion of “on” time - Period – number of pulses per second Thus, using PWM we can cover a voltage amplitude from 0-3.3V, although in reality we can only produce “on” or “off” signals. RGB LEDs can be categorized into common anode LED and common cathode LED. In this experiment, we use a common cathode RGB LED. The schematic diagram of the module is as shown below: Notice that the current will flow from VCC through the LED’s cathode, through the GPIO pin and finally to ground. That means that the LED will light up when the GPIO outputs 0V. A PWM of 0% will light up the led with maximal current flow. We will be using the RPi.GPIO library which provide software PWM utility. Here are the main functions: # Create a PWM instance p = GPIO.PWM(channel, frequency) # Start PWM p.start(dc) # dc is the duty cycle (0.0 <= dc <= 100.0) # Change the frequency p.ChangeFrequency(freq) # freq is the new frequency in Hz # Change the duty cycle p.ChangeDutyCycle(dc) # 0.0 <= dc <= 100.0 # Stop PWM p.stop() Experiment 1: Single LED Let’s start with a very simple PWM example and just one LED. Step 1 Build the circuit according to the following method. Please refer to the pinout below for the hardware connection. Note: Check first where pin 1 is and then go to the wanted pin. You can choose any of the three available LEDs. We will start with the red one. Step 2 Run the code below. You should see the LED dim, and brighten. import time import RPi.GPIO as GPIO LedPin = 11 GPIO.setmode(GPIO.BCM) GPIO.setup(LedPin, GPIO.OUT) # We want here to let that led blink 50 times each second # channel = LedPin , frequency=50Hz p = GPIO.PWM(LedPin, 50) # start with duty cyle = 0% p.start(0) try: while 1: for dc in range(0, 101, 5): p.ChangeDutyCycle(dc) time.sleep(0.1) for dc in range(100, -1, -5): p.ChangeDutyCycle(dc) time.sleep(0.1) except KeyboardInterrupt: pass p.stop() GPIO.cleanup() Experiment 2: 3 LEDs Step 1 Build the circuit according to the following method: Step 2 Here we input any value between 0 and 255 to the three pins of the RGB LED to make it display different colors. Run the code below and you will see LED light up, and display different colors in turn. Now it is your turn to play with the code. So feel free to take the code apart and modify it as you want.
https://fullstackembedded.com/tutorials/controlling-an-led-using-pwm-through-the-gpio-pins/
CC-MAIN-2018-47
refinedweb
593
76.72
What's Happening Deere & Co. ( DE ). Technical Analysis DE was recently trading at $110.15, just $0.10 below its 12-month high and $35.24 above its 12-month low. Technical indicators for DE are bullish and the stock is in a strong upward trend. The stock has recent support above $105.60 and is trading above recent resistance. Of the 19 analysts who cover the stock, six rate it a "strong buy", eight rate it a "hold", and five rate it a "strong sell". The stock receives S&P Capital IQ's 3 STARS "Hold" ranking. Analyst's Thoughts Enthusiasm is running higher for Deere, and its main competitor Caterpillar ( CAT ). The current outlook is strong, but even with those gains the valuation is not too higher to avoid the stock., but it will still need to show a good set of quarterly numbers in order for shares to build on recent gains. The company has a solid earnings track record, posting better than expected earnings in each of the last 16 quarters, and revenue beats each of the last four quarters. Look for another solid report, and the stock to move higher in reaction. Stock Only Trade Bullish Trade If you want to set up a bullish hedged trade on DE, consider a June 85/90 bull-put credit spread for a 35-cent credit. That's a potential 7.5% return (21.8% annualized*) and the stock would have to fall 18.0% to cause a problem. Bearish Trade If you want to take a bearish stance on DE at this time, consider a June 130/135 bear-call credit spread for a 25-cent credit. That's a potential 5.3% return (15.3% annualized*) and the stock would have to rise 18.3%.
https://www.nasdaq.com/articles/deere-co-reports-q1-earnings-february-17-2017-02-11
CC-MAIN-2020-45
refinedweb
299
76.72
CGI::URI2param - convert parts of an URL to param values use CGI::URI2param qw(uri2param); uri2param($req,\%regexes);'); If you are using mod_perl, please take a look at Apache::URI2param. It provides an Apache PerlInitHandler to make running CGI::URI2param easier for you. Apache::URI2param is distributed along with CGI::URI2param. $req has to be some sort of request object that supports the method param, e.g. the object returned by CGI->new() or by Apache::Request->new(). \%regexs is hash containing the names of the parameters as the keys, and corresponding regular expressions, that will be applied to the URL, as the values. %regexs=( id => 'id(\d+)\.html', style => 'st_(fancy|plain)', order => 'by_(\w+)', ); You should add some capturing parentheses to the regular expression. If you don't do, all the buzz would be rather useless. uri2param won't get exported into your namespace by default, so you have to either import it explicitly use CGI::URI2param qw(uri2param); or call it with it's full name, like so CGI::URI2param::uri2param($r,$regex); Basically noting, but you can use CGI::URI2param if you cannot use mod_rewrite (e.g. your not running Apache or are on some ISP that doesn't allow it). If you can use mod_rewrite you maybe should consider using it instead, because it is much more powerfull and possibly faster. See mod_rewrite in the Apache Docs () perl Build.PL ./Build ./Build test sudo ./Build install None so far. Please report any bugs or feature requests to bug-cgi-uri2param@rt.cpan.org, or through the web interface at. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes. Implement options (e.g. do specify what part of the URL should be matched) A module that supplies some sort of request object is needed, e.g.: Apache::Request, CGI Thomas Klausner, domm@cpan.org, Thanks Darren Chamberlain <dlc@users.sourceforge.net> for the idea to write a mod_perl handler for CGI::URI2param This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
http://search.cpan.org/~domm/CGI-URI2param-1.01/lib/CGI/URI2param.pm
CC-MAIN-2016-44
refinedweb
357
66.23
A Brief Introduction to OpenOffice.org Writer Files Open Office.org Writer, a no-cost, open-source answer to otherwise pricey, commercial word processing applications, stores its files with an "odt" extension. Even users with casual familiarity with Writer may be surprised to know this file is nothing more than a standard "zip" file full of XML files. The implication behind this fact is this: armed with a little knowledge of these internal files, you can programmatically create and edit them. In this article, I will discuss some of the basic concepts relating to the ODT file itself. I will not discuss how to actually use OpenOffice.org Writer itself—the lessons involved to gain efficient competency with any word processing application would provide ample material to fill a book. Opening the ODT File To get started, you of course need an ODT file. Once you have one, unzipping the file gives you (among other things) four XML files: - content.xml: The actual content of a document. - meta.xml: Meta-data such as creation date, editor, and statistics (word count, and so forth). - settings.xml: OpenOffice.org program settings and preferences local to the document itself. - styles.xml: Formatting styles (for paragraphs, characters, and so on) defined by OpenOffice.org and by the author. Additional files and directories will turn up (some of them depending on just what is in the document, such as a possible "Pictures" directory). However, for the purposes of this article, I will mainly discuss the content.xml and styles.xml files. The main reason for dismissing the presence of the additional files is this: If you're reading or editing material in an existing ODT file, their presence does not generally matter anyway, and if you are creating a new document programmatically, the simplest way is to "edit" an empty template file and save it to a new name. This is perhaps the safest strategy to use because it lets you focus entirely on the content of the document you want to process. Content The content.xml file, as mentioned above, is the real meat of an ODT file: Your actual document material is stored in this file. Feel free to open the content.xml file in any text or, better yet, XML editor you have available. You should see something similar to this: <office:document-content ... > <office:automatic-styles ... > <office:body> <office:text> <!-- YOUR STUFF HERE --> </office:text> </office:body> </office:document-content> Note that I am taking some liberties to omit the elements I won't discuss, and I am sure you will forgive me for not listing all twenty-two namespace declarations in the root element. Once you have navigated to this point, note that the XML structure of your actual document material is stored in just a handful of "block-level" elements: <text:h ... >Your Heading Here</text:h> <text:p ... >Some paragraph of stuff here.</text:p> <text:list ... > <text:list-item ... > <text:p ... >First list item text here.</text:p> </text:list-item> </text:list> The "inline-level" (that is, the character-level) formatting entities occur in span elements: <text:p ... >Some <text:span ... >fancy text</text:span> here.</text:p> Aside from the container elements for tables and images, you know enough of the basic document structure to read or edit an OpenOffice.org file. Granted, there are still a few things worth knowing. Notably, in the above snippet examples, the ellipses are omitting the rather important "text:style-name" attribute that defines the formatting information for the material contained in that element. Before focusing attention on formatting styles, however, I want to mention a couple other pieces of information. As in all other word processors, Writer allows a "line break" that puts the cursor at the beginning of the next line without starting a new paragraph. The element for this is simply: <text:p ... >Blah blah blah<text:line-break/>yadda yadda.</text:p> You can get a line break in Writer by pressing SHIFT+ENTER instead of just ENTER. Also, the "list item" element above shows a single paragraph element. However, multiple paragraph elements are possible here. (Visually, you get a separated paragraph without an additional bullet or number.) You can get these in Writer in the following way: When you type text in a given list item, pressing ENTER takes you to the next list item; however, immediately pressing BACKSPACE once returns you in the previous list item but leaves you in a new paragraph. (And immediately pressing BACKSPACE a second time takes you out of the list mode entirely, returning you to a new standard paragraph.) Finally, as far as the content.xml file is concerned, bulleted and numbered lists are both just lists. The formatting style of the given list and list items determines whether a bullet or a number is used to represent it in the interface to the author. Formatting Styles Defined styles One thing that is not obvious to casual users of Writer is this: The most "correct" formatting your content in OpenOffice.org involves the use of pre-defined or user-defined styles in the "Styles and Formatting" tool. From here on, I will simply say "defined style" to mean both pre-defined and user-defined styles. There are style families for page-level entities (such as page and margin sizes), paragraph-level entities (which includes headers and titles), character-level entities (such as emphasis on just one word in a paragraph), and list entities. Note there are toolbar buttons in the Styles and Formatting tool window of OpenOffice.org that correspond to these families. The actual definitions of these defined styles—which font to use, what color the background is, and the like—is stored in the styles.xml file. Moreover, defined styles behave in an inheritance fashion within their family: A given defined style is related to a parent style. In nearly object-oriented fashion, a change to a top-level defined style formatting entity (such as text color) propagates downward through related descendant styles until those descendant styles override that formatting entity. Direct and controlled use of defined styles can give some nice control and semantic meaning to content that is otherwise totally lost in the hapless application of the usual formatting buttons. Sometimes, it is important to know "why" something is in a red font face, and a defined style preserves and conveys this meaning ... not to mention gives you one central location to change all the instances in the document to a blue font face instead. The name of the defined style in the styles.xml file generally matches the name the author sees in OpenOffice.org's interface. The biggest caveat to that statement is that special characters, including the space character, are converted to their hex-code value representation, which is then surrounded by underscores. (There is also the notable exception that the style seen as "Default" in the user interface is labeled as "Standard".) In other words, if an author applied the "Heading 1" defined style to a paragraph of text, the content.xml file would include: <text:h text:style-name="Heading_20_1" ... >Your Heading Here</text: h> The "Heading_20_1" style itself, as mentioned above, is detailed in the styles.xml file itself. These details include: - That it belongs to the "paragraph" family. - That its parent style is a style simply called "Heading" (which is a valid style to be used in the user interface, but which functions mostly like an abstract base class in programming parlance). - That, when the author presses ENTER, the style for the next section of text will automatically be set to the Text Body style. - That its text properties involve being bold and 115% larger than whatever the parent style (Heading, in this case) is set to. ... and so on. In other words, all the values and settings necessary to reconstitute the look, feel, and behavior of that style (and its parent styles all the way back to the Standard/Default style) are present in the styles.xml file. Automatic styles Here's the minor rub: Any time a document author drags through a paragraph or series of characters and uses a toolbar button—the Bold button, for example—they are not applying a defined style but are instead implicitly creating an "automatic style." Conceptually speaking, they store the same information. However, while the pre-defined and user-defined styles are stored in the styles.xml file, the automatic styles are stored in the content.xml file. (Go back to the XML snippet I showed for the content.xml file above and you'll see where the automatic styles element is located.) Even so, at some point (which is likely immediately), the automatic style references a defined "parent" style which is, as I've mentioned, present in the styles.xml file. As for their style names, automatic styles are created by combining a letter (such as "P" for paragraph style) with some integer. There is nothing particularly "special" about the naming convention ... it just seems to be a simple thing OpenOffice.org itself does when it saves information out to a file. You can carefully change the "P1" style to "foo_bar" and, so long as you update all such instances, the file should work. However, OpenOffice.org will likely rename it for you next time. (Beware the assumption that you can programmatically create an arbitrarily named automatic style and have its name survive a few editing sessions.) What this means is that, if you want to (programmatically) understand the formatting applied to some piece of text in the content.xml file, you'll probably have to first read through the automatic style and then trace back into the defined styles. Page 1 of 2
http://www.developer.com/xml/article.php/3653101/A-Brief-Introduction-to-OpenOfficeorg-Writer-Files.htm
CC-MAIN-2014-49
refinedweb
1,628
54.52
Entry points specification¶ Entry points are a mechanism for an installed distribution to advertise components it provides to be discovered and used by other code. For example: - Distributions can specify console_scriptsentry points, each referring to a function. When pip (or another console_scripts aware installer) installs the distribution, it will create a command-line wrapper for each entry point. - Applications can use entry points to load plugins; e.g. Pygments (a syntax highlighting tool) can use additional lexers and styles from separately installed packages. For more about this, see Creating and discovering plugins. The entry point file format was originally developed to allow packages built with setuptools to provide integration point metadata that would be read at runtime with pkg_resources. It is now defined as a PyPA interoperability specification in order to allow build tools other than setuptools to publish pkg_resources compatible entry point metadata, and runtime libraries other than pkg_resources to portably read published entry point metadata (potentially with different caching and conflict resolution strategies). Data model¶ Conceptually, an entry point is defined by three required properties: The group that an entry point belongs to indicates what sort of object it provides. For instance, the group console_scriptsis for entry points referring to functions which can be used as a command, while pygments.stylesis the group for classes defining pygments styles. The consumer typically defines the expected interface. To avoid clashes, consumers defining a new group should use names starting with a PyPI name owned by the consumer project, followed by .. Group names must be one or more groups of letters, numbers and underscores, separated by dots (regex ^\w+(\.\w+)*$). The name identifies this entry point within its group. The precise meaning of this is up to the consumer. For console scripts, the name of the entry point is the command that will be used to launch it. Within a distribution, entry point names should be unique. If different distributions provide the same name, the consumer decides how to handle such conflicts. The name may contain any characters except =, but it cannot start or end with any whitespace character, or start with [. For new entry points, it is recommended to use only letters, numbers, underscores, dashes and dots (regex [\w-.]+). The object reference points to a Python object. It is either in the form importable.module, or importable.module:object.attr. Each of the parts delimited by dots and the colon is a valid Python identifier. It is intended to be looked up like this: import importlib modname, qualname_separator, qualname = object_ref.partition(':') obj = importlib.import_module(modname) if qualname_separator: for attr in qualname.split('.'): obj = getattr(obj, attr) Note Some tools call this kind of object reference by itself an ‘entry point’, for want of a better term, especially where it points to a function to launch a program. There is also an optional property: the extras are a set of strings identifying optional features of the distribution providing the entry point. If these are specified, the entry point requires the dependencies of those ‘extras’. See the metadata field Provides-Extra (multiple use). Using extras for an entry point is no longer recommended. Consumers should support parsing them from existing distributions, but may then ignore them. New publishing tools need not support specifying extras. The functionality of handling extras was tied to setuptools’ model of managing ‘egg’ packages, but newer tools such as pip and virtualenv use a different model. File format¶ Entry points are defined in a file called :file: entry_points.txt in the :file: *.dist-info directory of the distribution. This is the directory described in PEP 376 for installed distributions, and in PEP 427 for wheels. The file uses the UTF-8 character encoding. The file contents are in INI format, as read by Python’s configparser module. However, configparser treats names as case-insensitive by default, whereas entry point names are case sensitive. A case-sensitive config parser can be made like this: import configparser class CaseSensitiveConfigParser(configparser.ConfigParser): optionxform = staticmethod(str) The entry points file must always use = to delimit names from values (whereas configparser also allows using :). The sections of the config file represent entry point groups, the names are names, and the values encode both the object reference and the optional extras. If extras are used, they are a comma-separated list inside square brackets. Within a value, readers must accept and ignore spaces (including multiple consecutive spaces) before or after the colon, between the object reference and the left square bracket, between the extra names and the square brackets and colons delimiting them, and after the right square bracket. The syntax for extras is formally specified as part of PEP 508 (as extras). For tools writing the file, it is recommended only to insert a space between the object reference and the left square bracket. For example: [console_scripts] foo = foomod:main # One which depends on extras: foobar = foomod:main_bar [bar,baz] # pytest plugins refer to a module, so there is no ':obj' [pytest11] nbval = nbval.plugin Use for scripts¶ Two groups of entry points have special significance in packaging: console_scripts and gui_scripts. In both groups, the name of the entry point should be usable as a command in a system shell after the package is installed. The object reference points to a function which will be called with no arguments when this command is run. The function may return an integer to be used as a process exit code, and returning None is equivalent to returning 0. For instance, the entry point mycmd = mymod:main would create a command mycmd launching a script like this: import sys from mymod import main sys.exit(main()) The difference between console_scripts and gui_scripts only affects Windows systems. console_scripts are wrapped in a console executable, so they are attached to a console and can use sys.stdin, sys.stdout and sys.stderr for input and output. gui_scripts are wrapped in a GUI executable, so they can be started without a console, but cannot use standard streams unless application code redirects them. Other platforms do not have the same distinction. Install tools are expected to set up wrappers for both console_scripts and gui_scripts in the scripts directory of the install scheme. They are not responsible for putting this directory in the PATH environment variable which defines where command-line tools are found. As files are created from the names, and some filesystems are case-insensitive, packages should avoid using names in these groups which differ only in case. The behaviour of install tools when names differ only in case is undefined.
https://python-packaging-user-guide.readthedocs.io/specifications/entry-points/
CC-MAIN-2019-22
refinedweb
1,092
55.24
Simple RSS Reader built in AIR for Mobile Tonight I whipped up a quick port of Mike Chamber’s code that demonstrates RSS parsing in ActionScript. I took his code and built a simple native AIR for Mobile application from it. The more I work with Flash Builder “Burrito” and Flex SDK “Hero” (the new AIR framework with mobile support), the more I really appreciate how easy Adobe has made mobile development. I’ve got a full application here that downloads a RSS feed, displays it nicely, and allows you to read the entry text. While this isn’t that special, what impresses me is that steps done to make it easy to create the application. For example, it’s trivial to tell the application to move from one screen to another. It’s trivial to pass data from one view to another. These are all things that aren’t terribly complex in a traditional AIR application - but frankly there is nothing at all wrong with making things even simpler. Let’s take a look at the code - and again - credit goes to Mike Chambers for the original. Let's start off with the first page of the application. This view is responsible for: - Getting the RSS from a remote feed, in my case, AndroidGator.com - Turning the RSS string into data. This is done with an open source library called as3syndicationlib - Setting the RSS items into a list. - Providing a way to click from the list into a detail </ul> Here is that template in full. I'm going to skip over the things covered in Mike's post. <?xml version="1.0" encoding="utf-8"?> <s:View xmlns: <fx:Declarations> <!-- Place non-visual elements (e.g., services, value objects) here --> </fx:Declarations> <fx:Script> <![CDATA[ import com.adobe.utils.XMLUtil; import com.adobe.xml.syndication.rss.Item20; import com.adobe.xml.syndication.rss.RSS20; import mx.collections.ArrayCollection; [Bindable] private var COMPANY: </s:layout> <s:List <s:Button </s:View> As I said, I won't bother discussing what Mike's post does, but let me point out a few things. I've got 3 variables that define how the application works and is displayed. COMPANY (which should really be SITE) is simply a label for the application. It tells you what site's RSS feed is being used. URL and RSSURL are the main URL and RSS feed URLs respectively. Make note of how we can load the main URL using the navigateToURL function. Nice and simple, right? Now take a look at the loadEntry function, repeated below. private function loadEntry(evt:Event):void { navigator.pushView(ItemView,{item:rssListing.selectedItem}); } This is exactly what I was talking about in terms of Adobe going out of it's way to simplify things. The pushView API does exactly what you would imagine - put up a view in front of the user. The second argument is a set of data that is passed into the view. This makes it easy to handle navigation between different views and pass data around. Love it. Here is how it renders. Now let's look at the rss item viewf. <?xml version="1.0" encoding="utf-8"?> <s:View xmlns: <fx:Declarations> <mx:DateFormatter </fx:Declarations> <fx:Style> @namespace s "library://ns.adobe.com/flex/spark"; @namespace mx "library://ns.adobe.com/flex/mx"; #titleValue { font-size: 20px; font-weight: bold; } </fx:Style> <fx:Script> <![CDATA[ import spark.components.supportClasses.MobileTextField; private function init():void { //credit to Brian Rinaldi: MobileTextField(bodyText.textDisplay).htmlText = data.item.description; dateValue.text = myDateFormat.format(data.item.pubDate); } ]]> </fx:Script> <s:actionContent> <s:Button </s:actionContent> <s:layout> <s:VerticalLayout </s:layout> <s:Label <s:Label <s:TextArea <s:Button </s:View> For the most part, this isn't anything special. Note how I make use of data.item.*. This is the RSS item I passed in with my pushView. Also make note of the button that let's me go back. I don't need this. The hardware itself has a back button. But I like having the obvious button there. Lastly, make note of the nice hack I got from Brian Rinaldi. This is - as far as I know - the only way to display HTML in a mobile component. I'm sure it will be corrected later. Here is how one typical RSS item renders in the application. And that's it. I've included a zip that includes all the source code. The zip also includes an APK file if you want to skip compiling it yourself. I've got an interesting idea for a follow up to this - and if I can stay off of Warcraft enough - I'll get it out tomorrow night.
https://www.raymondcamden.com/2010/12/08/Simple-RSS-Reader-built-in-AIR-for-Mobile
CC-MAIN-2019-30
refinedweb
789
67.86
>>." I want to see someone claim again (Score:5, Insightful) Now if only could PHP also fix their performance and inconsistencies.. Re: su Re: (Score:3, Funny) Right. PHP's the fastest language out there, as proven in this test [debian.org]. Re: (Score:2) Perl is usually better [debian.org] as well, as is Python, Tcl, etc. In PHP's defense, how does performance compare once some sort of accelerator is involved? Are those fancy output caching engines or do they actually precompile/cache the code or something like that?: (Score:1, Flamebait) If you tried using Mono/C# in a real world situation you'd find that it would be horrible because it would run as a CGI. The initialization for it would kill the server. I notice that none of the tests were remotely related to a web page as well. How the hell is Mandelbrot relevant? Re: (Score:2) Or perhaps even build an interpreter into the web server itself (mod_mono). Spped problems eliminated. Re: (Score:2) mod_mono actually just sends the request to a mod_mono_server, which is a special version of the Mono ASP.NET web server that has a special interface. mod_mono's advantage is the ability to manage the mod_mono_server processes for you, while using standard HTTP proxying would require the user to start the process on their own. It is pretty similar to server-side Java. FastCGI support [mono-project.com] for Mono would be nice so that non-Apache servers cou Re: (Score:1, Troll) I don't think there's many high-perormance websites out there that work using forking (standard CGI). In fact, IIRC Mono doesn't even support working as CGI, and I'm pretty sure Java doesn't as well. They only support running via an external process server (much like Java), e.g. via FastCGI, local proxying, or a special webserver/process s Re: (Score:3, Insightful) Heck you can make a bash script output your website for you. Or even QBASIC. Re: (Score:2) Re: (Score:2) It wont work or you wont get support if you bork your system doing it? Re: (Score:2) CGI is unsuitable for any high-performance website, anyway. Re:I want to see someone claim again (Score:5, Informative) There are plenty of good criticisms for PHP (and every other language), but performance is only a factor in PHP web apps when the programmers do really stupid things. Re: (Score:1, Insightful) What you're saying: PHP is only good for gluing your DB to your HTML, straight procedural code. But that was true Re: (Score:2) care to site benchmarks? I saw one that had zend framework doing horribly as well. They were using version 0.4 beta. They're up to Re: (Score:2) Re: (Score:2) Re: (Score:2) What's also important is that PHP is meant to be parallelized, which lets it scale better to higher traffic. The l: (Score:1) Re: (Score:1) Re: (Score:2) I'm not against monetization, but if I don't understand what the provider is getting out of it, it makes me uneasy about using the service even if I like the service. Comparing mono with C# is unfair (Score:2, Interesting):I want to see someone claim again (Score:4, Informative) So how worried you should be about PHP security comes down to whether you'll be running your own code you trust, or hosting someone else's code you don't trust. Re: (Score:2) The only way to get this kind of security is to rely on the operating system to provide it for you; this is done by running PHP interpreters belonging to different security contexts as seperate users. With such a setup, the worst the user can do is screw up their own files (boo hoo!). Re: (Score:2) Re: (Score:2) That way, all the PHP code is executing as the individual web hosting user, and not as the global apache user. Thus: A bug in one user's site compromises their own account, but cannot mess with any of the other accounts. You cant stop users running buggy code, and its their own fault if they do. But you certainly should keep that code in a sandbox. Re: (Score:2) I'm using it, it works just fine... Even supports eaccelerator too. Re: (Score:1) It's not that simple. In the case of web hosts with the open_basedir restriction in effect, you can't *open() or system() anything outside the basedir. It's a pretty effective jail. Here's an excerpt from the open_basedir documentation [php.net]: Re: (Score:2) I think the month of bugs helps consumers in the long term, but its certainly a bitch for the vendor to get flooded with tons of holes at once. Re: (Score:1) I've never had a script break with version jumps (including 4 to 5) because I write good proper code. Some older crap wont work on PHP 5 but why would you want to run crap? Re: (Score:2) Besides, if Zend added the code to begin with how does one seperate what is going to go away from what is useful? Are they supposed to read minds? Seems very much like random windows apis that disappear or change. Re: (Score:2) Care to provide examples of either? Re: (Score:3, Funny) Re: (Score:3) Re: (Score:2): (Score:2, Interesting) Yep, there still is. I think you are thinking about this one: perfo: (Score:1) As far as the thread-safe issue goes, [IMO] it has always been better to run Apache under a process-based MPM, as it's: 1) more secure, isolating 2) more stable The common misconception of the performance penalty arises more from the lack of any further MPM configuration to the specific task and system. Re: (Score:2) Oh, you forgot: 5,343 built-in functions [php.net], assuming all the standard modules are installed. By comparison Python has 71 [python.org]. In other words, you have to keep track of about 75 times the number of name collisions when dealing with PHP versus Python. This could be almost instantly fixed if they'd add namespaces to PHP, but that keeps getting shot down. Re: (Score:2) Re: (Score:2) Yep. They were removed from 5.0.0 beta 2 [php.net] for various reasons [sitepoint.com]. Re: (Score:1) Bad release practices (Score:5, Insightful) See, for example, the 4.6.6 release notes [php.net]: Thank god Python doesn't do that. At least they keep all the big changes to individual versions! Re: (Score:1, Insightful) If you use register_globals, you deserve all bugs that hit you. Period. Re: (Score:1) Or maybe not? Re: (Score:1) Re: (Score:2) $msg = preg_replace('/register_globals/', 'php', $msg); Re: (Score:1) msg=msg.replace('register_globals, 'php') Re: (Score:2) Re: (Score:2) Re: (Score:2) Re:Bad: (Score:2) Re: (Score:2) Re: (Score:2) Re:Bad release practices (Score:4, Informative) Re: (Score:2) Re: (Score:2) Re: (Score:2) Re: (Score:3, Informative) I also recommend reading over PEP 0008 [python.org], the "standard" coding structure for the Re: (Score:2) I used to fall on the spaces side until I realized how iritating it is to respace things when you move down an indentation level and you're not using an IDE. I've been a staunch tab supporter ever since. It's not just that, either. If one uses tabs, then anyone else who has to edit it can set the tab size to whatever they wish. If Paul has a super widescreen monitor and wants his tab size set to 16 characters, more power to him! If George has a super small monitor and Re: (Score:2) The Tab key is not a shortcut for pressing space 8 times, damnit! Re: (Score:2) some_call(arg1, arg2, arg3, arg4) but moved over, obviously. If you used tabs in there instead of spaces, and someone changes their tab size, your code instantly becomes completely unreadable. Re: (Score:2) (I haven't learned Python yet, so I'm just guessing) Re: (Score:2) Tabs should be used for the initial indentation. Once you reach the indentation level that you want, use spaces to line things up (the clue is in the name... you can't "line things up" by using a spacing character that has a variable length... so don't!) Re: (Score:1) To answer your question, though, Python doesn't "like" mixing tabs and spaces. It's also nice that almost all Python code follows "PEP 8". When interviewing for Python-heavy positions, for instance, I can ask if they know what PEP 8 syntax is. If they've never even heard of it, they aren't really interested in the language as far as I'm concerned. I wasn't a fan of spaces, either, until I switched into Python as my language o Hate to whine, but... (Score:2) I failed to include support for curl when 5.2.1 came out and just spent close to an hour waiting for PHP 5.2.1 to compile, yesterday. Guess it's time to run ./configure again.: (Score:1) Re: . Honestl Re: (Score:1) Re: (Score:1) Re: (Score:2) Are you implying that those two items are mutually exclusive? I would be very impressed with any software project beyond "Hello World" that has never had a security problem. Having said that, a lot of the negative reputation is because people who haven't written more than 10 lines of PHP code think that phpBB and phpNuke demonstrate the only possible way to write PHP. Any language that lets you ru Re: (Score:1) yeah yeah yeah (Score:1, Redundant) Re: . T Re: (Score:1) It has been discussed before that many of the larger hosts (GoDaddy, et al) run simple RedHat installations with specific packages of Apache, PHP and MySQL that the Re: (Score:2) I can understand that it's not practical to upgrade existing code just for the sake of upgrading. But for new projects, I think maybe you're holding yourself back. Missing file from 5.2.2 for Win32: php_xmlrpc.dll (Score:1) [php.net] The file can be obtained from the latest snapshot, though: [php.net] Updating (Score:1) better (Score:1) Re: (Score:2) [secunia.com] So yes, while PHP's advisories are about 10 orders of magnatude more numerous than Tomcat's, it still "bug that would let a remote user execute code or change configuration settings or read files or doing a double-free or any of that kind of thing". And trust me, it's just as easy to create fragile code in Java that can open your server like goatse as it is in Re: (Score:1, Informative) Re: (Score:3, Insightful) Unfortunately, mod_php is still more programmer and administrator friendly than mod_perl, which probably explains why it has a higher usage rate. Try Fastcgi (Score:2) With fastcgi you can use perl, python, ruby, C++ or whatever - just like yo Re: (Score:2) Re: (Score:2) The mod_perl stuff tries to do the persistent DB stuff but in a kludgy untidy way that has a lot more gotchas. Same for PHP's mysql_pconnect. Go see people say "turn off persistent DB connections" in one answer and then "turn on persistent DB connections" in another answer I've tried mod_perl, FastCGI is cleaner, Re: (Score:1, Insightful) If people like you were right, we'd all have ditched perl long ago because of the phf bug. PHP, like any software has its holes, but a properly secured sy
https://developers.slashdot.org/story/07/05/04/2156256/php-522-and-447-released?sdsrc=nextbtmprev
CC-MAIN-2017-22
refinedweb
1,963
71.65
Users can subscribe to (or follow) a section in the knowledge base, but the Help Center doesn't list the section followers. This tutorial describes how to use the API to list the followers of a specified section in your knowledge base. Subjects like sideloading and pagination are covered along the way. The scripting language used is Python, a powerful but beginner-friendly programming language with a clear and readable syntax. If you work in another language, you should still be able to follow the code logic and adapt it to your script. The logic is similar in all languages. The API requests in the tutorial are authenticated using an API token. Therefore, the script should only be used internally. If you want to make the functionality more widely available, you should switch to OAuth authentication. Topics covered: - What you need - The plan - Get the section id from the user - Make the request - Sideload the users - Paginate through the results - Code complete - Feature enhancement: Get article followers - Appendix: Using Perl What you need You need a text editor and a command-line interface like the command prompt in Windows or the Terminal on the Mac. You'll also need Python 3.2 or greater.2 or 3.3, download and install pip if you don't already have it. pip is plan is to create a script that lets a user specify a section id on the command line and lists all the followers when the user hits Enter. Example: $ python3 list_followers.py 234304094 >> Chuck Brown >> George Lukas >> Attila Hon ... The subscriptions API gets the followers of a section. However, the API returns user ids, not actual user names. You'll also need to get the names from the users API. To avoid unneccesary API requests, you can sideload the users with the subscriptions. Sideloading lets you download two or more recordsets in a single request. The subscriptions API only returns 30 subscriptions at a time, so the script also needs to paginate through all the results to make sure it doesn't skip anyone. Here are the script's basic tasks: Get the section id from the user In a text editor, create a text file and save it as list_followers.py. Enter the following lines at the top of the file: import argparse parser = argparse.ArgumentParser() parser.add_argument("id") The script imports the built-in argparsemodule, which provides access to command-line arguments. The script then creates an ArgumentParser object and defines one command-line argument named id. Grab the argument value the user entered on the command line and assign it to a variable: args = parser.parse_args() hc_id = args.id If all goes well, the user should enter a section id on the command line after the script name. Example: $ python3 list_followers.py 123456789 If the user forgot to specify an id, the script displays an error message and exits: $ python3 list_followers.py usage: list_followers.py [-h] id list_followers.py: error: the following arguments are required: id Make the request The next step is to configure the API requests. You'll use the requests library, a third-party Python library for making HTTP requests. You should have installed it earlier. See What you need. Import the requests library at the top of the file: import requests ... Create a requests Sessionobject and configure it with your authentication information: session = requests.Session() session.headers = {'Content-Type': 'application/json'} session.auth = ('your_user_email/token', 'your_api_token') The Sessionobject is useful for making multiple requests, such as when paginating through API results. The session.authproperty specifies your Zendesk Support sign-in email and API token. Replace your_user_email and your_api_token with your information, making sure '/token' stays appended to your email. You can grab an API token from the Zendesk Support admin interface at Admin > Channels > API.Note: You should only use the script internally with an API token. If you want to make it more widely accessible, you should switch to OAuth authentication. Construct the url for the request: zendesk = '' endpoint = '/api/v2/help_center/sections/{}/subscriptions.json' url = zendesk + endpoint.format(hc_id) The endpoint is listed as follows in the Subscriptions API doc: GET /api/v2/help_center/sections/{section_id}/subscriptions.json The script combines your Zendesk Support url with the endpoint url. Replace your_subdomain with your information. The format()method replaces the {}placeholder in the url with the value of the hc_id variable. Make the API request and assign the response to a variable: response = session.get(url) Check the response for errors and exit if any are found: if response.status_code != 200: print('Failed to get followers the JSON response into a Python data structure and assign it to a variable. The line should be flush with the left margin. data = response.json() The Zendesk API returns data formatted as JSON. The json()method from the requests library decodes the JSON into the equivalent Python data structure to make it easier to manipulate. Consult the Zendesk API docs to figure out how the response data is structured in Python. For example, according to the subscriptions API doc, the JSON returned by the API has the following structure: { "subscriptions": [ { "id": 35467, "user_id": 888887, "source_type": "Section", ... }, ... ] } You can deduce from the doc that the decoded data is a Python dictionary with one key named subscriptions. Its value is a list of subscriptions, as indicated by the square brackets. Each item in the list is a dictionary of subscription properties, as indicated by the curly braces. A dictionary is simply a set of key/value pairs formatted almost identically to JSON. Example: {'id': 35436, 'user_id': 88887} Equipped with this knowledge of the data's structure, you can add the following temporary snippet to check the results so far: for subscription in data['subscriptions']: print(subscription['user_id']) The snippet iterates through the value of the 'subscriptions' key (a list of subscriptions) and prints the value of the 'user_id' key of each subscription. You can do a test run on the command line as follows, replacing the section id with one of your own: $ python3 list_followers.py 234567891 When you're done testing, delete the test snippet from the script. As you problably noticed, the subscriptions API only returns the user id, not the user name. You'll need to get the names from the users API, as described in the next section. Sideloading users Because the subscriptions API returns user ids, not actual user names, you'll need to get the names from the users API. To avoid unneccesary API calls, you can sideload the users along with the subscriptions. Sideloading lets you download both recordsets in a single request. Where previously the response data consisted of a dictionary with a single 'subscriptions' key, the updated data will have an additional key named 'users' containing a list of all the users mentioned in the subscriptions: { 'subscriptions': [ { 'user_id': 7, ... }, ... ], 'users': [ { 'id': 7, 'name': 'Bob Bobberson', ... } ] } Critically, sideloading doesn't get all the users in your Zendesk Support instance. It gets only the users specified in the subscriptions. So listing a section's followers becomes a simple matter of listing the names of the sideloaded users. Adapt your script as follows to list the followers. To sideload the users, add an ?include=usersparameter to the endpoint url: endpoint = '.../subscriptions.json?include=users' At the end of the script, print the names of the section's followers: for user in data['users']: print(user['name']) The script will list the users of the first 30 subscriptions and stop. In the next section, you'll check for more results and paginate through them to make sure you get every follower. Paginate through the results For bandwidth reasons, the API doesn't return large record sets all at once. It breaks up the results into smaller subsets and returns them in pages. The number of items per page varies by endpoint. The subscriptions endpoint returns 30 items per page. After each request, the script should check to see if more results exist. The JSON response contains a next_page property with the URL of the next page of results, if any. Example: "subscriptions": [ ... ], "next_page": "", ... If there's no next page, the value is null: "subscriptions": [ ... ], "next_page": null, ... With this information, the script can paginate through the results. Just before script makes the request, create a list variable to cumulatively store the users found while paginating through the results: users = [] ... Indent the request block under a new whilestatement, as follows: users = [] while url: response = session.get(url) if response.status_code != 200: print('Failed ...') exit() data = response.json() The block runs while url has a value. It stops running when url is null, such as when the last page is reached. After getting data in a response, add the list of users to the cumulative total: ... if data['subscriptions']: users.extend(data['users']) First, make sure to check the initial request returned at least one subscription. If the section doesn't have any subscriptons, then the data['users']variable won't exist and you'll get an error when you try to use it. The extend()method in Python adds the contents of one list (in this case data['users']) to another list (the users list you declared before the loop). Get the url of the next page of results: ... url = data['next_page'] If the value is null, which Python considers false, the script exits the loop. In the for loop that prints the followers, change the list variable from data['users'], which contains only a subset of users, to users, which contains the cumulative list of all the users: for user in users: print(user['name']) After the updates, the final part of the script should look like this (ignore the line breaks cause by the margins): ... users = [] while url: response = session.get(url) if response.status_code != 200: print('Failed to get followers with error {}'.format(response.status_code)) exit() data = response.json() if data['subscriptions']: users.extend(data['users']) url = data['next_page'] for user in users: print(user['name']) Code complete Feature enhancement: Get article followers As well as sections, users can also follow articles in Help Center. You can modify the script to list article followers too. Users can include a command-line flag like -a or -s to specify whether the id they enter on the command line refers to an article or section. Example: $ list_followers.py -a 998877665 To upgrade the script to support article followers: Add two new arguments to your parser object near the top of the file, after creating the object but before parsing the args: ... parser.add_argument('-s', action='store_true') parser.add_argument('-a', action='store_true') ... If the user specifies one of the arguments, the script assigns it the value of True. Not specifying it implies False. In the section that builds the request url, replace the endpointvariable declaration with the following ifblock (ignore the line breaks): if args.a: endpoint = '/api/v2/help_center/articles/{}/subscriptions.json?include=users' else: endpoint = '/api/v2/help_center/sections/{}/subscriptions.json?include=users' If the user specifies the -aflag, the script uses the list article subscriptions endpoint. By default if the user doesn't specify a flag, the script uses the list section subscriptions endpoint. To learn more, see the Argparse tutorial on the Python website. Appendix: Using Perl You can create and run the script with Perl. The syntax is slightly different but the logic is the same. See the previous sections if something in the flow isn't clear. To run the script, you'll need to install Perl on your computer if you don't already have it. If you use a Mac, Perl is probably already installed. Run the following command in Terminal to find out: perl -v. If you don't have Perl or have a version older than 5.10 on Mac or Windows, see to download and install the latest stable version. On the Mac, Perlbrew (perlbrew.pl) is a useful tool for managing Perl installations. After installing Perl, download and install the following modules if you don't already have them: See these instructions to install the modules. The LWP modules are for communicating with the REST API. The JSON module is for reading and converting the JSON data returned by the API. Here's one way to write the script. Make sure to replace your_zd_email, your_api_token, and your_subdomain with your information. If you're interested in learning Perl for your projects, see the following resources: - Learn Perl in about 2 hours 30 minutes by Sam Hughes - Perl Programming by tutorialspoint.com - Learning Perl, 6th Edition, by Randal L. Schwartz Really helpful article. I've written the code with Python, but what I need to do next to integrate my API? Thank you! Charles, your excellent article helped me finally create a list of followers to a section of articles. (I cannot believe zendesk doesn't offer this as basic functionality 101, listing section followers, but it is what it is.) I am not a coder but was able to follow your instructions above and get the python file to work. It has done so for several weeks, then today it has run but listed only 3 names, where I expected 20+. I haven't changed anything about the .py file since authoring it, so wonder what could cause this reduction/error. (It is not 20 people unfollowing as I have confirmation they received a recent article posting). Thanks for your help. Michael Hi Mike, Hard to tell what's going on. I tested the script again to check for any change in the JSON attribute names since I wrote it, but everything still seems to be working for me. Is there something in common with the users who are actually listed? For example, are they all agents? Charles, The three people being listed are customers who follow a section we have called AO Enhancements (AO is our software). The full list of 20+ that was being reported did include three agents. I do need to get this resolved quickly, as we are adding new customers and I need to be able to track software enhancement followers. Should I submit a help request, or can I send you my .py file to run and diagnose? Thanks for your support. Michael Hi Mike, Can you send me your Python file with the credentials removed? Also, can you send me the Help Center settings for the section in question? Click the section name, then click Edit. I'm particularly interested in the Who Can View? setting. Thanks. Hi Mike, I think I found the problem. The last 2 lines of your script to print the results are: The first line of the snippet should be: The users variable is where you cumulatively save the user records if the API returns multiple pages of results. The data['users'] variable is different. It contains only the page of results returned by the API. For the subscribers API, each page consists of a maximum of 30 records. If more than 30 people subscribe to a section, then the API returns a second page of results with only the additional people. The contents of data['users'] consists of only those records. And so on when you reach 60 +1 subscribers. Your script worked when you had less than 30 subscribers. As soon as you had over 30 subscribers, the value of data['users'] at the end of the script only contained the second page of results -- I think 3 users in in your case. However, all 33 users were stored in the users variable. Hope this makes sense. Charles Charles, sorry for the delay in responding, vacation. Your adjustment to the code worked perfectly. Thank You. Up and running again. Please sign in to leave a comment.
https://help.zendesk.com/hc/en-us/articles/229136987-Listing-the-followers-of-a-KB-section-with-the-Zendesk-API-
CC-MAIN-2017-39
refinedweb
2,628
66.03
import arcpy from arcpy import env ## Change this to your workspace location env.workspace = "C://WEXFORD//DATA" ## Change this to your spreadsheet and workbook name inTable = "C://WEXFORD//DATA//calculator.xlsx/sheet1$" outLocation = ""C://WEXFORD//DATA" outTable = "cal" arcpy.TableToTable_conversion(inTable,outLocation,outTable) I'm not entirely sure about why you're getting that error, but can tell you that you can't use Excel tables with GP Services in 10.1. You can use excel as a FILE (there are Python modules which read excel FILES...) But ArcGIS Server cannot use Excel TABLES (the sheet you reference in your code with $). You'll have to replace the excel table, or access it with other Python modules as a file.
https://community.esri.com/t5/geoprocessing-questions/accessing-excel-data-when-publishing-python-script/td-p/154167
CC-MAIN-2022-33
refinedweb
120
56.86
and we are back to the regular craziness ~~ for intro to PCB I’ll focus on last semester’s project I’ve done for Wearables Techonology class: an elbow patch for bikers. It has a fringe (fabric + fiber optic) that you could swipe (indicating if you are turning left/right) and lights up when it gets dark. for some reason vimeo is rotating the video but this is the last version of it: even though it worked as it should, this is how the circuit was inside it: it’s a mess and it’s tiny. this was the first time i did a perf board and it was really fun but i was kind of scared of soldering things wrongly and shortening the circuit. I had a lilytiny (just a attiny85 on a pcb) connected to a: photoresistor, a tiny servo motor and an LED. and the lilytiny was also connected to an energy converter (i needed more amperage to make the servo work) + the LiPo battery. list of materials/components: ATtiny85 (lilytiny PCB board) HS-35HD Servo Super bright LED Toggle Switch Lithium Ion Battery (3.7v / 500mAh) PowerBoost 500 Charger Schematic: Code : #include <Adafruit_SoftServo.h> // SoftwareServo library #define SERVO1PIN 4 // Servo control line (orange) on Trinket Pin #0 Adafruit_SoftServo myServo1; //create servo object int pos = 0; // variable to store the servo position int photoPin = 3; int ledPin = 1; int brightness; int sensorValue; void setup() { // Set up the interrupt that will refresh the servo for us automagically OCR0A = 0xAF; // any number is OK TIMSK |= _BV(OCIE0A); // Turn on the compare interrupt (below!) myServo1.attach(SERVO1PIN); // Attach the servo to pin 0 on Trinket pinMode(ledPin, OUTPUT); //LED on Model A or Pro pinMode(photoPin, INPUT); //photosensor } void loop() { sensorValue = analogRead(photoPin); brightness = map(sensorValue, 0, 1023, 255, 0); analogWrite(ledPin, brightness); for (pos = 0; pos <= 180; pos += 10) // goes from 0 degrees to 180 degrees { // in steps of 1 degree myServo1.write(pos); // tell servo to go to position in variable 'pos' delay(15); // waits 15ms for the servo to reach the position } for (pos = 180; pos >= 0; pos -= 10) // goes from 180 degrees to 0 degrees { myServo1.write(pos); // tell servo to go to position in variable 'pos'(); } }Leave a Comment
http://www.gauirenata.com/category/fall-2016/pcb/
CC-MAIN-2020-34
refinedweb
374
50.2
Hello Everyone, I've a problem with java & SQLServer 2005 interface, i installed a SQLServer 2005 and SP2 software bundle to enable SQLServer to run on Windows Vista, i'm using the "Windows Authentication" in SQLServer 2005 which don't need the username or password, and i've the classpath to jar archive Microsoft JDBC-ODBC driver, i've used the following sample code which comes with Microsoft dirver package. import java.sql.*; public class connectURL { public static void main(String[] args) { // Create a variable for the connection string. String connectionUrl = "jdbc:sqlserver://127.0.0.1:1433;" + "databaseName=msdb some data. String SQL = "SELECT TOP 10 * FROM Person.Contact"; stmt = con.createStatement(); rs = stmt.executeQuery(SQL); // Iterate through the data in the result set and display it. while (rs.next()) { System.out.println(rs.getString(4) + " " + rs.getString(6)); } } // Handle any errors that may have occurred. catch (Exception e) { e.printStackTrace(); } finally { if (rs != null) try { rs.close(); } catch(Exception e) {} if (stmt != null) try { stmt.close(); } catch(Exception e) {} if (con != null) try { con.close(); } catch(Exception e) {} } } } When i tried to run to code above i get the following error: com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host 127.0.0.1, port 1433 has failed. Error: Connection refused: connect. Please verify the connection properties and check that a SQL Server instance is running on the host and accepting TCP/IP connections at the port, and that no firewall is blocking TCP connections to the port. So, i absolutly run the SQLServer Manag. Studio, i've checked my IP address, and ports but also have the problem could someone help me for URGENT. Thanks in advance :)
https://www.daniweb.com/programming/software-development/threads/156783/help-in-java-and-sql-server-2005-interfacing
CC-MAIN-2017-17
refinedweb
283
61.33
Question: Suppose a firm uses a constant WACC to calculate the Suppose a firm uses a constant WACC to calculate the NPV of all of its capital budgeting projects, rather than adjusting for the risk of the individual projects. What errors will the firm make in its capital budgeting decisions? View Solution: View Solution: Answer to relevant QuestionsA firm has the following capital structure based on market values: equity 65 percent and debt 35 percent. The current yield on government T-bills is 2 percent, the expected return on the market portfolio is 10 percent, and ...What is the cost of equity (Ke) given RF = 2%, beta (β) = 1.5, expected market return (ERM) =12%?What is the intercept and slope of the financial leverage (ROE-ROI) line in Practice Problem 13? Explain the meaning of the slope. What is the pecking order according to Myers’ argument?In the M&M no-tax world, calculate the value of the levered firm (VL). Cost of unlevered equity (KU) = 15%; cost of debt (KD) = 7%; debt (D) = $400,000; and NI = $520,000. What is the cost of levered equity?Describe the factors that can affect a firm’s capital structure in practice. Post your question
http://www.solutioninn.com/suppose-a-firm-uses-a-constant-wacc-to-calculate-the
CC-MAIN-2017-30
refinedweb
204
65.93
, suggested reading at the top). First I'm going to throw a whole bunch of code at you. This example contains the basics for setting up a KDE application gui and connecting a button to a dbus method._ () Lets go through this example to try and understand it. First we import the libraries that are needed to make it all work. Most of the Qt and KDE ones should be familiar to you, but to get dbus we need the one at the end: "import dbus". Now we have imported our libraries, we need to write our main window. In the __init__ (constructor, for the C++ people here) method, we set up the dbus connections: self.sessionBus = dbus.SessionBus() self.powerdevil = self.sessionBus.get_object('org.freedesktop.PowerManagement', '/modules/powerdevil') Because the org.freedesktop.PowerManagement is on the Session Bus, we create an object self.sessionBus that represents that bus. We also grab our powerdevil Object via its path /moddules/powerdevil. We can now call methods on the object, but first we need to set up the gui framework, a button and its connection (via Qt signals/slots) to a python method that will call the dbus method.) If you need help understanding the above, you should consult the reading list linked at the top of this page. We now need to define the self.screenOff method that we have just connected to the button. def screenOff(self): self.powerdevil.turnOffScreen(dbus_interface='org.kde.PowerDevil') It's relatively simple. We call the method turnOffScreen() on our powerdevil object (the method turnOffScreen was shown on the interface org.kde.PowerDevil in qdbusviewer) The rest of the application sets up the KDE app and populates it with author/name info. Again, if you need help with that, see the other reading linked to from the top of this tutorial.
https://techbase.kde.org/index.php?title=Development/Languages/Python/PyKDE_DBus_Tutorial&diff=40066&oldid=40009
CC-MAIN-2015-32
refinedweb
307
66.44
Important: Please read the Qt Code of Conduct - Apple Silicon The pyside2 code cannot run on Apple Silicon, the process exists, but no window will pop up.! alt text Code Like This: import sys from PyQt5.QtWidgets import QApplication, QWidget if name == 'main': app = QApplication(sys.argv) w = QWidget() w.setWindowTitle('Test') w.show() sys.exit(app.exec_()) @JerryMazeyu Your link is broken. Do you see any errors/warnings when starting from a terminal? Also, you are talking about PySide, but in the code you posted you're using PyQt. Both pyside and pyqt have the same result. When I run this code on latest MAC, this icon pop up but I cannot see any QT window. And my code does not report errors. I dont know why. @JerryMazeyu Please start your app from a terminal and check there whether there are any errors/warnings. @JerryMazeyu Is your python native ARM build or x86? This Python virtual environment is migrated from x86 Macbook. @JerryMazeyu But is the Python interpreter ARM or x86 build? @jsulm This python environment is built on x86, translated by Rosetta2 and run on the ARM architecture Mac. @JerryMazeyu You should check the Qt libs from PySide/PyQt you're using: whether those are also x86 (most probably they are). @JerryMazeyu On Linux file PATH_TO_A_LIB_FILE Should be same on MacOS. @JerryMazeyu Yes, so that is not the issue. You can try to run your script through the Python debugger. Well, I fix this bug... The problem seems to be in anaconda. I migrate my anaconda from old x86 MacBook. When I try to change the interpreter to my real system environment /usr/loacl/bin/python3.7, it works. Thx a lot!@jsulm
https://forum.qt.io/topic/121810/apple-silicon
CC-MAIN-2021-10
refinedweb
285
78.04
This file is fc.def, from which is created fc.c. It implements the builtin "fc.c $BUILTIN fc $FUNCTION fc_builtin $DEPENDS_ON HISTORY $SHORT_DOC fc [-e ename] [-nlr] [first] [last] or fc -s [pat=rep] [cmd] fc is used to list or edit and re-execute commands from the history list. FIRST and LAST can be numbers specifying the range, or FIRST can be a string, which means the most recent command beginning with that string. -e ENAME selects which editor to use. Default is FCEDIT, then EDITOR, then vi. -l means list lines instead of editing. -n means no line numbers listed. -r means reverse the order of the lines (making it newest listed first). With the `fc -s [pat=rep ...] [command]' format, the command is re-executed after the substitution OLD=NEW is performed. A useful alias to use with this is r='fc -s', so that typing `r cc' runs the last command beginning with `cc' and typing `r' re-executes the last command. $END #include <config.h> #if defined (HISTORY) #ifndef _MINIX # include <sys/param.h> #endif #include "../bashtypes.h" #include "posixstat.h" #if ! defined(_MINIX) && defined (HAVE_SYS_FILE_H) # include <sys/file.h> #endif #if defined (HAVE_UNISTD_H) # include <unistd.h> #endif #include <stdio.h> #include <chartypes.h> #include "../bashansi.h" #include "../bashintl.h" #include <errno.h> #include "../shell.h" #include "../builtins.h" #include "../flags.h" #include "../bashhist.h" #include "maxpath.h" #include <readline/history.h> #include "bashgetopt.h" #include "common.h" #if !defined (errno) extern int errno; #endif /* !errno */ extern int current_command_line_count; extern int literal_history; extern int posixly_correct; extern int unlink __P((const char *)); extern FILE *sh_mktmpfp __P((char *, int, char **)); extern int delete_last_history __P((void)); /* **************************************************************** */ /* */ /* The K*rn shell style fc command (Fix Command) */ /* */ /* **************************************************************** */ /* fc builtin command (fix command) for Bash for those who like K*rn-style history better than csh-style. fc [-e ename] [-nlr] [first] [last] FIRST and LAST can be numbers specifying the range, or FIRST can be a string, which means the most recent command beginning with that string. -e ENAME selects which editor to use. Default is FCEDIT, then EDITOR, then the editor which corresponds to the current readline editing mode, then vi. -l means list lines instead of editing. -n means no line numbers listed. -r means reverse the order of the lines (making it newest listed first). fc -e - [pat=rep ...] [command] fc -s [pat=rep ...] [command] Equivalent to !command:sg/pat/rep execpt there can be multiple PAT=REP's. */ /* Data structure describing a list of global replacements to perform. */ typedef struct repl { struct repl *next; char *pat; char *rep; } REPL; /* Accessors for HIST_ENTRY lists that are called HLIST. */ #define histline(i) (hlist[(i)]->line) #define histdata(i) (hlist[(i)]->data) #define FREE_RLIST() \ do { \ for (rl = rlist; rl; ) { \ REPL *r; \ r = rl->next; \ if (rl->pat) \ free (rl->pat); \ if (rl->rep) \ free (rl->rep); \ free (rl); \ rl = r; \ } \ } while (0) static char *fc_dosubs __P((char *, REPL *)); static char *fc_gethist __P((char *, HIST_ENTRY **)); static int fc_gethnum __P((char *, HIST_ENTRY **)); static int fc_number __P((WORD_LIST *)); static void fc_replhist __P((char *)); #ifdef INCLUDE_UNUSED static char *fc_readline __P((FILE *)); static void fc_addhist __P((char *)); #endif /* String to execute on a file that we want to edit. */ #define FC_EDIT_COMMAND "${FCEDIT:-${EDITOR:-vi}}" #if defined (STRICT_POSIX) # define POSIX_FC_EDIT_COMMAND "${FCEDIT:-ed}" #else # define POSIX_FC_EDIT_COMMAND "${FCEDIT:-${EDITOR:-ed}}" #endif int fc_builtin (list) WORD_LIST *list; { register int i; register char *sep; int numbering, reverse, listing, execute; int histbeg, histend, last_hist, retval, opt; FILE *stream; REPL *rlist, *rl; char *ename, *command, *newcom, *fcedit; HIST_ENTRY **hlist; char *fn; numbering = 1; reverse = listing = execute = 0; ename = (char *)NULL; /* Parse out the options and set which of the two forms we're in. */ reset_internal_getopt (); lcurrent = list; /* XXX */ while (fc_number (loptend = lcurrent) == 0 && (opt = internal_getopt (list, ":e:lnrs")) != -1) { switch (opt) { case 'n': numbering = 0; break; case 'l': listing = 1; break; case 'r': reverse = 1; break; case 's': execute = 1; break; case 'e': ename = list_optarg; break; default: builtin_usage (); return (EX_USAGE); } } list = loptend; if (ename && (*ename == '-') && (ename[1] == '\0')) execute = 1; /* The "execute" form of the command (re-run, with possible string substitutions). */ if (execute) { rlist = (REPL *)NULL; while (list && ((sep = (char *)strchr (list->word->word, '=')) != NULL)) { *sep++ = '\0'; rl = (REPL *)xmalloc (sizeof (REPL)); rl->next = (REPL *)NULL; rl->pat = savestring (list->word->word); rl->rep = savestring (sep); if (rlist == NULL) rlist = rl; else { rl->next = rlist; rlist = rl; } list = list->next; } /* If we have a list of substitutions to do, then reverse it to get the replacements in the proper order. */ rlist = REVERSE_LIST (rlist, REPL *); hlist = history_list (); /* If we still have something in list, it is a command spec. Otherwise, we use the most recent command in time. */ command = fc_gethist (list ? list->word->word : (char *)NULL, hlist); if (command == NULL) { builtin_error (_("no command found")); if (rlist) FREE_RLIST (); return (EXECUTION_FAILURE); } if (rlist) { newcom = fc_dosubs (command, rlist); free (command); FREE_RLIST (); command = newcom; } fprintf (stderr, "%s\n", command); fc_replhist (command); /* replace `fc -s' with command */ return (parse_and_execute (command, "fc", SEVAL_NOHIST)); } /* This is the second form of the command (the list-or-edit-and-rerun form). */ hlist = history_list (); if (hlist == 0) return (EXECUTION_SUCCESS);. */ /* "When not listing, he fc command that caused the editing shall not be entered into the history list." */ if (listing == 0 && hist_last_line_added) delete_last_history (); last_hist = i - 1 - hist_last_line_added; if (list) { histbeg = fc_gethnum (list->word->word, hlist); list = list->next; if (list) histend = fc_gethnum (list->word->word, hlist); else histend = listing ? last_hist : histbeg; } else { /* The default for listing is the last 16 history items. */ if (listing) { histend = last_hist; histbeg = histend - 16 + 1; /* +1 because loop below uses >= */ if (histbeg < 0) histbeg = 0; } else /* For editing, it is the last history command. */ histbeg = histend = last_hist; } /* We print error messages for line specifications out of range. */ if ((histbeg < 0) || (histend < 0)) { sh_erange ((char *)NULL, _("history specification")); return (EXECUTION_FAILURE); } if (histend < histbeg) { i = histend; histend = histbeg; histbeg = i; reverse = 1; } if (listing) stream = stdout; else { numbering = 0; stream = sh_mktmpfp ("bash-fc", MT_USERANDOM|MT_USETMPDIR, &fn); if (stream == 0) { builtin_error (_("%s: cannot open temp file: %s"), fn ? fn : "", strerror (errno)); FREE (fn); return (EXECUTION_FAILURE); } } for (i = reverse ? histend : histbeg; reverse ? i >= histbeg : i <= histend; reverse ? i-- : i++) { QUIT; if (numbering) fprintf (stream, "%d", i + history_base); if (listing) { if (posixly_correct) fputs ("\t", stream); else fprintf (stream, "\t%c", histdata (i) ? '*' : ' '); } fprintf (stream, "%s\n", histline (i)); } if (listing) return (EXECUTION_SUCCESS); fclose (stream); /* Now edit the file of commands. */ if (ename) { command = (char *)xmalloc (strlen (ename) + strlen (fn) + 2); sprintf (command, "%s %s", ename, fn); } else { fcedit = posixly_correct ? POSIX_FC_EDIT_COMMAND : FC_EDIT_COMMAND; command = (char *)xmalloc (3 + strlen (fcedit) + strlen (fn)); sprintf (command, "%s %s", fcedit, fn); } retval = parse_and_execute (command, "fc", SEVAL_NOHIST); if (retval != EXECUTION_SUCCESS) { unlink (fn); free (fn); return (EXECUTION_FAILURE); } /* Make sure parse_and_execute doesn't turn this off, even though a call to parse_and_execute farther up the function call stack (e.g., if this is called by vi_edit_and_execute_command) may have already called bash_history_disable. */ remember_on_history = 1; /* Turn on the `v' flag while fc_execute_file runs so the commands will be echoed as they are read by the parser. */ begin_unwind_frame ("fc builtin"); add_unwind_protect ((Function *)xfree, fn); add_unwind_protect (unlink, fn); unwind_protect_int (echo_input_at_read); echo_input_at_read = 1; retval = fc_execute_file (fn); run_unwind_frame ("fc builtin"); return (retval); } /* Return 1 if LIST->word->word is a legal number for fc's use. */ static int fc_number (list) WORD_LIST *list; { char *s; if (list == 0) return 0; s = list->word->word; if (*s == '-') s++; return (legal_number (s, (intmax_t *)NULL)); } /* Return an absolute index into HLIST which corresponds to COMMAND. If COMMAND is a number, then it was specified in relative terms. If it is a string, then it is the start of a command line present in HLIST. */ static int fc_gethnum (command, hlist) char *command; HIST_ENTRY **hlist; { int sign = 1, n, clen; register int i, j; register char *s; /* Count history elements. */. */ i -= 1 + hist_last_line_added; /* No specification defaults to most recent command. */ if (command == NULL) return (i); /* Otherwise, there is a specification. It can be a number relative to the current position, or an absolute history number. */ s = command; /* Handle possible leading minus sign. */ if (s && (*s == '-')) { sign = -1; s++; } if (s && DIGIT(*s)) { n = atoi (s); n *= sign; /* If the value is negative or zero, then it is an offset from the current history item. */ if (n < 0) { n += i + 1; return (n < 0 ? 0 : n); } else if (n == 0) return (i); else { n -= history_base; return (i < n ? i : n); } } clen = strlen (command); for (j = i; j >= 0; j--) { if (STREQN (command, histline (j), clen)) return (j); } return (-1); } /* Locate the most recent history line which begins with COMMAND in HLIST, and return a malloc()'ed copy of it. */ static char * fc_gethist (command, hlist) char *command; HIST_ENTRY **hlist; { int i; if (hlist == 0) return ((char *)NULL); i = fc_gethnum (command, hlist); if (i >= 0) return (savestring (histline (i))); else return ((char *)NULL); } #ifdef INCLUDE_UNUSED /* Read the edited history lines from STREAM and return them one at a time. This can read unlimited length lines. The caller should free the storage. */ static char * fc_readline (stream) FILE *stream; { register int c; int line_len = 0, lindex = 0; char *line = (char *)NULL; while ((c = getc (stream)) != EOF) { if ((lindex + 2) >= line_len) line = (char *)xrealloc (line, (line_len += 128)); if (c == '\n') { line[lindex++] = '\n'; line[lindex++] = '\0'; return (line); } else line[lindex++] = c; } if (!lindex) { if (line) free (line); return ((char *)NULL); } if (lindex + 2 >= line_len) line = (char *)xrealloc (line, lindex + 3); line[lindex++] = '\n'; /* Finish with newline if none in file */ line[lindex++] = '\0'; return (line); } #endif /* Perform the SUBS on COMMAND. SUBS is a list of substitutions, and COMMAND is a simple string. Return a pointer to a malloc'ed string which contains the substituted command. */ static char * fc_dosubs (command, subs) char *command; REPL *subs; { register char *new, *t; register REPL *r; for (new = savestring (command), r = subs; r; r = r->next) { t = strsub (new, r->pat, r->rep, 1); free (new); new = t; } return (new); } /* Use `command' to replace the last entry in the history list, which, by this time, is `fc blah...'. The intent is that the new command become the history entry, and that `fc' should never appear in the history list. This way you can do `r' to your heart's content. */ static void fc_replhist (command) char *command; { int n; if (command == 0 || *command == '\0') return; n = strlen (command); if (command[n - 1] == '\n') command[n - 1] = '\0'; if (command && *command) { delete_last_history (); maybe_add_history (command); /* Obeys HISTCONTROL setting. */ } } #ifdef INCLUDE_UNUSED /* Add LINE to the history, after removing a single trailing newline. */ static void fc_addhist (line) char *line; { register int n; if (line == 0 || *line == 0) return; n = strlen (line); if (line[n - 1] == '\n') line[n - 1] = '\0'; if (line && *line) maybe_add_history (line); /* Obeys HISTCONTROL setting. */ } #endif #endif /* HISTORY */
http://opensource.apple.com/source/bash/bash-80/bash/builtins/fc.def
CC-MAIN-2014-41
refinedweb
1,778
62.27
Gimp Batch Processing Task: run scripts in Gimp. Possibly non-interactive. And I don't want to learn Scheme just now. Let's try python. I hear Perl and Ruby have bindings as well, but I seem to have the python ones installed already. Existing literature An introductory blog entry GIMP Batch Mode turial, but only covers Scheme David's Batch Processor, which is a Gimp plugin to automate some batch tasks David's Batch Processor tutorial in Italian carol.gimp.org's python resources and blog Basics from gimpfu import * This will import Gimp's functions. In particular, there will be an object called 'pdb' which has all the methods you'd like to call. There is a 'PDB Browser' in Gimp that will show you documentation about all the PDB methods. Note that the parameters of the function don't necessarily match the ones found in the PDB browser. In particular, you must not specify the run_mode in python. Example code This snipped converts lots of images from XPM to PNG. I had to write it because I had lots of XPM files that imagemagick could not read, but Gimp could. from gimpfu import * def process (file): img=pdb.file_xpm_load(file+".xpm", file+".xpm") pdb.file_png_save_defaults(img, img.active_layer, file+".png", file+".png") # Destroy img, as it isn't getting garbage collected pdb.gimp_image_delete(img) for i in range(1, 10000): process("img_%05d" % i) This script would work, but you get a load progress popup and a save progress popup for every image. I could not find out now not to display those progress popups, and I had to resort to running gimp inside a VNC server in order not to have the popup coming up constantly on top of whatever I was doing. Running the code One way of running the code is pasting it, one line at a time, inside Gimp's Python console. But this is inconvenient. Another way is packaging as a registered plugin, which you can find documented in the Gimp-Python pages. In the case of the script above one would need to add an interface to ask for the range of images to convert and then run the conversion. Finally, it seems that to run the script unattended one can run it inside a 'Gimp server'. I'm trying to figure out how it works. Ideally, I'd like to have my 'script.py' and tell Gimp to run it.
https://wiki.debian.org/GimpBatchProcessing
CC-MAIN-2017-04
refinedweb
410
72.36
This tutorial is designed to assist you in making special collections wrappers. There are times you like using List, Array, or other collections. You want to do special operations on these collections, so you make a custom class. You don't want to expose the list to the public, forcing users to use the functions you provided. However, you can no longer enumerate through the list. You can write a foreach statement against your class, but you get an error about using IEnumerable. This tutorial will show you how to get around this problem. Basic Set Up It is almost lunch time as I write this, and I'm hungry. So I created a simple Food class. It contains just two fields and a simple constructor. public class Food { #region Fields public string Name; public int Calories; #endregion #region Constructors public Food(string Name, int Calories) { this.Name = Name; this.Calories = Calories; } #endregion } I then created a container class called Meal. It holds a List of Food, along with a name. Again, just a simple constructor and the two fields. public class Meal { #region Fields public string Name; private List<Food> FoodList; #endregion #region Constructors public Meal(string Name, List<Food> FoodList) { this.Name = Name; this.FoodList = FoodList; } #endregion } In our Main, let's create a List<Food> and a Meal and test it. static void Main(string[] args) { List<Food> FoodList = new List<Food>() { new Food("Salad", 90), new Food("Steak", 202), new Food("Potato", 157), new Food("Cake", 235) }; Meal dinner = new Meal("Dinner", FoodList); Console.WriteLine("I was sitting, having {0} ...", dinner.Name); int calories = 0; foreach (Food item in dinner) { Console.WriteLine("\t{0} with {1} calories", item.Name, item.Calories); calories += item.Calories; } Console.WriteLine("I consumed {0} calories. It's time to go work it off", calories); Console.ReadLine(); } The code refuses to run. foreach contains an error "foreach statement cannot operate on variables of type '*.Meal' because '*.Meal' does not contain a public definition for 'GetEnumerator'". This can be solved. IEnumerator Go back to the Meal class. The Meal class needs to inhierit from IEnumerable. You will need the using System.Collections; declaration. It needs a public definition for GetEnumerator. This is where it gets tricky. We will create two definitions for GetEnumerator. The first one will not have an access modifier on it. IEnumerator IEnumerable.GetEnumerator() So it needs to return an IEnumerator. What do we return? The solution is to create your own IEnumerator. We can call this class MealEnumerator, so everyone knows what it's used for. MealEnumerator also needs to declare using System.Collections;. MealEnumerator inherits from IEnumerator. First, give it two fields. One is a private readonly of our food list. The other is a private int of position. Set the position to -1. #region Fields private readonly List<Food> _food; private int position = -1; #endregion We want a basic constructor that takes a list and saves it to the readonly field. #region Constructor public MealEnumerator(List<Food> FoodList) { _food = FoodList; } #endregion Now we need two properties, both will be readonly. The first one will return the type of object to return in our enumerations, in this case Food. We also need to make sure to have a try/catch block in case it enumerates past the length of our collection. public Food Current { get { try { return _food[position]; } catch (IndexOutOfRangeException) { throw new InvalidOperationException(); } } } The other property is from IEnumerator. It returns an object. This is the hook to the class. IEnumerator.Current is called, and we just need to point it towards the property we just made. object IEnumerator.Current { get { return Current; } } IEnumerator also has two methods we need to implement. The first is MoveNext that returns a boolean value. What we want is for it increment the position and return whether there are more items in the collection. We can compare the position to the collection length for this. public bool MoveNext() { position++; return (position < _food.Count); } The other method we need is Reset. This one simply starts the iteration over. public void Reset() { position = -1; } You may notice that we set the default position to -1. We also set it to -1 with the method Reset. This is because MoveNext is called before Current is read, even at the beginning of the iteration. If we set these to 0, we will never see the first object of the collection. Back to Meal Before we finish our first method, we need our second method. Just like we did in IEnumerator.Current, the IEnumerable.GetEnumerator is a hook we can use to point to a custom GetEnumerator. This will be a public method that simply creates a MealEnumerator and returns it. public MealEnumerator GetEnumerator() { return new MealEnumerator(FoodList); } Our first method will call this method, casting the result as an IEnumerator. IEnumerator IEnumerable.GetEnumerator() { return (IEnumerator)GetEnumerator(); } We can now compile this code without being yelled at by the IDE. You can see that Meal is much easier to use. You can call foreach (Food item in dinner) to iterate through every food item in your class, without exposing the collection as public. I have included a .zip copy of the files for your use. Attached File(s) Robin19.zip (27.99K) Number of downloads: 945
http://www.dreamincode.net/forums/topic/191489-getenumerator-basics/page__pid__1121888__st__0
CC-MAIN-2016-22
refinedweb
880
60.72
* A friendly place for programming greenhorns! Big Moose Saloon Search | Java FAQ | Recent Topics Register / Login JavaRanch » Java Forums » Java » Performance Author Map<Integer, String> or String[] ? Vishal Srivastav Ranch Hand Joined: Nov 29, 2008 Posts: 46 I like... posted May 08, 2012 22:51:00 0 Hi Friends, I am creating a Java EE client where I need to make a call to a node (js) server to get the response. So I made a single class through which requests are made to node server. Everytime I get a response, I need to send back the response code and the response itself. So I thought of creating a String array which would contain the response code and the response. Here is my class:; import com.sun.jersey.api.client.filter.LoggingFilter; import com.sun.jersey.core.impl.provider.entity.StringProvider; public class RequestHandler { /** * Makes a HTTP Request for a given url. The type * determines which type of request, post or get, * will be made. The params cane be in form of * name=value pair or JSON format. * * @param type Request method. 1 - Get, 2 - Post. * @param url url string to which request has to be * made. * @param path path of the resource or service for a * url. * @param params request parameters. Can be either * name=value pair or JSON request. * * @return String representation of the response. * */ public static String[] makeRequest(int type, String url, String path, String params) { String[] response = new String[2]; ClientResponse clientResponse = null; try { ClientConfig config = new DefaultClientConfig(); config.getClasses().add(StringProvider.class); Client client = Client.create(config); WebResource service = client.resource(url); client.addFilter(new LoggingFilter()); service.path("rest"); // 1 - GET, 2 - POST switch (type) { case 1: { System.out.println("Making GET request to: " + url + path); System.out.println("Request Params: " + params); clientResponse = service.path(path).type(MediaType.APPLICATION_JSON_TYPE).accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); //TODO Code to be corrected, include params break; } case 2: { System.out.println("Making POST request to: " + url + path); System.out.println("Request Params: " + params); clientResponse = service.path(path).type(MediaType.APPLICATION_JSON_TYPE).accept(MediaType.APPLICATION_JSON).post(ClientResponse.class, params); break; } } } catch (Exception e) { e.printStackTrace(); response[0] = "500"; response[1] = "Internal Server Error"; return response; } response[0] = String.valueOf(clientResponse.getStatus()); response[1] = clientResponse.getEntity(String.class); System.err.println("Response status: " + response[0]); return response; }//end of makeRequest() }//end of class But I am not convinced by creating too much string objects which would cause performance issues. So I thought of creating a Map<Integer, String> which would send back the response code and the response. response.put(500, "Internal Server Error"); But again, creating a map with integer and checking everytime the response code creates overhead of boxing and unboxing of Integer object, which again could result in performance. HashMap<Integer, String> response = RequestHandler.makeRequest(2, urlString, "/login", params); if (response.get(500) { return Message.INTERNAL_SERVER_ERROR; } Which one should I use? Or is there any better alternative out of it? Vishal Srivastava, Software Engineer (Android), Paradigm Creatives SCJP 5, SCWCD 5 - Claude Moore Ranch Hand Joined: Jun 24, 2005 Posts: 211 posted May 09, 2012 00:12:40 0 As from your code excerpt, I see that you'll send back for each response exactly two string values. I think that with so few data to be sent, performance overhead should be negligible; I just only guess that from a JSON's perspective, handling string arrays instead of maps would be more efficient. But it's just a guess. With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime. subject: Map<Integer, String> or String[] ? Similar Threads AJAX response to a Restful Jersey Resource Jersey RESTful web service - How to post XML file using jersey framework webservice calling from url Jersey REST -(Un)Marshaller JSF 2.0 and REST(Jeresy) Integratio All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter JForum | Paul Wheaton
http://www.coderanch.com/t/580426/Performance/java/Map-Integer-String-String
CC-MAIN-2013-48
refinedweb
655
51.04
standard C/C++ code, look at the following functions: mbstowcs wcstombs These functions can be used to convert UNICODE to ANSI string and ANSI string to UNICODE. WideCharToMultiByte MultiByteToWideChar These are WIN32 API functions that can be used to convert between UNICODE and ANSI string. const char * FileWithWideChar = "widecharfile.txt"; const char * FileWithAnsiChar = "ansicharfile.txt"; void SetupTestEnvironment() { wstring Data1 = L"Hello1, my name is Axter"; wstring Data2 = L"Hello2, my name is Axter"; wstring Data3 = L"Hello3, my name is Axter"; wofstream wfile(FileWithWideChar); wfile << Data1 << endl; wfile << Data2 << endl; wfile << Data3 << endl; } int main(int argc, char* argv[]) { SetupTestEnvironment(); wifstream wide_file(FileWithWideChar wstring TmpLineData; string CmpFileData_InAnsi, AnsiTmpLine; while(getline(wide_file, TmpLineData)) { AnsiTmpLine.resize(TmpLine wcstombs(AnsiTmpLine.begin CmpFileData_InAnsi += AnsiTmpLine + "\n"; } ofstream ansi_file(FileWithAnsiChar ansi_file.write(CmpFileDat ansi_file << endl; return 0; } We value your feedback. Take our survey and automatically be enter to win anyone of the following: Yeti Cooler, Amazon eGift Card, and Movie eGift Card! Example: void Function(void) { char dataBuff[] = "abcdefghijklmnopq"; DWORD Pos = 10; CString tmpStr = ""; wchar_t* pwsz = tmpStr.GetBufferSetLength ((Pos+1)*sizeof(wchar_t)); MultiByteToWideChar(CP_ACP tmpStr.ReleaseBuffer(); } Example: const wchar_t WideChrData[] = L"Hello World"; char AnsiBuffer[255]; WideCharToMultiByte(CP_ACP CString Msg = AnsiBuffer; AfxMessageBox(Msg); const wchar_t WideChrData[] = L"Hello World"; wstring Data1 = L"Hello1, my name is Axter"; The L tells the compiler that the string literal is a wide character string. In a UNICODE project, you do not need to make *ALL* strings as UNICODE. There are some strings that will have to be ANSI string. For example, to open a file that contains a wide character string, you need to use a file name that is of ANSI type. const char * FileWithWideChar = "widecharfile.txt"; //This is an ANSI string wofstream wfile(FileWithWideChar); wfile << L"Hello World" << endl; So although you may have to modify your original code by prefixing the string literals with L, you don't necessarily want to do this to all your string literals. If this is a Windows application, in the future you may want to consider using _T() macro and using _tcs??? functions like _tcsstr, _tcscpy, _tcslen, etc.. This allows for minimal modifications when converting ANSI string code to UNICODE projects. --------8<-------- #include <iostream> #include <fstream> #include <string> #include <sys/types.h> #include <sys/stat.h> using namespace std; int main() { const string filename = "three.dat"; wstring wstr = L"123"; wofstream fout(filename.c_str()); fout << wstr; fout.close(); struct stat s; if (stat(filename.c_str(),&s) wcout << L"File for \"" << wstr << L"\" is " << s.st_size << L" bytes long\n"; } --------8<-------- The external representation is char rather than wchar_t. Only internally do you get your wchar_t. Externally thay are not wide character files :-( Try using TEXT() Macro and TCHAR datatype, Also there are different function for UNICODE like: size_t __cdecl wcslen(const wchar_t *); to calculate length of a Uniccode string and many more Otherwise it depends upon your programs requirement what you need. Regards, msjammu Note: in the post below when I say wchar. I am not sure if it should be TCHAR wchar or wchar_t. I am using VC++6.0 and have seen of TCHAR and L macro. But wondering which to use. What I have is many classes which have many functions that use char array, instead of CString or wchar arrays. (I know, I know, stupid ) Since I did not really understand back then how to use CString I settled for string.h functions. Mainly strcpy and strcat. I think that I would be happy with replacing all the many many instances of char with wchar or TCHAR or whatever. As I assume arrays of one these data type to hold the values of Unicode. I want this so my applications can be used internationally. The main issue is the many dialog classes. Since I did not use CString and I liked controlling the values to and from dialog child objects I used GetWindowText or GetText to obtain the value and SetWindowText to set static, edit and listbox ect.. Although this may work to my advantage. example: MyEditBox.GetWindowText(Ch MyListBox.GetText(Index, CharString); or strcpy(ss,"fun fun fun!"); Dlg.MyStaticText.SetWindow Dlg.DoModal(); etc... MYMAXVALUE is a largish value that I feel confident wont be a problem. After the dialog instance I would take that value CharString and copy to some other variable strcpy(Other,Dlg.CharStrin So, I am looking for a way to simplify the change. I was wondering if I could use typedef somehow? My other thoughts is to have my own string.h class, Mystring.h class in which I woud use wchar and the L macro? Some of my classes output text to a large area static using DrawText. I am wondering if Unicode will effect that. Also will newlines '\n' be interpreted correctly. (Probably will). As far as file routines, I use fopen, fwrite, fread. in binary mode only. So I see no problem there. My applications dont depend upon reading any pre-existing file. The file routines are not so many so I could be happy with doing find/replace on them. Most of them write and read a structure I define, so in reality I would only be needing to change each of the char array structure members to wchar array. Also I am not sure exactly what Windows api's are effected by modifying all the refferences to char array to wchar array or TCHAR array. So I am hoping none. In order to export my applications to other countries I need to use the Unicode data set. For both input from user and output text displayed to user (My application specific text) Apreciate any opinions/ gotchas etc.. RJ That best way to simplify the change, is to convert all your char* strings to either CString or TCHAR. You can even use CString with the example code you posted. example: CString MyData; MyEditBox.GetWindowText(My MyData.ReleaseBuffer(); MyListBox.GetText(Index, MyData);//Can be used with CString directly or MyData = _T("fun fun fun!"); //Notice the use of _T() macro Dlg.MyStaticText.SetWindow Dlg.DoModal(); By using above method with _T() macro, this makes your code easy to compile in both ANSI and UNICODE projects, with little-to no modifications. >>So although you may have to modify your original code by prefixing the string literals with L, you don't necessarily want to do this to all your string literals. I dont really see a problem with this unless something like fopen could not take Unicode. Is this correct? >>If this is a Windows application, in the future you may want to consider using _T() macro and using _tcs??? functions like _tcsstr, _tcscpy, _tcslen, etc.. This allows for minimal modifications when converting ANSI string code to UNICODE projects. Ok. So I should do simple find/replace here. I guess I could not get away with a typedef here....? I dont know if typedef can modify something like _tcscpy to strcpy? or #define??? I have Jeff Prosise book so I am familiar with the _T() but book is not in front of me now. But mostly I believe your on track... Any comments are apreciated. RJ I garantee it will be worth your time, and you'll be surprise of the functionallity this class has. I'm not a big MFC fan, and IMHO most of the MFC classes that imulate the classes in the STL, are really poor. CArray, CMap, ..... There implementation leaves a lot to be desire. However, IMHO, the CString class is one of the best class in MFC, and IMHO it's even better then the std::string class. (IMHO) CString is one class Microsoft got right! For the most part, in an MFC application, that should be the only type of code you have to worry about. >> I dont know if typedef can modify something like _tcscpy to strcpy? or #define??? No, it can't, and I wouldn't recommend it if it could. You can just do a search trough all your project files using VC++ FindInFile tool. I *think* you can also find them all if you temporarily comment out all the str??? functions in the string.h header. Yes. I got familiar with CString allong the way and agree with you. But since I had already nailed my coffin in the direction I took. I found it hard to change gears. Even had absolute need to format a string using CString format to express float values. Next project for sure. I guess I am lazy. But I am mostly sure it will take me all day to replace string literals with a leading L. It is definitley goint to take some time replacing the char with wchar. ( I assume I should use wchar rather than TCHAR (not sure)?). The char change is gonna be a pain... But I guess that is the proper way to do it. So I got allot of replacing to do... Thanks RJ When I first started using VC I was not sure why but I swear I could not put CString variables in a struct to be read into and wrote from using fopen/fread/fwrite. Ex. struct SS { int a; int b; CString as; CString bs; int flag; }Inst; Then when I loaded values into Inst from some user input and stored it as a file. I believe I remember that I could not read the values back correctly. Inst.a=1; Inst.b=2; Inst.as="test"; Inst.bs="this"; flag=0; fopen... fwrite(&Inst,sizeof(Inst), fclose... fopen... fread(&Inst,sizeof(Inst),1 fclose... The data would be corrupt. I was not sure why but it seemed that the CString was somehow messed up. the size. But I could be mis-quoting myself because this was a while back when I made the decision to avoid CString. It could have also been that I was trying to fwrite and fread a single CString with bad results dont remember. This is also important because items are saved and used in structures. RJ I recommend that you use TCHAR instead of wchar if this is an MFC project. If you use TCHAR, then you can easily convert your program from ANSI to UNICODE, and then back to ANSI if need be. If you use wchar, changing your code back to ANSI will require the same amount of work to convert it to UNICODE. >>The data would be corrupt. I was not sure why but it seemed that the CString was somehow messed up. That's correct. You can not read directly from a file to an object that contains NON-POD types. A CString is a non-POD type. >>This is also important because items are saved and used in structures. For this type of requirement, it would not be good to use CString unless you created an operator>>() and operator<<() for your struct You could use TCHAR instead of char for your struct. RJ That’s a bit of a problem, though, because the run-time library functions have different names, you’re defining characters differently, and then there’s that nuisance of preceding the string literals with an L. One answer is to use the TCHAR.H header file included with MS VC++. This header file is not part of the ANSI C standard, so every function and macro definition defined therein is preceded by an underscore. TCHAR.H provides a set of alternative names for the normal run-time library functions requiring string parameters e g _tprintf, _tcslen. Thses are something referred to as generic function names because they can refer to either the UNICODE or non-UNICODE versions of the functions. If an Identifier named _UINCODE is defines and the TCHAR.h header file is included in your program, -tcslen is defined to be wcslen. If _UNICODE isn’t defined, _tcslen is defined to be strlen And so on. TCHAR.h also solves the problem of the two character data types with a new data type named TCHAR. If the UNICODE identifier is defined TCHAR is wchar_t otherwise, TCHAR is simply a char. Therefore, the choice is yours. Regards, msjammu Thanks RJ Pod = plain old data. Basically the reason it can be written to file is because the data is contiguos. Where as a Non pod class created item (like CString) has things like private constructors and virtual members so it is not contiguos data. To write a structure to file requires that all elements be contiguos. Be pod. There are conditions that a class object can meet to be considered a pod. reff.
https://www.experts-exchange.com/questions/21126082/Convert-old-code-to-Unicode.html
CC-MAIN-2017-51
refinedweb
2,095
74.08
Jan Stranik wrote: > My question was why does the output from writer shows first all output > from server, then followed by all output from client. The effect of "mfix" is that the side-effects of the calculation still occur in the lexical order. Since server is before client, the output of the server precedes the client. > I would like to > see output from client and server to alternate in the order in which the > computation occurs, namely [server, client, server, client, server, > client, …]. Then you have to restructure the code slightly. This works: > import Control.Monad > > import Control.Monad.Writer.Lazy > > client:: [Integer] -> Writer [String] [Integer] > client as = do > dc <- doClient as > return (0:dc) > where > doClient (a:as) = do > tell ["Client " ++ show a] > as' <- doClient as > return ((a+1):as') > doClient [] = return [] > > server :: [Integer] -> Writer [String] [Integer] > server [] = return [] > server (a:as) = do > tell ["Server " ++ show a] > rs <- server as > return (2*a:rs) > > simulation :: [(String,String)] > simulation = > let (clientOut,clientLog) = runWriter (client serverOut) > (serverOut,serverLog) = runWriter (server clientOut) > in zip serverLog clientLog > > main = print (take 10 simulation)
http://www.haskell.org/pipermail/haskell/2008-January/020134.html
CC-MAIN-2014-10
refinedweb
179
50.67
Quick Sort Quicksort is a highly efficient sorting algorithm in which a list or array of elements is partitioned into smaller arrays. A pivot(or central) element is selected in the array. The pivot element can be the first element, the last element, or any random element. The elements smaller than the pivot element are put to its left and greater elements to its right. Implementation Steps : Fix a pointer at the pivot element. Compare it with the elements starting with the first index. Set a second pointer for the greatest element. Set a third pointer to compare the pivot element with all the other elements. If an element smaller than the pivot element is found, swap the smaller element with the greater element. - This process is continued til the second last element is reached. The pivot element is then swapped with the second pointer. - Pivot elements are again chosen for each of the created sub arrays separately. These pivot elements are then placed at the their correct position. The elements smaller than the pivot element are then put on the left and the elements greater than the pivot element are put on the right. - The sub arrays are further divided into smaller subarrays until a single element sub array is created. - The array is now sorted Code: // partition the A on the basis of pivot element int partition(int A[], int start, int end) { int pivot = A[end]; int i = (start - 1); for (int j = start; j < end; j++) { if (A[j] <= pivot) { i++; swap(&A[i], &A[j]); } } printA(A, 7); cout << "........\n"; swap(&A[i + 1], &A[end]); return (i + 1); } void QuickSort(int A[], int start, int end) { if (start < end) { // Select pivot position and put all the elements smaller than pivot on left and greater than pivot on right int p = partition(A, start, end); // Sort the elements on the left of pivot QuickSort(A, start, p - 1); // Sort the elements on the right of pivot QuickSort(A, p + 1, end); } }
https://prepfortech.in/interview-topics/divide-and-conquer/quick-sort
CC-MAIN-2021-17
refinedweb
336
60.75
if endif Wietse, Thank you for adding if-endif to header and body checks. A report on About.com states that in 2010 there were about 294 billion emails sent per day, 90% of which were spam. With numbers like that, trying to go through and blacklist individual IP addresses or users is a waste of time. Spam through here had become such a nightmare that a few years back I informed all my clients that I was done hosting email. I kept the accounts for the Mrs. and myself active, but there continued to be so much spam and gray mail that we quit checking our accounts. Recently I've had a couple of hard drives crash on the servers. So in the process of replacing the hard drives and reinstalling PostFix, I stumbled across your if-endif conditional. Experimenting with it, I've been able to close the door to world wide access to my email accounts and only allow certain users by placing whitelisted conditions up front, and blocking everyone else. The REJECT action includes instructions how to bypass the filter: if /\w+/ /lan-server-1/ OK /lan-server-2/ OK /lan-server-3/ OK /debian/ OK /dovecot/ OK /fvwm/ OK /mybank/ OK /myemployer/ OK /postfix/ OK … if /^Subject/ !/\[Key Word\]/ REJECT "UNAUTHORIZED MAIL. To bypass the spam filter, include the following anywhere in the Subject line: [Key Word]" endif endif If I understand correctly, without the if-endif conditional, the only way to exit header_checks before reaching the end of the file is if a REJECT action is matched. There's no way for me to say "This email is from my wife, so accept the email and exit header_checks immediately": /my.wife@.../ ACCEPT But with the if-endif conditional, I can use it to dump out of the check if a "white listed" condition is met. Glen - gle@...: > If I understand correctly, without the if-endif conditional, the only way toAccording to, > exit header_checks before reaching the end of the file is if a REJECT action > is matched. There's no way for me to say "This email is from my wife, so > accept the email and exit header_checks immediately": header_checks and body_checks implement light-weight content inspection. If you have a spam problem, use a real content filter. Most header_checks and body_checks actions say "do X and inspect the next input line". Only a few actions are "final", including DISCARD and REJECT. Also as documented, if-endif have line scope, not message scope. Wietse
https://groups.yahoo.com/neo/groups/postfix-users/conversations/topics/295937
CC-MAIN-2017-34
refinedweb
420
69.01
<script type='text/javascript'> var form = document.getElementById('login'); setDefaultText(form.elements.response, 'Write a comment...'); function setDefaultText(field, text) { text = text || field.defaultText; if (field.value === '') { field.value = text; field.defaultText = text; addClass(field, 'faded'); } field.onfocus = function () { removeDefaultText(this); }; field.onblur = function () { setDefaultText(this); }; } function removeDefaultText(field) { if (field.value === field.defaultText) { field.value = ''; removeClass(field, 'faded'); } } function hasDefaultText(field) { return (field.value === field.defaultText); } function hasClass(ele,cls) { return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)')); } function addClass(ele,cls) { if (!this.hasClass(ele,cls)) ele.className += ' '+cls; document.getElementById('gg').style.height = '20px'; document.getElementById('ggr').style.display = 'none'; } function removeClass(ele,cls) { if (hasClass(ele,cls)) { var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)'); ele.className=ele.className.replace(reg,' '); document.getElementById('ggr').style.display = 'block'; document.getElementById('gg').style.height = '80px'; } } </script> Are you are experiencing a similar issue? Get a personalized answer when you ask a related question. Have a better answer? Share it in a comment. From novice to tech pro — start learning today. You would not have to do anything but swap my jquery script in to replace your javascript. You already have two versions of jquery.min.js included so there's no additional overhead. One is all you need to get this to work. Your "faded" class is already in place so no need for re-styling. I recommend you to just ask the user if he really wants to leave (if he has already made the changes): <script language="javascript"> window.onbeforeunload = changesMade; var changes = false; // indicates if the changes have been made function changesMade() { if(changes==true){ //changes have been made return "Do you really want to leave? You will loose all the changes made."; } } </script> Of course, you have to add the "changes = true" code to the controls which might be changed by the user... Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation. One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community. Can you provide a step by step on how to re-create the problem. Is it happening in a specific browser? "Throwing off all my settings" refers to what settings? and it loses the fade property and no longer activates my script upon clicking on it. var form = document.getElementById('l setDefaultText(form.elemen JQuery is not my strong suit, but this code worked in Chrome, Firefox, and IE8. JQuery experts, feel free to improve on it if the author is not averse to using jquery. Open in new window I tried to add the onload but it doesnt seem to be doing anything.... i added: function redo() { var form = document.getElementById('l setDefaultText(form.elemen } and the onload='redo()' into the body tag no luck though. ie Open in new window This works perfect though. Thanks for everyone else's help too. BTW, if you want to know why the javascript doesn't work in Chrome, it's that when you navigate to another page and then come back using the back button, the value of the textarea is "Write a comment..." instead of an empty string as you might expect, so this line, if (field.value === '') evaluates to false in Chrome so the default text and styling is never restored. Must have something to do with the way Chrome caches textarea values that other browsers handle differently. How to work around something like that is a mystery to me.
https://www.experts-exchange.com/questions/27386643/Javascript-not-executing-on-back-button.html
CC-MAIN-2018-26
refinedweb
592
60.82
If it ain't broke, make it better. I finally got a chance to play with the Ajax futures release over the weekend. The controls look very impressive!Just for fun, I wrote a simple drag overlay extender that allows you to drag and drop rows in/across GridViews. Anytime a Gridview row is dragged and dropped onto another row or header, a post back occurs raising a RowDrop event with details about the rowIndex and GridView where the drag started and where it was dropped onto.Initially, the drag in IE 6/7 was sluggish. It looks like when you register a drop target using the Sys.Preview.UI.DragDropManager.registerDropTarget method, a reference to the DOM element is stored in an internal array. When a drag is in progress, IE continuously loops through the array of registered dropped targets looking for a potential drop target. This is done by calculating the bounds of each element in the array with the help of the Sys.UI.DomElement.getBounds method. This seemed to make IE sluggish. The workaround I have in the sample code, which should work in most simple scenarios, is to store the bounds of each element as an expando property of the element so that on subsequent loops, it is fetched from the property rather than being calculated again. The sample contains the original implementation and the one with the tweak. The tweak is stored in a js file in the Scripts folder. Note that the Ajax Control Toolkit already contains a cool ReorderList control.You can download my sample here (look under Flan Future AJAX Controls):Primary Mirrorv.0.0.3 Updated to fix the duplicate data issuePlease note that this code was written for .NET 2.0 Raj, Real cool ! Is it possible to drag-drop the Columns in the same girdview using this extender ? Thanks, Gopi Gopi, It is not possible to do that with this extender. Sorry.... Pingback from links for 2007-06-15 » mhinze.com I am trying to run your sample site but everytime I run it I get this error. Could not load file or assembly 'Microsoft.Web.Preview, Version=1.1.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified. What am I doing wrong? Jesus, You need the Ajax futures release - The datagrid row sample is exactly what I have been looking for. I have the futures set installed and loaded up your project in Visual Web developer, however it throws an error about the type of project when I open it. Can you provide the complied binaries from your Futures samples so I can add the dll directly? Thanks i have Ajax futures and installed it , but it si still giving error Hi i wasn't able to download your sample gridview.??? Hi! Thanks a lot for this, exactly what I was looking for. One thing though: while I drag an element IE becomes a little sluggish. I noticed you mentionned this issue but then, your text is strikethrough so I believe your workaround is no longer valid. Have you solve this problem? Thanks Alex, When testing the Futures June 2007 release, I did not notice the sluggishness so I took out the tweak. Since you have noticed the issue with IE, you may want to download v 0.0.1. I hope the ASP.net fixes the problem soon. Raj Thanks Raj The tweak reduced the sluggishness but it's still a little slow; I hope ASP.NET fixes the problem too! One other thing, my Website uses framesets which seems to cause some problems with the RowDragOverlay as there is a gap, while dragging, between the FloatTable and the cursor vertical position. Have you any idea how I could solve this? Thanks again for your excellent work Hi,The sample works fine. It should the original index before the drag and the new index after the drop, but the grid view itself is not repainted. Meaning the row stays in the same location. Is there a way to really simulate the drag/drop >Meaning the row stays in the same location Ray, The extender only gives you information about the drag-drop that occurs. It is left to you to decide what you want to do with that information. ie. You could make changes to the DB with that information. I am using the Drag Overlay Extender in a content area, and I also had issues with the location of the FloatTable. When setting the FloatTable location, I adjusted the current location by the offsetWidth of my sidebar content area, and the offsetHeight of my header content area, and all is well. This is a great control, however I'm having a bit of an issue with it. I've writen a Custom GridView that allows edit of all rows that are on the view at the same time. So that means that all the rows have input boxes active all at the same time. the draging of rows works perfectly, but the drag screws up the content in the input boxes. for example, If an input box has the value of "Hello" and I drag that row, then the value being sent to the server on the drop is "Hello,Hello" It looks like the javascript is joining the value twice, Once might be comming from the form and once from the javascript. I'm not exactly sure since I haven't looked at the javascript code yet. Does anyone have any suggestions where I should look for the issue? Thank you. That's the version I am using. I looked at the description of bug reported and it doesn't look like it's the same bug. It's simila but not exactly the same. I've debugged what is happening, and have trace the duplicate values being posted back to having multiple(Once from the GridView and once from the floatTable) input fields being posted back to the server. In the javascript the hideVisuals function is called twice. Once before the postback event and once after. For some reason floatTable variable is null on the call to the function before the postback and not null on the call after. So the floatTable row gets posted back to the server and then gets cleared afterward. I have fixed it in a somewhat dirty way, but it works. In the createFloatTable function, I assign an Id to the floatTable and in the hideVisuals I use getElementById to get the floatTable and then remove it. It's not exactly the cleanest way since I'm not keeping it OO, but I really didn't have the time to figure out why the floatTable was null on the first call to hideVisuals. Thanks for the great code. Can we drag and drop multiple rows at a time? Satish how to lock the Row Drag any events are availble in your control You mentioned that it's possible to drag between two gridviews. However I've not been able to get the event to fire when I drag a row to another gridview. Did I misunderstand what it could do? It works as intended when dragging from within the gridview for me. Daniel, Did you try the sample? Hi Raj This is working great.can you guide me how can i add a javascript into this as when i am tring to add onclick of any row in gridview it is not working and let me know how can i change the cursor to hand. Sounds like a really usefull extender, do you have a running live demo in your own controlled environment, where people that have problems can test your code on their own machine against your fully working live sample - and compare, thanks good job strange, why I could not post? I am having the same problem Steve had, did you test it with textbox in Gridview row? I am now able to reproduce the issue. Any form element in a drag row gets duplicated when a drag occurs. I shall post a fix as soon as I figure out the issue. Thanks for your patience. Hello Raj Can we use extender with some other kind of grid beside Gridview type. I m using special grid called HierarGrid. This extender is not working with this grid? Any workaround Raj, Great extender. Been looking for something like this for GridView. Having an issue where it seems the overlay is not centered over the GridView. Any thoughts on what I can do to fix? Ron Any update on the textbox in gridview row issue? I am waiting to use it. thanks Pingback from The GridView Row Drag Overlay Extender The control has been updated to fix the duplicate data bug. Worked like a charm, thanks.... Hi, Great control. However, I've got a problem building in 3.5. I (think) I fixed the .config but can't fix the scriptreferencies. I directly tried the following (exchanging Microsoft.web.preview). ScriptReference reference = new ScriptReference("PreviewScript.js", "System.Web.Extensions"); But it doesn't work. Where are the *.js-files in framework 3.5? //Thanks Where can I find the link to downLoad the GridView Row Drag Overlay Extender, I clicked on "Pimary and Mirror" links as instructed and downloaded Flan controls but this extender is not included in the download? May, Please look under Flan Future AJAX Controls. Pingback from Webmaster 38 » Blog Archive » Row Drag overlay for .net at ajax scripts compound Have you tried the GridView Row Drag Overlay Extender in framework 3.5? As I wrote on december 21 I can't get the scriptreferencies to work. giving the following error. please help me Server Error in '/SampleWebSite' Application. -------------------------------------------------------------------------------- Configuration Error Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately. Parser Error Message: The configuration section cannot contain a CDATA or text element. Source Error: Line 61: <add assembly="System.Web.Services, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/></assemblies> Line 62: <buildProviders> Line 63: <add extension="*.asbx" type="Microsoft.Web.Preview.Services.BridgeBuildProvider"/>--> Line 64: </buildProviders> Line 65: </compilation> Source File: C:\Documents and Settings\James1\Desktop\Flan.FutureControls_v_0.0.3\SampleWebSite\web.config Line: 63 Version Information: Microsoft .NET Framework Version:2.0.50727.42; ASP.NET Version:2.0.50727.213 when i drag an item the source is displayed but not the drop location. What might be the cause of this? And thank you. anybody know how to convert this to VB litSourcePK.Text = ((GridView)Page.FindControl(e.SourceGridViewID)).DataKeys[e.SourceRowIndex].Value.ToString(); @ Michael Moore litSourcePK.Text = CType(Page.FindControl(e.SourceGridViewID),GridView).DataKeys(e.SourceRowIndex).Value.ToString Looks like i found a problem: i do not seem to be able to move/insert a gridview row after the last row in gridview. The workaround is to move/insert a row before the last row and then move the last row in front of inserted one. Has anyone found any solutions to this problem? Otherwise, this extender works pretty good. I even extended it further: I added CSS support for "insert indicator" (originally blue line) and dragged row (originally white background with 0.75 opacity). I also added property DroppableHere - sometimes you do not wish to be able to drop a row somewhere (only to pick it), so setting this parameter to "true" prevents it. If anyone is interested in this extension, i will post a link. Thanks for this sample, it works great except some delay on I7 , but it's fine. Is it possible to get the dll source code. is it possible to get the dll code, i impelemented the sample, it works good, the only issue i have is to avoid dropping to the first row in the gridview. Hi I downloaded ur application but im getting some error unknownserver tag <cc1:RowDragOverlayExtender> How to include into my present project. Plz help me out Thanx Sandhya What it takes to convert this extender to be used with asp.net listview control? Hey guys I???. Works great in 2.0. But how to get it working in 3.5? Hi Sandhya, The application is working perfectly. You can open it as, "Open Solution...". But Before You must have latest asp.net ajax ctp and add reference to FlanControls Assembly. If any problem then tell again. Hi Raj, The Gridview is not upgrading, it seems nothing is happening. What can I do? Hi, This is working fine in I.E and Mozilla but when i am in safari and scroll the page to bottom this is working but the blue line goes to top means not foucusing on particuler row which i drag...Please help me.Waiting for reply Hey guys I too???. Congratulations per this very nice control. I need Drag a row and drop over a Cell, how can I do this? is it possible? what files must I modify? Hi, Great control but I've faced troubles with safari, is this a know issue regarding this control? I can drag it to every but I can't drop it on any destination grid, please can you provide some help? Regards, Jonathan Hi Raji, What is dependencies on .NET Future relase package(Microsoft.Web.Preview.dll). Is there any way to remove the dependencies from the future release package? I want to use your control on the project, but I do not want to deploy the future relase package in the production servers. Thank you for providing a such a great control!! I'm sorry ... i speak spanish, i'm not good with this language, i hop that you understand. I have the next error on web.config file: <add verb="GET" path="SearchSiteMaps.axd" type="Microsoft.Web.Preview.Search.SearchSiteMapHandler" validate="true"/> if i'll try comment the last tag .... the next error is in this tag: <add verb="*" path="Diagnostics.axd" type="Microsoft.Web.Preview.Diagnostics.DiagnosticsHandler" validate="true"/> And,if i'll try comment the last tag .... the next error is this: Line 11: <asp:ScriptManager Compiler Error Message: CS0234: The type or namespace name 'Diagnostics' does not exist in the namespace 'Microsoft.Web.Preview' (are you missing an assembly reference?) Source File: c:\Documents and Settings\jadiazs\Escritorio\SampleWebSite\MasterPage.master I was try to fix, looking for on all sides, but i'm not finding nothing at all. Please, help me with this error. Thanks. Pingback from 22 drag & drop scripts « The Adventures of Amit Dua Thank you for providing a such a great control!i have one question.Can we remove the DataKeyNames from the gridview and still find the source/destination index as datakey name has some issues.Please respond me at this blog or email me at simardeepchawla@gmail.com Simar chawla Thanks for this extender! It's working well for me except for one small problem - the RowDropEventArgs always contain the same values everytime I do a drag and drop - 0. Any ideas? Pingback from Drag And Drop Row in DataView | keyongtech Sehr wertvolle Informationen! Empfehlen! Is there a version for Framework 3.5? Does anyone know how to disable feature of dragging and drop between the tables? Dongonzales is it possible to use this with the 3.5 framework? I have been trying but I get an exception (Input string was not in a correct format) Pingback from Something about nothing » The GridView Row Drag Overlay Extender (.net 3.5) I have modified this to use the ajax control toolkit instead of the Microsoft Preview. This will also work on the 3.5 framework. You can look at it here. You will need to download the ajax control toolkit from ajax.asp.net.
http://weblogs.asp.net/rajbk/archive/2007/06/13/the-gridview-row-drag-overlay-extender.aspx
crawl-002
refinedweb
2,648
66.64
XHTML/XHTML Documents Contents Basic XHTML documents[edit] All XHTML documents follow a minimal pattern for document layout: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" ""> <html xmlns="" xml: The <!DOCTYPE> tag is the document type definition (described in the previous chapter) that identifies the standard being used. The <html>...</html> tag pair is the root tag that specifies an XHTML document. It requires two tags: the xmlns is the namespace tag that restates the specific context of the standard, and is normally a URL to the W3 specification. The xml:lang tag specifies the language of the document. <head> <title>My Document's title</title> </head> The <head> tag pair of the document concerns the meta data of the document. It must contain the title of the document enclosed within the <title tags. <body> <p>Hello World!</p> </body> The <body> tag pair indicates the main content of the XHTML document. Within this tag, it encloses additional sub-tags to indicate paragraphs and other formatting information that is presented to the user. XHTML Structure[edit] Within the body of the html document, content is broken into a discrete structure. The most common form of separation involves the <p> tag pair, which marks a section of text as a paragraph. A paragraph is a section of text, and may also also include quotes, listings or other components that are contained in nested tags. However, it does not directly contain another paragraph. Headers of text are identified the numbered series ranging from <h1> through <h6>. They may also be identified by <h> tag pair, in combination with the <section> tag pair; the sections may contain additional headers or paragraphs. Additional structure to the document can be created using the <div. This tag pair is used to aid layouts within the document, and may contain additional paragraphs or headers within the container. To separate two parts of the document, the <separator /> is places between two paragraphs or elements. [edit] <address>is used to mark contact information, normally with the hrefattribute. <blockcode>is used to mark a block of code where whitespaced layout is important. <blockquote>is used to identify a large quotation. <pre>is used to identify preformatted text. [edit] A set of text within text may have tags to describe modifiers to the text. Lists[edit] Hyperlinking[edit] Hyperlinks work in XHTML in the same manner as HTML. An href attribute is added to the an anchor element: <a href="">Example</a> In XHTML 2.0, hyperlinks be placed directly on any element without the need of an anchor tag. As such, elements such as images can be used for a hyperlink. Image maps[edit] A more advanced form of hyperlinking involved navigation maps. This requires an element to use an image, and to include the usemap attribute to reference an id of a navigation map. Within the navigation list, there are two additional attributes to use: shape, and coords. The coordinates are comma-delimited. Within the navigation list, items apparing first within the list take priority if they overlap with another entry in the navigation map. In addition, navigation lists that do not include an href attribute will be inactive. If ismap="ismap" is used on the image attribute, the image map is treated as a server-side map. The client will automatically append the coordinates to the URL sent to the server on this form of map (or "0,0" if they are unable to do so.) Tables[edit] Tables are created in an XHTML document using the <table> tag pair. A table is a grid of cells that is displayed. Within a table, the <colgroup> and <col> tags are used to specify a formatting or class to a set of columns. These two tags, which allow the span attribute, will cause a given column of cells to obtain a specific format (such as background colour or style sheet). The <summary> tag pair is used to provide a summary of the table. This is usually a caption about the table, such as a brief description about the table itself. The <tbody> tag pair identifies the body of the table. It will enclose the row and cell tags that will be described shortly. The <tr> tag pair identifies a row within the table. Each pair of this tag will contain the cell definitions, whether they are a header or content cell. The <td> tag pair identifies a cell within a table. The <th> tag pair identifies a cell within a table, which is treated as a header and given emphasis. Cells may span multiple columns or rows with the colspan or rowspan attribute. Some cells may require uting an abbreviation, which is performed using the abbr attribute. The <thead> tag pair identifies the table's header. The <tfoot> tag pair identifies the table's footer. Stylesheets[edit] Style sheets give a description on how to render an XHTML document. Style sheets are not a direct part of the XHTML standard, but are extremely important for determining the layout or display of the document. They are declared using an empty <style tag, and use the src attribute for the document source and type to specify the type of style sheet (usually "text/css"). An inline style sheet omits the src attribute and contains the affected text within the main element. External stylesheets may also be included by using <?xml-stylesheet ?> with the href and type showing the source and type of stylesheet. If desired, a style can be included directly within an HTML element using the style attribute. Metadata[edit] The <head> tag pair contains the initial description of the document. In addition to the basic title, this section of the document contains metadata useful for categorizing the document. Meta data has the following atributes available: Metadata also provides properties that describe additional information in the document. When the property attribute is set to an entry in the following table, it has the following effect or result: Meta hyperlinks[edit] In the head tag, you can include hyperlinks to provide information about the next and previous documents. This is done using an empty <link tag, with the href and rel attribute.
https://en.wikibooks.org/wiki/XHTML/XHTML_Documents
CC-MAIN-2015-35
refinedweb
1,032
56.15
{-# LANGUAGE GADTs, OverloadedStrings, DeriveDataTypeable, TypeFamilies, FlexibleContexts, BangPatterns #-} ----------------------------------------------------------------------------- -- | -- Module : Data.Acid.Core -- Copyright : PublicDomain -- -- Maintainer : lemmih@gmail.com -- Portability : non-portable (uses GHC extensions) -- --(coreMethods) , Method(..) , MethodContainer(..) , Tagged , mkCore , closeCore , closeCore' , modifyCoreState , modifyCoreState_ , withCoreState , lookupHotMethod , lookupColdMethod , runHotMethod , runColdMethod , MethodMap , mkMethodMap ) where import Control.Concurrent ( MVar, newMVar, withMVar , modifyMVar, modifyMVar_ ) import Control.Monad ( liftM ) import Control.Monad.State ( State, runState ) import qualified Data.Map as Map import Data.ByteString.Lazy as Lazy ( ByteString ) import Data.ByteString.Lazy.Char8 as Lazy ( pack, unpack ) import Data.Serialize ( runPutLazy, runGetLazy ) import Data.SafeCopy ( SafeCopy, safeGet, safePut ) import Data.Typeable ( Typeable, typeOf ) import Unsafe.Coerce ( unsafeCoerce ) -- | The basic Method class. Each Method has an indexed result type -- and a unique tag. class ( Typeable ev, SafeCopy ev , Typeable (MethodResult ev), SafeCopy (MethodResult ev)) => Method ev where type MethodResult ev type MethodState ev methodTag :: ev -> Tag methodTag ev = Lazy = closeCore' core (\_st -> return ()) -- | Access the state and then mark the Core as closed. Any subsequent use -- will throw an exception. closeCore' :: Core st -> (st -> IO ()) -> IO () closeCore' core action = modifyMVar_ (coreState core) $ \st -> do action st return errorMsg (storedMethodTag, methodContent) = case Map.lookup storedMethodTag (coreMethods core) of Nothing -> missingMethod storedMethodTag Just (Method method) -> liftM (runPutLazy . safePut) (method (lazyDecode methodContent)) lazyDecode :: SafeCopy a => Lazy.ByteString -> a lazyDecode inp = case runGetLazy safeGet inp of Left msg -> error msg Right val -> val missingMethod :: Tag -> a missingMethod tag = error msg where msg = "This method is required but not available: " ++ show (Lazy.unpack tag) ++ ". Did you perhaps remove it before creating a checkpoint?" -- | Apply an in-memory method to the state. runHotMethod :: Method method => Core (MethodState method) -> method -> IO (MethodResult method) runHotMethod core method = modifyCoreState core $ \st -> do let (a, st') = runState (lookupHotMethod (coreMethods core) method) st return ( st', a) -- | Find the state action that corresponds to an in-memory method. lookupHotMethod :: Method method => MethodMap (MethodState method) -> method -> State (MethodState method) (MethodResult method) lookupHotMethod methodMap method = case Map.lookup (methodTag method) methodMap of Nothing -> missingMethod (methodTag)
http://hackage.haskell.org/package/acid-state-0.5.1/docs/src/Data-Acid-Core.html
CC-MAIN-2015-11
refinedweb
323
51.34
25 February 2010 08:15 [Source: ICIS news] By Prema Viswanathan SINGAPORE (ICIS news)--Polymer offers for March into the Gulf Cooperation Council (GCC) were raised by $30-60/tonne (€22.2-44.4/tonne), or upto 4%, due to tight supply and high monomer prices that may force some converters to cut production, industry sources said on Thursday. This follows a $130-250/tonne hike in February. (please see graph below) “We are shocked by the spate of polymer price increases we have seen in the past few months. We will be forced to reduce operating rates at our plants if we are unable to pass down the high raw material costs, which seems likely,” said a polymer converter in ?xml:namespace> Producers, on their part, justified the price hikes, citing high monomer costs and shortages. “One major Middle East producer has cut its production by 25% due to shortage of gas feedstocks, while others have lost output due to maintenance shutdowns or outages caused by technical problems,” said a source close to one of the producers. Although several new capacities have come on stream in the GCC in the past few months, feedstock shortages, a human resource crunch, overstretched utilities and technical hiccups have kept operating rates at the new plants low. High propylene and ethylene costs in Asia and Ethylene prices in Asia were at $1,290/tonne CFR northeast Asia last Friday, up $240/tonne from two months earlier, while propylene was up $75/tonne at $1,125/tonne CFR NE Asia, according to ICIS pricing data. Polypropylene (PP) production has been the worst hit. Oman Polypropylene shut down its Sohar PP unit this month for a two-month turnaround, Al Waha Petrochemical restarted its Al Jubail PP plant early this week after a prolonged outage, while Advanced Petrochemical Co plans to shut its 450,000 tonne/year PP plant on 11 March for a three week turnaround. High density/linear low density polyethylene (HDPE/LLDPE) and PP offers have been raised by $30/tonne and $30-40/tonne from February levels to $1,380-1,400/tonne delivered ( Offers for general purpose polystyrene (GPPS) and high impact PS (HIPS) have been hiked by $60/tonne to $1,540/tonne DEL GCC and $1,640/tonne DEL GCC, while polyvinyl chloride (PVC) offers have seen a $30/tonne increase to $1,100/tonne DEL GCC. ($1 = €0.74) For more on polymers
http://www.icis.com/Articles/2010/02/25/9337746/GCC-polymer-offers-hiked-by-30-60tonne-for-March.html
CC-MAIN-2014-23
refinedweb
406
59.67
We often solve polynomial equations in mathematics to find the roots of the equations. Have you ever wondered how to solve those mathematical equations using programming? Well, without using python, it would be a bit stressful to solve those equations. Let me tell you about an amazing library called numpy. In today’s tutorial, we will explore numPy in python and have some detailed analysis of numpy and its uses. Introduction of Numpy in python Numpy stands for Numerical Python. It is an open-source scientific computing library for the Python programming language. NumPy is a library of numerical routines that helps in solving scientific problems. Numpy array is a very famous package in the numpy library. It also has functions in the domain of linear algebra, Fourier transformations, and matrices. Why to use numpy in python? In our previous tutorial, we have learned about lists. Lists are similar to arrays in python, but it is a slower process. On the other hand, NumPy arrays are stored at one continuous location in memory, so it is straightforward to access and manipulate them very efficiently. What are Numpy roots in Python? Numpy root helps in finding the roots of a polynomial equation having coefficients in python. It can be found using a couple of methods. Let’s discuss them in detail. A polynomial equation is written as: – p[0] * xn + p[1] * x(n-1) + … + p[n-1]*x + p[n] Method 1: Using np.roots() function in python In this method, we will look at how to use the function of the numpy root and print the given function help of the print function in python. numpy.roots() function returns the roots of a polynomial with coefficients given in p. The coefficients of the polynomial are to be put in a numpy array in a sequence. Syntax Syntax: numpy.roots(p) Parameter It takes the coefficients of an given polynomial. Return Value The function will return the roots of the polynomial. Let’s do some code to understand. Example 1: Let us consider an equation: x2 + 5*x + 6 The coefficients are 1, 5 and 6. import numpy as np p = [1, 5, 6] roots = np.roots(p) print(roots) OUTPUT: - [3. 2.] Explanation of the code - To use the numpy library in python, we need to import it. - np is the alias name of numpy. - p is the list having the coefficients. - To find the roots of the equation, we used np.roots passing the coefficients as the parameter. - Printing the roots. Example 2: Now let us consider the following polynomial for a cubic equation: x3 – 6 * x2 + 11 * x – 6 The coefficients are 1, -6 , 11 and -6. import numpy as np coeff = [1, -6, 11, -6] print(np.roots(coeff)) OUTPUT:- [3. 2. 1.] Explanation of the code - To use the numpy library in python, we need to import it. - np is the alias name of numpy. - coeff has the list of the coefficients. - To find the roots of the equation, we used np.roots passing the coefficients as the parameter and printing it. Also, Read | Numpy Square Root | Usecase Evaluation of Math Toolkit Method 2: Using poly1D() function in python poly1D helps us to define a polynomial function in python. We use this function as it makes it easy to apply the operations on polynomials. The coefficients of the polynomial are to be put in a numpy array in a sequence. Syntax numpy.poly1d(arr, root, var) Parameter arr:- [array_like] The polynomial coefficients are in the decreasing order of powers. So if the second parameter, i.e., the root, is assigned to the True value, then array values will be the roots of the polynomial equation. root: – [bool, optional] The default value of root is False. True means polynomial roots. var: – variables like x, y, z that we need in polynomial. The default variable is x. Return value poly1D returns the polynomial equation along with the operation applied on it. for example, let the polynomial be x2 + 5 * x + 6 , then the array will be [1, 5 , 6] respectively. import numpy as np p = np.poly1d([1, 5, 6]) root = p.r print(p) print(root) OUTPUT:- x2 + 5x +6 [-3. -2.] Explanation of the code - To use the numpy library, we need to import it. - np is the alias name of numpy. - Entered the coefficients of a polynomial into an array. - Multiplying by r to get the roots. - Displaying the polynomial equation and the roots of the equation. Also, Read | How to Calculate Square Root in Python How numpy solves the equation of a Companion Matrix? Python even helps us to solve a companion matrix as well with the help of numpy. The method which we use to solve this is np.legcompanion(). The np.legcompanion() will return the companion matrix . Syntax: np.legcompanion(c) Parameter c :[array_like] 1-D arrays of legendre series coefficients which is ordered from low to high. Return Value It returns a ndarray Companion matrix of dimensions (degree, degree). import numpy as np import numpy.polynomial.legendre as npl s = (1, 2, 3, 4, 5) res = npl.legcompanion(s) print(res) OUTPUT:- [ [ 0. 0.57735027 0. -0.30237158] [ 0.57735027 0. 0.51639778 -0.34914862] [ 0. 0.51639778 0. 0.10141851] [ 0. 0. 0.50709255 -0.4571428] ] Explanation of the code - Importing numpy having alias name as np. - Importing numpy.polynomial.legendre module as npl. - Storing Legendre series coefficients in the variable s. - Using np.legcompanion() method. - Printing the resultant companion matrix. Conclusion Numpy is an essential library python has. It is used in many applications for data scientists and machine learning engineers. This article has discussed a few of its features, such as root function and polynomial.legendre function. If you have any doubts please drop a comment in the comment section below.
https://www.pythonpool.com/numpy-roots/
CC-MAIN-2021-43
refinedweb
974
68.26
Creating Shared Libraries The following sections list certain things that should be taken into account when creating shared libraries. Using Symbols from Shared Libraries Symbols - functions, variables or classes - contained in shared libraries intended to be used by clients, such as applications or other libraries, must be marked in a special way. These symbols are called public symbols that are exported or made publicly visible. The remaining symbols should not be visible from the outside. On most platforms, compilers will hide them by default. On some platforms, a special compiler option is required to hide these symbols. When compiling a shared library, it must be marked for export. To use the shared library from a client, some platforms may require a special import declaration as well. Depending on your target platform, Qt provides special macros that contain the necessary definitions: - Q_DECL_EXPORT must be added to the declarations of symbols used when compiling a shared library. - Q_DECL_IMPORT must be added to the declarations of symbols used when compiling a client that uses the shared library. Now, we need to ensure that the right macro is invoked -- whether we compile a shared library itself, or just the client using the shared library. Typically, this can be solved by adding a special header. Let us assume we want to create a shared library called mysharedlib. A special header for this library, mysharedlib_global.h, looks like this: #include <QtCore/QtGlobal> #if defined(MYSHAREDLIB_LIBRARY) # define MYSHAREDLIB_EXPORT Q_DECL_EXPORT #else # define MYSHAREDLIB_EXPORT Q_DECL_IMPORT #endif In the .pro file of the shared library, we add: DEFINES += MYSHAREDLIB_LIBRARY In each header of the library, we specify the following: #include "mysharedlib_global.h" MYSHAREDLIB_EXPORT void foo(); class MYSHAREDLIB_EXPORT MyClass... This ensures that the right macro is seen by both library and clients. We also use this technique in Qt's sources. Header File Considerations Typically, clients will include only the public header files of shared libraries. These libraries might be installed in a different location, when deployed. Therefore, it is important to exclude other internal header files that were used when building the shared library. For example, the library might provide a class that wraps a hardware device and contains a handle to that device, provided by some 3rd-party library: #include <footronics/device.h> class MyDevice { private: FOOTRONICS_DEVICE_HANDLE handle; }; A similar situation arises with forms created by Qt Designer when using aggregation or multiple inheritance: #include "ui_widget.h" class MyWidget : public QWidget { private: Ui::MyWidget m_ui; }; When deploying the library, there should be no dependency to the internal headers footronics/device.h or ui_widget.h. This can be avoided by making use of the Pointer to implementation idiom described in various C++ programming books. For classes with value semantics, consider using QSharedDataPointer. Binary compatibility For clients loading a shared library, to work correctly, the memory layout of the classes being used must match exactly the memory layout of the library version that was used to compile the client. In other words, the library found by the client at runtime must be binary compatible with the version used at compile time. This is usually not a problem if the client is a self-contained software package that ships all the libraries it needs. However, if the client application relies on a shared library that belongs to a different installation package or to the operating system, then we need to think of a versioning scheme for shared libraries and decide at which level Binary compatibility is to be maintained. For example, Qt libraries of the same major version number are guaranteed to be binary compatible. Maintaining Binary compatibility places some restrictions on the changes you can make to the classes. A good explanation can be found at KDE - Policies/Binary Compatibility Issues With C++. These issues should be considered right from the start of library design. We recommend that the principle of Information hiding and the Pointer to implementation technique be used wherever possible. No notes
http://qt-project.org/doc/qt-4.8/sharedlibrary.html
crawl-003
refinedweb
654
53.92
Restricted Boltzmann Machines (RBM)¶ Note This section assumes the reader has already read through Classifying MNIST digits using Logistic Regression and Multilayer Perceptron. Additionally it uses the following Theano functions and concepts : T.tanh, shared variables, basic arithmetic ops, T.grad, Random numbers, floatX and scan. If you intend to run the code on GPU also read GPU. Energy-Based Models (EBM)¶: (1) The normalizing factor is called the partition function by analogy with physical systems. An energy-based model can be learnt by performing (stochastic) gradient descent on the empirical negative log-likelihood of the training data. As for the logistic regression we will first define the log-likelihood and then the loss function as being the negative log-likelihood. ![ \mathcal{L}(\theta, \mathcal{D}) = \frac{1}{N} \sum_{x^{(i)} \in \mathcal{D}} \log\ p(x^{(i)})\\ \ell (\theta, \mathcal{D}) = - \mathcal{L} (\theta, \mathcal{D})](_images/math/95a46acb679d27dfb79d6f1e3ee05597b82096b7.png) using the stochastic gradient , where are the parameters of the model. EBMs with Hidden Units In many cases of interest, we do not observe the example fully, or we want to introduce some non-observed variables to increase the expressive power of the model. So we consider an observed part (still denoted here) and a hidden part . We can then write: (2) In such cases, to map this formulation to one similar to Eq. (1), we introduce the notation (inspired from physics) of free energy, defined as follows: (3) which allows us to write, The data negative log-likelihood gradient then has a particularly interesting form. (4) ![ - \frac{\partial \log p(x)}{\partial \theta} &= \frac{\partial \mathcal{F}(x)}{\partial \theta} - \sum_{\tilde{x}} p(\tilde{x}) \ \frac{\partial \mathcal{F}(\tilde{x})}{\partial \theta}.](_images/math/6e8377004d5180185830f2509f9a92b38890a4f1.png) Notice that the above gradient contains two terms, which are referred to as the positive and negative phase. The terms positive and negative do not refer to the sign of each term in the equation, but rather reflect their effect on the probability density defined by the model. The first term increases the probability of training data (by reducing the corresponding free energy), while the second term decreases the probability of samples generated by the model. It is usually difficult to determine this gradient analytically, as it involves the computation of . This is nothing less than an expectation over all possible configurations of the input (under the distribution formed by the model) ! The first step in making this computation tractable is to estimate the expectation using a fixed number of model samples. Samples used to estimate the negative phase gradient are referred to as negative particles, which are denoted as . The gradient can then be written as: (5) ![ - \frac{\partial \log p(x)}{\partial \theta} &\approx \frac{\partial \mathcal{F}(x)}{\partial \theta} - \frac{1}{|\mathcal{N}|}\sum_{\tilde{x} \in \mathcal{N}} \ \frac{\partial \mathcal{F}(\tilde{x})}{\partial \theta}.](_images/math/52699d07e7ec91a97a8b952c99df6ca3a01716e2.png) where we would ideally like elements of to be sampled according to (i.e. we are doing Monte-Carlo). With the above formula, we almost have a pratical, stochastic algorithm for learning an EBM. The only missing ingredient is how to extract these negative particles . While the statistical literature abounds with sampling methods, Markov Chain Monte Carlo methods are especially well suited for models such as the Restricted Boltzmann Machines (RBM), a specific type of EBM. Restricted Boltzmann Machines (RBM)¶ Boltzmann Machines (BMs) are a particular form of log-linear Markov Random Field (MRF), i.e., for which the energy function is linear in its free parameters. To make them powerful enough to represent complicated distributions (i.e., go from the limited parametric setting to a non-parametric one), we consider that some of the variables are never observed (they are called hidden). By having more hidden variables (also called hidden units), we can increase the modeling capacity of the Boltzmann Machine (BM). Restricted Boltzmann Machines further restrict BMs to those without visible-visible and hidden-hidden connections. A graphical depiction of an RBM is shown below. The energy function of an RBM is defined as: (6) where represents the weights connecting hidden and visible units and , are the offsets of the visible and hidden layers respectively. This translates directly to the following free energy formula: Because of the specific structure of RBMs, visible and hidden units are conditionally independent given one-another. Using this property, we can write: ![ p(h|v) &= \prod_i p(h_i|v) \\ p(v|h) &= \prod_j p(v_j|h).](_images/math/6d150bdd1676c2e990ff6d11ab439555e7db97af.png) RBMs with binary units In the commonly studied case of using binary units (where and ), we obtain from Eq. (6) and (2), a probabilistic version of the usual neuron activation function: (7) (8) The free energy of an RBM with binary units further simplifies to: (9) Update Equations with Binary Units Combining Eqs. (5) with (9), we obtain the following log-likelihood gradients for an RBM with binary units: (10) ![ - \frac{\partial{ \log p(v)}}{\partial W_{ij}} &= E_v[p(h_i|v) \cdot v_j] - v^{(i)}_j \cdot sigm(W_i \cdot v^{(i)} + c_i) \\ -\frac{\partial{ \log p(v)}}{\partial c_i} &= E_v[p(h_i|v)] - sigm(W_i \cdot v^{(i)}) \\ -\frac{\partial{ \log p(v)}}{\partial b_j} &= E_v[p(v_j|h)] - v^{(i)}_j](_images/math/712eca5eb5d241fe1dedce7ebb8f59922f9bf258.png) For a more detailed derivation of these equations, we refer the reader to the following page, or to section 5 of Learning Deep Architectures for AI. We will however not use these formulas, but rather get the gradient using Theano T.grad from equation (4). Sampling in an RBM¶ Samples of can be obtained by running a Markov chain to convergence, using Gibbs sampling as the transition operator. Gibbs sampling of the joint of N random variables is done through a sequence of N sampling sub-steps of the form where contains the other random variables in excluding . For RBMs, consists of the set of visible and hidden units. However, since they are conditionally independent, one can perform block Gibbs sampling. In this setting, visible units are sampled simultaneously given fixed values of the hidden units. Similarly, hidden units are sampled simultaneously given the visibles. A step in the Markov chain is thus taken as follows: ![ h^{(n+1)} &\sim sigm(W'v^{(n)} + c) \\ v^{(n+1)} &\sim sigm(W h^{(n+1)} + b),](_images/math/dcec7ec01a9668449f23b2325f627c43cf501ccf.png) where refers to the set of all hidden units at the n-th step of the Markov chain. What it means is that, for example, is randomly chosen to be 1 (versus 0) with probability , and similarly, is randomly chosen to be 1 (versus 0) with probability . This can be illustrated graphically: As , samples are guaranteed to be accurate samples of . In theory, each parameter update in the learning process would require running one such chain to convergence. It is needless to say that doing so would be prohibitively expensive. As such, several algorithms have been devised for RBMs, in order to efficiently sample from during the learning process. Contrastive Divergence (CD-k)¶ Contrastive Divergence uses two tricks to speed up the sampling process: - since we eventually want (the true, underlying distribution of the data), we initialize the Markov chain with a training example (i.e., from a distribution that is expected to be close to , so that the chain will be already close to having converged to its final distribution ). - CD does not wait for the chain to converge. Samples are obtained after only k-steps of Gibbs sampling. In pratice, has been shown to work surprisingly well. Persistent CD¶ Persistent CD [Tieleman08] uses another approximation for sampling from . It relies on a single Markov chain, which has a persistent state (i.e., not restarting a chain for each observed example). For each parameter update, we extract new samples by simply running the chain for k-steps. The state of the chain is then preserved for subsequent updates. The general intuition is that if parameter updates are small enough compared to the mixing rate of the chain, the Markov chain should be able to “catch up” to changes in the model. Implementation¶ We construct an RBM class. The parameters of the network can either be initialized by the constructor or can be passed as arguments. This option is useful when an RBM is used as the building block of a deep network, in which case the weight matrix and the hidden layer bias is shared with the corresponding sigmoidal layer of an MLP network. class RBM(object): """Restricted Boltzmann Machine (RBM) """ def __init__( self, input=None, n_visible=784, n_hidden=500, W=None, hbias=None, vbias=None, numpy_rng=None, theano_rng=None ): """ RBM constructor. Defines the parameters of the model along with basic operations for inferring hidden from visible (and vice-versa), as well as for performing CD updates. :param input: None for standalone RBMs or symbolic variable if RBM is part of a larger graph. :param n_visible: number of visible units :param n_hidden: number of hidden units :param W: None for standalone RBMs or symbolic variable pointing to a shared weight matrix in case RBM is part of a DBN network; in a DBN, the weights are shared between RBMs and layers of a MLP :param hbias: None for standalone RBMs or symbolic variable pointing to a shared hidden units bias vector in case RBM is part of a different network :param vbias: None for standalone RBMs or a symbolic variable pointing to a shared visible units bias """ self.n_visible = n_visible self.n_hidden = n_hidden if numpy_rng is None: # create a number generator numpy_rng = numpy.random.RandomState(1234) if theano_rng is None: theano_rng = RandomStreams(numpy_rng.randint(2 ** 30)) if W is None: # W is initialized with `initial_W` which is uniformely # sampled from -4*sqrt(6./(n_visible+n_hidden)) and # 4*sqrt(6./(n_hidden+n_visible)) the output of uniform if # converted using asarray to dtype theano.config.floatX so # that the code is runable on GPU initial_W = numpy.asarray( numpy_rng.uniform( low=-4 * numpy.sqrt(6. / (n_hidden + n_visible)), high=4 * numpy.sqrt(6. / (n_hidden + n_visible)), size=(n_visible, n_hidden) ), dtype=theano.config.floatX ) # theano shared variables for weights and biases W = theano.shared(value=initial_W, name='W', borrow=True) if hbias is None: # create shared variable for hidden units bias hbias = theano.shared( value=numpy.zeros( n_hidden, dtype=theano.config.floatX ), name='hbias', borrow=True ) if vbias is None: # create shared variable for visible units bias vbias = theano.shared( value=numpy.zeros( n_visible, dtype=theano.config.floatX ), name='vbias', borrow=True ) # initialize input layer for standalone RBM or layer0 of DBN self.input = input if not input: self.input = T.matrix('input') self.W = W self.hbias = hbias self.vbias = vbias self.theano_rng = theano_rng # **** WARNING: It is not a good idea to put things in this list # other than shared variables created in this function. self.params = [self.W, self.hbias, self.vbias] Next step is to define functions which construct the symbolic graph associated with Eqs. (7) - (8). The code is as follows: def propup(self, vis): '''This function propagates the visible units activation upwards to the hidden(vis, self.W) + self.hbias return [pre_sigmoid_activation, T.nnet.sigmoid(pre_sigmoid_activation)] def sample_h_given_v(self, v0_sample): ''' This function infers state of hidden units given visible units ''' # compute the activation of the hidden units given a sample of # the visibles pre_sigmoid_h1, h1_mean = self.propup(v0_sample) # get a sample of the hiddens given their activation # Note that theano_rng.binomial returns a symbolic sample of dtype # int64 by default. If we want to keep our computations in floatX # for the GPU we need to specify to return the dtype floatX h1_sample = self.theano_rng.binomial(size=h1_mean.shape, n=1, p=h1_mean, dtype=theano.config.floatX) return [pre_sigmoid_h1, h1_mean, h1_sample] def propdown(self, hid): '''This function propagates the hidden units activation downwards to the visible(hid, self.W.T) + self.vbias return [pre_sigmoid_activation, T.nnet.sigmoid(pre_sigmoid_activation)] def sample_v_given_h(self, h0_sample): ''' This function infers state of visible units given hidden units ''' # compute the activation of the visible given the hidden sample pre_sigmoid_v1, v1_mean = self.propdown(h0_sample) # get a sample of the visible given their activation # Note that theano_rng.binomial returns a symbolic sample of dtype # int64 by default. If we want to keep our computations in floatX # for the GPU we need to specify to return the dtype floatX v1_sample = self.theano_rng.binomial(size=v1_mean.shape, n=1, p=v1_mean, dtype=theano.config.floatX) return [pre_sigmoid_v1, v1_mean, v1_sample] We can then use these functions to define the symbolic graph for a Gibbs sampling step. We define two functions: gibbs_vhvwhich performs a step of Gibbs sampling starting from the visible units. As we shall see, this will be useful for sampling from the RBM. gibbs_hvhwhich performs a step of Gibbs sampling starting from the hidden units. This function will be useful for performing CD and PCD updates. The code is as follows: def gibbs_hvh(self, h0_sample): ''' This function implements one step of Gibbs sampling, starting from the hidden state''' pre_sigmoid_v1, v1_mean, v1_sample = self.sample_v_given_h(h0_sample) pre_sigmoid_h1, h1_mean, h1_sample = self.sample_h_given_v(v1_sample) return [pre_sigmoid_v1, v1_mean, v1_sample, pre_sigmoid_h1, h1_mean, h1_sample] def gibbs_vhv(self, v0_sample): ''' This function implements one step of Gibbs sampling, starting from the visible state''' pre_sigmoid_h1, h1_mean, h1_sample = self.sample_h_given_v(v0_sample) pre_sigmoid_v1, v1_mean, v1_sample = self.sample_v_given_h(h1_sample) return [pre_sigmoid_h1, h1_mean, h1_sample, pre_sigmoid_v1, v1_mean, v1_sample] Note that we also return the pre-sigmoid activation. To understand why this is so you need to understand a bit about how Theano works. Whenever you compile a Theano function, the computational graph that you pass as input gets optimized for speed and stability. This is done by changing several parts of the subgraphs with others. One such optimization expresses terms of the form log(sigmoid(x)) in terms of softplus. We need this optimization for the cross-entropy since sigmoid of numbers larger than 30. (or even less then that) turn to 1. and numbers smaller than -30. turn to 0 which in terms will force theano to compute log(0) and therefore we will get either -inf or NaN as cost. If the value is expressed in terms of softplus we do not get this undesirable behaviour. This optimization usually works fine, but here we have a special case. The sigmoid is applied inside the scan op, while the log is outside. Therefore Theano will only see log(scan(..)) instead of log(sigmoid(..)) and will not apply the wanted optimization. We can not go and replace the sigmoid in scan with something else also, because this only needs to be done on the last step. Therefore the easiest and more efficient way is to get also the pre-sigmoid activation as an output of scan, and apply both the log and sigmoid outside scan such that Theano can catch and optimize the expression. The class also has a function that computes the free energy of the model, needed for computing the gradient of the parameters (see Eq. (4)). Note that we also return the pre-sigmoid def free_energy(self, v_sample): ''' Function to compute the free energy ''' wx_b = T.dot(v_sample, self.W) + self.hbias vbias_term = T.dot(v_sample, self.vbias) hidden_term = T.sum(T.log(1 + T.exp(wx_b)), axis=1) return -hidden_term - vbias_term We then add a get_cost_updates method, whose purpose is to generate the symbolic gradients for CD-k and PCD-k updates. def get_cost_updates(self, lr=0.1, persistent=None, k=1): """This functions implements one step of CD-k or PCD-k :param lr: learning rate used to train the RBM :param persistent: None for CD. For PCD, shared variable containing old state of Gibbs chain. This must be a shared variable of size (batch size, number of hidden units). :param k: number of Gibbs steps to do in CD-k/PCD-k Returns a proxy for the cost and the updates dictionary. The dictionary contains the update rules for weights and biases but also an update of the shared variable used to store the persistent chain, if one is used. """ # compute positive phase pre_sigmoid_ph, ph_mean, ph_sample = self.sample_h_given_v(self.input) # decide how to initialize persistent chain: # for CD, we use the newly generate hidden sample # for PCD, we initialize from the old state of the chain if persistent is None: chain_start = ph_sample else: chain_start = persistent Note that get_cost_updates takes as argument a variable called persistent. This allows us to use the same code to implement both CD and PCD. To use PCD, persistent should refer to a shared variable which contains the state of the Gibbs chain from the previous iteration. If persistent is None, we initialize the Gibbs chain with the hidden sample generated during the positive phase, therefore implementing CD. Once we have established the starting point of the chain, we can then compute the sample at the end of the Gibbs chain, sample that we need for getting the gradient (see Eq. (4)). To do so, we will use the scan op provided by Theano, therefore we urge the reader to look it up by following this link. # perform actual negative phase # in order to implement CD-k/PCD-k we need to scan over the # function that implements one gibbs step k times. # Read Theano tutorial on scan for more information : # # the scan will return the entire Gibbs chain ( [ pre_sigmoid_nvs, nv_means, nv_samples, pre_sigmoid_nhs, nh_means, nh_samples ], updates ) = theano.scan( self.gibbs_hvh, # the None are place holders, saying that # chain_start is the initial state corresponding to the # 6th output outputs_info=[None, None, None, None, None, chain_start], n_steps=k, name="gibbs_hvh" ) Once we have the generated the chain we take the sample at the end of the chain to get the free energy of the negative phase. Note that the chain_end is a symbolical Theano variable expressed in terms of the model parameters, and if we would apply T.grad naively, the function will try to go through the Gibbs chain to get the gradients. This is not what we want (it will mess up our gradients) and therefore we need to indicate to T.grad that chain_end is a constant. We do this by using the argument consider_constant of T.grad. # determine gradients on RBM parameters # note that we only need the sample at the end of the chain chain_end = nv_samples[-1] cost = T.mean(self.free_energy(self.input)) - T.mean( self.free_energy(chain_end)) # We must not compute the gradient through the gibbs sampling gparams = T.grad(cost, self.params, consider_constant=[chain_end]) Finally, we add to the updates dictionary returned by scan (which contains updates rules for random states of theano_rng) to contain the parameter updates. In the case of PCD, these should also update the shared variable containing the state of the Gibbs chain. # constructs the update dictionary for gparam, param in zip(gparams, self.params): # make sure that the learning rate is of the right dtype updates[param] = param - gparam * T.cast( lr, dtype=theano.config.floatX ) if persistent: # Note that this works only if persistent is a shared variable updates[persistent] = nh_samples[-1] # pseudo-likelihood is a better proxy for PCD monitoring_cost = self.get_pseudo_likelihood_cost(updates) else: # reconstruction cross-entropy is a better proxy for CD monitoring_cost = self.get_reconstruction_cost(updates, pre_sigmoid_nvs[-1]) return monitoring_cost, updates Tracking Progress¶ RBMs are particularly tricky to train. Because of the partition function of Eq. (1), we cannot estimate the log-likelihood during training. We therefore have no direct useful metric for choosing the optimal hyperparameters. Several options are available to the user. Inspection of Negative Samples Negative samples obtained during training can be visualized. As training progresses, we know that the model defined by the RBM becomes closer to the true underlying distribution, . Negative samples should thus look like samples from the training set. Obviously bad hyperparameters can be discarded in this fashion. Visual Inspection of Filters The filters learnt by the model can be visualized. This amounts to plotting the weights of each unit as a gray-scale image (after reshaping to a square matrix). Filters should pick out strong features in the data. While it is not clear for an arbitrary dataset, what these features should look like, training on MNIST usually results in filters which act as stroke detectors, while training on natural images lead to Gabor like filters if trained in conjunction with a sparsity criteria. Proxies to Likelihood Other, more tractable functions can be used as a proxy to the likelihood. When training an RBM with PCD, one can use pseudo-likelihood as the proxy. Pseudo-likelihood (PL) is much less expensive to compute, as it assumes that all bits are independent. Therefore, ![ PL(x) = \prod_i P(x_i | x_{-i}) \text{ and }\\ \log PL(x) = \sum_i \log P(x_i | x_{-i})](_images/math/9afc7d86b2124474783cdcea6107b600dc87c921.png) Here denotes the set of all bits of except bit . The log-PL is therefore the sum of the log-probabilities of each bit , conditioned on the state of all other bits. For MNIST, this would involve summing over the 784 input dimensions, which remains rather expensive. For this reason, we use the following stochastic approximation to log-PL: ![ g = N \cdot \log P(x_i | x_{-i}) \text{, where } i \sim U(0,N), \text{, and}\\ E[ g ] = \log PL(x)](_images/math/2cfd1b83d48af48b58613116a4082a4650db9f73.png) where the expectation is taken over the uniform random choice of index , and is the number of visible units. In order to work with binary units, we further introduce the notation to refer to with bit-i being flipped (1->0, 0->1). The log-PL for an RBM with binary units is then written as: ![ \log PL(x) &\approx N \cdot \log \frac {e^{-FE(x)}} {e^{-FE(x)} + e^{-FE(\tilde{x}_i)}} \\ &\approx N \cdot \log[ sigm (FE(\tilde{x}_i) - FE(x)) ]](_images/math/e2477c343b6cd503ab7e7b468be34d0c96d80a3c.png) We therefore return this cost as well as the RBM updates in the get_cost_updates function of the RBM class. Notice that we modify the updates dictionary to increment the index of bit . This will result in bit cycling over all possible values , from one update to another. Note that for CD training the cross-entropy cost between the input and the reconstruction (the same as the one used for the de-noising autoencoder) is more reliable then the pseudo-loglikelihood. Here is the code we use to compute the pseudo-likelihood: def get_pseudo_likelihood_cost(self, updates): """Stochastic approximation to the pseudo-likelihood""" # index of bit i in expression p(x_i | x_{\i}) bit_i_idx = theano.shared(value=0, name='bit_i_idx') # binarize the input image by rounding to nearest integer xi = T.round(self.input) # calculate free energy for the given bit configuration fe_xi = self.free_energy(xi) # flip bit x_i of matrix xi and preserve all other bits x_{\i} # Equivalent to xi[:,bit_i_idx] = 1-xi[:, bit_i_idx], but assigns # the result to xi_flip, instead of working in place on xi. xi_flip = T.set_subtensor(xi[:, bit_i_idx], 1 - xi[:, bit_i_idx]) # calculate free energy with bit flipped fe_xi_flip = self.free_energy(xi_flip) # equivalent to e^(-FE(x_i)) / (e^(-FE(x_i)) + e^(-FE(x_{\i}))) cost = T.mean(self.n_visible * T.log(T.nnet.sigmoid(fe_xi_flip - fe_xi))) # increment bit_i_idx % number as part of updates updates[bit_i_idx] = (bit_i_idx + 1) % self.n_visible return cost Main Loop¶ We now have all the necessary ingredients to start training our network. Before going over the training loop however, the reader should familiarize himself with the function tile_raster_images (see Plotting Samples and Filters). Since RBMs are generative models, we are interested in sampling from them and plotting/visualizing these samples. We also want to visualize the filters (weights) learnt by the RBM, to gain insights into what the RBM is actually doing. Bear in mind however, that this does not provide the entire story, since we neglect the biases and plot the weights up to a multiplicative constant (weights are converted to values between 0 and 1). Having these utility functions, we can start training the RBM and plot/save the filters after each training epoch. We train the RBM using PCD, as it has been shown to lead to a better generative model ([Tieleman08]). # it is ok for a theano function to have no output # the purpose of train_rbm is solely to update the RBM parameters train_rbm = theano.function( [index], cost, updates=updates, givens={ x: train_set_x[index * batch_size: (index + 1) * batch_size] }, name='train_rbm' ) plotting_time = 0. start_time = timeit.default_timer() # go through training epochs for epoch in range(training_epochs): # go through the training set mean_cost = [] for batch_index in range(n_train_batches): mean_cost += [train_rbm(batch_index)] print('Training epoch %d, cost is ' % epoch, numpy.mean(mean_cost)) # Plot filters after each training epoch plotting_start = timeit.default_timer() # Construct image from the weight matrix image = Image.fromarray( tile_raster_images( X=rbm.W.get_value(borrow=True).T, img_shape=(28, 28), tile_shape=(10, 10), tile_spacing=(1, 1) ) ) image.save('filters_at_epoch_%i.png' % epoch) plotting_stop = timeit.default_timer() plotting_time += (plotting_stop - plotting_start) end_time = timeit.default_timer() pretraining_time = (end_time - start_time) - plotting_time print ('Training took %f minutes' % (pretraining_time / 60.)) Once the RBM is trained, we can then use the gibbs_vhv function to implement the Gibbs chain required for sampling. We initialize the Gibbs chain starting from test examples (although we could as well pick it from the training set) in order to speed up convergence and avoid problems with random initialization. We again use Theano’s scan op to do 1000 steps before each plotting. ################################# # Sampling from the RBM # ################################# # find out the number of test samples number_of_test_samples = test_set_x.get_value(borrow=True).shape[0] # pick random test examples, with which to initialize the persistent chain test_idx = rng.randint(number_of_test_samples - n_chains) persistent_vis_chain = theano.shared( numpy.asarray( test_set_x.get_value(borrow=True)[test_idx:test_idx + n_chains], dtype=theano.config.floatX ) ) Next we create the 20 persistent chains in parallel to get our samples. To do so, we compile a theano function which performs one Gibbs step and updates the state of the persistent chain with the new visible sample. We apply this function iteratively for a large number of steps, plotting the samples at every 1000 steps. plot_every = 1000 # define one step of Gibbs sampling (mf = mean-field) define a # function that does `plot_every` steps before returning the # sample for plotting ( [ presig_hids, hid_mfs, hid_samples, presig_vis, vis_mfs, vis_samples ], updates ) = theano.scan( rbm.gibbs_vhv, outputs_info=[None, None, None, None, None, persistent_vis_chain], n_steps=plot_every, name="gibbs_vhv" ) # add to updates the shared variable that takes care of our persistent # chain :. updates.update({persistent_vis_chain: vis_samples[-1]}) # construct the function that implements our persistent chain. # we generate the "mean field" activations for plotting and the actual # samples for reinitializing the state of our persistent chain sample_fn = theano.function( [], [ vis_mfs[-1], vis_samples[-1] ], updates=updates, name='sample_fn' ) # create a space to store the image for plotting ( we need to leave # room for the tile_spacing as well) image_data = numpy.zeros( (29 * n_samples + 1, 29 * n_chains - 1), dtype='uint8' ) for idx in range(n_samples): # generate `plot_every` intermediate samples that we discard, # because successive samples in the chain are too correlated vis_mf, vis_sample = sample_fn() print(' ... plotting sample %d' % idx) image_data[29 * idx:29 * idx + 28, :] = tile_raster_images( X=vis_mf, img_shape=(28, 28), tile_shape=(1, n_chains), tile_spacing=(1, 1) ) # construct image image = Image.fromarray(image_data) image.save('samples.png') Results¶ We ran the code with PCD-15, learning rate of 0.1 and a batch size of 20, for 15 epochs. Training the model takes 122.466 minutes on a Intel Xeon E5430 @ 2.66GHz CPU, with a single-threaded GotoBLAS. The output was the following: ... loading data Training epoch 0, cost is -90.6507246003 Training epoch 1, cost is -81.235857373 Training epoch 2, cost is -74.9120966945 Training epoch 3, cost is -73.0213216101 Training epoch 4, cost is -68.4098570497 Training epoch 5, cost is -63.2693021647 Training epoch 6, cost is -65.99578971 Training epoch 7, cost is -68.1236650015 Training epoch 8, cost is -68.3207365087 Training epoch 9, cost is -64.2949797113 Training epoch 10, cost is -61.5194867893 Training epoch 11, cost is -61.6539369402 Training epoch 12, cost is -63.5465278086 Training epoch 13, cost is -63.3787093527 Training epoch 14, cost is -62.755739271 Training took 122.466000 minutes ... plotting sample 0 ... plotting sample 1 ... plotting sample 2 ... plotting sample 3 ... plotting sample 4 ... plotting sample 5 ... plotting sample 6 ... plotting sample 7 ... plotting sample 8 ... plotting sample 9 The pictures below show the filters after 15 epochs : Filters obtained after 15 epochs. Here are the samples generated by the RBM after training. Each row represents a mini-batch of negative particles (samples from independent Gibbs chains). 1000 steps of Gibbs sampling were taken between each of those rows.
http://www.deeplearning.net/tutorial/rbm.html
CC-MAIN-2017-17
refinedweb
4,737
56.35
J2ME Random Number J2ME Random Number In this application we are going to generate the random number using Random... this random number generator's sequence and the setSeed method is used to sets random number random number Please How do I generate a program that gives me random integer from 115 to 250? Using java.util.random. Thank you very much!  ...[] args){ int min = 115; int max = 250; Random random = new Random random number random number Sir could u please send me the code registration form of roseindia.net with image varification number and display the length of longest incresing series using random number using random number generate 10 digit number and display the length of longest incresing swries Get Random Number Get Random Number Random Number is the set of unordered arranged number. The class ... to describe you a code that helps you in understanding to Get Random Number PHP Random Number PHP Generate Random Numbers: A random number is becoming more useful.... To generate random number, PHP provides rand() function. ... rand() function could generate another random number as follows:</b> Random Number Generation - Java Beginners Random Number Generation Can any one tell me about to generate integers that should be a 10 numbered integer. Should be between 100000000 to 9999999999. Core Application Hi friend, Code to solve the problem Random Number | J2ME Label | J2ME KeyEvent | J2ME Key Codes... Map | Business Software Services India J2ME Tutorial Section Java Platform Micro Edition | MIDlet Lifecycle J2ME | jad and properties file random numbers random numbers Hi I need some help with the code for the this program. This program should randomly choose a number between 1 and 1000... the computer has randomly chosen the number 759.] Guess my number! It's between 1 and 1000 MySQL random number MySQL random number You may fall in the condition when you want to create random number for your... create a random number by the use of RAND() function of MySQL. There are two Random Numbers - shuffling The random number methods generate numbers with replacement. This means that a particular random number may be generated repeatedly. If you don't want the same... Random(); // Random number generator int[] cards = new int[52 Random numbers - Introduction generate a random number? Computers are deterministic -- they do the same thing... for a computer to compute a truly random number. But the methods that are used generate... to as pseudorandom numbers. These random number generates will produce exactly the same - created a variable Number in which generated random number is being taken... MySQL random In MySQL we can get the random records by using the method RAND() of MySQL to fine a software - Java Beginners to fine a software Is ther any software or utility available to create a jar file as in the case of zip file utility Default constructor generate two random equations Default constructor generate two random equations Need to create a default constructor in a programmer defined class that generates a random question, addition or subtraction. And when adding the numbers must be random from 0-12 J2ME Tutorial . J2ME Random Number In this application we are going to generate the random number using Random class. The Random class within... J2ME Tutorial   j2me j2me why we extends class MIDlet in j2me application j2me j2me how to compile and run j2me program at command prompt j2me j2me i need more points about j2me Random classes Random classes Hello... What is Random class? What's the purpose J2ME how to use form and canvas is same screen in J2ME Hi how to accept time in textField using constraints in case of J2ME Hello Friend, Please visit the following link: Thanks PHP Random image, PHP Randomizing image ); This line generates a random value not greater than number of files...PHP Random image PHP Random image Tutorial Ever wanted to know how to create the random gallery? Well, here is the way you can do it: <?php Generate array of random numbers Generate array of random numbers You can generate a random number either by using the Random class or by using the static method Math.random... then there is no need to create a new Random object for each new random number j2me j2me What is JAD file what is necesary of that Hi Friend, Please visit the following link: JAD File Thanks Hi Friend, Please visit the following link: JAD File Thanks Generating Random Numbers to Fill array. Java Beginner needing help! Generating Random Numbers to Fill array. Java Beginner needing help!  ... a program that produces random permutations of the numbers 1 to 10. eg... displayPermutedArray(){} // Repeat the selection of a number 10 times to populate Random numbers - API to the constructor if you wish), then call one of the methods below to get a new random number... return a random number. These methods return a uniform distribution... (true or false) double d = xrnextGaussian()Returns random number with mean 0 Books J2ME Books Free J2ME Books J2ME programming camp..., and development. This book also contains a number of advanced EJB topics, giving you GUESS NUMBER - Java Beginners GUESS NUMBER Create a guessing game that picks a random number...() { super("Guess Number"); randomNumber = new Random().nextInt(100) + 1..., "CONGRATULATIONS! You got it!!", "Random Number: " + randomNumber J2ME J2ME i wann source code to find out the difference between two dates.. and i wan in detail.. plz do favour for me.. import java.util.... (ParseException e) { e.printStackTrace(); } } } i wann j2me code Pick at Random the entry from the array before selecting another name at random Random Access File. Random Access File. Explain Random Access File JSTL - check odd/even number - JSP-Servlet to generate random numbers and to check whether they are odd/even and print "this is an even (odd) number and it is in between so and so number? e.g. the random number... Friend, Try the following code: Random Number: Random number Random Access File class Random Access File class Write a short note on Random Access File class. Please visit the following link: Java Random Access File problem on server which works fine on another - Java Server Faces Questions problem on server which works fine on another I am having a problem when a tab is clicked, the action listener class is called guess number - Java Interview Questions ! You got it!!", "Random Number: " + randomNumber, JOptionPane.INFORMATION...guess number i am doing a java program for user to guess number. i...) { input=JOptionPane.showInputDialog("Invalid number!Please re-enter Generate Random Numbers Generate Random Numbers hi,,, Please give me answer with example How do you generate random numbers within a given limit with actionscript... This function generate random numbers with in given limit RANDOM ACCESS FILE CONCEPT RANDOM ACCESS FILE CONCEPT In a random access file, first write the alphabets a,b, c, d till z. Read the file in reverse order and print it on screen random numbers - Java Beginners random numbers write a program to accept 50 numbers and display 5... java.util.*; class RandomNumberExample { static Random generator = new Random...(); System.out.println("Random numbers are: "); int random[]=new int[5]; for(int i=0;i Guess Number Games in Java Guess Number Games in Java Here we are going to create guess number game where user have to guess the randomly generated number. For this, we have allowed the user to enter any number through the textfield and click the 'try' button ACCESS FILE CONCEPT RANDOM ACCESS FILE CONCEPT Write a program to use a File object and print even numbers from two to ten. Then using RandomAccessFile write numbers from 1 to 5. Then using seek () print only the last 3 digits List in J2ME List in J2ME J2ME Canvas List Example will explain you, how to create list of items...;Display.getDisplay(this); } You can add any number Generating random numbers in a range with Java Generating random numbers in a range with Java Generating random numbers in a range with Java
http://roseindia.net/tutorialhelp/comment/83617
CC-MAIN-2014-15
refinedweb
1,331
52.49
The Quasar Method Make your Vue.js project fast, cheap and good! code base using tricks of the trade, best-practices and for all intents and purposes it really gives development teams super-powers. Still a tightly kept secret in the industry, the Quasar command-line-interface leverages Evan You’s Vue 2 : “a progressive framework for building user interfaces” and produces distributable artifacts from one set of code using a Webpack-4 hot-reloading development server, Babel-7 transpiling, eslint code linting, ES6 constructs and stylus css preprocessing. Out of the box it offers 117 custom components, 9 directives and 13 plugins, all of which adhere to the Material Design specification. Do things once, do them well and do it now. Let’s assume you are pressed for time and just want to make a quick POC multi-platform app to showoff Quasar’s color-picker component and two-way binding with Vue using the whole Quasar Kitchensink: a Single Page Application (SPA— like a classical website), a Progressive Web App (PWA) a native app (with Electron) for Windows, Mac and Linux as well as an app (via Cordova) for Android and iOS. Then, once you have all that stuff built, you are going to need to tl;dr $ quasar init outoftime $ quasar dev $ quasar build $ quasar build -m pwa $ quasar build -m electron --target all --bundler builder $ quasar build -m cordova -T android $ quasar build -m cordova -T ios Quasar just built you a website, a PWA, electron apps (mac, windows and linux) and mobile apps (Android and iOS). Read on for more insight into each of these commands. Although Quasar makes it simple, you have to make sure that your development environment embodies all of the requirements needed to properly execute quasar-cli. This is doubly true if you are doing anything with Cordova. You can find detailed instructions about the setup in our docs. Everything here (with the obvious exception of publishing to the Mac and iOS stores) will work for you on all major platforms: Linux, MacOS and Windows. QUASAR INIT $ quasar init outoftime This command will create a new project folder for you at outoftime, scaffold it with all of the folders and files needed for a bare-bones project and initialize a package.json file. Of special note is the /outoftime/quasar.conf.js file, as its object contains the configurations you will need to add components, plugins, theme overrides etc. QUASAR DEV $ cd outoftime $ quasar dev Change into your new folder and start the development server. When the webpack dev server starts up it spends a little extra time to create fresh versions of all of the cache files it needs to build a server. After it has finished webpack will automatically open a browser tab and show you what it built: This is the stock “smoke test” of the Quasar Framework. If you do not see this page after running quasar dev, then something is wrong. Now we can get to work changing the source to say “Out of Time” in the Header bar and show a color picker that you can use to change the address bar color. So the first thing to do is to edit quasar.conf.js and tell Quasar to import the QColorPicker component by adding it to the list of components. framework: { components: [ 'QColorPicker', ... ] } Then we’ll edit the /outoftime/src/layouts/default.vue file: <template> <q-layout <q-layout-header> <q-toolbar <q-toolbar-title> Out of Time Color Picker <div slot="subtitle"> Running on Quasar v{{ $q.version }} </div> </q-toolbar-title> </q-toolbar> </q-layout-header> <q-page-container> <q-color-picker </q-page-container> </q-layout> </template><script> import { colors } from 'quasar' export default { data: () => ({ modelHex: '#C7044B' }), watch: { modelHex: { handler (val, oldVal) { colors.setBrand('primary', val) }, immediate: true } } } </script> As soon as you save the new default.vue file, webpack sees that there has been a change and assuming your work passes all of the ESlint tests, you should see the following in the browser: Move the slider or the “picker circle” and the address bar color will change accordingly. Great. Now lets build the project so you can host it as a website. QUASAR BUILD $ quasar build Now you just have to serve that folder somehow, for example with http-server. $ http-server dist/spa-mat/ Now visit your localhost:8080 and you should see the exact same thing as the webpack dev server showed you. QUASAR BUILD PWA $ quasar build -m pwa Now you just have to serve that folder somehow, for example with http-server. $ http-server dist/pwa-mat/ Now visit your localhost:8080 and you should see the exact same thing as the webpack dev server showed you — as opposed to the SPA mode, now you have a Progressive Web App. QUASAR BUILD ELECTRON So you want to have your color-picker available as a native app for all desktop versions. Easy: $ quasar build -m electron --target all --bundler builder If you haven’t done this before, the latest electron binaries for the respective platforms will be downloaded. This is a screenshot of the MacOS app: QUASAR BUILD CORDOVA Since Electron was so easy, why not just make the little color-picker as a Cordova app for iOS and Android. Guess what? Except that you have to run it in two steps, it is just as easy: $ quasar build -m cordova --target ios $ quasar build -m cordova --target android That wraps it up. In this article you saw how mind-numbingly simple Quasar makes it for you to create SPA, PWA, Electron, Cordova and SSR app from a single vue.js codebase. For your information, this code for this article was originally written using quasar-cli v0.16.4 and I have just published the accompanying project as a git repo. To use it git clone as usual, cd into the directory and run npm install or yarn, and then quasar dev … If you want to find out more about the Quasar-Framework and its method, please consider:
https://medium.com/quasar-framework/the-quasar-method-e19daf9abb5f
CC-MAIN-2021-43
refinedweb
1,012
57.2
Question on handling Max's global namespaces (for tables in particular)… Hi All – Still trucking along nicely in my Max eval (14 days remaining) and I’ve run into this question a few times, without finding any great solutions yet, so I thought I’d throw it out to get some opinions. As I’ve learned, Max seems to use a "global" namespace for all named objects. For example, if you create two table objects, both named "table mytable", they will reference the same shared data. This aspect of tables can be very useful, particularly when combined w/ the "refer" command, however it seems I also have scenarios where it complicates matters. The most direct and obvious problem is an abstraction which I would like to use multiple times within a patch (or even in a different patch loaded at the same time) – If I use a normally defined "table mytable", then each instance of the abstraction will share the table data, while in this case I need each instance to have its own table data. I’ve hit upon a few possible workarounds – I’ve looked at the commands to dynamically create tables and I’ve successfully done this using programmatically generated table names (so they can be made unique), but this adds complexity because I have to create table, patch table, etc. I’ve also looked at just passing in the tables to each instance, so they can be uniquely defined in the meta project, or possibly passing in an ID that will be used to create a unique identified dynamically, but this clutters the parent patch with details that should be hidden in the abstraction. None of these options seem particularly elegant – Is there any easier solutions I’m overlooking? Why aren’t namespace clashes a bigger problem in Max (or are they)? Isn’t it correct that if I make an abstraction/patch and call my table "mytable", and someone else does the same thing, our patches will not work together correctly? This seems like it could be a tricky problem to hunt down in complex setups… What’s the solution? As a precaution I am now prefacing all my names w/ a unique extension, a poor man’s namespace, like mylib_myobj_myname, where only myname changes within each object. Are there better practices I should consider? Of course this doesn’t solve the table namespace issue, but I feel like one is less likely to run into namespace collision problems this way. Thanks in Advance, and Best Regards – tangent I think I’ve found a solution so I’ll follow-up in case someone else see’s this down the road… It looks like for this I need to use the "#0" argument. I did not realize this was a special automatic argument that resolves to a random id. I think this will solve the problem nicely, as I can use "table #0mytable" to generate unique table names as well as messages (refer #0mytable) to pass as table names reference. A bit of work to redo all my table/send/receive etc names but worthwhile because it solves all the namespace issues for objects meant to be used multiple times. Cheers. Forums > MaxMSP
https://cycling74.com/forums/topic/question-on-handling-maxs-global-namespaces-for-tables-in-particular/
CC-MAIN-2015-35
refinedweb
537
59.26
In the above example, we retreived: import socketimport time mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)mysock.connect(('', 80))mysock.send('GET HTTP/1.0\n\n') count = 0picture = "";while True: data = mysock.recv(5120) if ( len(data) < 1 ) : break # time.sleep(0.25) count = count + len(data) print len(data),count picture = picture + data mysock.close() # Look for the end of the header (2 CRLF)pos = picture.find("\r\n\r\n");print 'Header length',posprint picture[:pos] # Skip past the header and save the picture datapicture = picture[pos+4:]fhand = open("stuff.jpg","w")fhand.write(picture);fhand.close() When the program runs it produces the following output: $ python urljpeg.py2920 29201460 43801460 58401460 7300...1460 627801460 642402920 671601460 686201681 70301Header length 240HTTP/1.1 200 OKDate: Sat, 02 Nov 2013 02:15:07 GMTServer: ApacheLast-Modified: Sat, 02 Nov 2013 02:01:26 GMTETag: "19c141-111a9-4ea280f8354b8"Accept-Ranges: bytesContent-Length: 70057Connection: closeContent-Type: image/jpeg You can see that that for this url, the Content-Type header indicates that body of the document is an image (image/jpeg). Once the program completes, you can view the image data by opening the file stuff.jpg in an image viewer. As the program runs, can see that we don’t get 5120 characters each time we call the recv() method. We get as many characters calls recv() by uncommmenting the call to time.sleep(). This way, we wait a quarter of a second after each call so that the server can “get ahead” of us and send more data to us before we call recv().”. - 瀏覽次數:1178
http://www.opentextbooks.org.hk/zh-hant/ditatopic/6787
CC-MAIN-2021-17
refinedweb
269
66.13
In this post I will describe all the steps needed to execute custom Java code upon the selection of an entry in the action menu or the click of a button in the toolbar. Add a sigoptionFirst you need to create a new sigoption. Open the Application Designer and select the application you want to modify. Select 'Add/Modify Signature Options' and create a new signature RUNJAVA. Add the menu entryThe second step is to create the custom entry in the action menu (or a new button). Select 'Add/Modify Select Action Menu' and create the new entry RUNJAVA of type OPTION. Beware that the name must be the same as the sigoption. Grant sigoption permissions and test the dummy actionBefore going on I recommend the test that the new menu entry is visible. Go in the Security Groups application, select the group you want to be able to see and execute the custom code. Go in the Applications tab and select your application. Now you should see the RUNJAVA sigoption on the bottom of the page. Click on the checkbox to grant access to the new menu entry. Disconnect and login with a user belonging to the chosen group, go in the application and verify that you see the new menu entry. Now it's time to attach your Java code to it. Write your Java codeThe most suitable place to put your Java code is in the 'App Bean Class' which is the custom Java class that manages the application. To determine which Java bean handles the application, open Application Designer and select the application, from the Action menu choose 'Toggle Show All Controls' and display the properties of the 'presentation' section. The 'App Bean Class' defines the Java class that you need to customize. Here is the WOTRACK application App Bean Class definition. You should extend this class and create a new method with the same name of the sig option in the Java bean class (RUNJAVA in our example). Don't forget to change the App Bean Class property setting your own custom class. Here is an example of how the custom class should look like. package cust.psdi.webclient.beans.workorder; public class CustWorkorderAppBean extends psdi.webclient.beans.workorder.WorkorderAppBean { public int RUNJAVA() throws MXException, RemoteException { // put your custom code here return EVENT_HANDLED; } } Implement your custom logic in the RUNJAVA method and copy the class file under [SMPDIR]\maximo\applications\maximo\maximouiweb\webmodule\WEB-INF\classes folder. Rebuild and redeploy Maximo EAR file. thanks you for the article. Can You help me with other problem ? Is there any possibility to execute custom class by typing this link Can you please try to extend psdi.webclient.beans.asset.AssetAppBean (the ASSET app bean) as described in this post and call the xxxxxx method from the action menu? You can put some traces to see if it works. Then try invoking it with the link. I think it should work. Regards, Bruno thank you again, it's working now. I forgot to change class in application designer Hi, I followed all steps and I now made the class 'CustWorkorderAppBean' Where should I put this class to run it? Thanks, This article explains how to deploy custom classes: Hi Bruno, Thank you very much. It worked. Your techincal posts are really good for us ..the maximo thecno consultants. If possible can you share some Functional posts especially Work Management , Purchasing and Inventory with workflow ...in terms business cases. It will really helpful for the community. Hello, I am a total beginner. And have a question. How and where can I make this class Thank
http://maximodev.blogspot.com/2011/08/call-java-method-on-action-menu-or.html
CC-MAIN-2017-30
refinedweb
606
57.47
#include <c4d_fielddata.h> FieldOutput sub block class. FieldOutputBlock never own the memory of the sampling arrays, it is owned by the FieldOutput structure. Lifetime of a block is the same as its owner. Resizing, resetting the owner, or any other operation that will have the owner reallocate or deallocate memory will invalidate the blocks. Creates and empty sampling block, with not data. Move construction. Does not actually steal anything as FieldOutputBlock never owns the memory. Gets a sub-section of "this" which can be indexed from 0 to "blockSize". Resets the FieldOutputBlock to default state (i.e. null count, no owner, no data, empty). Gets the number of elements in the sub block. Gets the number of elements used in the owning FieldOutput. Gets the offset of the sub block in the FieldOutput. Returns the owner FieldOutput. Copies from the FieldOutputBlock described by src. Note that FieldOutputBlock never owns the arrays, so the copy only copies the raw pointers. Copies from the FieldOutput array content from src. Block size and flags will not be affected by this action. The destination allocated size must be big enough to accept the full content of the src block. Destination block will own memory if it is a normal block or not own it if it is a subblock. Reset the sample's data to default values, optionally only the deactivated content too. Values are reset to 0, colors to 1.0, direction to 0, deactivated to 0. Reset the sample's data to default values, optionally only the deactivated content too. Values are reset to 0, colors to 1.0, direction to 0, deactivated to 0. Clears the deactivated array. Calculates a crc on all internal data using maxon::Crc32C. Crc is not kept internally and will be calculated from scratch on each CalculateCrc call. Checks if the FieldOutputBlock allocations and sizes are valid (empty is considered valid). Checks if the FieldOutputBlock is valid and non-empty. The weight value at this point in space. The alpha value for color and direction at this point in space, only available when color or direction are allocated. The color at this point in space. The slope at this point in space. The rotational velocity (axle + magnitude) The rotational pivot point in space. The deactivated state for this point (i.e. cut from interior shape will be true) this skips remapping. The number of elements in the sample arrays. Data offset in the original arrays (owner).
https://developers.maxon.net/docs/Cinema4DCPPSDK/html/struct_field_output_block.html
CC-MAIN-2020-24
refinedweb
410
61.02
Edward Hyde, 1st Earl of Clarendon, was an English historian and statesman and grandfather to two British monarchs, Mary II and Queen Anne. ------------------------------------------------------------- Dictionary of National Biography, 1885-1900, Volume 28 Hyde, Edward (1609-1674) by Charles Harding Firth HYDE, EDWARD, Earl of Clarendon (1609-1674), descended from a family of Hydes established at Norbury in Cheshire, son of Henry Hyde of Dinton, Wiltshire, by Mary, daughter of Edward Langford of Trowbridge, was born on 18 Feb. 1608-9 (Lister, Life of Clarendon, i. l; The Life of Clarendon, written by himself, ed. 1857, i. § 1). In Lent term 1622 Hyde entered Magdalen Hall, Oxford; failed, in spite of a royal mandate, to obtain a demyship at Magdalen College, and graduated B.A. on 14 Feb. 1626 (Lister, i. 4; Wood, Athenæ Oxon. ed. Bliss, iii. 1018). He left the university 'rather with the opinion of a young man of parts and pregnancy of wit, than that he had improved it much by industry' (Life, i. 8). His father had destined him for the church, but the death of two elder brothers made him heir to the paternal estate, and in 1625 he became a member of the Middle Temple (Lister, i. 6). In spite of the care which his uncle, Chief Justice Sir Nicholas Hyde [q.v.], bestowed on his legal education, he preferred to devote himself to polite learning and history, and sought the society of wits and scholars. In February 1634 Hyde was one of the managers of the masque which the Inns of Court presented to the king as a protest against Prynne's illiberal attack upon the drama (Whitelocke, Memorials, f.19). Jonson, Selden, Waller, Hales, and other eminent writers were among his friends. In his old age he used to say ' that he owed all the little he knew and the little good that was in him to the friendship and conversation of the most excellent men in their several kinds that lived in that age,' but always recalled with most fondness his ‘entire and unreserved' friendship with Lord Falkland (Life, i. 25, 35). In 1629 Hyde married Anne, daughter of Sir George Ayliffe of Gretenham, Wiltshire. She died six months later, but the marriage connected him with the Villiers family, and gained him many powerful friends (Lister, i. 9; Life, i. 13). This connection was one of the motives which induced Hyde to vindicate Buckingham's memory in his earliest historical work, a tract entitled ' The Difference and Disparity between the Estate and Condition of George, Duke of Buckingham, and Robert, Earl of Essex' (Religuics Wottoniance, ed. 1685, pp. 185-202). According to Hyde's friend, Sir John Bramston, Charles I was so pleased with this piece that he wished the author to write Buckingham's life (Autobiography of Sir John Bramston, p.255). Hyde's second marriage, 10 July 1634, with Frances, daughter of Sir Thomas Aylesbury, one of the masters of requests, still further improved his fortunes (Chester, Westminster Registers, p.167). He had been called to the bar on 22 Nov. 1633, began now seriously to devote himself to his profession, and soon acquired a good practice in the court of requests. In December 1634 he was appointed keeper of the writs and rolls of the common pleas (Bramston, p.255; Doyle, Official Baronage, i. 402). The courage and ability with which Hyde conducted the petition of the London merchants against the late lord treasurer, Portland, gained him the favour of Laud. He was consequently ' used with more countenance by all the judges in Westminster Hall and the eminent practisers, than is usually given to men of his years' (Life, i.23). His income grew, he increased his paternal estate by buying adjoining land, and he made influential friends. Hyde began his political career as a member of the popular party. Although he did not share the hostility ot the puritans to Laud's ecclesiastical policy, nor the common animosity of the lawyers to the churchmen, he was deeply stirred by the perversions and violations of the law which marked the twelve years of the king's personal rule (1628-40). In the Short parliament of 1640 he sat for Wootton Bassett, was a member of seven important committees, and gained great applause by attacking the jurisdiction of the earl marshal's court (Lister, i. 62; Life, i. 78). According to his own account, which cannot be implicitly trusted, he endeavoured to mediate between the king and the commons, and used his influence with Laud to prevent a dissolution. In the Long parliament Hyde represented 'Saltash, and, as before, principally directed his reforming zeal to questions connected to the administration of the law. He renewed his motion against the marshal's court, obtained a committee, and produced a report which practically abolished that institution. Hyde also acted as chairman of the committees which examined into the jurisdictions of the council of Wales and the council of the North, and gained great popularity by his speech against the latter (26 April 1641; Rushworth, iv. 230). He took a leading part in the proceedings against the judges, and laid before the lords (6 July 1641) the charge against the barons of the exchequer (ib. iv. 333). In the proceedings against Strafford he acted with the popular party, helped to prepare the articles of impeachment, was added on 25 March 1641 to the committee for expediting the trial, and on 28 April took up a message to the lords begging that special precautions might be taken to prevent Strafford's escape (Commons Journals, ii. 112, 130). Hyde's name does not appear in the list of those voting against the attainder bill, and it is hardly possible to doubt that he voted for that measure. He may have ultimately joined the party who were contented with Strafford's exclusion from affairs of state; but the story of his interview with Essex on this subject contains manifest impossibilities (Rebellion, iii. 161; Gardniner, ix. 840). Church questions soon led Hyde to separate himself from the popular party. He opposed, in February 1641, the reception of the London petition against episcopacy, and in May the demand of the Scots for the assimilation of the English ecclesiastical system to the Scottish (ib. ix. 281, 377). He opposed also, differing for the first time with Falkland, the bill for the exclusion of the clergy from secular office, and was from the beginning the most indefatigable adversary of the Root and Branch Bill. The house went into committee on that bill on 11 July 1641, and its supporters, hoping to silence Hyde, made him chairman. In this capacity he so successfully obstructed the measure that it was dropped (Rebellion, iii. 150-6, 240-2). Hyde's attitude attracted the notice of the king, who sent for him and urged him to persist in the church's defence (Life, i. 93). At the opening of the second session his severance from his former friends was still more marked, and Secretary Nicholas recommended him to the king as one of the chief champions of the royal prerogative (Evelyn, Diary, ed. 1879, iv. 116). He resisted Pym's attempt to make the grant of supplies for the reconquest of Ireland dependent on parliament's approval of the king's choice of councillors, and opposed the Grand Remonstrance, though admitting that the narrative part of it was true and modestly expressed' (Gardiner, x. 55, 76; Verney, Notes on the Long Parliament, pp. 121, 126). He sought by an attempted protest to prevent the printing (ib. vi. 79 n.) The House of Commons expelled him (11 Aug. 1642), and he was one of the eleven persons who were to be excepted from pardon (21 Sept.), an exception which was repeated in subsequent propositions for peace (Husbands, p.633). During his stay at Oxford, from October 1642 to March 1645, Hyde lived in All Souls College. In the spring of 1643 he at last exchanged the position of secret adviser for that of an avowed and responsible servant of the crown. On 22 Feb. he was admitted to the privy council and knighted, and on 3 March appointed chancellor of the exchequer (Life, ii. 77; Black, Oxford Docquets, p.351). The king wished to raise him still higher. 'I must make Ned Hyde secretary of state, for the truth is I can trust nobody else,' said an intercepted letter from Charles to the queen. But Hyde was unwilling to supersede his friend Nicholas, and refused the offered post both now, and later after Falkland's death. Promotion so rapid for a man of his age and rank aroused general jealousy, especially among the members of his own profession. Courtiers considered him an upstart, and soldiers regarded him with the hostility which they felt for the privy council in general (cf. Rebellion, vii. 278-82; Life, ii. 73, iii. 37). As chancellor of the exchequer Hyde, in his endeavours to raise money for the support of the war, was concerned in procuring the loan known as 'the Oxford engagement,' and became personally bound for the repayment of some of the sums lent to the king (Cal. Committee for Advance of Money, p. 1002; Clarendon State Papers, ii. 154). His attempt to bring the Bristol custom-dues into the exchequer brought him into collision with Ashburnham, the treasurer of the army (Life, iii. 33). In the autumn of 1643 the king created a secret committee, or 'junto,' who were consulted on all important matters before they were discussed in the privy council. It consisted of Hyde and five others, and met every Friday at Oriel College (Life, iii. 37, 58; Clarendon State Papers, ii. 286, 290). In the different conferences for peace Hyde was habitually employed in the most delicate personal negotiations, a duty for which his former intimacy with many of the parliament's commissioners specially qualified him. Over-estimating, as his history shows, the influence of personal causes in producing the civil war, he believed that judicious concessions to the leaders would suffice to end it. In the summer of 1642 he had made special efforts to win over the Earl of Pembroke (ib. ii. 144-8; Rebellion, vi. 401 n.) During the Oxford negotiations in March 1643 he intrigued to gain the Earl of Northumberland, and vainly strove to persuade the king to appoint him lord high admiral (Life, iii. 4-12). In the following summer, when Bedford, Clare, and Holland deserted the parliament, Hyde stood almost alone in recommending that the deserters should be well received by king, queen, and court, and held the failure to adopt this plan the greatest oversight committed by the king (Rebellion, vii. 185, 244). When it was too late, Hyde's policy was adopted. In February 1645, during the Uxbridge negotiations, he and three others were empowered to promise places of profit to repentant parliamentarians, but his conferences with Denbigh, Pembroke, Whitelocke, and Hollis led to no result (ib. viii. 243-8; Whitelocke, Memorials, f. 127; Harleian Miscellany, vii. 559). Throughout these negotiations Hyde opposed any real concessions on the main questions at issue between king and parliament. At Uxbridge (January 1645) he was the principal figure among the king's commissioners, prepared all the papers, and took the lead in all the debates (Rebellion, vii. 252). He defended Ormonde's truce with the Irish rebels, and disputed with Whitelocke on the question of the king's right to the militia (ib. viii. 256). Already, in an earlier negotiation with the Scottish commissioners (February 1643), he had earned their detestation by opposing their demands for "ecclesiastical uniformity, and at Uxbridge he was as persistent in defending episcopacy. Nevertheless, he was prepared to accept a limited measure of toleration, but regarded the offers made at Uxbridge as the extreme limit of reasonable concessions (Clarendon State Papers, ii. 237). The most characteristic, result of Hyde's influence during this period was the calling of the Oxford parliament (December 1643). He saw the strength which the name of a parliament gave the popular party, and was anxious to deprive them of that advantage. Some of the king's advisers urged him to dissolve the Long parliament by proclamation, and to declare the act for its continuance invalid from the beginning. Hyde opposed this course, arguing that it would alienate public opinion (Life, iii. 40). His hope was to deprive the Long parliament of all moral authority by showing that it was neither free nor representative (Rebellion, vii.326). With this object, when the Scots accepted the Long parliament's invitation to send an army into England, Hyde proposed the letter of the royalist peers to the Scottish privy council, and the summoning of the royalist members of parliament to meet at Oxford (ib. vii. 323). Both expedients proved ineffectual. The Oxford parliament was helpful in raising money, but useless in negotiating with the parliament at Westminster, while the king resented its independence and its demands for peace. With the failure of Hyde's policy the king fell completely under the influence of less scrupulous and less constitutional advisers. On 4 March 1645 Hyde was despatched to Bristol as one of the council charged with the care of the prince of Wales and the government of the west. The king was anxious to place so trustworthy a servant near the prince, and glad no doubt to remove so strong an opponent of his Irish plans. Already Charles had given to Glamorgan 'those strange powers and instructions ' which Hyde subsequently pronounced to be 'inexcusable to justice, piety, and prudence' (Clarendon State Papers, ii. 337; Life, iii. 50; Rebellion, viii. 253). The arrival of the prince in the west was followed by a series of disputes between his council and the local military commanders. Hyde, who was the moving spirit of the council, paints in the blackest colours the misconduct of Goring and Grenville; but the king's initial error in appointing semi-independent military commanders, and then setting a board of privy councillors to control them, was largely responsible for the failure of the campaign. Hyde complains bitterly that, but for the means used at court to diminish the power of the council, they would have raised the best army that had been in England since the rebellion began, and, with Hopton to command it, might have effected much (Lister, iii. 20; Rebellion, ix. 7 n, 43). But when Hopton at last took over the command of Goring' s 'dissolute, undisciplined, beaten army,' it was too late for success, and his defeat at Torrington (16 Feb. 1646) obliged the prince's councillors to provide for the safety of their charge. The king had at first ordered the prince to take refuge in France, and then, on the remonstrance of his council, suggested Denmark. Hyde's aim was to keep the prince as long as possible in English territory, and as long as possible out of France. As no ship could be found fit for the Danish voyage, the prince and his council established themselves at Scilly (4 March 1646), and, when the parliamentary fleet rendered the islands untenable, removed to Jersey (17 April). On the pretext that Jersey was insecure, the queen at once ordered the prince to join her in France, and, against the advice of Hyde and his council, the prince obeyed (Clarendon State Papers, ii. 240, 352; Rebellion, x. 3-48). Hyde distrusted the French government, feared the influence of the queen, and was afraid of alienating English public opinion (Clarendon State Papers, ii. 235, 287). Though Hyde's opposition to the queen in this matter was the main cause of her subsequent hostility to him, his policy was in other respects diametrically opposed to that which she advocated. She pressed the king to buy the support of the Scots by sacrificing the church. Hyde expected nothing good from their aid, and would not pay their price (ib. ii. 291, 339). He was equally hostile to her plans for restoring the king by French or foreign forces (ib. ii. 307, 329, 339). He was resolved not to sacrifice a foot of English territory, and signed a bond with Hopton, Capel, and Carteret to defend Jersey against Lord Jermyn's scheme for its sale to France (19 Oct. 1646; ib. ii. 279). During the king's negotiations with the parliament and the army Hyde's great fear was that Charles should concede too much. 'Let them,' he wrote, 'have all circumstantial 'temporary concessions, …. distribute as many personal obligations as can be expected, but take heed of removing landmarks and destroying foundations. … Either no peace can be made, or it must be upon the old foundations of government in church and state' (ib. ii. 326, 333, 379). Hyde faithfully practised the principles which he preached, declining either to make his peace with the parliament or to compound for his estate. 'We must play out the game,' he wrote, with that courage as becomes gamesters who were first engaged by conscience against all motives and temptations of interest, and be to let the world know that we were carried on only by conscience ' (ib. iii. 24). Hyde was already in great straits for money. But he told Nicholas that they had no reason to blush for a poverty which was not brought upon them by their own faults (ib. ii. 310). Throughout the fourteen years of his exile he bore privation with the same cheerful courage. During his residence in Jersey Hyde lived first in lodgings in St. Helier, and afterwards with Sir George Carteret in Elizabeth Castle. He occupied his enforced leisure by keeping up a voluminous correspondence, and by composing his 'History of the Rebellion,' which he began at Scilly on 18 March 1646. In a will drawn up on 4 April 1647 he directed that the unfinished manuscript should be delivered to Secretary Nicholas, who was to deal with it as the king should direct. If the king decided that any part of it should be published, Nicholas and other assistant editors were empowered to make whatever suppressions or additions they thought fit (Clarendon State Papers, ii. 289, 357). Hyde had also an immediate practical purpose in view. As soon as I found myself alone,' he wrote to Nicholas, 'I thought the best way to provide myself for new business against the time I should be called to it, was to look over the faults of the old, and so I resolved to write the history of these evil times ' (ib. ii. 288). By April 1648 he had carried his narrative down to the commencement of the campaign of 1644. Meanwhile, in February 1648 the Long parliament resolved to present no further addresses to the king, and published a scandalous declaration of its reasons. Hyde at once printed a vindication of his master: 'A full Answer to an infamous and traitorous Pamphlet entitled A Declaration of the Commons of England expressing their reasons of passing the late Resolutions of no further addresses to be made to the King' (published July 28, 1648. An earlier and briefer version of the same answer was published 3 May). On the outbreak of the second civil war, Hyde was summoned by the queen and the prince to join them at Paris. He left Jersey 26 June 1648, and made his way to Dieppe, whence he took ship for Dunkirk (Clarendon State Papers, ii. 406; Hoskins, Charles II in the Channel Islands, ii. 202). Finding at Dunkirk that the prince was with the fleet in the Thames, he followed him thither. On his way he fell into the hands of an Ostend corsair (13-23 July), who robbed him of all his clothes and money, nor did he succeed in joining Prince Charles till the prince's return to the Hague (7-17 Sept.: Life, v. 10-23; Rebellion, xi. 23, 78). There he found the little court distracted by feuds and intrigues. Hyde set himself to reconcile conflicting interests and to provide the fleet with supplies for a new expedition (Rebellion, xi. 127, 152; Warburton, Prince Rupert, iii. 274, 276, 279). He advised the prince not to trust the Scots, whose emissaries were urging him to visit Scotland, and was resolved that he himself would go neither to Scotland nor to Ireland. In any case, the Scots would not have allowed him to accompany the prince, and he held it safer to see the result of the negotiations at Newport before risking himself in Ireland. The king's concessions during the treaty had filled him with disgust and alarm. The best,' he wrote, which is proposed is that which I would not consent to, to preserve the kingdom from ashes' (Clarendon State Papers, ii. 459). When the army interrupted the treaty and brought the king to trial, Hyde vainly exerted himself to save his master's life. He drew up a letter from the prince to Fairfax, and after the king's death a circular to the sovereigns and states of Europe, invoking their aid to avenge the king's execution (Cal. State Papers, Dom. 1649-50, p. 5; Cal. Clarendon Papers, i. 465; cf. Warburton, iii. 283). Hyde's enemies thought his influence then at an end, but in spite of the queen's advice, Charles II retained as councillors all the old members of his father's privy council who were with him at the Hague (Rebellion, xii. 2). The question whether the new king should establish himself in Scotland or Ireland required immediate decision. As the presbyterian leaders demanded the king's acceptance of the covenant, and ' all the most extravagant propositions which were ever offered to his father,' Hyde advised the refusal of their invitation. He had conferred with Montrose, and expected more good from his expedition than from a treaty with Hamilton and Argyll. The Scots and their partisans regarded Hyde as their chief antagonist, and succeeded in suppressing the inaugural declaration which he drew up for the new king (ib. xii. 32; Clarendon State Papers, ii. 467, 473, 527). In the end Charles resolved to go to Ireland, but to pay a visit to his mother in France on the way. Hyde, who termed Ireland the nearest road to Whitehall, approved the first half of the plan, but objected to the sojourn in Paris. Accordingly, when Cottington proposed that they both should go on an embassy to Spain, Hyde embraced the chance of an honourable retreat (Nicholas Papers, i. 124; Rebellion, xii. 34). His friends complained that he was abandoning the king just when his guidance was most necessary. But Hyde felt that a change of counsellors would ultimately re-establish his own influence, and expected to rejoin the king in Ireland within a few months. The chief objects of the embassy were to procure a loan of money from the king of Spain, to obtain by his intervention aid from the pope and the catholic powers, and to negotiate a conjunction between Owen O'Neill and Ormonde for the recovery of Ireland. The ambassadors left Paris on 29 Sept. 1649, and reached Madrid on 26 Nov. The Spanish government received them coldly (Guizot, Cromwell, transl. 1854, i. 419-26). Their money was soon exhausted, and Hyde was troubled by the ' miserable wants and distresses ' of his wife, whom he had left in Flanders (Lister, i. 361). The subjugation of Ireland, and the defeat of Charles II at Dunbar, destroyed any hope of Spanish aid, while the share taken by a servant of the ambassadors in Ascham's murder made their presence inconvenient to the Spanish government. In December 1650 they were ordered to leave Spain. Hyde was treated with personal favour, and promised the special privileges of an ambassador during his intended residence at Antwerp (Rebellion, xiii. 25, 31). He left Spain in March 1651, and rejoined his family at Antwerp in the following June. In November 1651 Charles II, immediately after his escape from Worcester, summoned Hyde to Paris. He joyfully obeyed the summons, and for the rest of the exile was, the king's most trusted adviser. He was immediately appointed one of the committee of four with whom the king consulted in all his affairs, and a member of the similar committee which corresponded with the Scottish royalists (Rebellion, xiii. 123, 140). Till August 1654 he filled Nicholas's place as secretary of state. He accompanied the king in his removals to Cologne (October 1654) and Bruges (April 1658), and was formally declared lord chancellor on 13 Jan. 1658 (Lister, i. 441). For the first two years of this period repeated attempts were made to shake the king's confidence in Hyde. Papists and presbyterians both petitioned for his removal (Rebellion, xiv. 63). In 1653 Sir Robert Long incited Sir Richard Grenville to accuse Hyde of secret correspondence with Cromwell, but the king cleared him by a declaration in council, asserting that the charge was a malicious calumny (13 Jan. 1654; Lister, i. 384, iii. 63, 69, 75). Long also combined with Lord Gerard and Lord-keeper Herbert to charge Hyde with saying that the king neglected his business and was too much given to pleasure. Charles coolly answered that he did really believe the chancellor had used those words, because he had often said that and much more to himself ' (ib. iii. 74; Rebellion, xiv. 77). Of all Hyde's adversaries, the queen was the most persistently hostile. He made many efforts to conciliate her, arid in 1651 had persuaded the Duke of York to obey her wishes and return to Paris (1651; Rebellion, xiii. 36, 46). But she was so displeased at Hyde's power over the king that she would neither speak to him nor notice him. 'Who is that fat man next the Marquis of Ormonde?' asked Anne of Austria of Charles II during an entertainment at the French court. ' The king told her aloud that was the naughty man who did all the mischief and set him against his mother; at which the queen herself was little less disordered than the chancellor was, who blushed very much.' At the king's request Henrietta allowed Hyde a parting interview before he left France, but only to renew her complaints of his want of respect and her loss of credit (ib. xiv. 62, 67, 93). The Marquis of Ormonde and the chancellor believed that the king had nothing at this time (1652) to do but to be quiet, and that all his activity was to consist in carefully avoiding to do anything that might do him hurt, and to expect some blessed conjuncture from the amity of Christian princes, or some such revolution of affairs in England, as might make it seasonable for his majesty to show himself again' (ib. xiii. 140). In the meantime Hyde endeavoured to prevent any act which might alienate English royalists and churchmen. He defeated Berkeley's appointment as master of the court of wards, lest the revival of that institution should lose the king the affection of the gentry; and dissuaded Charles from attending the Huguenot congregation at Charenton, lest it should injure the church. Above all, he opposed any attempt to buy catholic support by promising a repeal of the penal laws or holding out hopes of the king's conversion (cf. Burnet, Own Time, ed. 1836, i. 135; Ranke, Hist. of England, vi. 21). The first favourable conjuncture which presented itself was the war between the English republic and the United Provinces (1652). Charles proposed a league to the Dutch, and intended to send Hyde as ambassador to Holland, but his overtures were rejected (Rebellion, xiii. 165; Clarendon State Papers, iii. 91-141). When war broke out between Spain and Cromwell, Hyde applied to Don Lewis de Haro, promising in return for aid in restoring his master to give the usurper such trouble in his own quarters that he may not have leisure to pursue and supply his new conquests.' Spain agreed to assist Charles with six thousand foot and ships for their transport, whenever he could cause a good port town in England to declare for him' (12 April 1656). Thereupon two thousand Irish soldiers in French service deserted and placed themselves at the disposal of Charles II (Rebellion,xv.22; Clarendon State Papers, iii. 276, 303). But Hyde now as before objected to isolated or premature movements in England, and in the end rested his hopes mainly on some extraordinary accident, such as Cromwell's death or an outbreak of the levellers (Clarendon State Papers, iii. 198, 330, 401). As early as 1649 he had drawn up a paper of considerations on future treaties, showing the advantages of an agreement with the levellers rather than the presbyterians. In 1656 their emissaries applied to Charles, were favourably received, and were promised indemnity for all except actual regicides. Hyde listened to their plots for the assassination of Cromwell without any sign of disapproval (ib. iii. 316, 325, 341, 343; Nicholas Papers, i. 138). On the Protector's death Hyde instructed the king's friends not to stir till some other party rose, then to arm and embody themselves without mentioning the king, and to oppose whichever party was most irreconcilable to his cause. When the Long parliament had succeeded Richard Cromwell, the king's friends were bidden to try to set the army and the parliament by the ears (Clarendon State Papers, iii. 411, 436, 482). The zeal of the royalist leaders in England obliged the king to sanction a rising in August 1659. The date fixed was earlier than Hyde's policy had contemplated, but the fear lest some vigorous dictator should seize power, and the hope of restoring the king without foreign help, reconciled him to the attempt. After its failure he went back to his old policy. 'To have a little patience to sit still till they are in blood' was his advice when Monck and Lambert quarrelled; to obstruct a settlement and demand a free parliament his counsel when the Rump was again restored (ib. iii. 436, 530, 534). Of Hyde's activity between Cromwell's death and the Restoration the thirteen volumes of his correspondence during that period give ample proof. The heads of all sections of the royalists made their reports to him, and he restrained their impatience, quieted their jealousies, and induced them to work together. He superintended the negotiations, and sanctioned the bargains by which opponents of influence were won to favour the king's return (ib. iii. 417, 443, 497, 673; Burnet, Own Time, i. 61). Hyde's aim was, as it had been throughout, to restore the monarchy, not merely to restore the king. A powerful party wished to impose on Charles II the conditions offered to his father in 1648. Left to himself, Charles might have consented. But, during the negotiations with the levellers in 1656, Hyde had suggested to Ormonde the expedient which the king finally adopted. When they are obstinate to insist on an unreasonable proposition that you find it necessary to consent to, let it be with this clause, "If a free parliament shall think fit to ask the same of his majesty"' (Clarendon State Papers, iii. 289). By the declaration of Breda the exceptions to the general amnesty, the limits to toleration, and the ownership of forfeited lands, were left, in accordance with this advice, to be determined by parliament. If the adoption of Hyde's policy rendered some of the king's promises illusory, it insured the co-operation of the two powers whose opposition had caused the civil war. On the eve of the Restoration an attempt was made to exclude Hyde from power. Catholics and presbyterians regarded him as their greatest enemy, and the French ambassador, Bourdeaux, backed their efforts for his removal. A party in the convention claimed for parliament the appointment of the great officers of state, and wished to deprive Hyde of the chancellorship. But he was strongly supported by the constitutional royalists, and the intrigue completely failed. Hyde entered London with the king, and took his seat in the court of chancery on 1 June 1660 (Campbell, Lives of the Chancellors, iii. 187). As the king's most trusted adviser he became virtually head of the government. He was the most important member of the secret committee of six, which, although styled the committee for foreign affairs, was consulted on all important business before it came to the privy council (Cont. of Life, § 46). For a time he continued to hold the chancellorship of the exchequer, but surrendered it finally to Lord Ashley (13 May 1661; Campbell, iii. 191). Ormonde urged Hyde to resign the chancellorship also, in order to devote himself entirely to the management of public business and to closer attendance on the king. He refused, on the ground that England would not bear a favourite, nor any one man who should out of his ambition engross to himself the disposition of public affairs,' adding that first minister was a title so newly translated out of French into English, that it was not enough understood to be liked' (ib. p. 85). On 3 Nov. 1660 Hyde was raised to the peerage by the title of Baron Hyde of Hindon, and at the coronation was further created Viscount Cornbury and Earl of Clarendon (20 April, 1661; Lister, ii. 81). The king gave him 20,000l. to support his new dignity, and offered him also a grant of ten thousand acres in the great level of the Fens. Clarendon declined the land, saying that if he allowed the king to be so profuse to himself he could not prevent extravagant bounties to others. But he accepted at various times smaller estates: ten acres of land in Lambeth, twenty in Westminster, and three manors in Oxfordshire forfeited by the attainder of Sir John Danvers [q.v.] In 1662 he was granted, without his knowledge, 20,000l. in rents due from certain lands in Ireland, but never received more than 6,000l. of this sum, and contracted embarrassing obligations in consequence. Though public opinion accused him of avarice, and several articles of his impeachment allege pecuniary corruption, it is plain that Clarendon made no attempt to enrich himself. Charles mocked at his scruples, but the legitimate profits of the chancellorship were large, and they sufficed him (Cont. p. 180; Lister, ii. 81; iii. 522). The revelation (3 Sept. 1660) of the secret marriage of the Duke of York to Clarendon's daughter Anne [q.v.] seemed to endanger, but really confirmed his power. According to his own account he was originally informed of it by the king, received the news with passionate indignation, urged his daughter's punishment, and begged leave to resign. Afterwards, finding the marriage perfectly valid, and public opinion less hostile than he expected, he adopted a more neutral attitude. On his part the king was reluctant to appeal to parliament to dissolve the marriage, was resolved not to part with Clarendon, and hoped through Anne's influence to keep the duke's public conduct under some control. Accordingly he supported the duke in recognising the marriage, which was publicly owned in December 1660 (Cont. pp. 48-76; Burnet, i. 302; Ranke, iii. 340; Lister, ii. 68). Clarendon's position thus seemed to be rendered unassailable. But at bottom his views differed widely from the king's. He thought his master too ready to accept new ideas, and too prone to take the French monarchy as his model. His own aim was to restore the constitution as it existed before the civil war. He held that the secret of good government lay in a well-chosen and powerful privy council. At present king and minister agreed on the necessity of carrying out the promises made at Breda. Clarendon wished the convention to pass the Indemnity Act as quickly as possible, although, like the king, he desired that all actual regicides should be excepted. He was the spokesman of the lords in their dispute with the commons as to the number of exceptions (Old Parl. Hist. xxii. 435, 446, 487). But of the twenty-six regicides condemned in October 1660 only ten were executed, and when in 1661 a bill was introduced for the capital punishment of thirteen more, Charles and the chancellor contrived to prevent it from passing (Lister, ii. 117, iii. 496; Clarendon State Papers, iii. App. xlvi). In his speech at the opening of the parliament of 1661, Clarendon pressed for a confirmation of the acts passed by the convention. He steadily maintained the Act of Indemnity, and opposed the provisos and private bills by which the angry royalists would have destroyed its efficacy. The merit of this firmness Hyde attributes partly to the king. According to Burnet, 'the work from beginning to end was entirely' Clarendon's. At all events the chancellor reaped most of the odium caused by the comprehensiveness of the Act of Indemnity (Burnet, i. 193, 297; Lords' Journals, xi. 240, 379; Cont. pp. 130, 184, 285; Pepys, 20 March 1669). He believed that 'the late rebellion could never be extirpated and pulled up by the roots till the king's regal power should be fully vindicated and the usurpations in both houses of parliament since the year 1640 disclaimed.' In declaring the king's sole power over the militia (1661), and in repealing the Triennial Act (1664), parliament fulfilled these desires (Cont. pp. 284, 510, 990). On ecclesiastical questions Charles and the chancellor were less in harmony. Clarendon's first object was to gradually restore the church to its old position. He seems to have entertained a certain doubt whether the king's adherence to episcopacy could be relied upon, and was anxious to give the presbyterians no opportunity of putting pressure upon him. Hence the anxiety to provide for the appointment of new bishops shown by his correspondence with Barwick in 1659, and the rapidity with which in the autumn of 1660 vacant sees were filled up. In 1661, when the Earl of Bristol, in the hope of procuring some toleration for the catholics, prevailed on the king to delay the progress of the bill for restoring the bishops to their place in the House of Lords, Clarendon's remonstrances converted Charles and frustrated the intrigue (ib. p. 289; Clarendon State Papers, iii. 613, 732; Life of Dr. Barwick, ed. 1724, p.205; Ranke, iii. 370). On the question of the church lands Clarendon's influence was equally important. After the convention had decided that church and crown lands should revert to their owners, a commission was appointed to examine into sales, compensate bona-fide purchasers, and make arrangements between the clergy and the tenants. Clarendon, who was a member of the commission, admits that it failed to prevent cases of hardship, and lays the blame on the clergy. Burnet censures Clarendon himself for not providing that the large fines which the bishops raised by granting new leases should be applied to the use of the church at large (Own Time, i. 338; Cont. p.189; Somers Tracts, vii. 465). Of the two ways of establishing the liberty for tender consciences promised in the Declaration of Breda the king preferred toleration, Hyde comprehension (cf. Lords' Journals, xi. 175). In April 1660 he sent Dr. Morley to England to discuss with the presbyterian leaders the terms on which reunion was possible (Clarendon State Papers, iii. 727, 738). After the Restoration bishoprics were offered to several presbyterians, including Baxter, who records the kindness with which Clarendm treated him (Reliquiæ Baxterianæ, ii. 281, 302, 381). Clarendon drafted the king's declaration on ecclesiastical affairs (25 Oct. 1660), promising limited religion' (Lister, ii. 295-303; Lords' Journals, xi. 237, 242, 476, 688). The settlement of Scotland and Ireland, and the course of colonial history also, owed much to Clarendon. The aims of his Scottish policy were to keep Scotland dependent on England and to re-establish episcopacy. He opposed the withdrawal of the Cromwellian garrisons, and regretted the undoing of the union which Cromwell had effected. Mindful of the ill results caused by the separation of Scottish and English affairs, which the first two Stuarts had so jealously maintained, he proposed to set up at Whitehall a council of state for Scotland to control the government at Edinburgh (Rebellion, ii. 17; Cont. pp. 92-106; Burnet, i. 202). His zeal to restore episcopacy in Scotland was notorious. Baillie describes him as corrupting Sharp and overpowering Lauderdale, the two champions on whom the presbyterian party had relied (Letters, iii. 464, 471; Burnet, i. 237). At Clarendon's persuasion the English bishops left Sharp to manage the reintroduction of episcopacy (ib. i. 240). Middleton's selection as the king's commissioner was largely due to his friendship with the chancellor (cf. ib. pp. 273, 365), and Middleton's supersession by Lauderdale in May 1663 put an end to Clarendon's influence over Scottish affairs (Memoir of Sir George Mackenzie, pp. 76, 112; Lauderdale and the Restoration in Scotland,' Quarterly Review, April 1884). Hyde's share in the settlement of Ireland is less easy to define. The fifteenth article of his impeachment alleges that he ' procured the bills for the settlement of Ireland, and received great sums of money for the same ' (Miscellaneous Tracts, p. 39). His answer is that he merely acted as one member of the Irish committee, and had no special responsibility for the king's policy; but his council-notes to Charles seem to disprove this plea (Cont. p. 277; Clarendon State Papers, iii. App. xlvii). Sympathising less strongly with the native Irish than the king did, he yet supported the settlement-commissioners against the clamour of the Irish parliament. ' No man,' he wrote to the Earl of Anglesey, ' is more solicitous to establish Ireland upon a true protestant English interest than I am, but there is as much need of temper and moderation and justice in the composing that establishment as ever was necessary in any affair of this world ' (ib. iii. App. xxxiv, xxxvi). He was anxious that the king should carry out his original intention of providing for deserving Irishmen out of the confiscated lands which had fallen to the crown, but was out-generalled by the Earl of Orrery (Cont. p. 272). His influence in Ireland increased after the Duke of Ormonde became lord-lieutenant (December 1661), and he supported Ormonde's policy. He did not share the common jealousy of Irish trade, and opposed the prohibition of the importation of Irish cattle (1665-6) with a persistency which destroyed his remaining credit with the English House of Commons (Carte, Ormonde, ed. 1851, iv. 244, 263-7; Cont. pp. 9, 55-9, 89). In the extension of the colonial dominions of England, and the institution of a permanent system of colonial administration, Hyde took a leading part. He was one the eight lords proprietors to whom on 24 March 1663 the first Carolina charter was granted, and the settlement they established at Cape Fear was called after him Clarendon County. He helped Baxter to procure the incorporation of the Company for the Propagation of the Gospel in New England, of which he was himself a member (7 Feb. 1662). He joined the general council for foreign plantations (1 Dec. 1660), and the special committee of the privy council charged to settle the government of New England (17 May 1661; Cal. State Papers, Colonial, 1574-1660 p. 492, 1661-8 pp. 30, 71, 125; Reliquiæ Baxterianæ, ii. 290). The policy, which Clarendon probably inspired, endeavoured to enforce the Acts of Parliament for the control of the shipping trade, to secure for members of the Church of England civil rights equal to those enjoyed by nonconformists, and to subordinate the Colonial jurisdiction by giving a right of appeal to the Crown in certain cases' (Doyle, The English in America; The Puritan Colonies, ii. 150). To prevent the united resistance of the New England states he supported measures to divide them from each other and to weaken Massachusetts (Cal. State Papers, Colonial, 1661-1668, pp. 198-203, 377; Hutchinson, History of Massachusetts, ed. 1795, i. 544). In dealing with the colonies circumstances made Clarendon tolerant. He granted freedom of conscience to all settlers in Carolina, and instructed the governors of Virginia and Jamaica not to molest nonconformists (Cal. State Papers, Colonial, 1661-8, p. 155; Stoughton, Ecclesiastical History of England, iii. 310). The worst side of his policy is shown in his support of the high-handed conduct of Lord Willoughby in Barbadoes, which was made the basis of the fifteenth article of his impeachment in 1667. Hyde, although playing a conspicuous part in foreign affairs, exerted little influence upon them. His views were purely negative. He thought a firm peace between the king and his neighbours necessary for the reducing his own dominions into that temper of obedience they ought to be in,' and desired to avoid foreign complications (Cont. p. 1170; Courtenay, Life of Temple, i. 127). But his position and his theory of ministerial duty obliged him to accept the responsibility of a policy which he did not originate, and a war of which he disapproved. Hyde wished the king to marry, but was anxious that he should marry a protestant The marriage between Charles and Catherine of Braganza was first proposed by the Portuguese ambassador to the king in the summer of 1660, and by the king to the lord chancellor (Ranke, iii. 344). Carte, on the authority of Sir Robert Southwell, describes Clarendon as at first remonstrating against the choice, but finally yielding to the king's decision (Carte, Ormonde, iv. 107, ed. 1851; Burnet, Own Time, i. 300). The council unanimously approved of the marriage, and the chancellor on 8 May 1661 announced the decision to parliament, and prepared a narrative of the negotiations (Lords' Journals, xi. 243; Cont. pp. 149-87; Lister, ii. 126, iii. 119, 513). When it became evident that the queen would give no heir to the throne, it was reported that Clarendon knew she was incapable of bearing children and had planned the marriage to secure the crown for his daughter's issue (Reresby, Memoirs, p.53, ed. Cartwright; Pepys, 22Feb.1664). Clarendon refused a bribe of 10,000l. which Bastide the French agent offered him, but stooped to solicit a loan of 50,000l. for his master and a promise of French support against domestic disturbances. The necessities of the king led to the idea of selling Dunkirk a transaction which the eleventh article of Clarendon's impeachment charged him with advising and effecting. In his 'Vindication' he replied that the parting with Dunkirk was resolved upon before he heard of it, and that 'the purpose was therefore concealed from him because it was believed he was not of that opinion ' (Miscellaneous Tracts, p.33). The authorship of the proposal was subsequently claimed by the Earl of Sandwich, and is attributed by Clarendon to the Earl of Southampton (Cont. p.455; Pepys, 25 Feb. 1666). Clarendon had recently rebuked those who murmured at the expense of Dunkirk, and had enlarged on its value to England. But since it was to be sold, he advised that it should be offered to France, and conducted the bargain himself. The treaty was signed on 27 Oct. 1662 (Lister, ii. 167; Ranke, iii. 388; Clarendon State Papers, iii. App. xxi-ii, xxv) Bristol charged him with having got 100,000l. by the transaction, and on 20 Feb. 1665 Pepys notes that the common people had already nicknamed the palace which the chancellor was building near St. James's, ' Dunkirk House.' At the beginning of the reign Mazarin had regarded Clarendon as the most hostile to France of all the ministers of Charles II, but he was now looked upon as the greatest prop of the French alliance (Chéruel, Mazarin, iii. 291, 320-31; Ranke, iii. 339). Contrary to his intentions, Clarendon also became engaged in the war with Holland. When his administration began, there were disputes of long standing with the United Provinces, and the Portuguese match threatened to involve England in the war between Holland and Portugal. Clarendon endeavoured to mediate between those powers, and refused to allow the English negotiations to be complicated by consideration of the interests of the prince of Orange. He desired peace with Holland because it would compose people's minds in England, and discourage the seditious party which relied on Dutch aid. A treaty providing for the settlement of existing disputes was signed on 4 Sept. 1662. De Witt wrote that it was Clarendon's work, and begged him to confirm and strengthen the friendly relations of the two peoples (Pontalis, Jean De Witt, i. 280; Lister, iii. 167, 175). Amity might have been maintained had the control of English foreign policy been in stronger hands. The king was opposed to war, and convinced by the chancellor's arguments against it (Cont. pp. 450-54). But Charles and Clarendon allowed the pressure of the trading classes and the Duke of York to involve them in hostilities which made war inevitable. Squadrons acting under instructions from the Duke of York, and consisting partly of ships lent from the royal navy, captured Cape Corso (April 1664) and other Dutch establishments on the African coast, and New Amsterdam in America (29 Aug. 1664). The Dutch made reprisals, and war was declared on 22 Feb. 1665. Clarendon held that the African conquest had been made without any shadow of justice,' and asserted that, if the Dutch had sought redress peaceably, restitution would have been granted (Lister, iii. 347). Of the attack on the Dutch settlements in America he took a different view, urging that they were English property usurped by the Dutch, and that their seizure was no violation of the treaty. He was fully aware of the intended seizure of the New Netherlands, and appears to have helped the Duke of York to make out his title to that territory (Cal State Papers, Colonial, 1661-1668, pp. 191, 200; Brodhead, History of New York, ii. 12, 15; Life of James II, i. 400). The narrative of transactions in Africa, laid before parliament on 24 Nov. 1664, was probably his work. After the war began Clarendon talked openly of requiring new cessions from the Dutch, and asserted in its extremest form the king's dominion over the British seas (Lords' Journals, xi. 625, 684; Lister, iii. 424; Ranke, iii. 425; Pepys, 20 March 1669). Rejecting the offered mediation of France, he dreamt of a triple alliance between England, Sweden, and Spain, 'which would be the greatest act of state and the most for the benefit of Christendom that this age hath produced' (Lister, iii. 422; Lords' Journals, xi. 488). Later still, when France had actively intervened on the side of Holland, Clarendon's eyes became open to the designs of Louis XIV on Flanders, and he claims to have prepared the way for the triple alliance (Cont. p. 1066). But the belief that he was entirely devoted to French interests was one of the chief obstacles to the conclusion of any league between England and Spain (Klopp, Der Fall des Hauses Stuart, i. 145, 192; Courtenay, Life of Temple, i. 128). Nor was that belief—erroneous though it was—without some justification. When Charles attempted to bring the war to an end by an understanding with Louis XIV, Clarendon drew the instructions of the Earl of St. Albans (January 1667); and though it is doubtful whether he was cognisant of all his master's intentions, he was evidently prepared to promise that England should remain neutral while France seized Flanders. In June 1667 the Dutch fleet burnt the ships in the Medway, and on 21 July the treaty of Breda was concluded. Public opinion held Clarendon responsible for the ill-success of the war and the ignominious peace. On the day when the Dutch attacked Chatham, a mob cut down the trees before his house, broke his windows, and set up a gibbet at his gate (Pepys, 14 June 1667; cf. ib. 24 June). According to Clarendon's own account, he took very little part in the conduct of the war, 'never pretending to understand what was fit to be done,' but simply concurring in the advice of military and naval experts (Cont. p. 1026). Clarendon's want of administrative skill was, however, responsible for much. He disliked the new system of committees and boards which the Commonwealth had introduced, and clung to the old plan of appointing great officers of state, as the only one suitable to a monarchy. He thought it necessary to appoint men of quality who would give dignity to their posts, and underrated the services of men of business, while his impatience of opposition and hatred of innovations hindered administrative reform. As the needs of the government increased, the power of the House of Commons grew, and Clarendon's attempt to restrict their authority only diminished his own. He opposed the proviso for the appropriation of supplies (1665) 'as an introduction to a commonwealth and not fit for a monarchy.' He opposed the bill for the audit of the war accounts (1666) as 'a new encroachment which had no bottom,' and urged the king not to 'suffer parliament to extend its jurisdiction. He opposed the bill for the prohibition of the Irish cattle trade (1666) as inexpedient in itself, and because its provisions robbed the king of his dispensing power; spoke slightingly of the House of Commons, and told the lords to stand up for their rights. In 1666, finding the House of Commons 'morose and obstinate,' and 'solicitous to grasp as much power and authority as any of their predecessors had done,' he proposed a dissolution, hoping to find a new house more amenable. Again, in June 1667 he advised the king to call a new parliament instead of convening the existing one, which had been prorogued till October (Cont. pp. 964, 1101; Lister, ii. 400). This advice and the immediate prorogation of parliament when it did meet (25-9 July 1667) deeply incensed the commons, and gave Clarendon's enemies an opportunity of asserting that he had advised the king to do without parliaments altogether (Pepys, 25 July 1667; Lister, ii. 402). Still more serious, with men who remembered the Protectorate, was the charge that he had designed to raise a standing army and to govern the kingdom by military power. What gave colour to the rumour was that, during the invasion of June 1667, Clarendon had recommended the king to support the troops guarding the coast by the levy of contributions on the adjacent counties until parliament met (Cont. p. 1104). In private the king himself owned the charge was untrue, but refused to allow his testimony to be used in the chancellor's defence. Popular hatred turned against Clarendon, and poets threatened Charles with the fate of his father unless he parted with the obnoxious minister (Marvell, Last Instructions to a Painter, 1. 870). The court in general had long been hostile to Clarendon, and the king's familiar companions took every opportunity of ridiculing him. Lady Castlemaine and he were avowed enemies. The king suspected him of frustrating his designs on Miss Stewart, and was tired of his reproofs and remonstrances. 'The truth is,' explained Charles to Ormonde, 'his behaviour and humour was grown so unsupportable to myself and to all the world else, that I could no longer endure it, and it was impossible to live with it, and do those things with the parliament that must be done, or the government will be lost' (Ellis, Original Letters, 2nd ser. iv. 39). The king therefore decided to remove the chancellor before parliament again met, and commissioned the Duke of York to urge him to retire of his own accord. Clarendon obtained an interview at Whitehall on 26 Aug. 1667, and told the king that he was not willing to deliver up the seal unless he was deprived of it; that his deprivation of it would mean ruin, because it would show that the king believed him guilty; that, being innocent of transgressing the law, he did not fear the justice of the parliament. Parliaments,' he said, were not formidable unless the king chose to make them so; it was yet in his own power to govern them, but if they found it was in theirs to govern him, nobody knew what the end would be.' The king did not announce his decision, but seemed deeply offended by some inopportune reflections on Lady Castlemaine. For two or three days the chancellor's friends hoped the king would change his purpose, but finally Charles declared that he had proceeded too far to retire, and that he should be looked upon as a child if he receded from his purpose.' On 30 Aug. Sir William Morrice was sent to demand the great seal. When Morrice brought it back to Whitehall, Charles was told by a courtier that this was the first time he could ever call him king of England, being freed from this great man' (Pepys, 27 Aug., 7 Oct. 1667; Cont. p. 1134 ; Lister, iii. 468). On Clarendon himself the blow fell with crushing severity (cf. Carte, Ormonde, v. 57), but he confidently expected to vindicate himself when parliament met. The next session opened on 10 Oct. 1667. The king's speech referred to the chancellor's dismissal as an act which he hoped would lay the foundation of greater confidence between himself and parliament. The House of Commons replied by warm thanks, which the king received with a promise never to employ the Earl of Clarendon again in any public affairs whatsoever (16 Oct.). Clarendon's enemies, however, were not satisfied, and determined to arraign him for high treason. The attack was opened by Edward Seymour on 26 Oct., and on 29 Oct. a committee was appointed to draw up charges. Its report (6 Nov.) contained seventeen heads of accusation, but the sixteenth article, which accused Clarendon of betraying the king's counsels to his enemies, was the only one which amounted to high treason. The impeachment was presented to the House of Lords on 12 Nov., but they refused (14 Nov.) to commit Clarendon as requested, because the House of Commons have only accused him of treason in general, and have not assigned or specified any particular treason.' As they persisted in this refusal, the commons passed a resolution that the non-compliance of the lords was an obstruction to the public justice of the kingdom and a precedent of evil and dangerous consequences' (2 Dec.) The dispute between the two houses grew so high, that it seemed as if all intercourse between them would stop, and a paralysis of the government ensue (Lister, iii. 474). The king publicly supported the chancellor's prosecutors, while the Duke of York stood by his father-in-law, but an attack of small-pox soon deprived the duke of any further power to interfere. As it was, York's conduct had increased the hostility of the chancellor's enemies, and they determined to secure themselves against any possibility of his return to power if James became king (4 Nov. 1667; Life of James II, i. 433; Cont. p. 1177). By the advice of friends Clarendon wrote to the king protesting innocence of the crimes alleged in his impeachment. I do upon my knees,' he added, beg your pardon for any overbold or saucy expressions I have ever used to you … a natural disease in old servants who have received too much countenance.' He begged the king to put a stop to the prosecution, and to allow him to spend the small remainder of his life in some parts beyond seas (ib. p. 1181). Charles read the letter, burnt it, and observed 'that he wondered the chancellor did not withdraw himself.' He was anxious that Clarendon should withdraw, but would neither command him to 'go nor grant him a pass for fear of the commons. Indirectly, through the Duke of York and the Bishop of Hereford, he urged him to fly, and promised that he should not be in any degree prosecuted, or suffer in his honour or fortune by his absence' (ib. p. 1185). Relying on this engagement, and alarmed by the rumours of a design to prorogue parliament and try him by a jury of peers, Clarendon left England on the night of 29 Nov., and reached Calais three days later. With Clarendon's flight the dispute between the two houses came to an end. The lords accepted it as a confession of guilt, concurred with the commons in ordering his petition to be burnt, and passed an act for his banishment, by which his return was made high treason and his pardon impossible without the consent of both houses (19 Dec. 1667; Lister, ii. 415-44, iii. 472-77; Cont. pp. 1155-97 ; Carte, Ormonde, v. 58 ; Lords' Journals, xii. 178; Commons' Journals, ix. 40-3). The rest of Clarendon's life was passed in exile. From Calais he went to Rouen (25 Dec.), and then back to Calais (21 Jan. 1668), intending by the advice of his friends to return to England and stand his trial. In April 1668 he made his way to the baths of Bourbon, and thence to Avignon (June 1668). For nearly three years he lived at Montpelier (July 1668-June 1671), removing to Moulins in June 1671, and finally to Rouen in May 1674 (Lister, ii. 478, 481, 487; Cont. p. 1238). During the first part of his exile his hardships and sufferings were very great. At Calais he lay for three months dangerously ill. At Evreux, on 23 April 1668, a company of English sailors in French service, holding Clarendon the cause of the non-payment of their English arrears, broke into his lodgings, plundered his baggage, wounded several of his attendants, and assaulted him with great violence. One of them stunned him by a blow with the flat of a sword, and they were dragging him into the courtyard to despatch him, when he was rescued by the town guard (ib. pp. 1215, 1225). In December 1667 Louis XIV, anxious to conciliate the English government, ordered Clarendon to leave France, and, in spite of his illness, repeated these orders with increasing harshness. After the conclusion of the Triple League had frustrated the hope of a close alliance with England, the French government became more hospitable, but Clarendon always lived in dread of fresh vexations (Cont. pp. 1202-1220, 1353). The Archbishop of Avignon, the governor and magistrates of Montpelier, and the governor of Languedoc, treated him with great civility, and he was cheered by the constant friendship of the Abbé Montague and Lady Mordaunt. His son, Laurence, was twice allowed to visit him, and Lord Cornbury was with him when he died (Correspondence of Henry Hyde, Earl of Clarendon, ed. Singer, i. 645; Lister, iii. 488). To find occupation, and to divert his mind from his misfortunes, Clarendon 'betook himself to his books,' and studied the French and Italian languages. Never was his pen more active than during these last seven years of his life. His most important task was the completion and revision of his ' History of the Rebellion ' together with the composition of his autobiography. In June 1671, and again in August 1674, he petitioned for leave to return to England, and begged the queen and the Duke of York to intercede for him (Clarendon State Papers, iii. App. xliv, xlv). These entreaties were unanswered, and he died at Rouen on 9 Dec. 1674 (Lister, ii. 488). He was buried in Westminster Abbey on 4 Jan. 1675, at the foot of the steps ascending to Henry VII's chapel, where his second wife had been interred on 17 Aug. 1667 (Chester, Westminster Abbey Register, pp. 167, 185). His two sons, Henry, earl of Clarendon (1638-1709), and Laurence, earl of Rochester (1642-1711), and his daughter, Anne, duchess of York (1637-1671), are separately noticed. A third son, Edward Hyde, baptised 1 April 1645, died on 10 Jan. 1665, and was also buried in Westminster Abbey (ib. p. 161). Clarendon's will is printed in Lister's ' Life of Clarendon ' (ii. 489). As a statesman, Clarendon's consistency and integrity were conspicuous through many vicissitudes and amid much corruption. He adhered faithfully to the principles he professed in 1641, but the circle of his ideas was fixed then, and it never widened afterwards. No man was fitter to guide a wavering master in constitutional ways, or to conduct a return to old laws and institutions; but he was incapable of dealing with the new forces and new conditions which twenty years of revolution had created. Clarendon is remarkable as one of the first Englishmen who rose to office chiefly by his gifts as a writer and a speaker. Evelyn mentions his ' eloquent tongue,' and his ' dexterous and happy pen.' Some held that his literary style was not serious enough. Burnet finds a similar fault in his speaking. 'He spoke well ; his style had no flow [flaw ?] in it, but had a just mixture of wit and sense, only he spoke too copiously; he had a great pleasantness in his spirit, which carried him sometimes too far into raillery, in which he showed more wit than discretion.' Pepys admired his eloquence with less reserve. I am mad in love with my lord chancellor, for he do comprehend and speak out well, and with the greatest ease and authority that ever I saw man in my life. … His manner and freedom of doing it as if he played with it, and was informing only all the rest of the company, was mighty pretty ' (cf. Warwick, Memoirs, p. 195; Evelyn, ii. 296; Pepys, Diary, 13 Oct. 1666). Apart from his literary works, the mass of state papers and declarations drawn by his hand and his enormous correspondence testify to his unremitting industry. His handwriting is small, cramped, and indistinct. During his residence in Jersey 'he writ daily little less than one sheet of large paper with his own hand,' and seldom spent less than ten hours a day between his books and his papers (Life, v.5; Clarendon State Papers, ii. 375). Lordnote). Clarendon to accept was a set of all the books printed at the Louvre (Evelyn, iii. 346, 446; Clarendon State Papers, iii. App. xi. xiii). Clarendon was an assiduous reader of the Roman historians. He quotes Tacitus continually in the 'History of the Rebellion,' and modelled his character of Falkland on that of Agricola. He was familiar with the best historical writers of his own period, and criticises Strada, Bentivoglio, and Davila with acuteness. Of English writers, Hooker, whose exordium he imitates in the opening of the 'History of the Rebellion,' seems to have influenced him most. But he did not disdain the lighter literature of his age, praised the amorous poems of Carew, prided himself on the intimacy of Ben Jonson, and thought Cowley had made a flight beyond all other poets. The muses, as Dryden remarks, were once his mistresses, and boasted his early courtship; but the only poetical productions of Clarendon which have survived are some verses on the death of Donne, and the lines prefixed to Davenant's 'Albovine ' in 1629. Clarendon's 'History' is the most valuable of all the contemporary accounts of the civil wars. Clarendon was well aware of one cause of its superiority. 'It is not,' he says, ' a collection of records, or an admission to the view and perusal of the most secret letters and acts of state [that] can enable a man to write a history, if there be an absence of that genius and spirit and soul of an historian which is contracted by the knowledge and course and method of business, and by conversation and familiarity in the inside of courts, and [with] the most active and eminent persons in the government' (Tracts, p. 180). But both from a literary and from an historical point of view the book is singularly unequal. At its best Clarendon's style, though too copious, is strong and clear, and his narrative has a large and easy flow. Often, however, the language becomes involved, and the sentences are encumbered by parentheses. As a work of art the history suffers greatly from its lack of proportion. Some parts of the civil war are treated at disproportionate length, others almost entirely neglected. The progress of the story is continually broken by constitutional digressions and lengthy state papers. The 'History' was, however, originally intended rather as an exact memorial of passages ' than 'a digested relation.' It was not to be published as it stood, but to serve as 'a store' out of which 'somewhat more proper for the public view' might be collected (Rebellion, i. 3). The ' History ' itself is to some extent a manifesto, addressed, in the first place, to the king, but appealing still more to posterity. It was designed to set forth a policy as well as to relate events, and to vindicate not so much the king as the constitutional royalists. To celebrate the memories of eminent and extraordinary persons ' Clarendon held one of the principal ends of history. Hence the portraits which fill so many of his pages. His characters are not simply bundles of characteristics, but consistent and full of life, sketched sometimes with affection, sometimes with light humour. Evelyn described them as 'so just, and tempered without the least ingredient of passion or tincture of revenge, yet with such natural and lively touches, as shew his lordship well knew not only the persons' outsides but their very interiors; whilst he treats the most obnoxious who deserved the severest rebuke, with a becoming generosity and freedom, even where the ill-conduct of those of the pretended loyal party, as well as of the most flagitious, might have justified the worst that could be said of their miscarriages and demerits.' Clarendon promised Berkeley that there should not be 'any untruth nor partiality towards persons or sides ' in his narrative (Macray, Clarendon, i., preface, p. xiii), and he impartially points out the faults of his friends. But lack of insight and knowledge prevented him from recognising the virtues of opponents. He never understood the principles for which presbyterians and independents were contending. In his account of the causes of the rebellion he under-estimates the importance of the religious grievances, and attributes too much to the defects of the king's servants, or the personal ambition of the opposition leaders. As a record of facts the 'History of the Rebellion' is of very varying value. It was composed at different times, under different conditions, and with different objects. Between 1646 and 1648 Clarendon wrote a ' History of the Rebellion' which ended with the defeat of Hopton at Alresford in March 1644. In July 1646 he wrote, by way of defending the prince's council from the aspersions of Goring and Grenville, an account of the transactions in the west, which is inserted in book ix. Between 1668 and 1670 he wrote a 'Life' of himself, which extended from 1609 to 1660. In 1671 he reverted to his original purpose, took up the unfinished ' History ' and the finished 'Life,' and wove them together into the narrative published as the 'History of the Rebellion.' During this process of revision he omitted passages from both, and made many important additions in order to supply an account of public transactions between 1644 and 1660, which had not been treated with sufficient fulness in his Life.' As the original ' History' was written when Clarendon's memory of events was freshest, the parts taken from it are much more accurate than those taken from the 'Life.' On the other hand, as the ' Life ' was written simply for his children, it is freer in its criticisms, both of men and events. Most of the characters contained in the ' History of the Rebellion ' are extracted from the 'Life.' The authorities at Clarendon's disposal when the original ' History ' was written supply another reason for its superior accuracy. He obtained assistance from many quarters. From Nicholas he received a number of official papers, and from Hopton the narrative of his campaigns, which forms the basis of the account of the western war given in books vi. and vii. At the king's command Sir Edward Walker sent him relations of the campaigns of 1644 and 1645, and many cavaliers of less note supplied occasional help. When the ' Life ' was written Clarendon was separated from his friends and his papers, and relied upon his memory, a memory which recalled persons with great vividness, but confused and misrepresented events. The additions made in 1671 are more trustworthy, because Clarendon had in the interval procured some of the documents left in England. Ranke's 'History of England' (translation, vi. 3-29) contains an estimate of the 'History of the Rebellion,' and Mr. Gardiner criticises Clarendon's general position as an historian (History of the Great Civil War, ii. 499). George Grenville, lord Lansdowne, attempted to vindicate his relative, Sir Richard Grenville, from Clarendon's censures (Lansdowne, Works, 1732, i. 503), and Lord Ashburnham examines minutely Clarendon's account of John Ashburnham (A Narrative by John Ashburnham, 2 vols. 1830). An excellent dissertation by Dr. Ad. Buff deals with parts of book vi. of the 'Rebellion' (Giessen, 1868). The 'True Historical Narrative of the Rebellion and Civil Wars in England,' generally termed the ' History of the Rebellion,' was first published at Oxford in 1702-4, in three folio volumes, with an introduction and dedications by Laurence, earl of Rochester. The original manuscripts of the work were given to the university at different dates between 1711 and 1753 (Macray, Annals of the Bodl. Lib. p.225). The first edition was printed, not from the originals, but from a transcript of them made under Clarendon's supervision by his secretary, William Shaw. This was copied for the printers under the supervision of the Earl of Rochester, who received some assistance in editing it from Dr. Aldrich, dean of Christ Church, and Sprat, bishop of Rochester. The editors, in accordance with the discretion given them by Clarendon's will, softened and altered a few expressions, but made no material changes in the text. A few years later, however, John Oldmixon published a series of attacks on them, and on the university, for supposed interpolations and omissions (Clarendon and Whitelocke compared, 1727; History of England during the Reigns of the Royal House of Stuart, preface, pp. 9, 227). These charges, based on utterly worthless evidence, were refuted by Dr. John Burton in 'The Genuineness of Lord Clarendon's History vindicated,' 1744, 8vo. Dr. Bandinel's edition, published in 1826, was the first printed from the original manuscripts. It restores the phrases altered by the editors, and adds in the appendix passages omitted by Clarendon in the revision of 1671-2. The most complete and correct text is that edited and annotated by the Rev. W. D. Macray (Oxford, 1888, 6 vols., 8vo). An account of the manuscripts of the 'History of the Rebellion' is given in the prefaces of Dr. Bandinel and Mr. Macray, and in Lewis's ' Lives of the Contemporaries of Lord Clarendon' (vol. i. Introduction, pt. ii.) A list of editions of the 'History' is given in Bliss's edition of Wood (Athenæ Oxon. iii. 1017). A supplement to the 'History of the Rebellion,' containing eighty-five portraits and illustrative papers, was published in 1717, 8vo. The Sutherland 'Clarendon' presented to the Bodleian Library in 1837 contains many thousand portraits, views, and maps, illustrating the text of Clarendon's historical works. A catalogue of the collection (2 vols. 4to) was published in 1837 (Macray, Annals of the Bodl. Lib. p.331). The work usually known as the 'Life of Clarendon' was originally published in 1759 ('The Life of Edward, Earl of Clarendon. … Being a Continuation of the History of the Grand Rebellion from the Restoration to his Banishment in 1667. Written by Himself,' Oxford, 1759, folio). It consists of two parts: the ' Life ' proper, written between 1668 and 1670, dealing with the period before 1660; and the 'Continuation,' commenced in 1672. The first consists of that portion only of the original life which was not incorporated in the 'History of the Rebellion.' The second contains an account of Clarendon's ministry and second exile. The 'History of the Reign of King Charles II, from the Restoration to the end of the year 1667,' 2 vols. 4to, n.d., is a surreptitious edition of the last work, published about 1755 (Lowndes, p. 468). The minor works of Clarendon are the following: 1. 'The Difference and Disparity between the Estate and Condition of George, Duke of Buckingham, and Robert, Earl of Essex' (Reliquiæ Wottonianæ, ed. 1685, p.185). 2. Speeches delivered in the Long parliament on the lord president's court and council in the north, and on the impeachment of the judges (Rushworth Historical Collections, iv. 230, 333). 3. Declarations and manifestos written for Charles I between 1642 and 1648. These are too numerous to be mentioned separately; the titles of the most important have been already given. Many are contained in the 'History of the Rebellion ' itself, and the rest may be found in Rushworth's 'Collections,' in Husband's Collection of Ordinances and Declarations ' (1643), and in the old ' Parliamentary History' (24 vols. 1751-62). 4. Anonymous pamphlets written on behalf of the king. 'Two Speeches made in the House of Peers on Monday, 19 Dec. 1642 ' (Somers Tracts, ed. Scott, vi. 576). 'Transcendent and Multiplied Rebellion and Treason, discovered by the Laws of the Land,' 1645; A Letter from a True and Lawful Member of Parliament … to one of the Lords of his Highness's Council,' 1656 (see Cal. Clarendon State Papers, i. 295, iii. 79; History of the Rebellion, ed. Macray,vi.l,xiv. 151). 5. 'Animadversions on a Book entitled Fanaticism fanatically imputed to the Church of England, by Dr. Stillingfleet, and the imputation refuted and retorted by Sam. Cressy,' 1674, 8vo (Lister, ii. 567). 6. 'A Brief View and Survey of the dangerous and pernicious errors to Church and State in Mr. Hobbes's book entitled Leviathan, ' Oxford, 1676 (see Clarendon State Papers, iii. App. p. xlii). 7. 'The History of the Rebellion and Civil War in Ireland,' 1720, 8vo. This is a vindication of Charles I and the Duke of Ormonde from the Bishop of Ferns and other catholic writers. It was made use of by Nalson in his 'Historical Collections,' 1682, and by Borlase in his 'History of the Irish Rebellion,' 1680. A manuscript is in the library of Trinity College, Dublin (Hist. MSS. Comm. 8th Rep. p.583). 8. 'A Collection of several Tracts of Edward, Earl of Clarendon,' 1727, fol. This contains (a) the 'Vindication' written by Clarendon in 1668 in answer to the articles of impeachment against him, the substance of which is embodied in the ' Continuation;' (b) Reflections upon several Christian Duties, Divine and Moral, by way of Essays;' (c) Two Dialogues on Education, and on the Respect due to Age;'(d) Contemplations on the Psalms.' 9. 'Religion and Policy, and the Countenance and Assistance each should give to the other, with a Survey of the Power and Jurisdiction of the Pope in the dominion of other Princes,' Oxford, 1811, 2 vols. 8vo. A work entitled 'A Collection of several Pieces of Edward, Earl of Clarendon, to which is prefixed an Account of his Lordship's Life, Conduct, and Character, by a learned and impartial pen,' was published in 1727, 8vo. The second volume is a reprint of the 'History of the Rebellion in Ireland.' The first contains a reprint of Clarendon's speeches between 1660 and 1666 extracted from the ' Journals of the House of Lords.' Bliss and the Bodleian ' Catalogue ' attribute to Clarendon (on insufficient evidence) a tract entitled 'A Letter sent from beyond seas to one of the chief Ministers of the Nonconforming Party. By a Lover of the Established Government both of Church and State,' dated Saumur, 7 May 1674. Two letters written by Clarendon in 1668 to the Duke and Duchess of York on the conversion of the latter to Catholicism, are printed in the 'Harleian Miscellany' (iii. 555, ed. Park); with the letter he addressed to the House of Lords on his flight from England (v. 185), under the title of ' News from Dunkirk House.' The great collection of Clarendon's ', correspondence, acquired at different times by the Bodleian Library, comprises over one hundred volumes. A selection from these papers, edited by Dr. Scrope and Thomas Monkhouse, was published between 1767 and 1786 (State Papers collected by Edward, Earl of Clarendon, 3 vols. folio, Oxford). They are calendared up to 1657 (3 vols. 8vo; vol. i. ed. by Ogle and Bliss, 1872; vols. ii. and iii. ed. by W. D. Macray, 1869, 1876). A number of the post-restoration papers are printed in the third volume of Lister's 'Life of Clarendon.' Letters to Sir Edward Nicholas are printed in the Nicholas Papers,' edited by G. F. Warner, Camden Society, 1886; to Sir Richard Browne, in the appendix to the Diary of John Evelyn,' edited by Bray, 1827, and by Wheatley, 1879; to Prince Rupert, in Warburton's 'Prince Rupert' (3 vols. 1849); to Dr. John Barwick in Barwick's Life of Barwick,' 1724; to Lord Mordaunt and others in 1659-60 (Hist. MSS. Comm. 10th Rep. pt. vi. pp. 189-216). [Clarendon's autobiographical works and letters form the basis of the Life of Clarendon published in 1837 by Thomas Lister Lord Campbell's memoir in his Lives of the Chancellors (iii. 110-271) has no independent value. An earlier life of little value is contained in Lives of all the Lord Chancellors, but more especially of those two great opposites, Edward, earl of Clarendon, and Bulstrode, lord Whitelocke, 2 vols. 18mo, 1708. Macdiarmid's Lives of British Statesmen, 1807, 4to, and J. H. Browne's Lives of Prime Ministers of England, 1858, 8vo, contain lives of considerable length, and shorter memoirs are given in Lodge's Portraits and Foss's Judges of England. The life of Clarendon given by Wood differs considerably in the first two editions of that work (see Bliss's edition, iii. 1018). Charges of corruption brought against Clarendon in the lives of judges Grlyn and Jenkvns led to the expulsion of Wood from the university and the burning of his book (1693). These and other charges are brought together in Historical Inquiries respecting the Character of Edward Hyde, Earl of Clarendon, by George Agar Ellis, 1827, and answered in Lewis's Lives of the Contemporaries of Lord Clarendon, 1852, vol. i. preface, pt. i.; and in Lister's Life, vol. ii. chap. xix. Other authorities are quoted in the text.] C. H. F.
http://www.geni.com/people/Sir-Edward-Hyde-of-Dinton/6000000006444674622
CC-MAIN-2015-11
refinedweb
13,860
59.43
(function( window, undefined ) { })(window); Is this used so you can define any functions inside there without littering up the global namespace?Then explicitly expose parts you want with window.xxx = yyy; ? What is the code precisely doing?It looks as if you can pass any number of objects into it - I'm not sure what the (window) at the end is doing. --2. prototype keyword:is the prototype keyword's sole purpose to add functions to all instances of existing objects? Car = function(make) { this.make = make; } var honda = new Car('honda'); Car.prototype.numberOfWheels = 4; alert(honda.numberOfWheels); Can't you just add all the properties to an object before you create instances of them? Why is it necessary to add this dynamically after initialisation?3. multiple = assignments:There's code like this used throughout: jQuery.fn = jQuery.prototype = {} It seems pretty straight-forward but wanted to check I had understood correctly, all variables on the left of the last assignment get the lasts value. var one = 1; var two = 2; var three = 3; var x = one = two = three; alert(one); alert(two); alert(three); alert(x); Thanks, All of those could have very easily been Googled, you know? Cheers,D. <sarcasm>Thanks for your help</sarcasm> I'm not sure what help you think you need. (function(arg) { var test = arg; alert(test); // prints 'robots' })('robots'); alert(test); // prints nothing It's just different to any other syntax to what I have seen - they weren't stupid questions. The second set of brackets () call the function inside the first set. I'm not saying they're stupid questions; just that you were probably better off asking a search engine than a forum. It would have been a lot quicker than waiting for somebody to reply.
http://community.sitepoint.com/t/unknown-js-syntax-features/47601
CC-MAIN-2014-52
refinedweb
297
65.12
Enum classPosted Tuesday, 25 September, 2007 - 12:49 by george in Hello, I was wondering why all the enums are defined within their own class? Seeing as the names are guanteed to be unique why can't the enums be declared in the global OpenGL namespace? Or alternatively, if they have to go inside a separate scope, why can't the Enum class instead be a namespace? Putting them inside a class of course forces people to write things like the following: GL.Clear(GL.Enums.ClearBufferMask.COLOR_BUFFER_BIT | GL.Enums.ClearBufferMask.DEPTH_BUFFER_BIT); which ends up longer than the equivalent Tao version: Gl.glClear(Gl.GL_COLOR_BUFFER_BIT | Gl.GL_DEPTH_BUFFER_BIT); albeit with a few less gls. Personally, I'd ideally like to be able to write something like: GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); On a slightly related note, how come the enum values are still upper case? After all, you've removed the GL_ prefix, so why not go all the way and make them fit a bit more nicely with standard .NET names? I realise I'm probably way too late to the discussion for any changes to be made, but I thought I'd mention it all the same. Woah, lots of questions Woah, lots of questions here! I'll start from the beginning: [...] why can't the enums be declared in the global OpenGL namespace? Two reasons: a) The OpenGL namespace would have to hold not only GL enums, but also GLU and GL3 (when it becomes available), and I wanted to avoid the possibility of clashes between GL and GL3 enums. b) Code-completion performance would take a big dive (I was experiencing 10+ second pauses each type I typed a dot). Or alternatively, if they have to go inside a separate scope, why can't the Enum class instead be a namespace? Because then you'd have to type the full path, e.g. "OpenTK.OpenGL.GLEnums". At least now there is a shortcut: "GL.Enums". While you could add a using directive for an enum, you wouldn't want to do it (due to the performance issues). On a slightly related note, how come the enum values are still upper case? After all, you've removed the GL_ prefix, so why not go all the way and make them fit a bit more nicely with standard .NET names? The reason is... well, I hadn't thought of that until you mentioned it! :) Yep, this is possible, indeed easy!, I'll try to add this capability to the generator for the next version. I must admit you've piqued my curiosity. I'll try to generate an 'ideal' set of bindings following the template you mentioned above, and see how it works out. Now, I don't want to break everything by changing the interface yet again, but I was going to split OpenTK into two assemblies in any case (OpenTK.dll and OpenTK.OpenGL.dll), so tt won't be unreasonable to release two different OpenTK.OpenGL.dlls for compatibility reasons. Have you noticed any other problems with the API? Because if yes, now would be a good to mention them! Ok, I hadn't thought of the Ok, I hadn't thought of the code completion issue. Final suggestion then, why not put them inside the GL class directly? At least then you'd get: GL.Clear(GL.ClearBufferMask.COLOR_BUFFER_BIT | GL.ClearBufferMask.DEPTH_BUFFER_BIT); which is a bit better, there's no chance of name clashes and code completion should be fast. I'm really just poking through the API trying to decide whether to go with OpenTK or Tao. Atm I'm leaning towards OpenTK because I prefer the neatness over the straight C->C# feel of Tao. Time permitting, I'm going to try and write a small windows forms app this week to get a better feel for it, so you may well hear more from me.
http://www.opentk.com/node/54
CC-MAIN-2015-32
refinedweb
654
73.27
A class which controls the pick and place actions for moving a single target in the environment. More... #include <drake/examples/kuka_iiwa_arm/pick_and_place/pick_and_place_state_machine.h> A class which controls the pick and place actions for moving a single target in the environment. Construct a pick and place state machine. The state machine will move the item counter-clockwise around the tables specified in configuration. If single_move is true, the state machine will remain in the kDone state after moving the object once, otherwise it will loop through the pick and place. Update the state machine based on the state of the world in env_state. When a new robot plan is available, iiwa_callback will be invoked with the new plan. If the desired gripper state changes, wsg_callback is invoked.
https://drake.mit.edu/doxygen_cxx/classdrake_1_1examples_1_1kuka__iiwa__arm_1_1pick__and__place_1_1_pick_and_place_state_machine.html
CC-MAIN-2018-47
refinedweb
128
55.95
Namespaces are mappings from simple (unqualified) symbols to Vars and/or Classes. Vars can be interned in a namespace, using def or any of its variants, in which case they have a simple symbol for a name and a reference to their containing namespace, and the namespace maps that symbol to the same var. A namespace can also contain mappings from symbols to vars interned in other namespaces by using refer or use, or from symbols to Class objects by using import. Note that namespaces are first-class, they can be enumerated etc. Namespaces are also dynamic, they can be created, removed and modified at runtime, at the Repl etc. The best way to set up a new namespace at the top of a Clojure source file is to use the ns macro. By default this will create a new namespace contains mappings for the classnames in java.lang plus clojure.lang.Compiler, and the functions in clojure.core. At the Repl it’s best to use in-ns, in which case the new namespace will contain mappings only for the classnames in java.lang. In order to access the names from the clojure.core namespace you must execute (clojure.core/refer 'clojure.core). The user namespace at the Repl has already done this. Creating and switching to a namespace: in-ns ns create-ns Adding to a namespace: alias def import intern refer Finding what namespaces exist: all-ns find-ns Examining a namespace: ns-name ns-aliases ns-imports ns-interns ns-map ns-publics ns-refers Getting a namespace from a symbol: resolve ns-resolve namespace Removing things: ns-unalias ns-unmap remove-ns
http://clojure.org/reference/namespaces
CC-MAIN-2016-07
refinedweb
277
61.87
Link for Previous Article :javascript:nicTemp(); PYTHON MEDIAN_LOW_low returns smaller of the two middle values. Sensitivity to Outliers: The median_low is a robust measure of central location and is less affected by the presence of outliers. How to calculate Median_Low: ( i ) When the number of data points is odd, the middle data point is returned. Eg: median([1, 3, 5]) gives value 3. (ii)When the number of data points is even, the median is interpolated by taking the smaller of the two middle values. Eg: median([1, 3, 5, 7]) gives value 3. NOTE: If data is empty, StatisticsError is raised. data can be a sequence or iterable. SAMPLE PROGRAM: import statistics as stif __name__=="__main__":
https://cppsecrets.com/users/15831129711610497115971051151171091051161045048505564103109971051084699111109/Python-Statistics-MedianLow.php
CC-MAIN-2021-21
refinedweb
117
58.89
This site uses strictly necessary cookies. More Information So I have this movement script but I want to be able to not move direction while jumping. At the moment, I can fly in any direction. I'm brand new to C# so obviously I have no idea, it's all a foreign language to me. Let me know what I need to change, thanks: using UnityEngine; using System.Collections; public class PlayerMovement : MonoBehaviour { // This component is only enabled for "my player" (i.e. the character belonging to the local client machine). // Remote players figures will be moved by a NetworkCharacter, which is also responsible for sending "my player's" // location to other computers. public float speed = 10f; // The speed at which I run public float jumpSpeed = 6f; // How much power we put into our jump. Change this to jump higher. // Booking variables Vector3 direction = Vector3.zero; // forward/back & left/right float verticalVelocity = 0; // up/down CharacterController cc; Animator anim; // Use this for initialization void Start () { cc = GetComponent<CharacterController>(); anim = GetComponent<Animator>(); } // Update is called once per frame void Update () { // WASD forward/back & left/right movement is stored in "direction" direction = transform.rotation * new Vector3( Input.GetAxis("Horizontal") , 0, Input.GetAxis("Vertical") ); // This ensures that we don't move faster going diagonally if(direction.magnitude > 1f) { direction = direction.normalized; } // Set our animation "Speed" parameter. This will move us from "idle" to "run" animations, // but we could also use this to blend between "walk" and "run" as well. anim.SetFloat("Speed", direction.magnitude); // If we're on the ground and the player wants to jump, set // verticalVelocity to a positive number. // If you want double-jumping, you'll want some extra code // here instead of just checking "cc.isGrounded". if(cc.isGrounded && Input.GetButton("Jump")) { verticalVelocity = jumpSpeed; } } // FixedUpdate is called once per physics loop // Do all MOVEMENT and other physics stuff here. void FixedUpdate () { // "direction" is the desired movement direction, based on our player's input Vector3 dist = direction * speed * Time.deltaTime; if(cc.isGrounded && verticalVelocity < 0) { // We are currently on the ground and vertical velocity is // not positive (i.e. we are not starting a jump). // Ensure that we aren't playing the jumping animation anim.SetBool("Jumping", false); // Set our vertical velocity to *almost* zero. This ensures that: // a) We don't start falling at warp speed if we fall off a cliff (by being close to zero) // b) cc.isGrounded returns true every frame (by still being slightly negative, as opposed to zero) verticalVelocity = Physics.gravity.y * Time.deltaTime; } else { // We are either not grounded, or we have a positive verticalVelocity (i.e. we ARE starting a jump) // To make sure we don't go into the jump animation while walking down a slope, make sure that // verticalVelocity is above some arbitrary threshold before triggering the animation. // 75% of "jumpSpeed" seems like a good safe number, but could be a standalone public variable too. // // Another option would be to do a raycast down and start the jump/fall animation whenever we were // more than ___ distance above the ground. if(Mathf.Abs(verticalVelocity) > jumpSpeed*0.75f) { anim.SetBool("Jumping", true); } // Apply gravity. verticalVelocity += Physics.gravity.y * Time.deltaTime; } // Add our verticalVelocity to our actual movement for this frame dist.y = verticalVelocity * Time.deltaTime; // Apply the movement to our character controller (which handles collisions for us) cc.Move( dist ); } } Answer by HappyMoo · Jan 09, 2014 at 12:41 AM Hi, no need to rush anything... you'll need to learn C# anyway eventually, so start now, so you actually understand what happens in the scripts you copy'n'paste and also can do the changes yourself Work through all this: If you need some things explained from another point of view, you can check this: Because, if you can't figure out the script yet, although it's documented so well, you wouldn't understand the answer anyway. It's really frustrating for everybody here to get so many questions, which are not really questions, but requests to program the game for you. Please don't do that. Educate yourself, do some basic research before you throw the code you copied somewhere at our feet. There are enough resources out there to learn everything you need and you should at least have some basic understanding before posting here. Once you understand how the above script works, here's what you need to do: Store your horizontal velocity in a variable and only update that variable while you are grounded. Well, first of all, in your first version you said you've been doing this for hours... now it's days. If you'd used that 3 days to go through the Learning $$anonymous$$odules, you wouldn't need to write in all of your questions that you are a total noob and obviously have not the slightest clue, because you didn't spend any time actually trying to learn something before posting here. This is no script fixing service. I meant 3 days working on movement, hours for the jump. Either way, your comment helped and I figured it out so thank you and I'm going to take a break and spend some time learning Then accept the answer and upvote it please. Also, if you haven't seen the tutorial video linked in the right bar on how this site works, give it a watch. I would upvote but I'm new, no. Animation Cycle Dilemma 0 Answers How to make smooth jump? 1 Answer why will my jump animation only play on multi-jumps? 0 Answers Moving during jumping animation 1 Answer Walking Motion 1 Answer EnterpriseSocial Q&A
https://answers.unity.com/questions/612172/how-to-lock-direction-while-jumping.html?sort=oldest
CC-MAIN-2021-31
refinedweb
942
55.34
In this tutorial, we will Explore the Java Keywords List and learn about some Important Reserved Words, their Meaning along with Examples: Keywords in Java are the reserved words that act as a key to the code. As these words are predefined, they cannot be used for any other purpose like variable name or object name or any other identifier. Java has around 51 reserved words or keywords. In this tutorial, we will discuss the list of keywords in Java. Then we will take up some of the important keywords in Java and see their meaning along with the programming examples. => Check Here To See A-Z Of Java Training Tutorials. What You Will Learn: Java Keyword List Given below is a list of all the keywords in Java. In this list, we have also included the keywords that are no longer used in Java. We will discuss the below keywords in a separate tutorial as they have a great significance as far as Java programming is concerned. These words are: #1) “this” keyword The keyword “this” points to the current object in the program. Also Read => Java ‘THIS’ Keyword With Code Examples #2) “static” keyword A static keyword is a keyword that is used to indicate an object that cannot be instantiated. So if we have a static method, then it need not be called using an object. It can be called just using a class name. Similarly, if we have a static variable, then its value is preserved throughout the program. #3) “super” keyword The “super” keyword in Java is used to refer to the objects of the immediate parent class. The parent class is also referred to as “Superclass”. We will explore the details of the super keyword while discussing inheritance in our OOPS tutorial series. #4) “final” keyword The keyword “final” is used with variables, methods, or classes. A final variable is a constant variable. A final method is a method that cannot be overridden. A final class is a class that cannot be inherited or extended. We will discuss the final one in detail in our OOPS tutorial series. Now let’s implement a program wherein we will use these important keywords in Java. import java.util.*; class MyClass { int i; MyClass() { System.out.println("MyClass:: Default Constructor"); } MyClass(int j) { this(); //calling statement to First Constructor System.out.println("MyClass:: Parameterized Constructor"); } //static method static void methodOne() { System.out.println("MyClass:: static methodOne"); } //final method final void methodTwo() { System.out.println("MyClass:: Final methodTwo"); System.out.println("MyClass::Calling methodOne from methodTwo"); //Accessing same class field this.methodOne(); //Accessing same class method } //regular method void methodThree() { System.out.println("MyClass::MethodThree"); //Accessing same class field System.out.println("MyClass::Calling methodTwo from methodThree"); this.methodTwo(); //Accessing same class method } } class MyDerivedClass extends MyClass{ void methodThree(){ System.out.println("MyDerivedClass::methodThree"); System.out.println("MyDerivedClass::Calling methodThree from MyClass"); super.methodThree(); //calling regular method super.methodTwo(); //calling final method super.methodOne(); //calling static method } //void methodOne(){} //overriding final method gives compiler error //void methodTwo(){} //overriding final method gives compiler error } public class Main{ public static void main(String[] args){ MyClass.methodOne(); //call static method from MyClass MyDerivedClass d1 = new MyDerivedClass (); d1.methodOne(); //call static method from MyDerivedClass d1.methodTwo(); //call final method from MyDerivedClass d1.methodThree(); } } As shown in the above program, the first keyword we have used is import followed by many other keywords like class, int, etc. The main keywords in this program are this, static, final, and super. We have used this keyword in the second constructor to call the first constructor. The parent class MyClass has a static method and a final method declared in it. In the derived class – MyDerivedClass, we override a regular method methodThree. Note that we also try to override methodOne and methodTwo but the compiler gives an error as they are static and final methods respectively. Note the commented code. In the main class, we first call the static class using MyClass and then create a derived class object. Note that no error is given even while calling static and final methods using the derived class objects. Output Note the colored output. This entire output is the result of calling methods using the derived class objects. Frequently Asked Questions Q #1) What is the use of Keywords in Java? Answer: Keywords are also called as Reserved words. These are the words that the programming language uses for internal processing and pre-defined actions. Thus programming language doesn’t allow these keywords to be used by the programmer as identifiers or variable names etc. Despite that, if we use these keywords it will result in a compiler error. Q #2) How many Keywords are present in Java? Answer: Java has a total of 51 keywords that have predefined meaning and are reserved for use by Java. Out of these 51 keywords, 49 keywords are currently used while the remaining 2 are no more used. Q #3) What is the difference between integer and int? Answer: Both int and Integer store integer values. But ‘int’ is a keyword that is a primitive data type int. An integer is a class type. Integer converts int into an object and vice versa. Q #4) Is null a keyword in Java? Answer: No. Null is not a keyword in Java but it is literal. Yet, we cannot use it for declaring identifiers. Q #5) Is new a keyword in Java? Answer: Yes, new is a keyword in Java. The new keyword is used to create a new object and allocate memory to this new object on the heap. Apart from the class objects, we also use the new keyword to create array variables and allocate memory. Conclusion In this tutorial, we have discussed various keywords used in Java. Java supports a total of 51 keywords out of which 49 keywords are currently used and 2 are not currently used. Of these keywords, four keywords i.e. this, static, super, and final are important keywords that need special attention. ‘This’ keyword points to the current object. The static keyword is used to indicate the instantiation that is not needed. The super keyword is used to refer to the parent class and the final keyword is used to indicate the constant or non-inheritance. => Visit Here To See The Java Training Series For All.
https://www.softwaretestinghelp.com/important-java-keywords/
CC-MAIN-2021-17
refinedweb
1,061
58.48
We’re living in the era of large amounts of data, powerful computers, and artificial intelligence. This is just the beginning. Data science and machine learning are driving image recognition, autonomous vehicles development, decisions in the financial and energy sectors, advances in medicine, the rise of social networks, and more. Linear regression is an important part of this. Linear regression is one of the fundamental statistical and machine learning techniques. Whether you want to do statistics, machine learning, or scientific computing, there are good chances that you’ll need it. It’s advisable to learn it first and then proceed towards more complex methods. By the end of this article, you’ll have learned: - What linear regression is - What linear regression is used for - How linear regression works - How to implement linear regression in Python, step by step Free Bonus: Click here to get access to a free NumPy Resources Guide that points you to the best tutorials, videos, and books for improving your NumPy skills. Regression Regression analysis is one of the most important fields in statistics and machine learning. There are many regression methods available. Linear regression is one of them. What Is Regression? Regression searches for relationships among variables. For example, you can observe several employees of some company and try to understand how their salaries depend on the features, such as experience, level of education, role, city they work in, and so on. This is a regression problem where data related to each employee represent one observation. The presumption is that the experience, education, role, and city are the independent features, while the salary depends on them. Similarly, you can try to establish a mathematical dependence of the prices of houses on their areas, numbers of bedrooms, distances to the city center, and so on. Generally, in regression analysis, you usually consider some phenomenon of interest and have a number of observations. Each observation has two or more features. Following the assumption that (at least) one of the features depends on the others, you try to establish a relation among them. In other words, you need to find a function that maps some features or variables to others sufficiently well. The dependent features are called the dependent variables, outputs, or responses. The independent features are called the independent variables, inputs, or predictors. Regression problems usually have one continuous and unbounded dependent variable. The inputs, however, can be continuous, discrete, or even categorical data such as gender, nationality, brand, and so on. It is a common practice to denote the outputs with 𝑦 and inputs with 𝑥. If there are two or more independent variables, they can be represented as the vector 𝐱 = (𝑥₁, …, 𝑥ᵣ), where 𝑟 is the number of inputs. When Do You Need Regression? Typically, you need regression to answer whether and how some phenomenon influences the other or how several variables are related. For example, you can use it to determine if and to what extent the experience or gender impact salaries. Regression is also useful when you want to forecast a response using a new set of predictors. For example, you could try to predict electricity consumption of a household for the next hour given the outdoor temperature, time of day, and number of residents in that household. Regression is used in many different fields: economy, computer science, social sciences, and so on. Its importance rises every day with the availability of large amounts of data and increased awareness of the practical value of data. Linear Regression Linear regression is probably one of the most important and widely used regression techniques. It’s among the simplest regression methods. One of its main advantages is the ease of interpreting results. Problem Formulation When implementing linear regression of some dependent variable 𝑦 on the set of independent variables 𝐱 = (𝑥₁, …, 𝑥ᵣ), where 𝑟 is the number of predictors, you assume a linear relationship between 𝑦 and 𝐱: 𝑦 = 𝛽₀ + 𝛽₁𝑥₁ + ⋯ + 𝛽ᵣ𝑥ᵣ + 𝜀. This equation is the regression equation. 𝛽₀, 𝛽₁, …, 𝛽ᵣ are the regression coefficients, and 𝜀 is the random error. Linear regression calculates the estimators of the regression coefficients or simply the predicted weights, denoted with 𝑏₀, 𝑏₁, …, 𝑏ᵣ. They define the estimated regression function 𝑓(𝐱) = 𝑏₀ + 𝑏₁𝑥₁ + ⋯ + 𝑏ᵣ𝑥ᵣ. This function should capture the dependencies between the inputs and output sufficiently well. The estimated or predicted response, 𝑓(𝐱ᵢ), for each observation 𝑖 = 1, …, 𝑛, should be as close as possible to the corresponding actual response 𝑦ᵢ. The differences 𝑦ᵢ - 𝑓(𝐱ᵢ) for all observations 𝑖 = 1, …, 𝑛, are called the residuals. Regression is about determining the best predicted weights, that is the weights corresponding to the smallest residuals. To get the best weights, you usually minimize the sum of squared residuals (SSR) for all observations 𝑖 = 1, …, 𝑛: SSR = Σᵢ(𝑦ᵢ - 𝑓(𝐱ᵢ))². This approach is called the method of ordinary least squares. Regression Performance The variation of actual responses 𝑦ᵢ, 𝑖 = 1, …, 𝑛, occurs partly due to the dependence on the predictors 𝐱ᵢ. However, there is also an additional inherent variance of the output. The coefficient of determination, denoted as 𝑅², tells you which amount of variation in 𝑦 can be explained by the dependence on 𝐱 using the particular regression model. Larger 𝑅² indicates a better fit and means that the model can better explain the variation of the output with different inputs. The value 𝑅² = 1 corresponds to SSR = 0, that is to the perfect fit since the values of predicted and actual responses fit completely to each other. Simple Linear Regression Simple or single-variate linear regression is the simplest case of linear regression with a single independent variable, 𝐱 = 𝑥. The following figure illustrates simple linear regression: When implementing simple linear regression, you typically start with a given set of input-output (𝑥-𝑦) pairs (green circles). These pairs are your observations. For example, the leftmost observation (green circle) has the input 𝑥 = 5 and the actual output (response) 𝑦 = 5. The next one has 𝑥 = 15 and 𝑦 = 20, and so on. The estimated regression function (black line) has the equation 𝑓(𝑥) = 𝑏₀ + 𝑏₁𝑥. Your goal is to calculate the optimal values of the predicted weights 𝑏₀ and 𝑏₁ that minimize SSR and determine the estimated regression function. The value of 𝑏₀, also called the intercept, shows the point where the estimated regression line crosses the 𝑦 axis. It is the value of the estimated response 𝑓(𝑥) for 𝑥 = 0. The value of 𝑏₁ determines the slope of the estimated regression line. The predicted responses (red squares) are the points on the regression line that correspond to the input values. For example, for the input 𝑥 = 5, the predicted response is 𝑓(5) = 8.33 (represented with the leftmost red square). The residuals (vertical dashed gray lines) can be calculated as 𝑦ᵢ - 𝑓(𝐱ᵢ) = 𝑦ᵢ - 𝑏₀ - 𝑏₁𝑥ᵢ for 𝑖 = 1, …, 𝑛. They are the distances between the green circles and red squares. When you implement linear regression, you are actually trying to minimize these distances and make the red squares as close to the predefined green circles as possible. Multiple Linear Regression Multiple or multivariate linear regression is a case of linear regression with two or more independent variables. If there are just two independent variables, the estimated regression function is. It represents a regression plane in a three-dimensional space. The goal of regression is to determine the values of the weights 𝑏₀, 𝑏₁, and 𝑏₂ such that this plane is as close as possible to the actual responses and yield the minimal SSR. The case of more than two independent variables is similar, but more general. The estimated regression function is 𝑓(𝑥₁, …, 𝑥ᵣ) = 𝑏₀ + 𝑏₁𝑥₁ + ⋯ +𝑏ᵣ𝑥ᵣ, and there are 𝑟 + 1 weights to be determined when the number of inputs is 𝑟. Polynomial Regression You can regard polynomial regression as a generalized case of linear regression. You assume the polynomial dependence between the output and inputs and, consequently, the polynomial estimated regression function. In other words, in addition to linear terms like 𝑏₁𝑥₁, your regression function 𝑓 can include non-linear terms such as 𝑏₂𝑥₁², 𝑏₃𝑥₁³, or even 𝑏₄𝑥₁𝑥₂, 𝑏₅𝑥₁²𝑥₂, and so on. The simplest example of polynomial regression has a single independent variable, and the estimated regression function is a polynomial of degree 2: 𝑓(𝑥) = 𝑏₀ + 𝑏₁𝑥 + 𝑏₂𝑥². Now, remember that you want to calculate 𝑏₀, 𝑏₁, and 𝑏₂, which minimize SSR. These are your unknowns! Keeping this in mind, compare the previous regression function with the used for linear regression. They look very similar and are both linear functions of the unknowns 𝑏₀, 𝑏₁, and 𝑏₂. This is why you can solve the polynomial regression problem as a linear problem with the term 𝑥² regarded as an input variable. In the case of two variables and the polynomial of degree 2, the regression function has this form:. The procedure for solving the problem is identical to the previous case. You apply linear regression for five inputs: 𝑥₁, 𝑥₂, 𝑥₁², 𝑥₁𝑥₂, and 𝑥₂². What you get as the result of regression are the values of six weights which minimize SSR: 𝑏₀, 𝑏₁, 𝑏₂, 𝑏₃, 𝑏₄, and 𝑏₅. Of course, there are more general problems, but this should be enough to illustrate the point. Underfitting and Overfitting One very important question that might arise when you’re implementing polynomial regression is related to the choice of the optimal degree of the polynomial regression function. There is no straightforward rule for doing this. It depends on the case. You should, however, be aware of two problems that might follow the choice of the degree: underfitting and overfitting. Underfitting occurs when a model can’t accurately capture the dependencies among data, usually as a consequence of its own simplicity. It often yields a low 𝑅² with known data and bad generalization capabilities when applied with new data. Overfitting happens when a model learns both dependencies among data and random fluctuations. In other words, a model learns the existing data too well. Complex models, which have many features or terms, are often prone to overfitting. When applied to known data, such models usually yield high 𝑅². However, they often don’t generalize well and have significantly lower 𝑅² when used with new data. The next figure illustrates the underfitted, well-fitted, and overfitted models: The top left plot shows a linear regression line that has a low 𝑅². It might also be important that a straight line can’t take into account the fact that the actual response increases as 𝑥 moves away from 25 towards zero. This is likely an example of underfitting. The top right plot illustrates polynomial regression with the degree equal to 2. In this instance, this might be the optimal degree for modeling this data. The model has a value of 𝑅² that is satisfactory in many cases and shows trends nicely. The bottom left plot presents polynomial regression with the degree equal to 3. The value of 𝑅² is higher than in the preceding cases. This model behaves better with known data than the previous ones. However, it shows some signs of overfitting, especially for the input values close to 60 where the line starts decreasing, although actual data don’t show that. Finally, on the bottom right plot, you can see the perfect fit: six points and the polynomial line of the degree 5 (or higher) yield 𝑅² = 1. Each actual response equals its corresponding prediction. In some situations, this might be exactly what you’re looking for. In many cases, however, this is an overfitted model. It is likely to have poor behavior with unseen data, especially with the inputs larger than 50. For example, it assumes, without any evidence, that there is a significant drop in responses for 𝑥 > 50 and that 𝑦 reaches zero for 𝑥 near 60. Such behavior is the consequence of excessive effort to learn and fit the existing data. There are a lot of resources where you can find more information about regression in general and linear regression in particular. The regression analysis page on Wikipedia, Wikipedia’s linear regression article, as well as Khan Academy’s linear regression article are good starting points. Implementing Linear Regression in Python It’s time to start implementing linear regression in Python. Basically, all you should do is apply the proper packages and their functions and classes. Python Packages for Linear Regression The package NumPy is a fundamental Python scientific package that allows many high-performance operations on single- and multi-dimensional arrays. It also offers many mathematical routines. Of course, it’s open source. If you’re not familiar with NumPy, you can use the official NumPy User Guide and read Look Ma, No For-Loops: Array Programming With NumPy. In addition, Pure Python vs NumPy vs TensorFlow Performance Comparison can give you a pretty good idea on the performance gains you can achieve when applying NumPy. The package scikit-learn is a widely used Python library for machine learning, built on top of NumPy and some other packages. It provides the means for preprocessing data, reducing dimensionality, implementing regression, classification, clustering, and more. Like NumPy, scikit-learn is also open source. You can check the page Generalized Linear Models on the scikit-learn web site to learn more about linear models and get deeper insight into how this package works. If you want to implement linear regression and need the functionality beyond the scope of scikit-learn, you should consider statsmodels. It’s a powerful Python package for the estimation of statistical models, performing tests, and more. It’s open source as well. You can find more information on statsmodels on its official web site. Simple Linear Regression With scikit-learn Let’s start with the simplest case, which is simple linear regression. There are five basic steps when you’re implementing linear regression: - Import the packages and classes you need. - Provide data to work with and eventually do appropriate transformations. - Create a regression model and fit it with existing data. - Check the results of model fitting to know whether the model is satisfactory. - Apply the model for predictions. These steps are more or less general for most of the regression approaches and implementations. Step 1: Import packages and classes The first step is to import the package numpy and the class LinearRegression from sklearn.linear_model: import numpy as np from sklearn.linear_model import LinearRegression Now, you have all the functionalities you need to implement linear regression. data The second step is defining data to work with. The inputs (regressors, 𝑥) and output (predictor, 𝑦) should be arrays (the instances of the class numpy.ndarray) or similar objects. This is the simplest way of providing data for regression: x = np.array([5, 15, 25, 35, 45, 55]).reshape((-1, 1)) y = np.array([5, 20, 14, 32, 22, 38]) Now, you have two arrays: the input x and output y. You should call .reshape() on x because this array is required to be two-dimensional, or to be more precise, to have one column and as many rows as necessary. That’s exactly what the argument (-1, 1) of .reshape() specifies. This is how x and y look now: >>> print(x) [[ 5] [15] [25] [35] [45] [55]] >>> print(y) [ 5 20 14 32 22 38] As you can see, x has two dimensions, and x.shape is (6, 1), while y has a single dimension, and y.shape is (6,). Step 3: Create a model and fit it The next step is to create a linear regression model and fit it using the existing data. Let’s create an instance of the class LinearRegression, which will represent the regression model: model = LinearRegression() This statement creates the variable model as the instance of LinearRegression. You can provide several optional parameters to LinearRegression: fit_interceptis a Boolean ( Trueby default) that decides whether to calculate the intercept 𝑏₀ ( True) or consider it equal to zero ( False). normalizeis a Boolean ( Falseby default) that decides whether to normalize the input variables ( True) or not ( False). copy_Xis a Boolean ( Trueby default) that decides whether to copy ( True) or overwrite the input variables ( False). n_jobsis an integer or None(default) and represents the number of jobs used in parallel computation. Noneusually means one job and -1to use all processors. This example uses the default values of all parameters. It’s time to start using the model. First, you need to call .fit() on model: model.fit(x, y) With .fit(), you calculate the optimal values of the weights 𝑏₀ and 𝑏₁, using the existing input and output ( x and y) as the arguments. In other words, .fit() fits the model. It returns self, which is the variable model itself. That’s why you can replace the last two statements with this one: model = LinearRegression().fit(x, y) This statement does the same thing as the previous two. It’s just shorter. Step 4: Get results Once you have your model fitted, you can get the results to check whether the model works satisfactorily and interpret it. You can obtain the coefficient of determination (𝑅²) with .score() called on model: >>> r_sq = model.score(x, y) >>> print('coefficient of determination:', r_sq) coefficient of determination: 0.715875613747954 When you’re applying .score(), the arguments are also the predictor x and regressor y, and the return value is 𝑅². The attributes of model are .intercept_, which represents the coefficient, 𝑏₀ and .coef_, which represents 𝑏₁: >>> print('intercept:', model.intercept_) intercept: 5.633333333333329 >>> print('slope:', model.coef_) slope: [0.54] The code above illustrates how to get 𝑏₀ and 𝑏₁. You can notice that .intercept_ is a scalar, while .coef_ is an array. The value 𝑏₀ = 5.63 (approximately) illustrates that your model predicts the response 5.63 when 𝑥 is zero. The value 𝑏₁ = 0.54 means that the predicted response rises by 0.54 when 𝑥 is increased by one. You should notice that you can provide y as a two-dimensional array as well. In this case, you’ll get a similar result. This is how it might look: >>> new_model = LinearRegression().fit(x, y.reshape((-1, 1))) >>> print('intercept:', new_model.intercept_) intercept: [5.63333333] >>> print('slope:', new_model.coef_) slope: [[0.54]] As you can see, this example is very similar to the previous one, but in this case, .intercept_ is a one-dimensional array with the single element 𝑏₀, and .coef_ is a two-dimensional array with the single element 𝑏₁. Step 5: Predict response Once there is a satisfactory model, you can use it for predictions with either existing or new data. To obtain the predicted response, use .predict(): >>> y_pred = model.predict(x) >>> print('predicted response:', y_pred, sep='\n') predicted response: [ 8.33333333 13.73333333 19.13333333 24.53333333 29.93333333 35.33333333] When applying .predict(), you pass the regressor as the argument and get the corresponding predicted response. This is a nearly identical way to predict the response: >>> y_pred = model.intercept_ + model.coef_ * x >>> print('predicted response:', y_pred, sep='\n') predicted response: [[ 8.33333333] [13.73333333] [19.13333333] [24.53333333] [29.93333333] [35.33333333]] In this case, you multiply each element of x with model.coef_ and add model.intercept_ to the product. The output here differs from the previous example only in dimensions. The predicted response is now a two-dimensional array, while in the previous case, it had one dimension. If you reduce the number of dimensions of x to one, these two approaches will yield the same result. You can do this by replacing x with x.reshape(-1), x.flatten(), or x.ravel() when multiplying it with model.coef_. In practice, regression models are often applied for forecasts. This means that you can use fitted models to calculate the outputs based on some other, new inputs: >>> x_new = np.arange(5).reshape((-1, 1)) >>> print(x_new) [[0] [1] [2] [3] [4]] >>> y_new = model.predict(x_new) >>> print(y_new) [5.63333333 6.17333333 6.71333333 7.25333333 7.79333333] Here .predict() is applied to the new regressor x_new and yields the response y_new. This example conveniently uses arange() from numpy to generate an array with the elements from 0 (inclusive) to 5 (exclusive), that is 0, 1, 2, 3, and 4. You can find more information about LinearRegression on the official documentation page. Multiple Linear Regression With scikit-learn You can implement multiple linear regression following the same steps as you would for simple regression. Steps 1 and 2: Import packages and classes, and provide data First, you import numpy and sklearn.linear_model.LinearRegression and provide known inputs and output: import numpy as np from sklearn.linear_model import LinearRegression x = [[0, 1], [5, 1], [15, 2], [25, 5], [35, 11], [45, 15], [55, 34], [60, 35]] y = [4, 5, 20, 14, 32, 22, 38, 43] x, y = np.array(x), np.array(y) That’s a simple way to define the input x and output y. You can print x and y to see how they look now: >>> print(x) [[ 0 1] [ 5 1] [15 2] [25 5] [35 11] [45 15] [55 34] [60 35]] >>> print(y) [ 4 5 20 14 32 22 38 43] In multiple linear regression, x is a two-dimensional array with at least two columns, while y is usually a one-dimensional array. This is a simple example of multiple linear regression, and x has exactly two columns. Step 3: Create a model and fit it The next step is to create the regression model as an instance of LinearRegression and fit it with .fit(): model = LinearRegression().fit(x, y) The result of this statement is the variable model referring to the object of type LinearRegression. It represents the regression model fitted with existing data. Step 4: Get results You can obtain the properties of the model the same way as in the case of simple linear regression: >>> r_sq = model.score(x, y) >>> print('coefficient of determination:', r_sq) coefficient of determination: 0.8615939258756776 >>> print('intercept:', model.intercept_) intercept: 5.52257927519819 >>> print('slope:', model.coef_) slope: [0.44706965 0.25502548] You obtain the value of 𝑅² using .score() and the values of the estimators of regression coefficients with .intercept_ and .coef_. Again, .intercept_ holds the bias 𝑏₀, while now .coef_ is an array containing 𝑏₁ and 𝑏₂ respectively. In this example, the intercept is approximately 5.52, and this is the value of the predicted response when 𝑥₁ = 𝑥₂ = 0. The increase of 𝑥₁ by 1 yields the rise of the predicted response by 0.45. Similarly, when 𝑥₂ grows by 1, the response rises by 0.26. Step 5: Predict response Predictions also work the same way as in the case of simple linear regression: >>> y_pred = model.predict(x) >>> print('predicted response:', y_pred, sep='\n') predicted response: [ 5.77760476 8.012953 12.73867497 17.9744479 23.97529728 29.4660957 38.78227633 41.27265006] The predicted response is obtained with .predict(), which is very similar to the following: >>> y_pred = model.intercept_ + np.sum(model.coef_ * x, axis=1) >>> print('predicted response:', y_pred, sep='\n') predicted response: [ 5.77760476 8.012953 12.73867497 17.9744479 23.97529728 29.4660957 38.78227633 41.27265006] You can predict the output values by multiplying each column of the input with the appropriate weight, summing the results and adding the intercept to the sum. You can apply this model to new data as well: >>> x_new = np.arange(10).reshape((-1, 2)) >>> print(x_new) [[0 1] [2 3] [4 5] [6 7] [8 9]] >>> y_new = model.predict(x_new) >>> print(y_new) [ 5.77760476 7.18179502 8.58598528 9.99017554 11.3943658 ] That’s the prediction using a linear regression model. Polynomial Regression With scikit-learn Implementing polynomial regression with scikit-learn is very similar to linear regression. There is only one extra step: you need to transform the array of inputs to include non-linear terms such as 𝑥². Step 1: Import packages and classes In addition to numpy and sklearn.linear_model.LinearRegression, you should also import the class PolynomialFeatures from sklearn.preprocessing: import numpy as np from sklearn.linear_model import LinearRegression from sklearn.preprocessing import PolynomialFeatures The import is now done, and you have everything you need to work with. Step 2a: Provide data. Keep in mind that you need the input to be a two-dimensional array. That’s why .reshape() is used. Step 2b: Transform input data This is the new step you need to implement for polynomial regression! As you’ve seen earlier, you need to include 𝑥² (and perhaps other terms) as additional features when implementing polynomial regression. For that reason, you should transform the input array x to contain the additional column(s) with the values of 𝑥² (and eventually more features). It’s possible to transform the input array in several ways (like using insert() from numpy), but the class PolynomialFeatures is very convenient for this purpose. Let’s create an instance of this class: transformer = PolynomialFeatures(degree=2, include_bias=False) The variable transformer refers to an instance of PolynomialFeatures which you can use to transform the input x. You can provide several optional parameters to PolynomialFeatures: degreeis an integer ( 2by default) that represents the degree of the polynomial regression function. interaction_onlyis a Boolean ( Falseby default) that decides whether to include only interaction features ( True) or all features ( False). include_biasis a Boolean ( Trueby default) that decides whether to include the bias (intercept) column of ones ( True) or not ( False). This example uses the default values of all parameters, but you’ll sometimes want to experiment with the degree of the function, and it can be beneficial to provide this argument anyway. Before applying transformer, you need to fit it with .fit(): transformer.fit(x) Once transformer is fitted, it’s ready to create a new, modified input. You apply .transform() to do that: x_ = transformer.transform(x) That’s the transformation of the input array with .transform(). It takes the input array as the argument and returns the modified array. You can also use .fit_transform() to replace the three previous statements with only one: x_ = PolynomialFeatures(degree=2, include_bias=False).fit_transform(x) That’s fitting and transforming the input array in one statement with .fit_transform(). It also takes the input array and effectively does the same thing as .fit() and .transform() called in that order. It also returns the modified array. This is how the new input array looks: >>> print(x_) [[ 5. 25.] [ 15. 225.] [ 25. 625.] [ 35. 1225.] [ 45. 2025.] [ 55. 3025.]] The modified input array contains two columns: one with the original inputs and the other with their squares. You can find more information about PolynomialFeatures on the official documentation page. Step 3: Create a model and fit it This step is also the same as in the case of linear regression. You create and fit the model: model = LinearRegression().fit(x_, y) The regression model is now created and fitted. It’s ready for application. You should keep in mind that the first argument of .fit() is the modified input array x_ and not the original x. Step 4: Get results You can obtain the properties of the model the same way as in the case of linear regression: >>> r_sq = model.score(x_, y) >>> print('coefficient of determination:', r_sq) coefficient of determination: 0.8908516262498564 >>> print('intercept:', model.intercept_) intercept: 21.372321428571425 >>> print('coefficients:', model.coef_) coefficients: [-1.32357143 0.02839286] Again, .score() returns 𝑅². Its first argument is also the modified input x_, not x. The values of the weights are associated to .intercept_ and .coef_: .intercept_ represents 𝑏₀, while .coef_ references the array that contains 𝑏₁ and 𝑏₂ respectively. You can obtain a very similar result with different transformation and regression arguments: x_ = PolynomialFeatures(degree=2, include_bias=True).fit_transform(x) If you call PolynomialFeatures with the default parameter include_bias=True (or if you just omit it), you’ll obtain the new input array x_ with the additional leftmost column containing only ones. This column corresponds to the intercept. This is how the modified input array looks in this case: >>> print(x_) [[1.000e+00 5.000e+00 2.500e+01] [1.000e+00 1.500e+01 2.250e+02] [1.000e+00 2.500e+01 6.250e+02] [1.000e+00 3.500e+01 1.225e+03] [1.000e+00 4.500e+01 2.025e+03] [1.000e+00 5.500e+01 3.025e+03]] The first column of x_ contains ones, the second has the values of x, while the third holds the squares of x. The intercept is already included with the leftmost column of ones, and you don’t need to include it again when creating the instance of LinearRegression. Thus, you can provide fit_intercept=False. This is how the next statement looks: model = LinearRegression(fit_intercept=False).fit(x_, y) The variable model again corresponds to the new input array x_. Therefore x_ should be passed as the first argument instead of x. This approach yields the following results, which are similar to the previous case: >>> r_sq = model.score(x_, y) >>> print('coefficient of determination:', r_sq) coefficient of determination: 0.8908516262498565 >>> print('intercept:', model.intercept_) intercept: 0.0 >>> print('coefficients:', model.coef_) coefficients: [21.37232143 -1.32357143 0.02839286] You see that now .intercept_ is zero, but .coef_ actually contains 𝑏₀ as its first element. Everything else is the same. Step 5: Predict response If you want to get the predicted response, just use .predict(), but remember that the argument should be the modified input x_ instead of the old x: >>> y_pred = model.predict(x_) >>> print('predicted response:', y_pred, sep='\n') predicted response: [15.46428571 7.90714286 6.02857143 9.82857143 19.30714286 34.46428571] As you can see, the prediction works almost the same way as in the case of linear regression. It just requires the modified input instead of the original. You can apply the identical procedure if you have several input variables. You’ll have an input array with more than one column, but everything else is the same. Here is an example: # Step 1: Import packages import numpy as np from sklearn.linear_model import LinearRegression from sklearn.preprocessing import PolynomialFeatures # Step 2a: Provide data x = [[0, 1], [5, 1], [15, 2], [25, 5], [35, 11], [45, 15], [55, 34], [60, 35]] y = [4, 5, 20, 14, 32, 22, 38, 43] x, y = np.array(x), np.array(y) # Step 2b: Transform input data x_ = PolynomialFeatures(degree=2, include_bias=False).fit_transform(x) # Step 3: Create a model and fit it model = LinearRegression().fit(x_, y) # Step 4: Get results r_sq = model.score(x_, y) intercept, coefficients = model.intercept_, model.coef_ # Step 5: Predict y_pred = model.predict(x_) This regression example yields the following results and predictions: >>> print('coefficient of determination:', r_sq) coefficient of determination: 0.9453701449127822 >>> print('intercept:', intercept) intercept: 0.8430556452395734 >>> print('coefficients:', coefficients, sep='\n') coefficients: [ 2.44828275 0.16160353 -0.15259677 0.47928683 -0.4641851 ] >>> print('predicted response:', y_pred, sep='\n') predicted response: [ 0.54047408 11.36340283 16.07809622 15.79139 29.73858619 23.50834636 39.05631386 41.92339046] In this case, there are six regression coefficients (including the intercept), as shown in the estimated regression. You can also notice that polynomial regression yielded a higher coefficient of determination than multiple linear regression for the same problem. At first, you could think that obtaining such a large 𝑅² is an excellent result. It might be. However, in real-world situations, having a complex model and 𝑅² very close to 1 might also be a sign of overfitting. To check the performance of a model, you should test it with new data, that is with observations not used to fit (train) the model. Advanced Linear Regression With statsmodels You can implement linear regression in Python relatively easily by using the package statsmodels as well. Typically, this is desirable when there is a need for more detailed results. The procedure is similar to that of scikit-learn. Step 1: Import packages First you need to do some imports. In addition to numpy, you need to import statsmodels.api: import numpy as np import statsmodels.api as sm Now you have the packages you need. Step 2: Provide data and transform inputs You can provide the inputs and outputs the same way as you did when you were using scikit-learn: x = [[0, 1], [5, 1], [15, 2], [25, 5], [35, 11], [45, 15], [55, 34], [60, 35]] y = [4, 5, 20, 14, 32, 22, 38, 43] x, y = np.array(x), np.array(y) The input and output arrays are created, but the job is not done yet. You need to add the column of ones to the inputs if you want statsmodels to calculate the intercept 𝑏₀. It doesn’t takes 𝑏₀ into account by default. This is just one function call: x = sm.add_constant(x) That’s how you add the column of ones to x with add_constant(). It takes the input array x as an argument and returns a new array with the column of ones inserted at the beginning. This is how x and y look now: >>> print(x) [[ 1. 0. 1.] [ 1. 5. 1.] [ 1. 15. 2.] [ 1. 25. 5.] [ 1. 35. 11.] [ 1. 45. 15.] [ 1. 55. 34.] [ 1. 60. 35.]] >>> print(y) [ 4 5 20 14 32 22 38 43] You can see that the modified x has three columns: the first column of ones (corresponding to 𝑏₀ and replacing the intercept) as well as two columns of the original features. Step 3: Create a model and fit it The regression model based on ordinary least squares is an instance of the class statsmodels.regression.linear_model.OLS. This is how you can obtain one: model = sm.OLS(y, x) You should be careful here! Please, notice that the first argument is the output, followed with the input. There are several more optional parameters. To find more information about this class, please visit the official documentation page. Once your model is created, you can apply .fit() on it: results = model.fit() By calling .fit(), you obtain the variable results, which is an instance of the class statsmodels.regression.linear_model.RegressionResultsWrapper. This object holds a lot of information about the regression model. Step 4: Get results The variable results refers to the object that contains detailed information about the results of linear regression. Explaining them is far beyond the scope of this article, but you’ll learn here how to extract them. You can call .summary() to get the table with the results of linear regression: >>> print(results.summary()) OLS Regression Results ============================================================================== Dep. Variable: y R-squared: 0.862 Model: OLS Adj. R-squared: 0.806 Method: Least Squares F-statistic: 15.56 Date: Sun, 17 Feb 2019 Prob (F-statistic): 0.00713 Time: 19:15:07 Log-Likelihood: -24.316 No. Observations: 8 AIC: 54.63 Df Residuals: 5 BIC: 54.87 Df Model: 2 Covariance Type: nonrobust ==============================================================================. No. 80.1 ============================================================================== Warnings: [1] Standard Errors assume that the covariance matrix of the errors is correctly specified. This table is very comprehensive. You can find many statistical values associated with linear regression including 𝑅², 𝑏₀, 𝑏₁, and 𝑏₂. In this particular case, you might obtain the warning related to kurtosistest. This is due to the small number of observations provided. You can extract any of the values from the table above. Here’s an example: >>> print('coefficient of determination:', results.rsquared) coefficient of determination: 0.8615939258756777 >>> print('adjusted coefficient of determination:', results.rsquared_adj) adjusted coefficient of determination: 0.8062314962259488 >>> print('regression coefficients:', results.params) regression coefficients: [5.52257928 0.44706965 0.25502548] That’s how you obtain some of the results of linear regression: .rsquaredholds 𝑅². .rsquared_adjrepresents adjusted 𝑅² (𝑅² corrected according to the number of input features). .paramsrefers the array with 𝑏₀, 𝑏₁, and 𝑏₂ respectively. You can also notice that these results are identical to those obtained with scikit-learn for the same problem. To find more information about the results of linear regression, please visit the official documentation page. Step 5: Predict response You can obtain the predicted response on the input values used for creating the model using .fittedvalues or .predict() with the input array as the argument: >>> print('predicted response:', results.fittedvalues, sep='\n') predicted response: [ 5.77760476 8.012953 12.73867497 17.9744479 23.97529728 29.4660957 38.78227633 41.27265006] >>> print('predicted response:', results.predict(x), sep='\n') predicted response: [ 5.77760476 8.012953 12.73867497 17.9744479 23.97529728 29.4660957 38.78227633 41.27265006] This is the predicted response for known inputs. If you want predictions with new regressors, you can also apply .predict() with new data as the argument: >>> x_new = sm.add_constant(np.arange(10).reshape((-1, 2))) >>> print(x_new) [[1. 0. 1.] [1. 2. 3.] [1. 4. 5.] [1. 6. 7.] [1. 8. 9.]] >>> y_new = results.predict(x_new) >>> print(y_new) [ 5.77760476 7.18179502 8.58598528 9.99017554 11.3943658 ] You can notice that the predicted results are the same as those obtained with scikit-learn for the same problem. Beyond Linear Regression Linear regression is sometimes not appropriate, especially for non-linear models of high complexity. Fortunately, there are other regression techniques suitable for the cases where linear regression doesn’t work well. Some of them are support vector machines, decision trees, random forest, and neural networks. There are numerous Python libraries for regression using these techniques. Most of them are free and open-source. That’s one of the reasons why Python is among the main programming languages for machine learning. The package scikit-learn provides the means for using other regression techniques in a very similar way to what you’ve seen. It contains the classes for support vector machines, decision trees, random forest, and more, with the methods .fit(), .predict(), .score() and so on. Conclusion You now know what linear regression is and how you can implement it with Python and three open-source packages: NumPy, scikit-learn, and statsmodels. You use NumPy for handling arrays. Linear regression is implemented with the following: - scikit-learn if you don’t need detailed results and want to use the approach consistent with other regression techniques - statsmodels if you need the advanced statistical parameters of a model Both approaches are worth learning how to use and exploring further. The links in this article can be very useful for that. If you have questions or comments, please put them in the comment section below.
https://realpython.com/linear-regression-in-python/
CC-MAIN-2019-22
refinedweb
6,401
57.98
! The KDE team working on Nepomuk aims to bring the Semantic Desktop to KDE 4, allowing applications to share and respond intelligently to meta data about files, contacts, web pages and more. Let us make this short: Nepomuk is an important project for the future KDE desktop. Its goal is to get all the information available on the system to the user. You are receiving an email - Nepomuk should show you information relevant to related projects or persons or tasks. You look at images of a person - Nepomuk should have links to other images of that person or unanswered emails or events you met that person at. You open the video player - Nepomuk should propose to watch the next episode in the series you are currently watching. These are all but examples of what Nepomuk should provide. It could all become reality. But for that more development power is needed. Now is the perfect time to enter the world of the semantic desktop. We finally have a decent database back end with Virtuoso support in Soprano (instructions for testing it here). This not only improves critical issues like the memory footprint and the scalability. It also provides us with a range of new features. We can for example embed full text queries directly in SPARQL expressions. We can use aggregate functions such as COUNT or MAX. We can nest SPARQL queries. We can update data using the SPARQL update syntax. And so on. All in all handling the available data gets way more powerful and convenient. At the same time the integration with Akonadi takes a leap. Akonadi already pushes all its contact, email, and event data into Nepomuk for us to consume and to enrich. This opens up many possibilities, ranging from tagging files, tasks and web pages with a particular contact to associating files with an event or linking a set of emails to a particular project. Apart from that the Nepomuk playground is already full of examples and prototypes that only wait to be enhanced, re-factored, and reused. All this information needs to be displayed and enriched via Plasma applets, application plugins, new frameworks, and most importantly your creativity. There are both simple and complex things to be done, from creating a search GUI to improving the data storage system or determining relationships between files. If you are interested in the semantic desktop, in gathering, presenting and using this information, check out the Nepomuk project page to get an idea of what you could help with. Of course it does not stop there. You can implement your own ideas or work on the core components like improving file indexing and extraction of information. The team would love new blood and any kind of input is appreciated! Join the Nepomuk mailing list and meet us on irc (freenode - #nepomuk-kde). We have the opportunity to be one step ahead of everybody else this time. Things like tagging files/emails to a particular project could really change how I work. At present I have a whole load of data files that I can often use in different projects simultaneously but I don't want to make copies for each one (they're big files). So they live in on folder under what I consider to be the main project, but that makes working with them in another project inconvenient. It would be great to be able to tag them and then find them easily or have meta-folders containing all the folders/files tagged to a particular project. With Amarok and Digikam I don't need to care where my files actually are in the directory structure, because there are much more intelligent ways of organising them by metadata (artist, genre, date, subjects, locations). Nepomuk, I think, has the potential to bring this kind of useful organisation to other types of files (and much more than that). So I really hope the help comes in let Nepomuk reach its potential. Isn't this something Dolphin should already be a capable of? It has tagging for some time. ... not to mention the recent innovation of symlinking ;) But seriously, this is something I think we could all use. Not least because a resource that is marked as related to a particular project may not be a file at all, but a contact, an email or a remote URL. We discussed this with Sebastian at the Akonadi meeting in Berlin last weekend. Our first thought is to use the tmo:Task class from the Nepomuk project as the definition of a 'project' - since you can decompose any project into tasks and from there into subtasks, conversely, a project is just a scaled up task. Have a look at tmo:Task and see if you think it's missing anything. I did think about saying "I know I could make symlinks to different folders", but I didn't. So of course, you're right :-) Offtopic Equally, I could symlink all my music files in to folders by genre or year. What I meant to get at is that basically I'm lazy and tagging is marginally easier and of course can be more easily preserved if I move inidividual files to another machine. /Offtopic From a very quick look at tmo:task it seems to have the right kind of ideas. I'll have a bit more of a look and try and think more about what I'd really want, ideally. It's so complicated now after a quick scan of Task that one should almost just make the semantic connection between obelisk, project, and elevating tag importance from a user POV. Let alone symlinks. A tag is worth spending the energy to see as a project in itself, differentiated from the historic purpose of an obelisk. We call such differentiation a project. Files are easily elevated as projects that are effectively types of interaction. Tags are the way to get there, monikers that make sense ironically on the ball are hard to push in semantics because some demozen has a right to stand there with a cigarette in his drink and semantics off his tongue. How do we see obelisk(s) (sem.) as opposed to sphynx (sem.) and pyramids (non-sem.)? We avoid such words as a matter for structural linguistics as professionals to show us the way through symlinks to manage our projections a little better on-disk as opposed to on-schedule. tmo:Task looks like it's proving nothing (in this description) from this professional demozen's point of view. As a reference it might prove its worth over time (not quite as old as symlinks) but not now. Here is an idea (that I also suggested to N900 people): Vision: * Provide more humane file handling * Allow a user to locate files not by filesystem location but by tags, type and other metadata. Most important are the tags * Allow applications to locate files/data by tags Sample schenarios: * Visit kde-look and download a wallpaper. Save it wherever you like and tag it as "wallpaper". After that, whenever you visit desktop settings you could be presented with all images in your disk(s) that are tagged as "wallpaper". Perhaps sort them by reverse date or have a view where most recent "appropriately tagged files" are listed and immediately find the last wallpaper. * Download an audio file (e.g. mp3) and tag it as "music". After that amarok can automatically include all files that are tagged as "music" * Download a couple of PDF files: One is tagged as PHD, another as KDE-tech and another as Request-form. Whenever you attempt to open a PDF file (from okular), you can lookup for all "PHD" files. How to do it (as far as I can think of it): * Be persuaded that file tags are essential in file handling. * Introduce the concept of file type. This is required in many places. This does not have to do with "PDF" etc. It may be more convenient to have Document/PDF (a'la. mime-type). * Introduce namespaces for tags. There can be a "System" namespace to serve some system activities, with fixed tags (System:wallpaper, System:KDM_Theme, System:Plasma_Applet, etc...). * Provide a two-way file handling (open/save/etc) dialog: Imagine the well-known "open file" dialog with two tabs: One for "file-based" file handling and one for "tag-based" or "semantic" file handling. Thus we will be able to locate files either the old way or using tags (and other criteria) * Extend core applications/settings to auto-lookup files by tags. E.g. the wallpaper handling. Let me start by pointing you to one of my blog entries: The smart file dialog targets exactly that idea. I agree completely that this is the way to go. We also need a file browser that allows to browse documents this way. Of course the filter system is already nice but not really semantic. We can only express direct key/value pairs, not traverse the information graph that is Nepomuk. And I agree with some of the commentators that the saving dialog should allow to choose the destination in addition to annotations. One thing is important: as far as tags go we need to be on the same page. Tags in Nepomuk are merely simple strings which are used to annotate resources. In this case it would be more interesting to have ontology knowledge, i.e. have a wallpaper type which can be understood by many applications and desktops. I noticed the same question was raised for digikam's metadata. It seems people have developed tag hierarchies as simple inheritance trees, given no other way to structure metadata and query it for entire sub-trees of tags. Some of these will be replaced by existing ontologies that describe the same structures. However, there will be other useful user-created structures that are not trivially replaced by existing ontologies. What will the KDE project do to support these? Will it be possible to define ontologies at runtime in the same way that a .ui file can be loaded to generate a UI? Could these be created semi-automatically from users' tag trees? What about ontology transformations between these ad-hoc ontologies and canonical ones as they are developed? If we only offer a limited set of ontologies, I predict users will begin to project structure onto simple Nepomuk tags using '/' to preserve their investment in tag hierarchies.
https://dot.kde.org/comment/108077
CC-MAIN-2017-34
refinedweb
1,743
62.98
RPC¶ This module allows calling the JSON-RPC endpoints of a geth node. from blockchain.ethereum import rpc ... address = "0x84db76Ea20C2f55F94A87440fBE825fBE5476da1" # setup node address eth = rpc.RPC("ethereum.zerynth.com:8545") # retrieve balance print("Balance:",eth.getBalance(address)) print("Gas Price:",eth.getGasPrice()) nonce = eth.getTransactionCount(address) print("Transaction Count:",nonce) print("Chain:",eth.getChainId()) RPC class¶ - class RPC(host)¶ Initialize a RPC instance with the geth node at host. host must also contain the port and the protocol (i.e.) call(method, params=(), retry=10)¶ Call endpoint method with params params. Return the resultfield of the endpoint json response or None in case of error. Error reason can be retrieved in self.last_error. getBalance(address, block_number="latest")¶ Return the current balance for address address. Previous balances can be retrieved by specifying a different block_number getTransactionCount(address, block_number="latest")¶ Return the current transaction count for address address. The returned value can be used as nonce for the next transaction. Transaction counts at specific points in time can be retrieved by specifying a different block_number. sendTransaction(tx, retry=10)¶ Send the raw transaction to the geth node in order to broadcast it to all nodes in the network. If correct, it will be eventually added to a mined block.
https://docs.zerynth.com/latest/official/lib.blockchain.ethereum/docs/official_lib.blockchain.ethereum_rpc.html
CC-MAIN-2020-24
refinedweb
207
53.17
As I looked over the TechEd session list, I was thinking “Where is the XML?” A few years ago, there would have been DOM, hierarchical XML data, XSLT, and other sessions speaking directly about XML; every timeslot would have had something to satiate the buzz-word crazed masses. Not this year . . . or so I thought. What really has happened is that XML is maturing beyond the buzzwords and being baked into applications and frameworks so that it's behind the scenes, driving the solution even though the user may not know it. The SharePoint talk I attended involved sending messages using xml as the message format. The BizTalk product (which I learned is Microsoft's largest pure c# application at 1.8 million lines of code) routes and receives based extensively on XML; the BizTalk Maps and Schemas are all building on XML. Web Service Enhancements version 2 relies on SOAP (a specific XML standard) for messaging. Even though XML doesn't figure prominently in the session titles and abstracts, XML is certainly present at TechEd in a profound way. That being said, there was one particularly xml-focussed session given by Mark Fussell entitled XML Today and Tomorrow and it was very interesting. He ran down a few main XML features in the .Net Framework today and compared them with what's coming tomorrow in Visual Studio 2005 (aka Whidbey). Mark asked the room: “who is using XPath today?” and the show of hands was only around 10%; apparently, my blog post on XPath back in 2003 hasn't taken the world by storm (or the other XPath proponents out there). Mark affirmed that XPathDocuments have a better DOM API than XMLDocument and are considerably quicker than XMLDocument -- use XPath unless you have a good reason not to. XMLDocument loads the whole xml file into memory and is generally more sophisticated than XMLDocument. This isn't new information. What's new is that XPath will get 20%-40% faster in the next version of the framework because they've rewritten the xslt processor from the ground up. Furthermore, we're getting an XPathEditableNavigator in the next version (v2 hereafter) that lets us modify the xml in memory. XMLDocument isn't going away, but XPath is where Microsoft has invested it's energy. Are you sitting down for this next part? XSLT will be compiled in v2; they'll generate MSIL from the XSLT! This also means a PDB file (a debugging file) can be generated from the code which means . . . you can step through the XSLT file as it processes a document with full VS.Net debugger support (Locals window, etc.). When you process a transformation, you can step into the xslt seamlessly; it's fully integrated into the VS.Net debugger. Mark demonstrated this and I saw it with my own eyes. Where was this during my hellish months with the “Microsoft B2C Reference Architecture based on XML and XSLT for Commerce Server” project so many years ago? I can't find anything official about that Reference Architecture because, I think, the reference has been set to null and marked for garbage collection! It wasn't a bad architecture, just very XSLT intensive at a time when there were no XSLT resources around. Debugging XSLT would have saved the day (and possibly the project). Generally, XML v2 will be faster. XSLT gets 400% faster because it's compiled; XMLTextWriter and XMLTextReader get 100% faster. Performance has been a knock on XML solutions in the past, so this perf gain is great news. “I love perf!“ exclaimed Mark Fussell at one point in his talk. Until version 2 becomes available in Visual Studio 2005, get on the XPath train and start working with your XML faster and easier today; when tomorrow roles around, you'll have an easier time taking advantage of the new stuff. Happy .Netting! Many great things today . . . too much for one blog post . . . San Diego sunny . . . must stay strong . . . TechEd is a marathon and NOT a sprint. This in mind! A few details from yesterday I meant to include but forgot. I said TechEd attendance is 11,000 . . . this is still true, but 3,000 of them are Microsoft staff. “Only“ 8,000 actual attendees. One of the Indiana whiz kids from the coding slave meet up is Erik Porter at. MSDN Search, while broken, has some cool features planned including personalization; think about Search storing your zip code in your profile and sharing links to a local user group on the topic you search for. This could be an interesting development. I have to change my “best free giveaway of the day” to the 750 ml of tequila from MSDN. Seriously. When I blogged last night I neglected to check the MSDN bag from the INETA summit. Hilarious. I'm assuming everyone got the tequila and not just me . . . or maybe that's part of the new MSDN Search personalization initiative . . . This post is dedicated to Darrell Norton who, although couldn't make it to San Diego this week, I know is with me in spirit while I'm at TechEd. I came in yesterday (Saturday), a day early, so I'd be able to make the INETA User Group Summit on Sunday. After waking up at 6 AM and going for a jog (I'm on East Coast time so that's really only like 9 AM), I elected to walk to the INETA conference at the Westin instead of take a shuttle. It seemed like a great idea since San Diego has such nice weather, but since I was cheap on my choice of hotels (I'm paying for the hotel out of my pocket) I ended up staying at the one on the other side of the airport from downtown San Diego. It's like a 5+ mile walk. Great for my metabolism, but terrible for me making the INETA Summit on time. 90 minutes after leaving my hotel I arrived at the Summit -- too late for the free breakfast, but the Summit had yet to begin so I was in the clear. Let's see . . . the Summit was very informative and I see now how INETA gets things done: a few very committed volunteers work their tails off and make the magic happen. That's it! I have a new appreciation for the level of effort involved and I drank the INETA kool-aid (it was free beer, actually) and offered to contribute to the cause, details to follow later. I ran into Julie Lerman (and I didn't call her “J-Ler”, although I was tempted to) and I happened to be sitting next to the regional INETA liaison for my user group WeProgram.net -- Scott Locke -- so it was good to finally meet these people after all this time. I also seemed to always go to the bathroom at the same time as Tim, the Maine Bytes user group guy. He's convinced me being a developer in Maine isn't such a bad idea. I also got to meet some of the California user group folks and the Microsoft Developer Champions -- it's just cool to learn what else is going on with user groups in the country from all these different perspectives. For example, California has 25+ .Net user groups and some can't find a place big enough to meet! If your group has 200+ attendees at each meeting, you need a big facility to support that load. One tactic San Diego's .Net group has taken is to have annual membership at $50/head . . . they've gotten 100 people to sign up so now they've got a $5,000 annual budget. As for more on the content of the Summit, I learned a few good tips for dealing with vendors and the community and how to handle meetings. It sounds like we need to get Infragistics to one of the WeProgram.Net meetings sometime -- they're user group presentations are NOT sales pitches and really informative. Same goes for Altova, which is great because Altova is coming to WeProgram.Net in a few months! One other thing about dealing with vendors: look to build a long term relationship instead of just a one-night stand. Wintellect's Sara Faatz did a nice piece about this vendor relations topic. The folks from MSDN came in and did an informal presentation. They confided that MSDN Search is broken -- and they know it -- and they're working on having a sophisticated search out in 6-9 months from now. Until then, is the easiest and fastest out there! One comment from the INETA peanut gallery: “Why doesn't Microsoft just buy Google?” The MSDN speaker chuckled and moved on to the next point. There were other good points and blog-worthy issues, but I don't feel like digging them out at the moment; I've got to save something for a slow blog day! Suffice it to say that the INETA Summit was a great experience and I'm grateful for the chance to be a part. Maybe we'll get Darrell Norton or Mark DiGiovanni, other fellow WeProgram.Net founders, out to the next one! Tonight was the highly anticipated (by me) Coding Slave meet-up organized by Rory Blyth. There were about a dozen of us that got together to socialize and discuss Coding Slavish things . . . but I don't know that there was much Coding Slavery in the evening. Many of the guys hadn't read the book yet, but author Bob Reselman brought some freebies out for everyone. While I didn't get to talk much with Bob, it was still a really fun time. Rory Blyth is a very entertaining character. I got to ask Carl Franklin, of .Net Rocks fame, about how he couldn't know what Tightie Whities were . . . turns out he just never heard of 'em. Go figure. Also met a couple boy-wonders from Indiana who run an INETA user group there; one of them is like 25 years old and an Microsoft MVP and an author and general whiz kid. Ian White shared his Cobol, .Net, and WS-I stories with me; I'm subscribed to his weblog effective immediately; he's part of some very interesting things. There were may others there, even one token Canadian from Calgary, but I don't recall their names or any specifics; I should've taken notes! I know most of them blog, so I'm hoping to catch up with them and get a business card -- they all seem like likeable, interesting guys. Whew . . . TechEd hasn't even officially started and I'm already feeling a bit beat. Let me conclude with a few quick facts: OK, off to bed. It's about midnight on the West Coast (which makes it . . . 3 AM on the East Coast) and I've got a call with a customer at 7:15 tomorrow morning. Seriously. At least this call isn't about MS Access . . . Ever try to program an R-Squared, Y-Intercept, and Slope calculator via a Linear Regression -- the good old sum of squares and codeviates from math class so many years ago? It sounds like an academic exercise, but this was an actual task I had to tackle for a custom reporting engine we wrote a while back. I had a rough time finding the nuts and bolts of the algorithm -- many online resources point you through Excel functions or a graphing calculator, but that wouldn't cut it for our app. In case there's another poor soul out there looking, let me post the foundation: First, we create a ReportPoint object: public class ReportPoint { private double _dblX ; private double _dblY ; public double X_Coord { get{ return _dblX ; } set{ _dblX = value ; } } public double Y_Coord { get{ return _dblY ; } set{ _dblY = value ; } } public ReportPoint( double X_Coordinate, double Y_Coordinate ) { _dblX = X_Coordinate ; _dblY = Y_Coordinate ; } } Nothing extraordinary there. Here is the good part, assuming you pass in an ArrayList of our ReportPoints above: public static void calcValues( ArrayList alPoints ) { double sumOfX = 0 ; double sumOfY =0 ; double sumOfXSq = 0 ; double sumOfYSq = 0 ; double ssX = 0 ; double ssY = 0 ; double sumCodeviates = 0 ; double sCo = 0 ; for( int ctr = 0; ctr < alPoints.Count; ctr++ ) { ReportPoint objPoint = ( ReportPoint ) alPoints[ ctr ] ; double x = double.Parse( objPoint.X_Coord.ToString() ) ; double y = double.Parse( objPoint.Y_Coord.ToString() ) ; sumCodeviates+= ( x*y ) ; sumOfX += x ; sumOfY += y ; sumOfXSq = sumOfXSq + ( x*x ) ; sumOfYSq = sumOfYSq + ( y*y ) ; } sumOfXSq = Math.Round( sumOfXSq, 2 ) ; sumOfYSq = Math.Round( sumOfYSq, 2 ) ; ssX = sumOfXSq - ( ( sumOfX*sumOfX ) / alPoints.Count ) ; ssY = sumOfYSq - ( ( sumOfY*sumOfY ) / alPoints.Count ) ; double RNumerator = ( alPoints.Count * sumCodeviates ) - (sumOfX * sumOfY ) ; double RDenom = ( alPoints.Count*sumOfXSq - ( Math.Pow( sumOfX, 2 ) ) ) * ( alPoints.Count*sumOfYSq - ( Math.Pow( sumOfY, 2 ) ) ) ; sCo = sumCodeviates - ( ( sumOfX*sumOfY ) / alPoints.Count ) ; double dblSlope = sCo / ssX ; double meanX = sumOfX / alPoints.Count ; double meanY = sumOfY /alPoints.Count ; double dblYintercept = meanY - ( dblSlope * meanX ) ; double dblR = RNumerator / Math.Sqrt( RDenom ) ; double dblSlope = dblSlope ; Console.WriteLine( "R-Squared: {0}", Math.Pow( dblR, 2 ) ) ; Console.WriteLine( "Y-Intercept: {0}", dblYIntercept ) ; Console.WriteLine( "Slope: {0}", dblSlope ) ; Console.ReadLine() ; } Yes, yes, yes, I know a typed collection instead of an ArrayList would be better; I moved this code into a Console program to make an easy to follow demo of the logic and wanted to keep non-essentials to a minimum. Let's say I'm saving myself for Generics! So, in our main method we'd have: [STAThread] static void Main(string[] args) { ArrayList al = new ArrayList() ; al.Add( new ReportPoint( 3, 2.6 ) ) ; al.Add( new ReportPoint( 5.6, 20 ) ) ; al.Add( new ReportPoint( 8.2, 30 ) ) ; al.Add( new ReportPoint( 8.4, 50.7 ) ) ; al.Add( new ReportPoint( 9, 51.4 ) ) ; al.Add( new ReportPoint( 10, 37.9 ) ) ; calcValues( al ) ; } There you have it. You really need to watch your order of operations. Do)! enough! If you're like me and often installing software to your computer, it can be a pain to burn ISO files (like the one you get from MSDN Subscriber downloads). Daemon-Tools to the rescue. It lets you create virtual drives and mount ISO files directly (no burning or Roxio-hell required!). Here's how it helped me: I downloaded an enormous ISO file from MSDN, fired up Virtual Daemon Manager to mount the ISO file without having to create a CD first. The Virtual CD-Rom drive read the ISO file fine and launched the installation. I thought I was in the clear until, in the process of the installation, the setup package prompted for me to swap out my CD and put another CD in the drive (apparently there were some file from a related MSFT product required for this install). My initial reaction was . . . crap . . . but the Daemon-Tool manager lets me mount up to 4 virtual drives at once, so I just mounted another drive to the other ISO file and I was in the clear. For those of you with functional CD burners (and functional burning software), this will still save you some hassle! Thanks to lil' Tim from Optimize for sharing this with me! I'm sure there's other interesting facets to Dameon-Tools, so check it out. The (at). I! With time! We .Netting! Building on my recent certification post, let me offer a few other sources for certification commentary. Is Certification a Tax We Developers Must Pay? Martin “UML and XP Expert” Fowler discusses Agile Certification and comments that “certification has little correlation to competence.” Although I have the developer certs from Microsoft (and even one from Sun Microsystems!), I have to agree with Martin. Just because you have the certification, doesn't make you a strong software developer. In the current climate, employers and particularly recruiters look for buzzwords and acronyms to fill a job -- certifications are an easy benchmark for employers to rely on. I have a friend who got a position with a big IT company and they never did any form of technical interview, mostly because those who made the hiring decisions were in Human Resources and wouldn't know WSDL from WD-40. Having those certifications on the resume make you more attractive to employers, even if all you did was memorize a Transcender exam prep CD. I do the cert exams because it's an insurance policy that I won't get passed over by the less experienced developer who memorized some exam questions; it's like a Software Developer Cert Tax that I'm obliged to pay. Besides that, I do like the intellectual challenge of puzzling out the answers to the questions. Call me compulsively analytical (as my wife is prone to do sometimes). It's unfortunate and I hope companies look beyond the Certs to see if there is real substance to the candidate. There are other ways to certify, last I knew Java's premium developer certification required submitting functioning applications and source code for review . . . I'm sure it's a pain to grade an exam like this, but just multiple choice questions (or multiple guess, for some people!) can't continue to cut it. As Martin Fowler points out in his post, however, certification has become an industry to itself and has a vested interest in maintaining the status quo. Cert Exam Hell Narrowly Diverted Joseph Cooney shares a bad planning for a cert exam experience story. It has a happy ending, though, and Joseph continues batting 1000 in cert exams. For what it's worth, the only cert exam I didn't pass was the old analyzing requirements for VB 6.0 -- I failed by 1 point. Something like 740 was needed to pass, and my score came up 739. This was five years ago, now, and I was still relatively new to the industry . . . but I'm proud to say I took the same exam two days later and passed it with room to spare. Darrell Norton Has A Nerd Crush on UML Let's not forget that Microsoft isn't the only Certifier out there. Darrell Norton took the UML Certification exam from IBM earlier this year and lived to tell about it. This is also a way for me to get Darrell back for outting me about my Nerd Crush on Johnnie “Flash“ Robbins. Let's see . . . where was I? I want to take this exam because 1) I think it'd be cool to validate my understanding of UML and 2) I think it's a key way to distinguish yourself in the eyes of customers/employers (see Is Certification a Tax We Developers Must Pay? above) -- UML isn't the sort of thing you cram for the night before (at least I hope not). I
http://codebetter.com/blogs/grant.killian/archive/2004/05.aspx
crawl-001
refinedweb
3,125
63.9
netlink, PF_NETLINK - Communication between kernel and user. #include <asm/types.h> #include <sys/socket.h> #include <linux/netlink.h> netlink_socket = socket(PF_NETLINK, socket_type, netlink_family); (cur- rently not implemented). NETLINK_TAPBASE...NETLINK_TAPBASE+15 are the instances of the ethertap device. Ethertap is a pseudo network tunnel device that allows an ethernet driver to be simu- lated from user space. NETLINK_SKIP Reserved for ENskip. NETLINK_USERSOCK is reserved for future user space protocols. Netlink messages consist of a byte stream with one or multiple nlmsghdr NLM_F_ACK flag. An acknowledgment is an NLMSG_ERROR packet with the error field set to 0. The application must generate multi- cast specifies more message types, see the appro- priate man pages for that, e.g. rtnetlink. NLM_F_DUMP not documented yet. process owning the destination socket, or 0 if the destination is in the kernel. nl_groups is a bitmask with every bit representing a netlink group number. This man page is not complete. It is often better to use netlink via libnetlink than via the low level kernel interface. The socket interface to netlink is a new feature of Linux 2.2 Linux 2.0 supported a more primitive device based netlink interface (which is still available as a compatibility option). This obsolete interface is not described here. cmsg(3), rtnetlink(7), netlink(3)* for libnetlink Linux Man Page 1999-04-27 netlink(7)
http://mirrors.ircam.fr/pub/planetccrma/man/man7/netlink.7.html
CC-MAIN-2016-50
refinedweb
224
53.07
GNU Makefile Documentation Table section Complex Makefile Example.' (see section. See section Writing Rules. A makefile may contain other text besides rules, but a simple makefile need only contain rules. Rules may look somewhat more complicated than shown in this template, but all fit the pattern more or less.main.o : main.c defs.h cc -c main.ck. See Arguments to Specify the section)' (see section How to Use Variables). Here is how the complete simple makefile looks when you use a variable for the object files: objects = main.o kbd.o command.o display.o \ insert.o search.o files.o utils.oedit : $ $(objects). See section Using.edit : $ : cleanclean : -rm edit $(objects) This prevents make from getting confused by an actual file called `clean' and causes it to continue in spite of errors from rm. (See section Phony Targets, and section Errors in Commands.)'. See section How to Run make. Writing Makefiles The information that tells make how to recompile a system comes from reading a data base called the makefile..). - `#'end Syntax In general, a rule looks like this: targets : prerequisites command ... or like this: targets : prerequisites ; prerequisites, section Using make to Update Archive Files) (see section Writing the Commands in Rules). happens automatically in targets, in prerequisites,) See section The Function wildcard. = *.ofoo : $.; see section Defining and Redef foovpath % blishvpath %.c bar will look for a file ending in `.c' in `foo', then `blish', then `bar', while vpath %.c foo:barvpath % blish will look for a file ending in `.c' in `foo', then `bar', then `bl: -. - `$^' (see section prerequisites include header files as well, which you do not want to mention in the commands. The automatic variable `$<' is just the first prerequisite: VPATH = src:../headersfoo.o : foo.c defs.h hack.h cc -c $(CFLAGS) $< -o $@ Directory Search and Implicit Rules of the parallel build capabilities of make using this method, (see section prerequisites. - (see section Automatic Variables). For example: bigoutput littleoutput : text.g generate text.g -$(subst output,,$@) > $@. See section Static Pattern Rules. prerequisites can be used to give a few extra prerequisites (see section Overriding Variables). see section Using Implicit Rules).. Syntax of Static Pattern Rules prerequisites of each target. Each target is matched against the target-pattern to extract a part of the target name, called the stem. This stem is substituted into each of the dep-patterns to make the prerequisite. See section Using Implicit Rules. (see; $(CC) -M $(CPPFLAGS) $< \ | sed 's/\($*\)\.o[ :]*/\1.o $@ : /g' > $@; \ [ -s $@ ] || rm prerequisites prerequisite makefiles, `foo.d bar.d'. See section Substitution References, for full information on substitution references.) Since the `.d' files are makefiles like any others, make will remake them as necessary with no further work from you. See section How Makefiles Are Remade. Writing the Commands in Rules The commands of a rule consist of shell command lines to be executed one by one. Each command line must start with a tab, except that the first command line may be attached to the target-and-prerequisites (see section Special Built-in Target Names). .SILENT is essentially obsolete since `@' is more flexible. Command Execution. (2: - In the precise place pointed to by the value of SHELL. For example, if the makefile specifies `SHELL = /bin/sh', make will look in the directory `/bin' on the current drive. - In the current directory. - says `SHELL = /bin/sh' (as many Unix makefiles do), will work on MS-DOS unaltered if you have e.g. `sh.exe' installed in some directory along your PATH.; this will override the value of SHELL. section Communicating Options to a Sub-make.. `accyand see section Defining Last-Resort Default Rules)..oprogram : $(objects) cc -o program $(objects)$(objects) : defs.h Variable references work by strict textual substitution. Thus, the rule foo = cproginclude := fooy := $(x) barx := later is equivalent to y := foo barx := (see..obar := $.obar := $(foo:%.o=%.c) sets `bar' to `a.c b.c cy =.). If you'd like a variable to be set to a value only if it's not already set, then you can use the shorthand operator `?=' instead of `='. These two settings of the variable `FOO' are identical (see section The origin Function): FOO ?= bar and ifeq ($(origin FOO), undefined)FOO = barend.gn section Functions for String Substitution and Analysis) to avoid interpreting whitespace as a non-empty value. For example: ifeq ($(strip $(foo)),)text-if-emptyendif (see section Conditional Parts of Makefiles). Thus, the following may fail to have the desired results: .PHONY: allifneq "$(needs_made)" ""all: $(needs_made)else all:;@echo 'Nothing to make!'endifReplacing. See section Conditionals that Test The override Directive). and e start from 1.. - $(wildcard pattern) - The argument pattern is a file name pattern, typically containing wildcard characters (as in shell file name patterns). The result of wildcard is a space-separated list of the names of existing files that match the pattern. See section Using Wildcard Characters in File Names.files := $. The if Function The if function provides support for conditional expansion in a functional context (as opposed to the GNU make makefile conditionals such as ifeq (see section. "$ Functions for String Substitution and Analysis. The shell Function The shell function is unlike any other function except the wildcard function (see sectionwill generate a fatal error during the read of the makefile if the make variable ERROR1 is defined. Or, ERR = $(error found an error!).PHONY: errerr: ; $. See section Instead of Executing the Commands. (see section Writing Makefiles). specify a different goal or goals with section Generating Prerequisites Automatically), so make won't create them only to immediately remove them again: sources = foo.c bar.cif (see section Standard Targets for Users,}' (See section How the MAKE Variable Works.) (see section Summary of Options)." (see section Summary of Options). section' (see section The override Directive). (see section Summary of Options).. Summary (see section Recursive Use.' section Instead of Executing the Commands. - `--warn-undefined-variables' - Issue a warning message whenever make sees a reference to an undefined variable. This can be helpful when you are trying to debug makefiles which use variables in complex ways.. - Compiling C programs - `n.o' is made automatically from `n.c' with a command of the form `$(CC) -c $(CPPFLAGS) $(CFLAGS)'. - Compiling C++ programs - `n.o' is made automatically from `n.cc' by running Lex. The actual command is `$(LEX) $(LFLAGS)'. - Lex for Ratfor programs - `n.r' is made automatically from `n.l' (see section Match-Anything Pattern (see section Prerequisites). $@'. Variables Used by Implicit Rules The commands in built-in implicit rules make liberal use of certain predefined variables. You can alter - Archive-maintaining program; default `ar'. - AS - Program for doing assembly; default `as'. - CC - Program for compiling C programs; default `cc'. -'. -. - PFLAGS - Extra flags to give to the Pascal compiler. - RFLAGS - Extra flags to give to the Fortran compiler for Ratfor programs. - YFLAGS - Extra flags to give to Yacc.. Defining and Redefining Pattern prerequisites. (see section Introduction to Pattern Rules), `$@' is the name of whichever target caused the rule's commands to be run. - $% - The target member name, when the target is an archive member. See section Using make to Update Archive Files. (see section Using Implicit Rules). - $? - (see section. (See section Archive Members as Targets.) - `$( `$<'.: . Old.atibilities and Missing Features The make programs in various other systems support a few features that are not implemented in GNU make. The POSIX.2 standard (IEEE Standard 1003.2-1992) which specifies make does not require any of these features. - A target of the form `file((entry))' stands for a member of archive file file. The member is chosen, not by name, but by being an object file which defines the linker symbol entry. This feature was not put into GNU make because of the nonmodularity of putting knowledge into make of the internal format of archive file symbol tables. See section Updating Archive Symbol Directories. - Suffixes (used in suffix rules) that end with the character `~' have a special meaning to System V make; they refer to the SCCS file that corresponds to the file one would get without the `~'. For example, the suffix rule `.c~.o' would make the file `n.o' from the SCCS file `s.n.c'. For complete coverage, a whole series of such suffix rules is required., the automatic variable $* appearing in the prerequisites of a rule has the amazingly strange "feature" of expanding to the full name of the target of that rule. We cannot imagine what went on in the minds of Unix make developers to do this; it is utterly inconsistent with the normal definition of $*. - In some Unix makes, implicit rule search (see section Using Implicit Rules) is apparently done for all targets, not just those without commands. This means you can do: foo.o: cc -c foo.cand Unix make will intuit that `foo.o' depends on `foo.c'. We feel that such usage is broken. The prerequisite properties of make are well-defined (for GNU make, at least), and doing such a thing simply does not fit the model. - GNU make does not include any built-in implicit rules for compiling or preprocessing EFL programs. If we hear of anyone who is using EFL, we will gladly add them. - It appears that in SVR4 make, a suffix rule can be specified with no commands, and it is treated as if it had empty commands (see section Using Empty Commands). For example: .c.a:will override the built-in `.c.a' suffix rule. We feel that it is cleaner for a rule without commands to always simply add to the prerequisite list for the target. The above example can be easily rewritten to get the desired behavior in GNU make: .c.a: ; - Some versions of make invoke.make = -gALL.infofoo.info: foo.texi chap1.texi chap2.texi $(MAKEINFO) $(srcdir)/foo.texiYou' in GNU Coding Standards. - ).
http://ocw.mit.edu/courses/civil-and-environmental-engineering/1-124j-foundations-of-software-engineering-fall-2000/lecture-notes/gnu_makefile_documentation/
crawl-003
refinedweb
1,635
60.01
eclipse svn - Subversion . Is it possible to do it with eclipse? Please help me... Thanks in advance...eclipse svn Hi I m using svn along with eclipse. I have so many commits in a branch named test. Suppose it have versions 101,102,103,104 ...200 Bad URL for SVN Eclipse plugin Bad URL for SVN Eclipse plugin I am trying to install the SVN Eclipse plugin On this page: both URLs are invalid Unable to find Software Updates in Help menu in MyEclipse to my eclipse. Can anyone please help me. Thanks, Suriya Hi Suriya, Please visit the following link: Thanks Subversion Eclipse Plugin Subversion Eclipse Plugin If you are using Subversion as source control tool and looking for good Subversion plugin for Eclipse IDE then you search ends... Eclipse Plugin in your Eclipse IDE. Learn the tutoial Subversion Eclipse Subversion Eclipse Plugin Subversion Eclipse Plugin This tutorial shows you how to install Subversion Eclipse Plugin on Eclipse IDE. Eclipse provides in-built plugin for CVS... Subversion as version controlling tool. Eclipse does not provide any in-built tool Unable to install Subversion plugins in MyEclipse Unable to install Subversion plugins in MyEclipse Thanks for your reply Deepak. I am using MyEclipse Blue Edition 8.6 M1. I tried adding Subversion.... Thanks, Suriya eclipse eclipse Hi how to debug in eclipse ide and how to find bug in eclipse ? Thanks kalins naik Thanks Thanks This is my code.Also I need code for adding the information on the grid and the details must be inserted in the database. Thanks in advance Subversion Subversion - Subversion Tutorials Subversion... subversion in detail. Subversion is source control server, it manages... can easily get the older version of the code from the Subversion repository Svn - Subversion which is better - Subversion which is better Dear sir, Could u pls tell which version control is better among the following four. Subversion, git, bazaar, Mercurial maven subversion issue maven subversion issue m doing work on maven and subversion i have created a maven project now i want to point it to my repository(created by svn...+in+Subversion but by following this site when i have added scm and tag base like scm:svn maven subversion issue maven subversion issue m doing work on maven and subversion i have... tortoise.so i want to take advantages of maven with maintaining subversion...://wiki.gxdeveloperweb.com/confluence/display/...ntrol+Management+in+Subversion SVN checkout in eclipse - Development process SVN checkout in eclipse How can i convert a checkout project from svn to java project using eclipse ide. since i should be able to run the junit.../library/os-ecl-subversion Subversive projection of Eclipse refactoring operations into Subversion Support...; The Subversive project is a brand new Eclipse plug-in that provides Subversion support. From a user point of view, Subversive provides Subversion to configure the tomcat and hibernate in eclipse?. Thanks, Anusha...Eclipse configuration Hi, I installed Eclipse and Tomcat 6.0. I configured the tomcat in the eclipse. When I execute simple JSP example it use Eclipse - IDE Questions Eclipse Hello Sir, I want to configure the eclipse IDE to perform...... Hi friend, For read more information on Eclipse IDE visit to : Thanks Emulator for j2me in eclipse for installing emulator so I can run it in Eclipse as well. Thanks in Advance...Emulator for j2me in eclipse I want to run my J2ME Application in Eclipse. Its made in Netbeans IDE but want to run in Eclipse. For that I installed crystal report plugin for eclipse crystal report plugin for eclipse Hi, I want to know whether unicode based crystal reports can be generated using jsp.?Also I need the crystal report plugin for eclipse . Thanks hibernate and struts integration in ECLIPSE and struts integration in ECLIPSE and not using ANT Can any One pls Help.. Thanks... Hibernate Integeration Thanks The given link isn't the right one I need without implementing with ANT... and in ECLIPSE Subversion Tutorials how to add plugins into eclipse how to add plugins into eclipse Hello, I have installed eclipse sdk... for that i don't have server option in my eclipse and i m trying to add plugins but m.... Thanks in advance object creation - Subversion Quartz Job Scheduler - Subversion software engineering - Subversion Eclipse Connectivity - JDBC Eclipse Connectivity Hello Friends.. I want to do connectivity with eclipse 3.4 Genemade with mysql Database. can u please help me to how to do.... Thanks in advance. Hi Friend, As you have described Eclipse Eclipse I am new to eclipse. i want to create a login page in eclipse and want to connect with mysql. what are the software and jar file i need to include in eclipse Eclipse Eclipse how to compile using Error In starting Glassfish in Eclipse. Error In starting Glassfish in Eclipse. Sir,I am new... in eclipse when i use Glassfish as server.I have installed Glassfish in C:\Glassfish Directory.Then install plugin for glassfish in my eclipse Indigo ide.Set eclipse eclipse how to add tomcat server first time in eclipse Eclipse Eclipse I am new to eclipse. I want to write a jsp program and want to connect it with mysql. What are the configurations i need to check in eclipse java,eclipse - Swing AWT java,eclipse Hi, I have made on program SimpleCalculator on eclipse 3.4.0.But while running the code I am getting the problem for Class File Editor... } Thanks in advance for early resolve. Thanks Deep Eclipse Eclipse How to develope web application servlets or jsp using eclipse id Lombaz configaration with eclipse - IDE Questions Lombaz configaration with eclipse how to configure lombaz plugin into eclipse. please send the steps to configure. Thanks Thirumalesh Linux GUI client for Subversion Subversion Client Linux  ... the Subversion clients available for the Linux machine. Subversion is one of the best open source source control servers available to the programmers. Subversion thanks - JSP-Servlet thanks thanks sir i am getting an output...Once again thanks for help thanks - JSP-Servlet thanks thanks sir its working Eclipse - Java Beginners Eclipse I having problems getting my program to run in Eclipse 3.2. Could I get some assistance perferabley by tomorrow morning. Thank You... with OfficeArea.java or not? Thanks Hibernate tutorial for beginners in Eclipse IDE Hibernate 4 Example with Eclipse First Hibernate Application Thanks...Hibernate tutorial for beginners in Eclipse IDE Hi, I am beginner in Hibernate and I want to learn Hibernate using Eclipse tool. I am aware Thanks - Java Beginners Thanks Hi, Thanks for reply I m solve this problem Hi ragini, Thanks for visiting roseindia.net site SWT in Eclipse - Java Beginners SWT in Eclipse hi.. how to call a function in SWT when the shell is about to close... ?? thanks in advance Creating SDO and SCA Application in eclipse eclipse Thanks in advance Regards Dinesh...Creating SDO and SCA Application in eclipse Hello Can u plz suggest me some step by step tutorials to create SDO and SDA applications in eclipse Eclipse instalation error - IDE Questions Eclipse instalation error hi, I have down loaded latest eclipse (eclipse-jee-galileo-SR2-win32.zip). while double clicking on eclipse.exe its... in environmental variable need to set please guide me thanks in advance; Hi Friend how to execute jsp and servlets with eclipse to create a web application in eclipse. Thanks... how to execute jsp or servlets with the help of eclipse with some small program.../java/javaee6/eclipseAndTomcat7Download.shtml Through this link you can read about downloading of eclipse Eclipse - Java Beginners [ ] E2[ ] E3[X] E4[X] E5[X] E6[X] Choose your seat:_ Thanks in advance ...;i Hi, thanks for helping me in the code but I got some seats Eclipse helios "Build Before Launch" Eclipse helios "Build Before Launch" Hi The IDE Eclipse Helios... look into this issue . i have tried these settings for Eclipse Helios... facing the problem please provide me the answer how to resolve it Thanks & Eclipse helios "Build Before Launch" Eclipse helios "Build Before Launch" Hi The IDE Eclipse Helios... into this issue . i have tried these settings for Eclipse Helios Disable... the problem please provide me the answer how to resolve it Thanks & Regards chakry My Eclipse deployed problem. - Struts My Eclipse deployed problem. Dear All, I am facing a problem. When First time I am deploying a web project in eclipse in jboss its fine... it again, it is taking the previous projectname.war , please help me. Thanks Error Message in Eclipse - Development process in servlet file is not reflected.Am using Eclipse ide and weblogic server. I think save option is not working in Eclipse. Am getting error message while saving. Now save... , " metadata error . thanks prakash Eclipse Plunging/Team Development project is a brand new Eclipse plug-in that provides Subversion support. From... Eclipse Plunging/Team Development MKS SCM for Eclipse MKS has what is the difference between the eclipse and myeclipse - IDE Questions with Eclipse IDE Thanks...what is the difference between the eclipse and myeclipse what is the difference between the eclipse and myeclipse Hi Friend hibernate configuration with eclipse 3.1 - Hibernate in eclipse. so facing more problem and need ur help. Thanks...hibernate configuration with eclipse 3.1 Dear Sir, i got your mail and found the link. i have already found that link. When i m deploying our Eclipse juno failed to load the jni shared library is the solution? Thanks Hi, To run the 64BIT of Eclipse juno you...Eclipse juno failed to load the jni shared library Hi, I have downloaded the 64 BIT version of Eclipse juno "eclipse-jee-juno-SR2-win32-x86_64.zip download eclipse helios for windows 7 64 bit download eclipse helios for windows 7 64 bit How to download eclipse helios for windows 7 64 bit? Thanks Eclipse jsf deseign palette - JSP-Servlet Eclipse jsf deseign palette i'm beginner in jsf i want to find an eclipse plug in that help me to design my site (jsf tags) ,thanks Hibernate Simple Program Using Java Application with Eclipse to write Hibernate Simple Program Using Java Application with Eclipse? I wish to learn Hibernate using very popular Eclipse IDE. Share me the best tutorial link Thanks Hi, Best link for learning Hibernate using Eclipse IDE What Is Subversion? What Is Subversion? Subversion is an advanced, open source version control... of files under version control. Simply it can be said that Subversion is a free... of your data including history and changed data. Subversion became self-hosting Convert Maven project to Eclipse Web Project management and Eclipse for development of application. Thanks to the Eclipse...Step by Step process of converting a maven web project into Eclipse Web Project and then testing in Eclipse. This tutorial teaches you to convert Configure apache Tomcat to work with Eclipse and PDT in php to implement PHP code in Eclipse, hope can learn more from you all. Thanks...Configure apache Tomcat to work with Eclipse and PDT in php I had... and install PDT to my Eclipse (Indigo) and write my php code in Eclipse. I had try to run regarding css file in my eclipse this....... thanks in advance Please help need quick!!! Thanks (); ^ 6 errors any help would be appreciated guys. Thanks so first entity bean example in eclipse europa - EJB first entity bean example in eclipse europa pls provide steps to create simple ejb3.0 application in eclipse .And also how to create entity bean... for you. Thanks using medini QVT in eclipse - Java Beginners using medini QVT in eclipse hello, I wish use medini QVT as plugin in eclipse for my application. Can someone help me to find these import that I....? if someone has used it thanks to help me Tomcat Server configuration with Eclipse at remote machine Tomcat Server configuration with Eclipse at remote machine "Several... instances. What is the solution to run same web application in Eclipse by two or more than two users having same remote IP address. Please Help Thanks In Advance Eclipse Plunging/Tool Eclipse Plunging/Tool  ... is a product that assists developers, who use Eclipse-based IDEs, in delivering... Machine Gear Eclipse Plug-in The Discovery Machine Eclipse Gear Plugin Answer me ASAP, Thanks, very important Answer me ASAP, Thanks, very important Sir, how to fix this problem in mysql i have an error of "Too many connections" message from Mysql server,, ASAP please...Thanks in Advance Maven Integration for Eclipse requires 'bundle org.eclipse.core.runtime 3.7.0' but it could not be found this issue? Thanks Hi, You should use the latest version of Eclipse Luna. Thanks Hello, Check the latest Eclipse tutorials at Thanks EasyEclipse for PHP as Subclipse providing connectivity to Subversion. There are currently 29 comments... This distribution includes the following plugins: Core components: Eclipse Platform - Shared platform services from Eclipse - Getting started Eclipse Plugin-Language Eclipse Plugin-Language  ...) development using AdaCores market leading GNAT Pro toolset on the Eclipse platform.... EasyEclipse for PHP Easy Eclipse for PHP is an Eclipse Project of a web application that performs login logout with eclipse / tomcat Project of a web application that performs login logout with eclipse / tomcat Building a web application that is able to handle the log-in and log... that it will be helpful for you. Thanks deployment in eclipse deployment in eclipse How to run the web project in eclipse in resin server without using GUI hard deployment Eclipse (Problem with combining 2 codes together) - Java Beginners Eclipse (Problem with combining 2 codes together) hi, I have 2...("Movie ID: 9 Title: The Twilight Saga: Eclipse Time: 5pm"); System.out.println("Movie ID: 10 Title: The Twilight Saga: Eclipse Time: 7pm"); System.out.println (Problem with combining 2 codes together)(Cont) - Java Beginners Eclipse (Problem with combining 2 codes together)(Cont) Hi, I have... to receive help ASAP. Thanks in advance :) import java.util.Scanner; public...: The Twilight Saga: Eclipse Time: 5pm Cost: $8.50"); System.out.println Advertisements If you enjoyed this post then why not add us on Google+? Add us to your Circles
http://www.roseindia.net/tutorialhelp/comment/94394
CC-MAIN-2015-48
refinedweb
2,351
65.42
Yes, this has been a busy few days for blog posts. One of the comments on my previous blog post suggested there may be some confusion over how the control flow works with async. It’s always very possible that I’m the one who’s confused, so I thought I’d investigate. This time I’m not even pretending to come up with a realistic example. As with my previous code, I’m avoiding creating a .NET Task myself, and sticking with my own custom "awaiter" classes. Again, the aim is to give more insight into what the C# compiler is doing for us. I figure other blogs are likely to concentrate on useful patterns and samples – I’m generally better at explaining what’s going on under the hood from a language point of view. That’s easier to achieve when almost everything is laid out in the open, instead of using the built-in Task-related classes. That’s not to say that Task doesn’t make an appearance at all, however – because the compiler generates one for us. Note in the code below how the return type of DemonstrateControlFlow is Task<int>, whereas the return value is only an int. The compiler uses Task<T> to wrap up the asynchronous operation. As I mentioned before, that’s the one thing the compiler does which actually requires knowledge of the framework. The aim of the code is purely to demonstrate how control flows. I have a single async method which executes 4 other "possibly asynchronous" operations: - The first operation completes synchronously - The second operation completes asynchronously, starting a new thread - The third operation completes synchronously - The fourth operation completes asynchronously - The result is then "returned" At various points in the code I log where we’ve got to and on what thread. In order to execute a "possibly asynchronous" operation, I’m simply calling a method and passing in a string. If the string is null, the operation completes syncrhonously. If the string is non-null, it’s used as the name of a new thread. The BeginAwait method creates the new thread, and returns true to indicate that the operation is completing asynchronously. The new thread waits half a second (to make things clearer) and then executes the continuation passed to BeginAwait. If you remember, that continuation represents "the rest of the method" – the work to do after the asynchronous operation has completed. Without further ado, here’s the complete code. As is almost always the case with my samples, it’s a console app: using System.Threading; using System.Threading.Tasks; public class ControlFlow { static void Main() { Thread.CurrentThread.Name = "Main"; Task<int> task = DemonstrateControlFlow(); LogThread("Main thread after calling DemonstrateControlFlow"); // Waits for task to complete, then retrieves the result int result = task.Result; LogThread("Final result: " + result); } static void LogThread(string message) { Console.WriteLine("Thread: {0} Message: {1}", Thread.CurrentThread.Name, message); } static async Task<int> DemonstrateControlFlow() { LogThread("Start of method"); // Returns synchronously (still on main thread) int x = await MaybeReturnAsync(null); LogThread("After first await (synchronous)"); // Returns asynchronously (return task to caller, new // thread is started by BeginAwait, and continuation // runs on that new thread). x += await MaybeReturnAsync("T1"); LogThread("After second await (asynchronous)"); // Returns synchronously – so we’re still running on // the first extra thread x += await MaybeReturnAsync(null); LogThread("After third await (synchronous)"); // Returns asynchronously – starts up another new // thread, leaving the first extra thread to terminate, // and executing the continuation on the second extra thread. x += await MaybeReturnAsync("T2"); LogThread("After fourth await (asynchronous)"); // Sets the result of the task which was returned ages ago; // when this occurs, the main thread return 5; } /// <summary> /// Returns a ResultFetcher which can have GetAwaiter called on it. /// If threadName is null, the awaiter will complete synchronously /// with a return value of 1. If threadName is not null, the /// awaiter will complete asynchronously, starting a new thread /// with the given thread name for the continuation. When EndAwait /// is called on such an asynchronous waiter, the result will be 2. /// </summary> static ResultFetcher<int> MaybeReturnAsync(string threadName) { return new ResultFetcher<int>(threadName, threadName == null ? 1 : 2); } } /// <summary> /// Class returned by MaybeReturnAsync; only exists so that the compiler /// can include a call to GetAwaiter, which returns an Awaiter[T]. /// </summary> class ResultFetcher<T> { private readonly string threadName; private readonly T result; internal ResultFetcher(string threadName, T result) { this.threadName = threadName; this.result = result; } internal Awaiter<T> GetAwaiter() { return new Awaiter<T>(threadName, result); } } /// <summary> /// Awaiter which actually starts a new thread (or not, depending on its /// constructor arguments) and supplies the result in EndAwait. /// </summary> class Awaiter<T> { private readonly string threadName; private readonly T result; internal Awaiter(string threadName, T result) { this.threadName = threadName; this.result = result; } internal bool BeginAwait(Action continuation) { // If we haven’t been given the name of a new thread, just complete // synchronously. if (threadName == null) { return false; } // Start a new thread which waits for half a second before executing // the supplied continuation. Thread thread = new Thread(() => { Thread.Sleep(500); continuation(); }); thread.Name = threadName; thread.Start(); return true; } /// <summary> /// This is called by the async method to retrieve the result of the operation, /// whether or not it actually completed synchronously. /// </summary> internal T EndAwait() { return result; } } And here’s the result: Thread: Main Message: After first await (synchronous) Thread: Main Message: Main thread after calling DemonstrateControlFlow Thread: T1 Message: After second await (asynchronous) Thread: T1 Message: After third await (synchronous) Thread: T2 Message: After fourth await (asynchronous) Thread: Main Message: Final result: 5 A few things to note: - I’ve used two separate classes for the asynchronous operation: the one returned by the MaybeReturnAsyncmethod ( ResultFetcher<T>), and the Awaiter<T>class returned by ResultFetcher<T>.GetAwaiter(). In the previous blog post I used the same class for both aspects, and GetAwaiter()returned this. It’s not entirely clear to me under what situations a separate awaiter class is desirable. It feels like it should mirror the IEnumerable<T>/ IEnumerator<T>reasoning for iterators, but I haven’t thought through the details of that just yet. - If a "possibly asynchronous" operation actually completes synchronously, it’s almost as if we didn’t use "await" at all. Note how the "After first await" is logged on the Main thread, and "After third await" is executed on T1 (the same thread as the "After second await" message). I believe there could be some interesting differences if BeginAwaitthrows an exception, but I’ll investigate that in another post. - When the first "properly asynchronous" operation executes, that’s when control is returned to the main thread. It doesn’t have the result yet of course, but it has a task which it can use to find out the result when it’s ready – as well as checking the status and so on. - The compiler hasn’t created any threads for us – the only extra threads were created explicitly when we began an asynchronous operation. One possible difference between this code and a real implementation is that MaybeReturnAsyncdoesn’t actually start the operation itself at all. It creates something which is able to start the operation, but waits until the BeginAwaitcall before it starts the thread. This made our example easier to write, because it meant we could wait until we knew what the continuation would be before we started the thread. - The return statement in our async method basically sets the result in the task. At that point in this particular example, our main thread is blocking, waiting for the result – so it becomes unblocked as soon as the task has completed. If you’ve been following along with Eric, Anders and Mads, I suspect that none of this is a surprise to you, other than possibly the details of the methods called by the compiler (which are described clearly in the specification). I believe it’s worth working through a simple-but-useless example like this just to convince you that you know what’s going on. If the above isn’t clear – either in terms of what’s going on or why, I’d be happy to draw out a diagram with what’s happening on each thread. As I’m rubbish at drawing, I’ll only do that when someone asks for it. Next topic: well, what would you like it to be? I know I’ll want to investigate exception handling a bit soon, but if there’s anything else you think I should tackle first, let me know in the comments. 20 thoughts on “C# 5 async: investigating control flow” Are you doing this from your laptop with a half-installed CTP? That would be a different explanation for why you’re avoiding the .net Task type :) @configurator: No, this is on my “bigger” laptop which has the full CTP installed. Still writing it all in a text editor rather than Visual Studio though :) I’d really like to see when an Exception is thrown with void-returning async methods. Given an example like this (assume WaitHalfASecAsync is something like your example in this post): async void Exceptional() { await WaitHalfASecASync(); throw new Exception(“Boom!”); } public static void Main(string[] args) { Console.WriteLine(“Calling exceptional”); Exceptional(); Console.WriteLine(“Waiting for it to fail”); Thread.Sleep(1000); Console.WriteLine(“This shouldn’t happen!”); } Note that in my example I’m explicitly *not* awaiting the result of Exceptional(). If it’s, for example, a logger that sends an email, I never want to wait for the email to be sent. If it’s an archive function, I may never need to wait for the archive to finish (assuming this is done in a UI-less fashion so no feedback is needed). @configurator: I’ve just investigated this. Because Exceptional() returns void, the exception will be thrown in the new thread (and the CLR will terminate, IIRC). If you returned Task instead, the exception would be ignored. But yes, I’m happy to go into exception handling in the next post if you like. Heck, that can probably be tomorrow… although if anyone wants me to just shut up for a while, I’d be happy to comply with that too :) The term bigger laptop makes me think of the ThinkPad W701 4323. I’m thinking of buying one, if, you know, I win £5,357.59 in the lottery or something :) I also started investigating control flow with “await”, but in the context of interleaving method execution on the same thread: The subject of exception handling is interesting to me, particularly with regard to unhandled exceptions. (TPL’s default behaviour for unobserved exceptions is (unquestionably, in my view) the right thing to do, but wreaks havoc with post-mortem debugging.) I really shouldn’t have included the “_never_” in yesterday’s comment, as it isn’t literally true. I. My assertion remains that keyword naming should be based on programmer intention, not the implementation. (And hence calling the keyword “return ” would be very bad.) I’d be curious to know what (if any) special behavior there is for continuing execution on a UI thread. For example, depending on how MaybeAsync runs (sync/async), and whether the framework uses the current synchronization context to marshal the continuation, the following code may not run consistently: TextBox tb = …; // e.g. from WPF UI string s = await MaybeAsync(); tb.Text = s; // returned to UI thread? Maybe this question is too simple, but so far I’ve only been keeping up with you and Eric, and have not had time to watch any videos or get the CTP to check for myself :) I get your point about ‘yield’ being potentially misleading, because control is not necessarily yielded. But I agree with an earlier commenter’s point that ‘yield’ does a good job at expressing the intent of the programmer. The programmer is saying, “I’m willing to YIELD control to the caller UNTIL the following method completes or causes an exception.” By the way, this English description of the programmer’s intent is also why I like ‘until’. ‘Yield until’ is a nice abbreviated way to capture the total sentiment. It’d be even better if I could think of a way to express the same concept in one word, but I’m not sure English has such a word. I have to admit I’m not a big fan of ‘continue after’. In trying to use these words to characterize the programmer’s intent, I end up with something less elegant and more vague: “I’m willing to give up control and CONTINUE execution of this method AFTER the following method completes or causes an exception.” Note that the notion of “giving up control” is implicit in the ‘continue after’ construction, whereas it is quite explicit in the ‘yield until’ formulation. Jon can probably do a better job than I did at paraphrasing the programmer’s intent using ‘continue’ and ‘after’. @Blake: The caller *may* be using await, or they may not. That doesn’t affect whether or not control returns to that caller. Control returns to the caller, which in turn gets to decide whether to wait for you to complete or not. @Empreror XLII: It’s up to the asynchronous operation to decide where the continuation will be run. It looks like the normal pattern will be to run the continuation via the caller’s current SynchronizationContext – which for UI threads will mean coming back to the UI thread, but for thread pool threads will mean firing the continuation on any thread pool thread (not necessarily the original one). Oops, I left my previous comment on the wrong thread. Sorry for the confusion. @skeet: True, the caller isn’t required to use await, anymore than the caller of a method implemented with ‘yield’ is required to enumerate over the results. In both cases, however, that is how the feature is intended to be used and how it facilitates reasoning about the overall code. I’m not arguing about your analysis of the implementation internals, which is certainly correct. This was about why such a keyword should never be called “return until”. @Blake: I’d say it shouldn’t be called “return until” because it *sometimes* won’t return to the caller. It seems we look at the feature in very different ways. Even if the caller *is* using await, they still get control back – which may well mean that *they* then return control to *their* caller. I believe you are primarily focused on how the feature is implemented. That’s certainly very useful and important. The implementation is _completely_ different than the F# implementation that I’m more familiar with, by the way. My comments have been based on how the feature is intended to be used. In particular, I’m basing that on how the F# feature is currently being used, because while the implementations are night and day different, the surface interface is very similar. Anders was clear during the PDC Q&A that the C# feature is ‘heavily inspired’ by the F# one. Regarding that returning back to the caller’s caller and so forth – yes, and in fact it generally ends up returning back to the message loop/threadpool/TPL, which dispatches the correct continuation and maintains the lovely appearance of a simple, synchronous call tree, even though it is async under the covers. Therein lies the beauty. @Blake: I’m *currently* focused on how the feature is implemented, in order to create a solid personal understanding on top of which I can build everything else. That’s the way I like to work – I don’t like black magic, basically :) Things like LINQ made a lot more sense to me when I understood what the compiler was doing under the hood. On the other hand, even from the higher level, I can’t see how it makes sense to claim control isn’t returned to the caller. Note that even within an async method, the task may well not be *immediately* awaited – for example if you want to launch multiple tasks in parallel, which I suspect will be pretty common. I think it makes more sense as a mental model to think that control will usually be returned to the caller, but that the caller may choose to await the result. I think that puts the responsibility in the right place. I’ve had one of those ‘aha’ moments since my last comment. I believe a big part of my disconnect here is the difference between the ‘hot’ Task/Task’s that C# uses and the ‘cold’ Async’s that F# uses. An Async is just a promise/future/etc, nothing runs until you run it. This is why the F# implementation doesn’t have the equivalent of BeginAwait returning false. The C# implemention is akin to every call to an F# async method being followed by “|> Async.StartImmediate”. That feels very unnatural, having been using the F# model for a while. I’m hoping there will be an Eric post dicussing why the C# team went a different direction in this area. @Blake: Yes, I believe that’s a definite difference… although one certainly *could* write a ColdTask which only started when GetAwaiter().BeginAwait(…) was called. That might be an interesting thing to experiment with, actually :) That leads straight to your next blog entry. An obvious advantage of cold tasks is when you want to compose them. Because they aren’t running yet, you can pass them to a piece of library code that manages their dependancies. @Blake: Right. And of course, one interesting feature is that you can easily build a hot task from a cold task via wrapping (by starting the cold task on construction), but not vice versa. Having just returned from Eric’s last posting, it appears that there won’t be any extensibility hooks to return your own ColdTask. Humbug. Assuming hot tasks remain the model in C# I suspect that wrapping his how all F# code will have to interop.
https://codeblog.jonskeet.uk/2010/10/30/c-5-async-investigating-control-flow/?replytocom=12380
CC-MAIN-2021-49
refinedweb
3,006
60.55
Running an SSIS Package Programmatically on a Remote Computer If a client (local) computer either does not have Integration Services installed or does not have access to all the resources that a package requires, you must start the package so that the package runs on the remote computer where the package is stored. You must take extra steps to ensure that the package runs on the remote computer, because a package runs on the same computer as the application that starts the package. Thus, if you run a remote package directly from an application on the local computer, the package will load and run from the local computer. Because the local computer either does not have Integration Services installed, or does not have access to all the resources that the package requires, the package will not run successfully. To start the package on the remote computer, you call one of the following programs: SQL Server Agent. Another application, component, or Web service that is running on the remote computer. You have to ensure that the process that runs the package on the remote computer has the required permissions. This process requires permission not only to start the package, but to find and open all the resources that the package uses. The default permissions are frequently not sufficient, especially in a Web-based solution. A full discussion of permissions, and of authentication and authorization, is beyond the scope of this topic.. The following sample code demonstrates how to call SQL Server Agent programmatically to run a package on the remote computer. The sample code calls the system stored procedure, sp_start_job, which in turn launches a SQL Server Agent job that is named, RunSSISPackage, and is on the remote computer. The RunSSISPackage job then runs the package on the remote computer where the job itself is running. For information on troubleshooting packages that are run from SQL Server Agent jobs, see the Microsoft article, An SSIS package does not run when you call the SSIS package from a SQL Server Agent job step. Sample Code The following code samples require a reference to the System.Data assembly.(); } } } In the previous section, the solution for running packages programmatically on a remote computer does not require any custom code on the remote computer. However, you may prefer a solution that does not rely on SQL Server Agent to run packages. The following example provides partial code that could be used in a remote component or a Web service on the server to start Integration Services packages on the remote computer. Sample Code The following code samples suggest an approach for creating and testing a remote class that runs a package remotely. These samples are not complete, but provide code that could be used as part of a solution built as a remote component or as a Web service. The samples require a reference to the Microsoft.SqlServer.ManagedDTS assembly. Creating the Function to Run the SSIS Package Remotely An Integration Services package can be loaded directly from a file, directly from SQL Server, or from the SSIS Package Store, which manages package storage in both SQL Server and special file system folders. To support all the available loading options, this sample uses a Select Case or switch construct to select the appropriate syntax for starting the package and to concatenate the input arguments appropriately. The LaunchPackage method returns the result of package execution as an integer instead of a DTSExecResult value so that client computers do not require a reference to any Integration Services assemblies. To create a remote class to run packages on the server programmatically Open Visual Studio and create a project of the appropriate type in your preferred programming language. The following sample code uses the name LaunchSSISPackageService for the project. Add a reference to the Microsoft.SqlServer.ManagedDTS assembly. Paste the sample code into the class file. The sample shows the whole contents of the code window. Add the code, attributes, or references that may be required to build and expose a remote component or service. Build and test the project that includes the sample code. using Microsoft.SqlServer.Dts.Runtime; using System.IO; public class LaunchSSISPackageServiceCS { public LaunchSSISPackageServiceCS() { } // LaunchPackage Method Parameters: // 1. sourceType: file, sql, dts // 2. sourceLocation: file system folder, (none), logical folder // 3. packageName: for file system, ".dtsx" extension is appended(); } } Calling the Function to Run the SSIS Package Remotely The following sample console application uses the remote component or service to run a package. The LaunchPackage method of the remote class remote class In Visual Studio, create a new console application using your preferred programming language. The sample code uses the name LaunchSSISPackageTest for the project. Add a reference to the local proxy assembly that represents the remote component or service. If necessary, adjust the variable declaration in the sample code for the name that you assign to the
https://msdn.microsoft.com/en-us/library/ms403355(v=sql.105).aspx
CC-MAIN-2017-26
refinedweb
813
51.58
ScarangoScarango ArangoDB client written in Scala SetupSetup Scarango is published to Sonatype OSS and Maven Central currently supporting Scala and Scala.js (core only) on 2.11 and 2.12. Configuring the driver in SBT requires: libraryDependencies += "com.outr" %% "scarango-driver" % "0.8.6" DependenciesDependencies Bringing in any new library is always risky as it contains its own baggage of third-party dependencies. In Scarango we try to keep the number of third-party dependencies to a minimum. Here are the main dependencies currently being used in Scarango: - Circe: JSON parsing and class encoding and decoding. - Reactify: Functional reactive paradigms. This is mostly manifested in the triggers. - Scribe: Logging framework. - YouI: HTTP restful calls are managed through the HttpClient. ImportsImports For the basics of Scarango you'll need: import com.outr.arango._ Because we're using the higher level abstraction we also need the managed package as well: import com.outr.arango.managed._ Case ClassesCase Classes Scarango relies primarily on case classes to represent documents (vertex and edges), so we can easily map to and from the database. We can extend from DocumentOption to access the extra information that an Arango document includes (_key, _id, and _rev): case class Fruit(name: String, _key: Option[String] = None, _id: Option[String] = None, _rev: Option[String] = None) extends DocumentOption Notice that we define _key, _id, and _rev as Option[String] and default them to None. This allows them to be populated by ArangoDB when they are inserted into the database. If you prefer to define the key yourself you may set the _key value before insert and Arango will accept it accordingly. Graph and CollectionGraph and Collection The next thing we need is a representation of our database. We can do this easily with our managed Graph: object Database extends Graph("example") { val fruit: VertexCollection[Fruit] = vertex[Fruit]("fruit") } The code above creates a representation of our database, graph, and maps the Fruit class as a vertex collection in Arango. The Graph class has default options for db, url, username, and password but can be set in the constructor as necessary. Initializing the CredentialsInitializing the Credentials Now that we have our mapping representation of a database we need to initialize to verify credentials and get a token that we can use for all communication to the database: val future: Future[Boolean] = Database.init() The result will be true if the credentials were accepted and no errors occurred. Creating the DatabaseCreating the Database Now that we're authenticated we need to create our graph and collection: val future: Future[GraphResponse] = Database.fruit.create() The GraphResponse contains a lot more information about what happened, but the primary thing to check in this situation is error and making sure it's false. Inserting FruitInserting Fruit We're finally ready to insert some content into our graph. Let's start with an Apple: val future: Future[Fruit] = Database.fruit.insert(Fruit("Apple")) Notice in the above we didn't include _id, _key, or _rev as these will be populated by the database. However, the Future[Fruit] we get back will include all the values generated from the database. Querying with AQLQuerying with AQL Scarango provides a compile-time validated AQL interpolator to give you proper compile-time errors if the query is invalid. Let's create a query to get all the fruit back: val query = aql"FOR f IN fruit RETURN f" In order to use this query we can call cursor on the fruit collection: val response: Future[QueryResponse[Fruit]] = Database.fruit.cursor(query) The QueryResponse object has several useful pieces of information, but for our immediate needs calling result on it will give us a List[Fruit] of the results of the query. Real-time / Streaming ChangesReal-time / Streaming Changes Scarango adds support for real-time events from the database to be handled. This was inspired by. Simply start the monitor: Database.realTime.start() Then you can listen to upserts and deletes on any collection: Database.fruit.triggers.upsert.attach { f => println(s"Fruit was upserted: $f") } Database.fruit.triggers.deletion.attach { f => println(s"Fruit was deleted: $f") } Finally, you can listen to the raw stream of events if you'd rather do something more generic: Database.realTime.events.attach { logEvent => println(s"Real-time event: $logEvent") } Further ReadingFurther Reading For more examples using managed graphs take a look at the ManagedSpec (). VersionsVersions Features for 2.0.0 (Future)Features for 2.0.0 (Future) - Scala.js wrapper for Foxx framework - Transactions Features for 1.0.0 (In-Progress)Features for 1.0.0 (In-Progress) - Migrate all case classes to corefor better re-use in Scala.js - DSL for creating AQL queries - Versioned Document functionality (replace and delete creates duplicate in another collection instead of updating) - Proper support for differentiating nulland exclusion of values - Better support for _key, _id, and _revas references and in case classes Features for 0.8.0 (Released 2017.08.31)Features for 0.8.0 (Released 2017.08.31) - Support for sequences in AQL queries - Support for null in AQL queries - Support for Option in AQL queries - Support for Boolean in AQL queries - Support for BigDecimal in AQL queries Features for 0.7.0 (Released 2017.07.25)Features for 0.7.0 (Released 2017.07.25) - Replace use of Typesafe Config with Profig for better support - Update driver for ArangoDB 3.2 changes - Test and update driver for RocksDB backing datastorage Features for 0.6.0 (Released 2017.06.23)Features for 0.6.0 (Released 2017.06.23) - Seamless Re-Authentication support for token timeout Features for 0.5.0 (Released 2017.05.16)Features for 0.5.0 (Released 2017.05.16) - Create Credentials support for better authentication paradigm - Support for Replication Logger () - Real-time change detection (upsert and deletion directly from the database) aka Triggers AbstractCollection.modifyfeature to modify a document by supplying an original and modified case class only updating with the changes - Diff support for modifythat properly handles null Features for 0.4.0 (Released 2017.05.10)Features for 0.4.0 (Released 2017.05.10) - Support for passing collection as reference in AQL interpolation - AQL executeconvenience method for no results - AQL callconvenience method for exactly one result - AQL firstconvenience method for optional first result - Complete Indexing support - Additional functionality for key/value collection (Map implementation) - Upsert functionality convenience functionality - Graph knowledge of all collections and Graph.initcan optionally create all missing collections - Trigger based modifiedupdates - Database Upgrade infrastructure - QueryResponsePagination to easily page through results - QueryResponseIterator to cleanly iterate over every result without loading everything into memory - Support ArangoDB with authentication disabled - Support AbstractCollection.replace by key to allow updating the document's key - Add support for Arango default configuration to be loaded optionally from typesafe.config Features for 0.3.0 (Release 2017.04.28)Features for 0.3.0 (Release 2017.04.28) - Renaming of project from arangodb-scala to scarango - Separation of core and driver for better re-use - Better documentation and examples Features for 0.2.0 (Released 2017.04.28)Features for 0.2.0 (Released 2017.04.28) - Higher level abstraction for working with documents - Triggers (Before and After) - Polymorphic Querying capabilities - Convenience functionality for adding and managing edges Features for 0.1.0 (Released 2017.04.05)Features for 0.1.0 (Released 2017.04.05) - Asynchronous client for all major HTTP end-points - Persist case classes - Query case classes - AQL compile-time validation
https://index.scala-lang.org/outr/scarango/scarango/0.8.4?target=_2.11
CC-MAIN-2018-26
refinedweb
1,243
50.02
#include <OW_CIMInstance.hpp> Inheritance diagram for OW_NAMESPACE::CIMInstance: CIMInstances are ref counted, copy on write objects. It is possible to have an CIMInstance object that is NULL. The method to check for this condition is as follows: CIMInstance ci = ch.getInstance(...); if (!ci) { // Null instance } else { // Valid instance } Providers generally follow these steps to create a CIMInstance object: 1. Obtain a CIMOMHandleIFC object hdl. 2. Use hdl to create a CIMClass object of the desired CIM class: CIMClass cc = hdl.getClass(namespace, class_name); 3. Use CIMClass cc to create a CIMInstance of the desired CIM class: CIMInstance inst = cc.newInstance(); 4. Assign properties of inst as desired using setProperty(). Definition at line 82 of file OW_CIMInstance.hpp.
http://openwbem.org/openwbem-docs/html/class_o_w___n_a_m_e_s_p_a_c_e_1_1_c_i_m_instance.html
CC-MAIN-2018-05
refinedweb
117
60.31
Is global temperature rising? How much? This is a question of burning importance in today's world! Data about global temperatures are available from several sources: NASA, the National Climatic Data Center (NCDC) and the University of East Anglia in the UK. Check out the University Corporation for Atmospheric Research (UCAR) for an in-depth discussion. The NASA Goddard Space Flight Center is one of our sources of global climate data. They produced this video showing a color map of the changing global surface temperature anomalies from 1880 to 2015. The term global temperature anomaly means the difference in temperature with respect to a reference value or a long-term average. It is a very useful way of looking at the problem and in many ways better than absolute temperature. For example, a winter month may be colder than average in Washington DC, and also in Miami, but the absolute temperatures will be different in both places. from IPython.display import YouTubeVideo YouTubeVideo('gGOzHVUQCw0') How would we go about understanding the trends from the data on global temperature? The first step in analyzing unknown data is to generate some simple plots using matplotlib. We are going to look at the temperature-anomaly history, contained in a file, and make our first plot to explore this data. We are going to smooth the data and then we'll fit a line to it to find a trend, plotting along the way to see how it all looks. Let's get started! We took the data from the NOAA (National Oceanic and Atmospheric Administration) webpage. Feel free to play around with the webpage and analyze data on your own, but for now, let's make sure we're working with the same dataset. Go to the folder data on the GitHub repository: Caminos, then select the file land_global_temperature_anomaly-1880-2016.csv, click where it says "raw" and finally right-click and select Save Page As (choosing a location on your local drive). This file contains the year on the first column averages of land temperature anomaly listed sequentially on the second column, from 1880 to 2016. We will read the file, then make an initial plot to see what it looks like. import numpy year, temp_anomaly = numpy.loadtxt(fname='data/land_global_temperature_anomaly-1880-2016.csv', delimiter=',', skiprows=5, unpack=True) Exercise Inspect the data by printing year and temp_anomaly Let's first load our plotting library, called matplotlib. To get the plots inside the notebook (rather than as popups), we use a special "magic" command, %matplotlib inline: from matplotlib import pyplot %matplotlib inline You can add a semicolon at the end of the plotting command to avoid that stuff that appeared on top of the figure, that Out[x]: [< ...>] ugliness. Try it. pyplot.plot(year, temp_anomaly); Now we have a plot but if I give you this plot without any information you would not be able to figure out what kind of data it is! We need labels on the axis, a title and why not a better color, font and size of the ticks. Publication quality plots should always be your standard for plotting. How you present your data will allow others (and probably you in the future) to better understand your work. Let's make the font of a specific size and type. We don't want to write this out every time we create a plot. Instead, the next few lines of code will apply for all the plots we create from now on. from matplotlib import rcParams rcParams['font.family'] = 'serif' rcParams['font.size'] = 16 We are going to plot the same plot as before but now we will add a few things to make it prettier and publication quality. #You can set the size of the figure by doing: pyplot.figure(figsize=(10,5)) #Plotting pyplot.plot(year, temp_anomaly, color='#2929a3', linestyle='-', linewidth=1) pyplot.title('Land global temperature anomalies. \n') pyplot.xlabel('Year') pyplot.ylabel('Land temperature anomaly [°C]') pyplot.grid(); Better ah? Feel free to play around with the parameters and see how it changes. Let's now fit a straight line through the temperature-anomaly data, to see the trends. We need to perform a least-squares linear regression to find the slope and intercept of a line $$y = mx+b$$ that fits our data. Thankfully, Python and NumPy are here to help! With polyfit(), we get the slope and y-intercept of the line that best fits the data. With poly1d(), we can build the linear function from its slope and y-intercept. m, b = numpy.polyfit(year, temp_anomaly, 1) f_linear = numpy.poly1d((m, b)) print(f_linear) 0.01037 x - 20.15 pyplot.figure(figsize=(10, 5)) pyplot.plot(year, temp_anomaly, color='#2929a3', linestyle='-', linewidth=1, alpha=0.5) pyplot.plot(year, f_linear(year), 'k--', linewidth=2, label='Linear regression') pyplot.xlabel('Year') pyplot.ylabel('Land temperature anomaly [°C]') pyplot.legend(loc='best', fontsize=15) pyplot.grid(); We have the linear function that best fits our data but this doesn't look like a good approximation. If you look at the plot you might have noticed that around 1970 the data temperature starts increasing faster. What if we break the data in two (before and after 1970) and we do a liear regression in each segment? To do that, we need to find in which position of our year array is the year 1970 located. Thanksfully, numpy has a function called numpy.where() that can help us. We need to pass a condition and numpy.where will tells us where in the array the condition is True. numpy.where(year==1970) (array([90]),) To split the data, we can use a powerful instrument: the colon notation. A colon between two indices indicates a range of values from a start to an end. The rule is that [start:end] includes the element at index start but excludes the one at index end. For example, to grab the first 3 years in our year array, we do: year[0:3] array([ 1880., 1881., 1882.]) Now we know how to split our data in two sets, to get two regression lines year_1 , temp_anomaly_1 = year[0:90], temp_anomaly[0:90] year_2 , temp_anomaly_2 = year[90:], temp_anomaly[90:] m1, b1 = numpy.polyfit(year_1, temp_anomaly_1, 1) m2, b2 = numpy.polyfit(year_2, temp_anomaly_2, 1) f_linear_1 = numpy.poly1d((m1, b1)) f_linear_2 = numpy.poly1d((m2, b2)) pyplot.figure(figsize=(10, 5)) pyplot.plot(year, temp_anomaly, color='#2929a3', linestyle='-', linewidth=1, alpha=0.5) pyplot.plot(year_1, f_linear_1(year_1), 'g--', linewidth=2, label='1880-1969') pyplot.plot(year_2, f_linear_2(year_2), 'r--', linewidth=2, label='1970-2016') pyplot.xlabel('Year') pyplot.ylabel('Land temperature anomaly [°C]') pyplot.legend(loc='best', fontsize=15) pyplot.grid();
http://nbviewer.jupyter.org/github/barbagroup/Caminos/blob/master/3--Earth_temperature_over_time.ipynb
CC-MAIN-2018-13
refinedweb
1,118
67.04
Saiba mais sobre a Assinatura do Scribd Descubra tudo o que o Scribd tem a oferecer, incluindo livros e audiolivros de grandes editoras. In order to prepare for an LBO modeling test, the first step is to understand the key assumptions and theprocess. These are provided in the tables below: In order to correctly complete the test, you must understand the basic assumptions and steps to create an LBObecause most modeling tests will only provide a few of the assumptions you will need. You will need to makeother basic assumptions based on what you know about the private equity firm youre interviewing with, anduse that to create the model. To make the accurate assumptions, you will have to understand the types ofcompanies the sponsor likes to invest in and their investment strategy, such as the purchase price, capitalstructure, growth and margin assumptions, and exit strategy. Whenever you have to make assumptions that arenot given or standard, document the assumptions that you make and be prepared to defend them.To prepare for this test, practice creating the different types of LBO tests you may receive from scratch (paperLBOs, short-form excel LBOs, long-form detailed 3-statement LBOs). This will help you become morefamiliar with modeling, but it also will give you a better idea of how an LBO works. For example, one of yourgoals should be to comprehend how an investments IRR is affected if you adjust the values of key levers suchas the purchase price, the amount of leverage, revenue growth rates, and the exit multiple. This is especiallyimportant for investment banking analysts and consultants who havent had a lot of exposure to LBO modeling.The more you practice these tests, the more prepared youll be, so spend as much time on this as you can.In the following chapters, we will walk through variations of an LBO modeling test and case study.II/ Paper LBO Model ExampleAn illustrative example of a paper LBO is provided below in 5 simple steps. In a paper LBO exercise, you willbe expected to complete the important components of a working LBO model with the use of paper and penciland without the use of a computer.Given LBO Parameters and Assumptions:- XYZ Private Equity Partners purchases ABC Target Company for 5.0x Forward 12 months (FTM)EBITDA at the end of Year 0.The debt-to-equity ratio for the LBO acquisition will be 60:40.Assume the weighted average interest rate on debt to be 10%.ABC expects to reach $100M in sales revenue with an EBITDA margin of 40% in Year 1.Revenue is expected to increase by 10% year-over-year (y-o-y).EBITDA margins are expected to remain flat during the term of the investment.Capital expenditures are expected to equal 15% of sales each year. (Notice that, because the exit value at the end of Year 5 will be based on a forward EBITDA multiple, we mustcalculate six years worth of income statement, not 5. Also note that the numbers might not agree perfectlybecause of rounding. It is reasonable to round your intermediate calculations to the nearest integer in carryingover calculations to the next step.)a) Project revenue: Revenue is expected to grow 10% annually.- $100 million Year 1 sales (1 + 10% growth rate) = $110 million sales in Year 2.$110 million Year 2 sales (1 + 10% growth rate) = $121 million sales in Year 3.$121 million Year 3 sales (1 + 10% growth rate) = $133.1 million sales in Year 4.$133 million Year 4 sales (1 + 10% growth rate) = $146.3 million sales in Year 5.$146 million Year 5 sales (1 + 10% growth rate) = $160.6 million sales in Year 6. $100 million Year 1 sales 40% EBITDA margin = $40 million Year 1 EBITDA.$110 million Year 2 sales 40% EBITDA margin = $44 million Year 2 EBITDA.$121 million Year 3 sales 40% EBITDA margin = $48 million Year 3 EBITDA.$133 million Year 4 sales 40% EBITDA margin = $53 million Year 4 EBITDA.$146 million Year 5 sales 40% EBITDA margin = $59 million Year 5 EBITDA.$161 million Year 6 sales 40% EBITDA margin = $64 million Year 6 EBITDA. $40 million Year 1 EBITDA $20 million D&A = $20 million Year 1 EBIT. (etc. for Years 2-6) d) Calculate interest expense using the debt amount used for purchase multiplied by the interest rate tocalculate the yearly interest expense line item.- $120 million of debt 10% interest rate = $12 million interest expense per year. $20 million Year 1 EBIT $12 million int. exp. = $8 million Year 1 EBT. (etc. for Years 2-6) f) Subtract taxes using the tax rate to get to tax-effected EBT (a proxy for Net Income).- $8 million Year 1 EBT 40% tax rate = $3 million taxes, so $5 million Year 1 t/e EBT.- $12 million Year 2 EBT 40% tax rate = $5 million taxes, so $7 million Year 2 t/e EBT.- $16 million Year 3 EBT 40% tax rate = $6 million taxes, so $10 million Year 3 t/e EBT.- $21 million Year 4 EBT 40% tax rate = $8 million taxes, so $13 million Year 4 t/e EBT.- $27 million Year 5 EBT 40% tax rate = $11 million taxes, so $16 million Year 5 t/e EBT.- $32 million Year 6 EBT 40% tax rate = $13 million taxes, so $19 million Year 6 t/e EBT.4. Calculate cumulative levered free cash flow (FCF). a) Start with EBT (Tax-effected) and then add back non-cash expenses (D&A).- c) Subtract the annual increase in operating working capital to get to Free Cash Flow (FCF).- $5mm Y1 t/a EBT + $20mm D&A $15mm Y1 capex $5mm NWC = $5mm Year 1 FCF.$7mm Y1 t/a EBT + $20mm D&A $17mm Y2 capex $5mm NWC = $6mm Year 2 FCF.$10mm Y1 t/a EBT + $20mm D&A $18mm Y3 capex $5mm NWC = $7mm Year 3 FCF.$13mm Y1 t/a EBT + $20mm D&A $20mm Y4 capex $5mm NWC = $8mm Year 4 FCF.$16mm Y1 t/a EBT + $20mm D&A $22mm Y5 capex $5mm NWC = $9mm Year 5 FCF. d) Calculate Cumulative Free Cash Flow during the life of the LBO.Cumulative FCF until exit equals total debt pay-down, if it is assumed that 100% of FCF is used to pay downdebt. (This is a standard assumption for a basic LBO model.)- $5 mm Year 1 FCF + $5 mm Year 2 FCF + $7 mm Year 3 FCF + $8 mm Year 4 FCF + $9 mm Year 5FCF = $34 mm Cumulative FCF.5. Calculate Ending Purchase Price (Exit Value) and Returns.a) Calculate Total Enterprise Value (TEV) at Exit.Take Forward EBITDA at exit (Year 6 EBITDA) along with a 5.0x exit multiple to calculate Exit TEV. $64million Year 6 EBITDA 5.0x multiple = $320 million Enterprise Value at Exit.b) Calculate Net Debt at Exit (also known as Ending Debt).Beginning Debt Debt Pay-down = Ending Debt.$120 million in Beginning Debt $34 million in Cumulative FCF = $86 million in Ending Debt.c) Calculate ending Equity Value (EV) by subtracting Ending Debt from Exit TEV.$320 Exit TEV $86 million Ending Debt = $234 million Ending EV.d) Calculate the Multiple-of-Money (MoM) EV return (Ending EV Beginning EV).- 6. Final StepsMake sure to take your time and calculate every formula correctly since this is not a race, and any error that youmake will flow through the model youre building. If you catch a mistake part-way through, you will have to goback and correct itsometimes causing you to have to recalculate nearly everything, and possibly leading tocompounding mistakes on top of the original one.In addition, the interviewer will ask you to walk through your thought process and calculations. Thus it isimportant to be able to build the proper paper LBO in simple, accurate steps, and make sure you can walkthrough the reasoning regarding the process and each calculation. This takes practice, so be sure to practice atleast one more paper LBO before your next private equity interview.III/ LBO Modeling Test ExampleWhen interviewing for a junior private equity position, a candidate must prepare for in-office modeling tests onpotential private equity investment opportunitiesespecially LBO scenarios. In this module, we will walkthrough an example of an in-office LBO modeling test. In-office case studies and modeling tests can occur atvarious stages of an interview process, and additional interviews with other members of the private equity teamcould occur on the same day. Therefore, you should strive to be able to do these studies effectively andefficiently without draining yourself so much that you cant quickly rebound and move on to the next interview.Make sure to take your time and build every formula correctly, since this process is not a race. There are manycomplex formulas in this test, so make sure you understand every calculation. This type of LBO test will not be mastered in a day or even a week. You must therefore begin practicing thistechnique in advance of meeting with headhunters. Repeated practice, checking for errors and difficulties andlearning how to correct them, all the while enhancing your understanding of how an LBO works, is the key tosuccess.In the following LBO Case Study module, we will cover the following key areas:- 4. G&A and other assumptions (assume constant throughout the projection period):- 6. Investment Assumptions:Due to the depressed macroeconomic and investing environment, the PE fund is able to acquire ABC Companyfor the inexpensive purchase price of 5.0x 2011 EBITDA (assuming a cash-free debt-free deal), which will bepaid in cash. The transaction is expected to close at the end of 2011.Assumptions include the following:- Senior Revolving Credit Facility: 3.0x (2.0x funded at close) 2011 EBITDA, LIBOR + 400bps, 2017maturity, commitment fee of 0.50% for any available revolver capacity. RCF is available to help fundoperating cash requirements of the business (only as needed).Subordinated Debt: 1.5x 2011 EBITDA, 12% annual interest (8% cash, 4% PIK interest), 2017maturity, $1 million required amortization per year. (Hint: add the PIK interest once you have a fullyfunctioning model that balances.)Assume that existing management expects to roll-over 50% of its pre-tax exit proceeds from thetransaction. Existing managements ownership pre-LBO is 10%.Assume a minimum cash balance (Day 1 Cash) of $5 million (this needs to be funded by the financialsponsor as the transaction is a cash-free / debt-free deal).Assume that all remaining funding comes from the financial sponsor.Assume that all cash beyond the minimum cash balance of $5 million and the required amortization ofeach tranche is swept by creditors in order of priority (i.e. 100% cash flow sweep).Assume that LIBOR for 2012 is 3.00% and is expected to increase by 25bps each year.The M&A fee for the transaction is $1.5 million. Assume that the M&A fee cannot be expensed(amortized) by ABC and will be paid out of the sponsor equity contribution upon close.In addition, there is a financing syndication fee of 1% on all debt instruments used. This fee will beamortized on a five-year, straight-line schedule.Assume New Goodwill equals Purchase Equity Value less Book Value of Equity. Hint: The first forecast year for the model will be 2012. However, you will need to build out the incomestatement for 2010 and 2011 to forecast the financial statements for years 2012 through 2016.6. Exercises:As part of the in-person LBO test, pre-MBA and post-MBA candidates are expected to complete the followingexercises in their entirety. Please note the assumptions given here apply for multiple scenarios:- Build an integrated three-statement LBO model including all necessary schedules (see below).Build a Sources and Uses table.Make adjustments to the closing balance sheet of ABC Company post-acquisition.Build an annual operating forecast for ABC Company with the following scenarios (using 2010 as thefirst year for the revenue forecast; note that 2010 EBITDA should be approximately $25 million).Assume that in 2011 there is 5% growth in units sold (both Cloud and Time units).2012-2016 assumptions include:o Upside Case: 5% annual growth in units sold (both Cloud and Time units)o Conservative Case: 0% annual growth in units sold (both Cloud and Time units)o Downside Case: 5% annual decline in units sold (both Cloud and Time units)Build a Working Capital schedule using Accounts Receivable Days, Accounts Payable Days, InventoryDays, and other assets and liabilities as a percentage of Revenue. Assume working capital metrics stayconstant throughout the projection period and assume 365 days per year.Build a Depreciation Schedule that assumes that existing PP&E depreciates by $1 million per year, andthat new capital expenditures of $1.5 million per year depreciate on a five-year, straight-line basis.Build a Debt schedule showing the capital structure described earlier. Use average balances forcalculating Interest Expense (except for PIK interestassume that PIK interest is calculated based onthe beginning year Subordinated Debt balance and not the average over the year).Create an Exit Returns schedule (including both cash-on-cash and IRR) showing the returns to the PEfirm equity based on all possible year-end exit points from 2012 to 2016, with exit EBITDA multiplesranging from 4.0x to 7.0x.Display the results of all of these calculations using the Upside Case. Note that the above description incorporates all of the information, assumptions and assignments that weregiven in this LBO in-person test example.Step 1: Income Statement ProjectionsAs part of the first step, build out the core operating Income Statement line items for years 2010 through 2016. Based on the provided assumptions, the Upside Case estimates an annual increase of 5.0% for Revenue from2012-2016. Next, you should build the following exhibit in Excel in order to be able to change the casescenarios easily (with the selected case driving the revenue growth numbers in the operating model).- Note that the highlighted 1 is the input to the operating model, and the 5.0% in grey background representsthe formula that is built to pick up the appropriate case. We use the =OFFSET() function in Excel to drive thisformula.- OFFSET is a simple Excel formula that is used commonly to interchange scenarios, especially if themodel becomes very complex. It simply reads the value in a cell that is located an appropriate numberof rows/columns away, based on the parameters given to the function. Thus, for example,=OFFSET(A1, 3, 1) will read the value in cell B4 (3 rows and 1 column after A1).Next, build the costs related to Revenue based upon the information given in the case. Using this graphic, you should be able to understand and build all the formulas. Be sure to think through eachnumber and how it is calculated, as this is the main summary of the LBO transaction as a whole. A few pointsworth noting:- This model assumes a debt-free/cash-free balance sheet pre-transaction for simplification. Without debtor cash, the transaction value is simply equal to the offer price for the equity (before fees and minimumcashdiscussed below).The funding for this model is fairly simple: the funded credit facility is 2.0x 2011E EBITDA, thesubordinated debt is 1.5x, and the remaining portion is the equity funding, which is a combination ofmanagement rollover equity and sponsor (PE firm) equity. (Note that the 5.0x 2011E EBITDA is theoffer value for the equity before the M&A and financing fees and the minimum cash balance, not after.After fees/cash, it ends up being 5.25x.)The management rollover is simply half of the management teams proceeds from selling the company.Since management owned 10% of the company before the transaction, it constitutes 5% of the offerprice for the original equity.The sponsor equity is the plug in this calculation. In other words, it is the amount that is solved foronce all other amounts are known (offer price + minimum cash + fees debt instruments management rollover equity).The total equity (including management rollover) represents about 30-35% of the funding for the deal,which is about right for a typical LBO transaction.Goodwill is simply the excess paid for the original equity (offer price book value of equity). Since this is a cash-free and debt-free deal to start, there are no Pro Forma adjustments for thecancelling or refinancing of debt.Cash increases by $5 million upon close because the sponsor is funding the minimum cash balance(minimum cash that is assumed to be needed to run the business).The New Goodwill is simply the purchase value of the equity (not including fees) less the original bookvalue of the equity.The adjustment for Debt Financing Fees reflects the cost of issuing the new debt instruments to buy thecompany. This fee is considered an asset, and is capitalized and amortized over 5 years.The Debt-related adjustments reflect the new debt instruments for the new capital structure.The Equity adjustment reflects the fact that the original equity is effectively wiped out in thetransactionthe adjustment amount shown here is simply the difference between the new equityvalue and the old one. The new equity value will equal the amount of the total equity funding for thetransaction (sponsor plus managements rollover) less the M&A fee, which is accounted for as an offbalance-sheet cost.VERY IMPORTANT: This stage of the LBO model development (once Pro Forma adjustments havebeen made to reflect the impact of the transaction on the balance sheet) is a very good time to check tomake sure that everything in the model so far balances and reflects the given assumptions. Thisincludes old and new assets equaling old and new liabilities plus equity; new sources of capitalequaling the transaction value, which equals the offer price for the original equity (adjusting for cash,old debt and fees), etc. You can link the Revenue, COGS and SG&A calculations to the operating model (built in Step 1) toget to EBITDA.To get from EBITDA to Net Income, set up the framework first (include line items to subtract D&A,and to subtract Interest and fees, to get to EBT. Then subtract taxes to get Net Incomebut keep inmind for now that calculating D&A and Interest will come a bit later, from other schedules you havenot yet created).o D&A will be linked to the Depreciation Schedule that you will need to build (schedule of theDepreciation of the existing PP&E and new Capital Expenditures made over the projectionperiod).o Interest Expense and Interest Income will be linked to the Debt Schedule that you will need tobuild. There will be a natural circular reference because of the cash flow sweep feature of theLBO model, combined with the fact that Interest Expense is dependent upon Cash balances.This is usually one of the last things you should build in an LBO model.o The amortization of Deferred Financing Fees is fairly straightforward: it uses a straight-line, 5year amortization of the fees described in the case write-up and computed in Step 2.o The tax rates apply to EBT after all of these expenses have been subtracted out. They are givenin the case write-up. Laying out the Balance Sheet is similar to laying out the Income Statementyoull have to set up theframework for some line items and leave the formulas blank at first, as they will be calculated in theother schedules you will create.Cash remains at $5 million throughout the life of the model, as were assuming a 100% cash flowsweep and that the minimum cash balance is $5 million. (Cash would only start to increase if weproject out long enough that all outstanding Debt is paid off.)Youll need to build out the Operating Working Capital line items (Accounts Receivable, Inventory,Other Current Assets, Accounts Payable, Other Current Liabilities) according to the assumptions statedin the case write-up.o Accounts Receivable (AR): Calculate AR days (AR Total Revenue 365) for 2011 and keepit constant throughout the projection period.o Inventory: Calculate Inventory days (Inventory COGS 365) for 2011 and keep it constantthroughout the projection period.o Other Current Assets: Keep this line item as a constant percentage of revenue throughout theprojection period.o Accounts Payable (AP): Calculate AP days (AP COGS 365) for 2011 and keep it constantthroughout the projection period.o Other Current Liabilities: Keep this line item as a constant percentage of revenue throughoutthe projection period.Total Deferred Financing Fees are computed based upon the Debt balances and percentage assumptionsgiven in the model. Deferred financing fees are then amortized, straight-line, over 5 years.The Credit Facility and Subordinated Debt line items will link to your Debt schedule. Their balanceswill decrease over time as a function of the cash available for Debt paydown (since the case write-upspecifies a 100% cash sweep function).Equity (specifically Retained Earnings) will increase each year by the same amount as Net Income,because there are no dividends being declared. If dividends were to be added into the model, you wouldcalculate ending Retained Earnings as Beginning Retained Earnings + Net Income DividendsDeclared. As discussed earlier, the balance sheet has the pleasing feature that if it balances, the model is probablyoperating correctly! Now is another good time to make sure everything balances before proceeding. The primary purpose of the Cash Flow Statement in the integrated financial model is to calculate the LeveredFree Cash Flow (LFCF) being generated by the business. This is for obvious reasons: cash generation is veryimportant in the eyes of PE investors, as it is used to pay down debt and thereby increase equity value (andthereby decrease future interest burdens on the business, which helps to decrease risk over time).- Start with Net Income and add back non-cash expenses from the Income Statement, such as D&A,Non-Cash Interest (PIK), and Deferred Financing Fees.Next, subtract uses of Cash that are not reflected in the Income Statement. These include the increase inOperating Working Capital (which you calculated using your balance sheet) and Capital Expenditures(which is calculated here or, alternatively, could be calculated in the Depreciation Schedule to be builtshortly).Next, calculate the change in cash, which will be interconnected with the Debt schedule. In this case,the model is assuming a 100% cash flow sweep (after mandatory debt amortization payments), so cashshould not change after the 2011PF Balance Sheet amount of $5 million.Even though the amount is not changing, the Cash line item should link back to the Balance Sheet. Thisis because the model could later be used to relax the assumption that 100% of excess cash is swept topay down Debt. If its less than 100%, Cash would accumulate, and that would need to tie in to theother financial statements. We need to build this schedule correctly! The Debt Schedule is probably the trickiest part of the LBOmodel to buildespecially for anyone who has not built an LBO model before. The Debt Schedule willcreate the circular (iterative) reference that is the defining characteristic of a true LBO model. Beforelinking the Debt, Cash, and Interest calculations to one another in the Debt schedule, be sure to turnIterations on in the Formulas section of Microsoft Excels Options menu.o WARNING: Be very careful about changing formulas once you have built the iterativecalculation. If you do so and introduce an error, it could bust your entire model if youre notcareful. This is because the error will travel all the way through the iterative calculations andend up everywhere! If you run into this problem, break the circular reference entirely (bydeleting it), reconstruct the calculations for the first forecast year (2012), and then copy andpaste them across the columns, one year at a time (2013, then 2014, etc.). Many PEprofessionals have spent late nights in the office trying to recover from an accidental errorintroduced into a circular LBO model formula!To compute the changes in Debt balances, calculate LFCF (the framework for this started already onthe Statement of Cash Flows). This determines how much debt is going to be paid down (bothdiscretionary and non-discretionary).o The non-discretionary portion is the required amortization payments made on debt (in this case,there is only required pay-down for subordinated debt).o The discretionary portion is the sweep portion of the remaining LFCF less requiredamortization. Since were assuming a 100% cash flow sweep, all of the LFCF is used to paydown debtfirst the Senior Credit Facility, then the Subordinated Debt. The cash flow sweepand required payments will help you calculate the beginning and ending balances of both of thedebt tranches.o The Senior/Revolving Credit Facility (S/RCF) is the first priority to get paid off via the cashflow sweep. It should be completely paid off before later tranches receive any discretionaryprincipal repayment in the Debt Schedule. Also note that we need to include a fee for the availability of the unused portion of theRCF, even if the business never uses itthis is a typical, annual commitment feearrangement for revolving credit facilities. The interest rate on the debt is a floating rate (this means an interest rate that isdependent on LIBOR, according to the assumptions provided). We need to calculateinterest based on this rate times the average S/RCF balance over the year.o Subordinated debt is the second priority to get paid off through the cash flow sweep. Otherthan required amortization, none of the Subordinated Debt gets paid off before the S/RCF isfully paid off. The 8% cash interest is calculated based upon the average of the debt balance, just likewith the S/RCF. However, the 4% PIK (non-cash) interest will accrue based upon the beginning debtbalance, not the average. Because of this difference (and the fact that one source of interest uses cash and theother does not), we need to make sure were using separate line items for the two typesof Interest Expense. We also need to be aware of the mandatory amortization payment of $1 million peryear, provided in the assumptions. This amount will get paid down out of LFCF nomatter what.o Interest Income on Cash is fairly easy to calculateit is the Cash interest rate (1%) times theaverage balance throughout the year. This amount will increase Cash.When weve finished with these calculations, we need to link these line items to various line items inthe integrated financial statement.o Total Interest needs to be linked to the Income Statement.o Non-Cash Interest needs to be added back to Net Income in the Statement of Cash Flows toassist in deriving LFCF (its a non-cash expense).o Any LFCF that is not used to pay down Debt needs to link to the Cash line item of the BalanceSheet. (In this model none will, but you should include this measure in case the model is laterused to either relax the 100% cash sweep assumption, or to project financials beyond the pointat which all debt has been paid off).o All Debt balances paid down by LFCF need to link to the Debt line items on the Balance Sheet. The last portion of the model to complete is the Equity Returns schedule. This is essentially a simplecalculation based upon the outputs generated by rest of the model.o For each year, we simply take EBITDA multiplied by a range of purchase multiples to get to atotal Exit Value for the company (Transaction Enterprise Value, or TEV).o Next, we subtract out Net Debt (which is dependent on the 3-statement model you just created)to get to Equity Value.o Next, we calculate the portion of the Equity Value that belongs to the management and thesponsor by using the initial equity breakdown for each party.From there its important to calculate both the internal rate of return (IRR) and the cash-on-cash returns(also known as the Multiple of Money or Multiple of Invested Capital). The only tricky part of thiscalculation is to make sure that youre calculating IRR correctly, by using the correct Net PresentValue or IRR formula and that, very importantly, youre discounting by the right number of years!After all the mental energy youve expended to get to this point, its easy to make this mistake.o Put simply, the IRR is equal to the cash-on-cash returns compounded by the number of years,minus 1. Thus, for example, for the 5-year, 5.0x Exit Multiple scenario: Muito mais do que documentos Descubra tudo o que o Scribd tem a oferecer, incluindo livros e audiolivros de grandes editoras.Cancele quando quiser.
https://pt.scribd.com/doc/308949711/LBO-Training
CC-MAIN-2019-51
refinedweb
4,768
53.51
This. Let’s walkthrough how we can use snippets to quickly implement a common security scenario. Specifically, we’ll implement the functionality necessary to display either a “[ Login ]” link or a “[ Welcome UserName ]” message at the the top right of a site depending on whether or not the user is logged in: The above functionality is automatically added for you when you create a project using the new ASP.NET Project Starter Template in VS 2010. For the purpose of this walkthrough, though, we’ll assume we are starting with a blank master page and will build it entirely from scratch. We’ll start by adding a standard ) Wow nice work !!! .This makes the development more faster and easy. Wow! It's amazing. Thanks for the interesting post. It would be nice to have a tooltip/description on each content parameter editing. Would love to see snippets available per project. So u can distribute snippets with version control gr8! really nice to have it in IDE yes this is a really good addition. Its very good for people who like to work source code much more than use designer. One question though, In case of a team, using TFS, can these snippets be automatically be updated in all machine. I mean what has been done to address the scenario, where one person creates snippet and want to share with team. Nice job guys... Especially the cool MVC integration into VS.. I loved these feature, great post !! I didn't know that javascript snippets are also available in VS 2010... Cant wait to get final version.. Great! What about XAML? Bah... I hope these new added features won't compromise VS 2010 performance. Hey Now Scott, Equip it with a snippet! that is what I've always been told. Thx 4 the info, Catto Awesome. I normally have to drop out to intype or similar text editor because VS just doesn't have the support for writing HTML fast. Hopefully now I won't have to! I'm glad these have made their way I to VS as they have been in other editors for a long time. Thanks, it shows VS10 will make developer life a lot easier It just keeps getting better and better Nice - but what about javascript code outlining? That would REALLY make a difference and something that is desperately wanted for javascript Great article! I read it at: thatstoday.com/.../aspnet-html-javascript-snippet-support-vs-2010-and-net-40-series Nice. But will we be able to use asp.net snippets when using "Code Optimized Web Development" mode? That's pretty cool stuff. One concern I have is that I often find that all that editor features like intellisense and snippets, can get in the way when I just want to type stuff in really fast. There are many time when I just want to quickly type in code and it gets annoying to have windows keep popping up w/suggestions. It would be great if there were a little unobtrusive button tucked off in a corner of the editor somewhere (and a keyboard shortcut) that allowed us to quickly toggle on/off the various pop-up editor help features. You mentioned JavaScript support...that makes me wonder if that includes any jQuery snippets? Another commenter brought up XAML...I want to echo that question as well. Thanks. I have question about javascript. If you have plans to add an object\function viewer such as class viewer in the c# editor? As always very helpful article. This looks great. Do you know if they have added the ability to automatically import the correct namespaces in custom C# snippets? I know that this has been available to vb.net users only up until now. JavaScript Snippet is one of my dreams.it's wonderful @Andy - there is a way to turn of the intellisense auto suggest. Then you would use the shortcut ctrl-space to popup the auto-suggest when you need it. This a common technique that you would use if you were doing TDD development as it gets in the way while you are writing test cases for code that doesnt exist yet. Thank you for a great posting. I have a question on javascript debugging and intellisense in vs 2010, will debugging and intellisense for javascript and jQuery finally be as good as it is for c# and other server side languages? Web 2.0 ++ depends on it I would claim. Even though Javascript and jQuery debugging and intellisense support in vs 2008 sp1 is great, it still has a long way to go before becomming fully supported( like eg. c#... ). I (And I think most of us) still need 5 times as much time to write code client side as I do writing serverside code and a rich internet application not utillizing Silverlight depends on our (we the developers) ability to debug and write jquery or even javascript in a productive mannor. That said, I think jQuery should become an integrated part of Visual Studio. Plain Javascript, due to its lack of browser independendcy is, I would claim, outdated. Hımm. Yes, good idea. Thanks a lot.. Waw! Javascript snippets is fabulous! I can't wait for VS 2010! Nice post... Congratulations! Thanks for sharing. Hi scottgu, Looks great! I'll give it a try if I had some more time :) Thanks, Vernon very cool & good tip, thank you very much for sharing. Hi, Thats a really nice feature to use.thanks for sharing. Thani Useful as ever Scott. Can't wait for .Net 4.0 :) Cool, snippets should save a lot of time! Is it going to be possible to add a 'Surround With' like you can in a code file but surround with a html snippet instead? e.g 'Surround With' and then choose 'form' would add <form> to the start and </form> at the end around a selected html block and increase the indent, placing the cursor in the start tag to add any required attributes. Cool Feature. Looking forward to the 2010 coming. Nice features,i am dying to have a final version of VS 2010. Also thanks for sharing. i really don't know VS 2010 support snippet to HTML, ASP.NET markup and JavaScript thanks for sharing information Ability to use tabs to navigate among snippet variables is great; never knew it existed. Not sure how snippets work. If I use snippets and later want to change the snippet, will a change in the snippet reflect in all the pages using the snippet? Is it better to use user controls instead when to comes to using snippets for asp.net controls? Wooowwww..... What an intelligence.... Visual Studio is making developer's life easy and easier. Snippts in JS and Markup is really a cool enhancement. Thanks for sharing it. What's needed now is a built-in snippet editor. Something that would allow me to select a block of text, right click, and select "Make snippet". The editor should also help me out with how to define parameters, code jump positions, and so on. Well, I must say, at last. I've always wondered why that support wasn't there from the beginning at least for .aspx-files. @shahed.kazi: snippets are more like shortcuts to generate short common lines of code. In Visual Studio 2005 they already exist in your codebehind. For example, enter "prop", press the tab-key twice and a short property snippet is generated. A few variables (the variable name, the variable type and the property name) are highlighted and by pressing the tab-key you can cycle between them and change them. When you press enter the snippet is permanently transformed into code. Or try entering "ctor" followed by two tabs in a class and watch a constructor appear. Changing a snippet has no influence on code previously generated with that snippet. Awesome. Much needed. Will the editor differentiate between MVC and WebForms views, to avoid showing webform controls snippets like LoginView in an MVC view? finally catching up with the textmate guys I see... 【原文地址】ASP.NET,HTML,JavaScriptSnippetSupport(VS2010and.NET4.0Series) 【原文发表日期】Friday,Sep... nice work !! a nice worke!!! i will create an application in a few time Visual Studio code snippets are pretty handy. VS 2010 introduces few more that might improve your coding Pingback from ASP.NET, HTML, JavaScript Snippet Support (VS 2010 and .NET 4.0 Series) - ScottGu's Blog
http://weblogs.asp.net/scottgu/archive/2009/09/04/asp-net-html-javascript-snippet-support-vs-2010-and-net-4-0-series.aspx
CC-MAIN-2013-20
refinedweb
1,413
75.2
, we’ve repeated this subsetting.. We deeply care about the dependencies between contracts and that they only have a single responsibility instead of being a grab bag of APIs. Contracts version independently and follow proper versioning rules, such as adding APIs results in a newer version of the assembly. We we, we we, we should provide a well factored implementation. This would allow verticals to simply share the same implementation. Convergence would no longer be something extra; it’s achieved by construction. Of course, there are still cases where we, our – we can provide you with our latest design and – if you don’t like it – simply change it. A good example of this is immutable collections. It had a beta period of about nine months. We spend a lot of time trying to get the design right before we., we’ve we. We. We. Enterprise ready The NuGet deployment model enables agile releases and faster upgrades. However, we we’ll provide the same experience. We’ll create the notion of a .NET Core distribution. This is essentially just a snapshot of all the packages in the specific version we. We expect distributions to be shipped at a lower cadence than individual packages. We. We’ll. we decided to open source .NET Core. From past experience we. We.! Join the conversationAdd Comment Congratulations to everyone involved. As a web developer, I am super excited about this and the scenarios it will create! Thanks to everyone for all the work they put into it! Thanks MS. This will be a great thing when it releases. As a hard core Linux user I welcome the steps you are taking in this cross platform direction. Well done, and keep up the good work. Glad to see the multiplatform move outside the Windows (iis, desktop, mobile, phone, tablet) space. It will make .net much better. How is moving away from COM based objects and the win32 based C API done on a large scale? Simply awesome! So how about open sourcing silverlight? W the biggest argument I've heard against ASP.Net over the years was the cost of Windows server production licenses. With that "issue" out of the way, hopefully we'll see some growth for the .Net stack outside enterprises Like everyone else, I'm excited about .NET Core, but something bothers me…. And what about WCF? Will it be part of the .NET Core? Will we be able to write console applications using .NET core / .NET native? Oh god this is a dream come true, Microsoft. Thank you developers! Thank you so much. Thanks for this detailed post. It clarifies a ton of questions I had. I would cast my vote to, over time, come up with new .NET Core-based versions of existing libraries and project types not already in scope for .NET Core. For example, MVC and Entity Framework are both releasing new versions that are not backwards compatible, but either directly evolved from or at least "highly inspired by" their previous versions, but compatible with the newer, more modern .NET Core. It would be great to see similar efforts for WPF, System.Drawing, Windows Services, etc. In some cases they may still be Windows-only (probably the case for both these examples), but that's OK — in the long run it will allow Microsoft to stop maintaining two versions of .NET, and allow us to share code without PCLs, and only deal with NuGet dependencies. Like with MVC and EF updates, each app could choose if/when they bite the bullet and accept the major breaking change. Another innovation from MS. One of my dream comes true. So what about alternative platforms for distribution of .Net Core? NuGet is Windows only. I think it will be essential to figure out a best practice for distribution to Mac and Linux based systems not just Windows based package managers. This article gives us plenty of information about where things are going on .net framework however it does not reply to real world multiplatform challenges we are facing. Let's say that I want to create a desktop application targeting windows, mac and linux. How can this be done? Is Microsoft going to release any tools where we can write cross platform code? How can we share UI code? How are we going to debug and compile cross platform code? I am truly excited about .NET again after many years. Keep up the fantastic work team and congradulations on this feat of engineering. FYI: cross-platform .Net native – probably not possible to port the Visual C++/Windows version to Linux. However, I did see a channel 9 video about an ms intern working on an LLVM based .net precompilation tool. His work went into an open source project that is still active. That might be another route to take for a linux/MacOS version of .Net native. This is so great! Too late MS. .NET is already a walking corpse. Dead but not quite buried. I just started ASP.NET and .NET in general and I am very pleased to see the advancements that will allow for web apps developed with ASP to be able to run under Linux. Continue the good work! Great news. In 2012, after the Microsoft .NET Framework version 1.0, there was the Shared Source Common Language Infrastructure initiative: what are the main differences and improvements of making .NET Core released to open source if compared to that old initiative? I find the framework-via-NuGet approach very intriguing and am dealing with a similiar situation on top of .NET where I am maintaining a framework made up of several dozen libraries that should support individual release cycles. Like the name 'distribution' very much for describing the "works in a tested fashion" release of the combined NuGet packages. Was looking for a descriptive name myself 🙂 Now, another question in this regard and I haven't yet analyzed the dependency graph within .NET Core, but I'm assuming you will have dependencies between some of the packages? Now, will you specify the upper boundary for your dependencies in the NuGet packages or will you leave it open until there is an actual breaking change that stops the next major version from working with the dependent package? David Ebbo blogged about his recommendation for innocent-until-proven-guilty (blog.davidebbo.com/…/nuget-versioning-part-2-core-algorithm.html), but I'm not sure yet about the impact this approach has for large scale frameworks. Best regards, Michael So basically WPF will die together with the old .NET Framework that will eventually be superseded by .NET Core? Like other commenter here, I'm still very confused about how (or even if) .net Core will ever impact the desktop? You talk about cross-platform development a lot, but you can't deploy a windows store app to linux or OSX (Or even Windows Vista/7) so what's the plan for these platforms? That's something I've never seen an answer for. This… is awesome. Well done all! Why that article so long? Just to explain "Core is not what you'll use in real Windows.NET"? Yiannis Berkos> This article… it does not reply to real world multiplatform challenges we are facing. That's because MS has nothing to offer! A whole article of blah-blah/open source/core/kernel/portable buzzwords, but nothing helpful to WPF/WinForms developers. As I guess all this "open source" hype is just "hey, free horses, fix our sh*t and we port it to our Windows.NET". I'd like to know a lot more about how the "System.Windows" and "System.Windows.Forms" .NET libraries will migrate to become cross-platform to run also on Linux and MacOS. Will these libraries be renamed to e.g. "System.NET.Forms" to remove the previous tie-in to the "Windows" OS? Who will develop and support the underlying presentation layer <-> OS bindings for Linux and MacOS? If we are talking about Linux, then which OS GUI(s) will be supported? Will X.Window manager, KDE, XFCE, E17, LXDE be supported for example? It seems to me that with over 20 different GUI/ Window managers for different Linux variants, it could be a difficult job for MS to support them all with a mapping to "System.Windows.Forms" or whatever its successor will be called. You guys are getting this all wrong, I don't see why you think MS is responsible to create platform everything, if they do great, but that's a giant ask kiddys, is it supposed to be better or at least as good as native on every platform, if it's not gonna be better like WPF then whats the point, the world is flush in second rate frameworks already, the key thing here is solid framework to base you app on then interop with whatever the targets best in breed native UI View, that is if you want to be world class right now, if you just want max reach for your CRUD or forms app switch to HTML5, this is meant for something way better then that, IMHO. Many great things, good to have a portable lean stack. Sounds great but you created one of main the problem yourself (starting 4.5) by not allowing .NET Framework to be installed side-by-side so applications could choose between 4.0, 4.5, 4.5.1, 4.5.2 in a shared environmement and by doing things like keeping the 4.0 as the displayed version number even if 4.5 is far from it and having a different CLR but same version and silent upgrading of the CLR on your dev machine just by installing VS 2012+ but can still target 4.0 but not really 4.0. Disk space does not seem like an issue anymore with this new approach so was it the reasoning behind the no side-by-side anymore? Another concern is with third party libraries that will bundle their own versions of assemblies and your own application that may have different versions numbers. Will that lead to something like having two System.Collections.dll files in your deployment folder? Little return of DLL hell? Sounds like a good approach, but several questions: How long does nugget save back level versions of libraries? If I have to do maintenance on a year or two old project, will I still be able to get the libs, or must I save them as part of my source repository? For those of us with no current interest in cross platform: You don't mention the WinRT stack. When will GDI and Win32 go away as a foundational layer for the .Net framework? Where do we go to find out info on the future path of WinRT and the full desktop? The obvious questions about the Road Map for the .Net Framework side of the house and the desktop are still out there. The info provided in "The Roadmap for WPF" is not much more than a list of bug fixes. This article at least outlines the plan for the .net core. We need the same for the .net framework please. Congratulations. You can really "feel" the maturity of Microsoft in the way decisions have been made to build this new .NET Core stack. I'm glad to see the direction you guys are going with more agile deliverables and per-app library deployments. However, I agree with the sentiment expressed by others that the desktop needs to be supported in .NET Core. At minimum this means console applications. I'd like to see MS develop a new, cross-platform UI technology that is not WPF and does not use XAML (which is a horrible, overly verbose language). There's a reason WinForms and WPF coexist after so many years- writing WPF applications is extremely powerful but overly complex. I also don't think WinStore/Metro apps fill this niche, as the sandbox these live in is not really appropriate for many enterprise apps and they're obviously not cross-platform ready. Perhaps HTML + Razor syntax (with C#) would work for a desktop technology as well as it's worked for ASP.NET MVC? I also have to say that MS really needs to lying about its support for "non-favored" platforms. It's clear that you guys are phasing out development of the .NET Framework proper, so you should be HONEST about that rather than giving empty pledges of ongoing support. Your developers have seen you do this over and over and over again- Silverlight, EF6, VB6 (just look at how many people are still angry at you after all these years!) You're not sparing anyone's "feelings" by telling these white-lies- it makes it hard for managers to make decisions about what dev platforms to use and it hurts developers careers by giving them false hope that their skill set will remain relevant without having to learn newer technologies. Tell people what support will really be like going forward for the .NET Framework- security fixes and critical bugs, with few if any new features. Now when you decided about .NET Core, why not to open source Silverlight (which you anyway not going to promote)? – The community can port its code to run on top of .NET Core and everyone will be happy. @Ron: How is moving away from COM based objects and the win32 based C API done on a large scale? The same as in small scale — very carefully 🙂 Seriously though, there is nothing wrong with using COM and Win32; in many cases they are simply the operating system APIs that we have to use to implement our libraries, such as System.IO.FileSystem. The key design goal is to keep the exposed APIs independent of the OS so that it's possible to support the same APIs on different operating system. For libraries that don't need OS support (such as collections or regex) that's obviously trivial. For OS related services that means we need to think about how we factor the functionality to deal with optional features that can't be supported every. The post provides the example of ACLs. @Thomas Levesque:. That's a fair point and I'm quite sympathetic to that view point. However, performing fundamental changes to a complex product like .NET is always a journey. Whenever we try to make too many drastic changes everybody loses because the chance of us getting it right is slim. That's why it's best to make the innovations in area that (1) immediately adds value and (2) is somewhat safe so that we can adjust if things turn out to be problematic. As explained in the post, the .NET Framework is a complex system but we're fully committed to move it forward. We understand that the current story isn't the addressing all the needs but we think of .NET Core as a stepping stone in the right direction. . @James S: WPF, System.Drawing, Windows Services on .NET Core For .NET Core we're currently focusing our resources to complete the support for touch based devices and ASP.NET related scenarios. We believe that we're currently serving our desktop customers best by investing in the existing, .NET Framework stack as this ensures that our investments are immediately consumable from existing code. For brand new code, such as immutable collections, we also make sure that it will work on top of the .NET Framework. @cjibo: So what about alternative platforms for distribution of .Net Core? NuGet is Windows Only. We're fully committed on using NuGet. Whenever there are limitations we believe it's better to improve NuGet than to build or leverage an alternative package manager. The reason being that dependencies across different package managers would be incredibly complicated to reason about. @Yiannis Berkos: Let's say that I want to create a desktop application targeting windows, mac and linux. How can this be done? I'm not aware of any plans to provide a cross-platform UI framework, if that's what you're asking for. In general, I don't think we believe in using the exact same bits on all platforms. From personal experience I'd say the goal of any successful cross-platform strategy is maximizing sharing while not compromising the experience due towards the lowest common denominator. So I'd say: think of your app as a burger, representing the layering. The bottom bun will require OS specific implementations, but we'll probably provide a good chunk of it. The top layer (UI) is also very likely to require leveraging OS/experience specific functionality. The beefy part in the middle represents your business logic and you should make sure you can share most of it across all platforms. OS specific concepts should be either pushed down or up (via inversion of control). Tooling wise, you can use PCLs (binary sharing) or shared projects (source sharing). There also additional tools which you can use to maximize sharing in the top layer. For example, Xamarin.Forms is a thin abstraction over the OS UI stack that allows you to share code that can be the same. It also allows to special case certain OSs. Does this help? @Craig .NET is already a walking corpse. I take this as a compliment as "The Walking Dead" is a pretty successful show 🙂 @Luigi Bruno: In 2012, after the Microsoft .NET Framework version 1.0, there was the Shared Source Common Language Infrastructure initiative: what are the main differences and improvements of making .NET Core released to open source if compared to that old initiative? I assume you meant 2002, not 2012. The Shared Source Common Language Infrastructure Implementation (SSCLI), also known as "Rotor" wasn't open source, it was shared source. Technically, open source means that the license is an OSI approved license. The .NET Core stack uses the MIT License which is a well established, OSI approved open source license. Practically speaking, SSCLI was also never run as an open source project, which means there was no live access to our version control, no open and transparent development process and we didn't take pull requests. On top of that, the license disallowed using the code to build a different product. @Michael: Now, another question in this regard and I haven't yet analyzed the dependency graph within .NET Core, but I'm assuming you will have dependencies between some of the packages? That's correct. Will you specify the upper boundary for your dependencies in the NuGet packages or will you leave it open until there is an actual breaking change that stops the next major version from working with the dependent package? Generally speaking, we always ship preview releases which don't commit on a final shape and will generally perform breaking changes between releases. By the time we ship a stable package we're fairly confident that there are no breaking changes. So we'll leave it open as we don't do breaking changes. If there are breaks, then we consider this a bug and rather fix the bug than to ship updated packages that limit the version range. The latter results in a game that the ecosystem can't win. @Dev: So basically WPF will die together with the old .NET Framework that will eventually be superseded by .NET Core? No. The .NET Framework doesn't die — it simply versions slower. You can think of .NET Core as the faster moving younger brother. @Stephen: You talk about cross-platform development a lot, but you can't deploy a windows store app to linux or OSX. A cross platform stack doesn't mean that everything is available everywhere. That's simply not feasible without a massive cost and/or compromising the experience in a fundamental way. Instead, cross platform means that you componentize the stack and for each component make it as broadly available as possible. Some components (such as the runtime) truly need to go everywhere in order to have a story in the first place. Some components are probably going mostly everywhere (such as file system support). Some components might only go to a few platforms (such as ACLs). And some components might only go to a single platform (such as WinRT support). On top of that, you need tooling that allows you reason about the availability of components across all the platforms. Your job as an application developer then is to factor your application according to the needs of cross platform. See my previous reply to Yiannis Berkos for more details. @Rob Sherratt: I'd like to know a lot more about how the "System.Windows" and "System.Windows.Forms" .NET libraries will migrate to become cross-platform to run also on Linux and MacOS. See my previous replies to Stephen and Yiannis Berkos. I'm not aware of any plans to provide a cross platform implementation for the UI technologies. I'm also doubtful that's what developers actually want. I think it's possible to provide a thing abstraction layer (such as Xamarin.Forms) but a true shared UI technology would be pointless. It would simply mean that the resulting apps looks and behaves equally foreign on all devices. @vibou: Disk space does not seem like an issue anymore with this new approach so was it the reasoning behind the no side-by-side anymore? It's tempting to think that way but that's actually (no longer) true. Many consumer devices, such as tablets or hybrid machines, have SSDs which, compared to regular disk drives, have a much more limited capacity. Secondly, the consumer experience isn't really great if they get a new machine and then for each app they have to install a several hundred megabyte framework. Also, each time we service it, NGen needs to update the native images which also binds CPU resources, depending on how many side-by-side frameworks exists. We could try to make our side-by-side story more sophisticated by allowing smart sharing between frameworks but that's actually as complicated as ensuring that the new framework is compatible. Also note that side-by-side doesn't mean we're out of the compat business either. At some point, you'll want to update to the higher framework anyways so we still need to invest in our compat strategy. That's why we came to the realization that at this point for the .NET Framework, in-place updates are a better story. However, we make sure that new components can be delivered in app-local fashion, even for .NET Framework applications. For example, immutable collections for .NET Framework developers are essentially side-by-side. Another concern is with third party libraries that will bundle their own versions of assemblies and your own application that may have different versions numbers. Will that lead to something like having two System.Collections.dll files in your deployment folder? Little return of DLL hell? While it's true that our NuGet components version independently a given application will only use a single version (the highest version required by any component in your application). We make sure that our components are always backwards compatible. Of course, there will always be cases where certain combinations don't blend well but that's why we also ship distributions which represent a set of components that are tested together and thus blend nicely. This will serve as the equalizer to minimize the different combinations that developers will encounter in practice. @pmont: How long does nugget save back level versions of libraries? Indefinitely. In other words, all version will be available forever. In fact, NuGet doesn't even provide any features to remove components from the server. If I have to do maintenance on a year or two old project, will I still be able to get the libs, or must I save them as part of my source repository? You don't to save the binaries in your repo. NuGet.org will still have the exact versions you used two years ago. Where do we go to find out info on the future path of WinRT and the full desktop? WinRT is a Windows technology, not a .NET technology. The Windows developer blog would be a good starting point. @MgSm88 You raise a bunch of good points. Of course, I can't promise that we'll not make any mistakes moving forward, we'll try really hard to be more transparent, open, and honest about our decision make process. However, you make one assumption that I'd like to debunk: it's easy to think from an outsider's perspective that we always have the perfect master plan that we simply don't share. That's not true. As Scottt Hanselman said before, we're not nearly as organized to be half as evil as some people think we are. The reality is that engineering is very complicated and takes a lot of time. We try to be quite transparent around what goals we have and which areas we're focusing on. So when I say "I don't know" or "I'm not aware of any plans" don't take this as the magic code words for "according to my master plan that's never going to happen". It simply means that I don't know and I'm not aware of any plans. Awesome work! Its a good time to be a .NET developer. Great job! Is there yet a list of what classes/namespaces that will be part of core vs not in core? @Meir: Now when you decided about .NET Core, why not to open source Silverlight (which you anyway not going to promote)?. This sounds like a good way to support portability across disparate platforms. As an iOS/Droid/MacOSX/WinPhone(WPF/XAML)/WinForms/Win32/Linux programmer, I look forward to being able to cross platforms more quickly, using a common codebase. Any plans for adding WinForms-like iOS/Droid/MacOSX/Linux modules to .NET Core? I could then use my favorite UI development stack (C# WinForms) to develop apps for all platforms (my favorites being iOS and MacOSX), with only minor re-tooling! Would it need to be done completely in the Mono space? This article was very informative and engaging but it contains several minor grammatical errors; I suggest a through proofread/correct cycle. Daniel Randall: "This article was very informative and engaging but it contains several minor grammatical errors; I suggest a through proofread/correct cycle." Did you mean to demonstrate by example ere? 🙂 @Immo Landswerth; As a cross-platform developer in C and C++, I'm perhaps more aware of what's available than the strictly C# Windows devlopers here are, so I'm glad to see Microsoft focusing on the "core" that the community needs, instead of inventing a new wheel. Having said that, I can sympathise with them wanting to be able to use what they are used to for developing software on new plaforms, but without a heck of a lot of effort from Microsoft and the Mono/Xamarin development teams, I don't see it happening soon. Great information, what a new direction for .NET application platform! What's the relationship between .NET Core and WinRT? Are .NET Core runtime and library built with WinRT on windows? Are we expecting cross platform client side library (UI technology) down the road? like Silverlight reborn for mobile and desktop client? First of all, thank you for answering our questions. I notice that .NET Native is always spoken of in context to .NET Core…are there no plans to bring .NET Native to WPF/WinForms? Never ever use #if. Use separate files with platform dependent code. Is there any plan to continue or open source XNA? It's still a much beloved framework to this day even as it ages. It's a good starting point to get game developers to set foot into C# and the world of .NET. I think it would be beneficial to the MonoGame project to make that code available for them to use. I need my nex web application to run in windows or Linux. I am concerned about how fast aspnet will run in Linux. Right now mono is very slow. I need something that will have a good performance.how long will we have to wait to test kestrel out in Linux? I may have to just go with Java if the wait is much longer… I think you should make some cross-platform UI, with VS designers support. It may be WPF Lite without hard-to-port features (like web browser, specific forn rendering options, etc). Without cross-platform, NET Core will be limited to console or ASP.NET 5 apps, and will not be popular. Do you plan to support android ? @Tristan: Check out Eto.Forms in the Visual Studio Gallery; it will do this now for .NET and Mono. Perhaps the author will add suport for .NET Core to it later on. Your post is benefited to my web developer. @Immo: Thanks for the details. It's cool that you plan on keeping breaking changes out of the major version increments, too. Best regards, Michael Awesome! Read the whole thing. I'm so exited to take a look at the CLR part when its released. I have couple questions: 1) Will any of this .NET Core stuff be used in .NET Micro? 2) What kind of memory constraints would .NET Core have? (Could it replace .NET Micro). 3) Will porting .NET Core CLR to other CPU types like MIPS, PPC ect be an easy task? 3.3) Will porting to asm.js/NaCl/WebGL for IE, Firefox, Chrome, ect be doable? How much of the CLR has CPU specific instructions? 5) Can I embed .NET Core and invoke the runtime like I can with "Embedded Mono"? 6) Will .NET Native be open sourced as well so we could port it to other platforms and CPU types? I like to speculate, is the reason you haven't talked about app ui's because you have something up your selves? Like open source and true cross platform DircertX which all ui will be based on? "…unable to accept pull requests…" worries me regarding how serious you are about open source worries me about the health and longevity of the project worries me that you're dumping .net, why should I bother with it when there are far more mature, open and versitile platforms around. I worked at MS as a dev long time back but now am all about linux/Java/JavaScript stuff. This makes me more excited about MS again. Good timing with "The Force Awakens" teaser as maybe the evil empire will awaken once again but this time, will be much cooler. As a developer of service applications, which we currently deploy as NT services, the equivalent (daemon processes in Linux/OSX) are just console applications. So support for Console apps gives us both the ability to write command line utilities on POSIX platforms, and the ability to write services on those platforms too. Heck, with a Console app we could implement FastCGI. Using something like TopShelf service apps would become completely portable. I appreciate you bringing ASP.NET but there are service applications that are not web apps that would really benefit from what you're working on. So if it's possible to keep the door open to making runnable console apps with the kind of performance we are hoping for, that would really let .NET explode into the POSIX world. Thanks! With .NET Core, on touch device, can the app has direct access to SQL server using SqlConnection? To be honest, this is way more confusing than just having a distribution release. Also any support for non-Windows platforms worries me as it indicates Microsoft is moving away from Windows OS. @Jens Larson: Why should Microsoft reinvent the wheel, when the Open Source community has already done this work? There are numerous projects that provide the "missing" functionality, if you know to look for them. @airtonix: There are two separate repositories; github.com/…/referencesource (the one he is talking about in the line you quote) and githup.com/…/corefx which they have fully opened to outside developers. Microsoft is not taking pull requests on the Reference Source simply because it is the past development and is being made available for the Mono Project to use to bring the two somewhat divergent implementations of .NET back together. .NET Core 5 is the future, and the open source development influence will make it into future releases of the .NET Framework, but in a somewhat more controlled fashion. @Alex: All this means is that Microsoft has realized that there is more to the world of computing, especially at the server level, than the Windows Server products that they've developed, and they are accepting that reality. It doesn't mean that they will abandon developing Windows, but it may mean that eventually they do what Apple did in the late 1990's and open up portions of the Windows Source itself, or something similar; Apple, with Mac OS X, proved that it was viable to utilize the open source community to build a strong platform under the GUI and still keep some proprietary elements. imo , your still missing the boat guys . the DX12 rewrite and TPL/opencompute should be coalesced , and dog fooded to hardware accelerate both OS internals and exposed for dev leveraging . that should have targeted/extended the WPF api and called winRT accelerating OS internals means graph data structures , processing , and C# language integration/extension Ok, I'm kind of late to the party but I wanted to really take my time and read the whole thing, plus the comments. I have a question I did not see addressed on the post or the comments. What will happen with native javascript/html5 windows store and phone programming model with WinRT? Will everything be sooner on the .net core? Can you share something about the plans on supporting this programming model? Hi together, thanks a lot for the detailed post. Was time to write something about your plans and what the core framework is. It is a little bit confusing to the people. They struggle with what the new core means. It is interesting to read what you are doing and how the teams are working. To explain the verticals and that there are several teams working on the different verticals was interesting, too. And I think, people aren't aware of the complexity and so the need for the core framework. I like to suggest some points in order to help the people understand what's going on in the .NET Framework and to keep them on the road with your plans and the technical possibilities as well as restrictions. Just to help them selecting the right things for their application developments and the help them mastering the complexity. Provide some more walkthroughs, text and video tutorials, small technical blogs and so on, just to explain what the core Framework is. Do it on a regularly base. Show people how to use the core and the full framework. Explain when they should use the one and when the other. Show/explain example use cases and applications for the core and the full framework. Guide them intensively and regularly. Do not only show what people can do. Show restrictions of the core and the full framework and show them what they cannot do with the one and/or the other framework vertical. Do it regularly. That's all! 🙂 Thanks a lot for all the great work! Looking forward what's coming especially on the other platforms! Hope to see a lot of the staff I like on Windows on the Mac and Linux in the future! 🙂 Kind regards from Berlin! Robin Ih Net Native will not use .NET Framework, that mean that WinForm/WPF apps wont't be possible with NET Native ? Please, give us ability to create Native (Portable) Class Libraries. <rant> Thanks. As a .net developer I'm glad I'm not 'legacy' anymore! That being said, it's getting too confusing to develop for MS platform. Right now when I open NewProject window of VS just to create a Store App I have "Universal App" option, "Windows Phone" option, as well as "Windows Phonge Silverlight" option. Apparently, soon there'll be a ".Net Core" option, right? It's hard to believe all these frameworks for the same platform aren't created by some competitor companies! Unfortunately what I read is this: "We are unable to produce a single framework for our one platform, yet we are going to provide a single framework for all other platforms including Mac and Linux". Please don't get me wrong. I love working with Microsoft platform and tools. I have tried 'eclipse', and 'netbeans' and they suck! I have used Android APIs as well as many firmware OSs. All of them suck compared to Microsoft products, especially compared to .net and VS. I absolutely respect the fact that Microsoft doesn't treat their programmers as crp like many other competitors(Google f.i.) by dumping on them crppy products and frameworks. I just wish one day the 'one' Microsoft dream becomes a reality again; to open Visual Studio and have that one yet best option for creating a Windows Phone project. .Net and C# was that option on desktop for years. Please bring us that one option for mobile and solve the confusion caused by too many incomplete choices. </rant> @Immo Landwerth – a couple of comments from the corporate WPF desktop trenches (major investment bank organisation) First and most importantly, the issue of in-place framework upgrades is a nightmare in this environment. We are still stuck using 4.0 because there are a couple of apps with 4.5.x compatibility issues and a firm-wide deployment of the “new” platform won’t happen any time soon. Our team must argue for commissioning non-standard workstation OS builds if we want to make use of 4.5/4.6 for our app, and this creates enormous friction within a large corporate as you can probably imagine. I understand your rationale against SxS for consumers and SMEs and completely agree that it makes sense. However, couldn’t you provide some kind of option to build and deploy a desktop app with the complete framework packaged in, with no “smart sharing”? We’d have to take the hit on disk space and load-time efficiency but those are trivial matters for us, while being stuck on an old framework version certainly isn’t. Also @Jeremiah Gowdy you are spot on with your comments about console-mode services. Our applications typically use Java on the middle tier for services of this type. If could use .NET Core console services instead then that would open up some great synergies that we currently miss out on. But in general, a big “way to go” to MSFT for this announcement; it’s a watershed point moment for .NET, no question. The problem with microsoft for the past lost decade has been that it has spent more time re-factoring than it has spent taking existing investment forward. This is yet again another massive re-factoring to put us where we have been stuck since WPF came out, only 10 years later. And now, just as winRT is in bad need of maturing to hopefully someday replace WPF, MS is yet doing another massive re-write and starting over yet again. Is it not indicative of all that is wrong with this approach the fact that we have two async patterns in winRT just because MS insists on starting from scratch all the time? However what is turly worrying about this is not that you'll do it anyways leading to yet another stack that will uncessfuly try to get .NET FX apps out of the established windows framework which is the one with 1.5 billion users, not your new thing. What worries me is that 3 years from now you'll do it again, and start over again with yet another stack because this one wasn't adopted outside of the asp.net folks and all this effort would have been better spent in the one thing every .net developer has been begging you to do: take existing .net, that is wpf, win forms, .net FX 4.5 and just let me make mobile apps with it using my existing code base. Scrap winRT forever as you did with silverlight and stop your internal cross teams wars. We already had a technology that worked until the windows 8 team decided for no reason to roll back the clock API wise 10 years, it and started over with a half baked framework that today has failed in the market. In trying to solve a problem which needs fixing: ASP.NET on linux, you're fragmenting yet again windows client development. Yet you're achieving nothing: client development is going to stay on iOS and Android's native stacks, and on the .NET FX for windows stacks. Why would anybody create these .net native apps based on .net core for mobile devices which won't run on windows 7's 1.5B install base? Better yet, you can only create them on winRT, which is pathetically inmature. All so I can share some logic between the app and asp.net's backend? who does this anyway? Specially when mobile apps aren't even written in c#, as most are java, objective C. The 1% of people who will care for this won't matter. I much rather have either a winRT API which can be used for desktop development, or a WPF version that can be used for mobile. If the price for that is that my .dll doesn't always work on some server backend, so be it. Yet most of the time, as long as you develop for mscorlib you're fine, and if your linux variant needs #if statements via the shared project way, so be it. How about merging all the verticals into one common core that doesn't change much? No forking, no compatiblity issues, less disk space in the long haul. Maybe call it ".net one". @Immo First of all let me say that I'm really excited about the whole .net core thing and your move toward open source. Neverthless I have to disagree when you say: ." Well, I think you missed the point here. Silverlight is a killer technology for building in-browser front-ends for line of business apps. I mean, productively. With C#, LINQ, and a predictable layout system designed for apps, not documents. Sure it has its flaws, but for the needs of a typical LOB application it's like WPF (cool) without the need for the full-blown .net framework, easily consumable through the browser, even on Macs. Now, you may have different plans for the future of the UI side of the .net story, but why not letting other people which are still interested in Silverlight take over the project? You don't have to participate if you think it's not worth the effort. It's not like getting free labor. It's letting the community decide wether the platform has to die or not. Maybe it still will. Maybe not. Will the CoreCLR provide the same Profiling API as the .NET Framework (msdn.microsoft.com/…/bb384493(v=vs.110).aspx)? Will it be part of the open source code as well? if you think you are "maintaining great interoperability " without the abilty to Wrap WCF services with MEF contacts interop will be degraded greatly, given the detail of the post and the question being ignored on every MSDN thread. I hope I'm wrong, @immo please tell me I am. I get the sick feeling I'm not. kind of makes the whole thing pointless if your not gonna include the best pieces, I wouldn't blame you, WCF and MEF are jewels, I don't see anyone else giving away there best stuff but it would instantly open up so many options. :{ I am really happy with the new path of the .NET team. Is there some chance of that the .NET Native Compiler generates native codes for non-windows platforms? It will be great to use C# as really an evolution of the C++. 怎么都是英文呀, 我来几句中文,不知道能不能展现! @hi @immo, I looks pretty difficult to do anything with .net core, so count me in !,LOL first trip down the rabbit hole ended at EventDescriptor.cs need InternalSR.ValueMustBeNonNegative found it here stangelandcl/pash-1/blob/master/External/System.ServiceModel.Internals/System.Runtime/InternalSR.Designer.cs ? looks like 15 other modules reference the InternalSR class as well, in the referencesource-masterSystem.ServiceModel.InternalsSystemRuntime vs in the mystersoius stangers path,LOL I am super excited about the direction of .net. You guys are just in the nick of time. When I look at new startups and a lot of fast growing companies, I see a lot of Ruby, Python, and a lot of other open source tech. Consumer facing app dev seems to revolve around open source a lot more than enterprise LOB app dev. By fully embracing an open source path, I think you'll be keeping ASP.NET (and .net in general) relevant for a very long time. It's always nice to read about the future of the .NET stack. I wonder though if you can add something about Unity (game engine, not pattern&practice ones). I understand that it probably depends only on Unity Technologies decisions and one should ask them indead, but if there are any plans on MS side about it, could you mention them, please? This is a fantastically succinct and articulate overview. 5 stars for content and clarity. Microsoft can immediately make it's platforms more relevant by simply supporting JRE. Today, migrating Android apps to Windows Phone is a major re-architecture. I realize Dalvick isn't a pure Java runtime, but it's closer than .NET. From my viewpoint, .NET is just Microsoft's version of a JRE. This basically tells us, .NET Framework is in maintenance mode, use .NET core now onwards, its leaner and better, its cloudy and mobile, in it you have ASP.NET which is your cross platform solution you can stick into Windows, Mac or Linux and use everywhere there is a browser, and you have .NET native which is native to Windows, and will work great with our One Microsoft vision, that means you will have specific little .NET verticals, which will all share the same BCL, be supported on whatever new shiny device we may spit out ranging from tiny micro boards to classic desktops and all the mobile jungle in between, and all that in a great to code by Modern Async Azure enabled Universal app model. And the rest of it is legacy maintenance enabled. I salute you! Now you may innovate some more. As Microsoft move away from supporting .Net and leave it to open source, why do they still refuse to open source the VB6 programming language ? How does this impact the micro framework (embedded devices)? I seem to spend way to much time, effort and money chasing Microsoft's next big idea, only to see it thrown out by the time I learn it and finish my first project. Then the cycle repeats. This gets old… Cuando ya creía que lo sabia todo… los dioses me cambian las reglas. No acaba uno de asimilar las nuevas tecnologías, cuando ya aparecen otras nuevas e indudablemente mejores. Pero para poderlas dominar se requieren también buena documentación. Dada la gran variedad de dispositivos y sistemas operativos, se debe contemplar realmente que las aplicaciones escritas desde Visual Studio tengan funcionalidad en Windows, Linux, OS X, iOS, Android, eso si sería una gran novedad. Porque de otro modo esto se esta asemejando a una torre de babel donde la comunidad informática será confundida. Its good to see MS taking such nice and useful initiatives. technologically all fine with the latest steps by ms / .net. but pleeeeease stop this ms-wide bullshit spree by using the word "experience" as often and as senseless as it gets. example here: "You can think of portable class libraries as an experience that unifies the different .NET verticals based on their API shape." Do we still need care about CLR version ? It's late from my end but really wish to congratulate MS. Glad to hear about this release. In overall, .NET is like the rest. It becomes a garbage. There is no clean direction. Even C# become a garbage. Microsoft need to separate the real Core, the language, and Microsoft products. Things like integration of Entity Framework in .NET is the best example of what I call garbage or ASP.NET MVC with Razor. .NET Core is just a helper of what developer don't understand on programming. I suppose this is useful for someone. But not me. Guess you have a target audience somewhere. Not here. This is awesome stuff, but I think if you really want to knock the socks off of people… Adapt WFP to run on Open GL or DirectX and build it to support linux and mac… It would (imo) be the best cross platform UI system to ever hit the streets. open sourcing silverlight is the next step :=) This announcement excites me most because if it comes to be and gains some production worthy reputations, I can finally do everything the JRE guys are doing but with .Net, and with a better IDE (imo) than Eclipse or IntelliJ… I can't wait to go up to the senior architect and show him a website running on apache in linux and go through the conversation… "So you finally moved to Java huh" Me: "No actually, it's .Net" "Oh so Mono….." Me: "No it's actual Microsoft .Net code" "Huh… it's a windows only platform, how can that be?" Me: "No, .Net Core 5 runs on Mac, Linux, and Windows, they went cross platform with the .Net Core 5 release." "Woah seriously?" Me: "It's also compiled to native machine code" "What????" I'm not nearly as excited about this announcement and .Net Native's announcement as I am for what that will bring us in the future. I can fully see a WPF version that sits on top of Open GL as opposed to DirectX (seeing as IE 11 already implemented WebGL), that could also bring us WPF browser support in the future should that come to be. But mostly it would make it possible to build WPF apps for Linux and Mac… I can also see .Net Native supporting Class Libraries, Windows Forms etc, and opening up a whole new can of worm's for AAA game development platform choices and seeing games come out built on .Net but compiled with .Net Native. E.g. Imagine if XNA Framework got picked up, converted to work on Open GL or DirectX, and then supporting .Net Native compilation? So to me, this news, is the basis for good things to come. What I didn't get yet is… will this .NET Core be a new version like 4, 4.5.1, 4.5.2, 4.6.0 etc, but the version here is "Core 2015"? Will it make the application has all its dependencies inside it, without forcing the user of that app to install .Net Framework on his machine? And it is not only about porting applications horizontally. It's about having to learn the singularities of every vertical stack when you think that you can program in C#. Good job. What work has been done to add better integration of .NET and apache on the windows platform? One thing to notice is the effort to discover the package. Say originally, if I used "List", I can "Alt+Shift+F10" to discover the namespace to import. And if the nugetalizing means I need to remember which nuget the "List" is in, that will become ridiculously annoying. Aaah finally my platform is cross platform.Thx Satya Nadella "…we’ll make .NET Core great for Windows, Linux and Mac OSX"… I've heard that before, minus the "Core". Thanks to you we're still struggling with silvers***e. I can't believe you will still continue to make changes to the .Net Framework. That sounds super redundant.. Good luck.. sherazlodhi.blogspot.ae/…/what.html @MustBe: The .NET Framework is in use on a lot of existing hardware, including the latest Windows 10 machines, so it makes perfect sense for them to maintain it in parallel with .NET Core. Also, .NET Core is in nearly constant flux at this time, so having a stable system for mainstream users makes more sense than subjecting them to the potential issues that simply dropping support for .NET Framework would cause. I am not clear about Microsoft's strategy for internet of things and support for devices like Raspberry Pi. Is there a future for .net Micro Framework? Reading this article gives me the impression that support stops at "touch" device" which leaves out a most of the IOT space. @Christopher I don't think so – Mac users mostly dont want to use anything non-conforming absolutelly to their UI. And also, imagine WPF as first golive prototype of totally new GUI approach (against Win32), heavily bound to full NET Framework, then Silverlight as second golive prototype based on WPF features stripped down enough to be useable in browser (in fact SL = CoreCLR +native "agcore.dll" UI renderer/eventing), then axing Silverlight (because of outside world too, though), so now opensourcing CoreCLR + part of BCL + AOT compiler + targets binding (devices, web/owin) as ".NET Core" … so "agcore.dl" part of SL was at least partially baked/rewriten as again stripped-down FINAL WinRT UI using enhanced COM-binding (reflective by any langunage, so JS too) … that's all because devices are constrained by battery power, so any heavy VM overhead si not good here (both CPU/RAM). …During last few years, we was helping to test their prototypes, in fact 😉 … as portable options for LOB, "Xamarin.Forms" seens to be good enough (databinding concepts similar to SL) and even more portable is "MonoGame/XNA" (and mono runtime used by these will by continuously replaced everywhere by .NET Core with MS support, it seems) Thanks MS. I never thought this would happen someday. Ultimately, you are back on the right track. If you are creating a "native" exe, i.e. windows, linux, osx etc,.. than how can you run in different kernal.. then how is it cross-pathform ? did you mean that you need to create different exe for specific platform? And in that case, who gurantees that the all the other framework are same ? for e.g. templates/algorithms/ os thread scheduling/context switching .. and optimization due to that.. –given this, it is almost impossible to have exact same behavior even if you compile for each platform… unless you are running your code in VM, then it can not be native All this cross platform awesomeness… Any plans to make PowerShell work cross platform against .Net Core 5? I don't think it would be to hard, people would just have to remember that only so many cmd-lets are available on Core 5. I would LOVVVEEEE to be able to leverage powershell cross platform for all kinds of things, even as a video game developer console. E.g. Copy-Item -Path $filePath -Destination $destPath Could work and do the copy on Linux, Mac, and Windows. But things like the windows registry provider and various other windows specific things wouldn't be part of the Runspace and not in the Pipeline. Good plan. Bad and confusing implementation. Core has ASP.NET 4.6 and ASP.NET 5. Why two? Can the core by Core and talk about ASP.NET? Please have a look at the following question regarding the feasibility of deploying a WF application to Linux: social.msdn.microsoft.com/…/workflow-fondation-on-linux Very helpful and well written introduction – thank you. very nice Very interesting. Thanks The .NET Core is so limited it is better to call it .NET Utilities @FM You say limited. What in particular are you missing? Good knowledge sharing…. Thanks for introduced new concept of .NET… .NET Core it's cool ! it's cool fine how to download .net soft ware and how to use it that is repeated twice in this sentence. 'The mscorlib provided by the .NET Framework contains many features that that can’t be supported everywhere (for example, remoting and AppDomains).' Great but we also need this? visualstudio.uservoice.com/…/8912350-bring-windows-10-universal-apps-to-android-and-ios Bring. Hi, while researching these days about rendering of WPF and SL and rewritten GDI and Direct2D and everything related to MILcore and my loved AgCore part of SL which has potential to run everywhere already, I can only point you outside to peek whats all possible – Embarcadero did thing FireMonkey and they do something native accross platforms by this; not knowing more and still learning to know also this part of world little bit, just now you can join theirs c++ bootcamp too: (truth is their IDE is anything but fast, as was usual all the time despite the native code; but the new FMX thing is interesting somehow) i wonder whether or not .net core will available for plesk panels ? Helped – thanks I just like the helpful info you supply to your articles. I’ll bookmark your blog and test once more here frequently. I’m moderately certain I’ll be informed many new stuff proper here! Best of luck for the next! NO ONE IS AS BIG AS MS Another innovation from MS. One of my dream comes true. Very well explained. Covered almost every topic of basics. Its a great help to me. Thanks for sharing 🙂
https://blogs.msdn.microsoft.com/dotnet/2014/12/04/introducing-net-core/?replytocom=34063
CC-MAIN-2018-34
refinedweb
9,742
74.29
Aflați mai multe despre abonamentul Scribd Descoperiți tot ce are Scribd de oferit, inclusiv cărți și cărți audio de la editori majori. The Erection Master By: Christian Gudnason Table of Contents How To Use The Program 4 Part 1: PC Muscle Exercises 5 PC 1: Pumping the Front 7 PC 2: Pumping the Back 8 PC 3: Lifting the testicles 9 PC 4: Fluttering 10 Part 2: Abdominal Exercises 11 Abdominal 1: Contract Relax (not pictured) Abdominal 2: Pelvic Tilt Abdominal 3: Quadruped Bracing Abdominal 4: Modified sit-ups 12 Abdominal 5: Bilateral leg lift Abdominal 6: Spiters Part 3: Low Back Exercises 13 Low Back 1: Knee Pulling Low Back 2: Butt Lifting Low Back 3: Back Stretching Low Back 4: Chest Clasping Part 4: The Five Exercises From The Himalaya 14 Lama 1 16 Lama 2 17 Lama 3 18 Lama 4 19 Lama 5 20 Part 5: Walking 21 Part 6: Breathing Exercises 22 Breathing 1: Relaxed breathing Breathing 2: Exhaling All The Air 23 Breathing 3: Breathing Through Mouth And Nose: 24 Part 7: Psychological Exercises: 25 Psychological 1: The 1-2 Rule: 26 Psychological 2: Positive Talking 27 Psychological 3: Realize Your Joy: 28 Psychological 4: Talking Things Out: 29 Part 8: Relaxation Exercises: 31 Relaxation 1: Doing Nothing: Relaxation 2: Relaxing Step-By-Step 32 Part 9: Awareness Exercises 33 How to Practice the Awareness Exercises Single Awareness Exercises 35 Single Awareness 1: Exploring Your Pleasure 36 Single Awareness 2: Spreading the Sexual Energy 38 Single Awareness 3: Rocking the Steps 39 Single Awareness 4: Rocking the Steps, Part 2 41 Single Awareness 5: The Reverse Focus 42 What to Do Next As a Single Master 44 Partner Awareness Exercises 45 Discussing and Setting the Rules 46 Partner Awareness 1: Exploring Each Other 47 Partner Awareness 2: Pleasuring Her 51 Partner Awareness 3: Partner Reverse Focus 54 Partner Awareness 4: Penetration 56. These are probably the most important exercises in the program. About 40% of those who suffer from erection dysfunction regain complete sexual strength by only practicing these exercises. That is as many as benefit from using Viagra and other similar drugs. To begin the PC muscle exercises, let’s go over just what the PC muscles are and why they are important. What Are the PC Muscles? The PC muscles are your internal pelvic muscles. The PC muscles are between your butt bone and your pelvic bone. It’s easier to understand this muscle by feeling it from the inside. Have you ever tried to stop urinating in the middle of a flow? Or tried to squeeze that last little bit out at the end of your pee? Your PC muscle is what allows you to do that. Next time you go to the bathroom, give it a try. In fact, you could go ahead to the bathroom right now to try it out so that you have an understanding as you continue reading. See how strong your PC muscles are now. Do you have little control or a lot of control? The difference between front and back PC muscles In the PC muscles exercises you'll be practicing two kinds of PC muscles. ∑ Front PC muscles (drawn in blue) ∑ Back PC muscles (drawn in red) This is the same muscles-group so it's very understandable that you have trouble making a distinction between the two. Later in the program when you do the testicle lifts and other techniques, you use both muscles. Think about it like two ropes. One loops around the genitals (both the penis and the balls) and then runs half way down to the anus. These are the front PC muscles. The other loops around the anus and then runs half way down to the balls. These are the back PC muscles. Their function is different too You use the front PC muscles when stopping an urine in a middle of a pee. You also use the front PC muscles when forcing out the last drops after you are done. You use the back PC muscles when holding in crap until you can get to the toilet. Think about the worst diarrhea, pushing to get out, but you have to hold on to it while running to the toilet. Then you're using the back PC muscles. It takes a while to get the feel for which muscles you're using so don't worry about it in the beginning. Where to practice? You can actually perform the PC exercises virtually anywhere. you do not have to be naked (although loose or comfortable clothing will make the exercise more comfortable). Onlookers will not be able to tell what you are doing. And since you cannot overwork your PC muscle, you can practice it pretty much anytime you think of it; in the shower, in the elevator, on the car ride to work. While it doesn't really matter when or where you practice, you may want to set up specific times or circumstances where you do, that way you have a routine and you are less likely to forget to practice. So use the flexibility of training the PC-Muscles and Practice these exercises as many times a day as you can. PC Muscle Training You are going to want to practice PC-Muscles exercise 1 and 2 first. When you feel you have mastered them, then you can move on to PC-Muscles exercise 3 and 4. Take your time; do not try to rush through the program. As with many other exercises, you will want to take this one in stages, starting out slowly and holding for longer and longer as you build up your muscles. Think of it like crunches or sit-ups; you don’t start out with un-toned abs doing 100 crunches at a time, do you? So, begin by: ● Perform quick flexes by squeezing and then releasing the muscle. Do this in repetitions of 20 or so each then work your way up to 30, then 40, 50 and eventually 60. If you are doing 60 or more easily you can move to the next step. ● Slow down the flexes and hold them for about 2 to 3 seconds each time before releasing. Breathe in on your flex and out you’re your release the flex and relax for 3 seconds. Continue building up your repetitions the same way. When you can comfortably do this for 6o times in a row, then you can move on to the next stage. ● NEXT stage Slow the flexes even more by holding for 6 or 7 seconds. Then you will want to relax for 6 seconds. When you can do this for 60 times in a row, then you can move on to the next stage. ● NEXT stage… Finally, train your muscle to hold the flex for 15 seconds or so. Relax for about 6 seconds after the flex. When you can do this for 60 times in a row, you can move on to the next exercise. Don’t forget when performing this exercise that the release is as important as the flex. In the beginning, when your flexes are quick, you will not notice the rest as much but once you’ve moved on to 2 or 3 second flexes, you should be having 2 to 3 second rests in between and so on as you move up. Because the PC muscle comes around the coccyx and the anus, past the privates and up to the pelvic bone, there are different areas of the muscle to train. This exercise deals with contractions of the muscle around the sphincter. This exercise is pretty simple. Think of it like when you are trying to hold a bowel movement; you’re dealing with the same muscle here. Take a half breath and push the air from your lungs down. Focus on your sphincter and tightening it as firmly as you can. You may feel like your anus is pushed outward slightly. You’re going to want to expand this contraction around to your genitals. At first you will want to practice holding the tightening for 3 seconds on each contraction. Try this in repetitions of 20 or so and work your way up to 60. Next, you will try holding the tightening for 7 seconds and work your way up to 60 times in a row. Last, move up to holding it for 15 seconds and work your self up to doing this for 60 times in a row. When you have mastered exercises 1 and 2 for 15 seconds, 60 times in a row, you can move on in the program to PC Exercises 3and 4. If you can find the time, it is best to also keep practicing exercises 1 and 2 even if you add exercises 3 and 4. When you are about to ejaculate, your testicle “lift” or are drawn up to your body. This exercise will help you learn to control that effect and you can control your arousal as you want to. You may want to try this one sitting, or standing with your legs spread slightly apart. You might also want to do this one naked at first so you can actually see the testicles lift. This PC exercise is way more difficult than the two PC exercises before since you need to use the front and back of your PC muscle. That’s why it’s important to get good at the first two PC exercises first before moving along to this one. Begin by holding for 3-5 seconds and then releasing. Try this for about 20 times in a row. You may want to cup your testicles with your hand so you can feel it at first. Work your way up to 60 times in a row and then move on to the next step. When you feel comfortable with the above steps move up to 7-10 seconds of holding. Do this for 20 sets or so and work your way up to 60 times in a row. Then, you can move on. Now you will work your way up to holding for 15 seconds and move on at each stage until you can master 60 times in a row. This is a variation of the first PC muscle exercise (PC-Muscles Exercise 1: Pumping the Front). It is basically the same concept of flexing but you are going to want to do it as quickly as possible in a fluttering motion. With this exercise you will learn to squeeze and release very quickly over and over again. Repeat these flexes for as often as you can until the point of exhaustion. Each time you practice the exercise, you should be able to go a little longer than the time before. Exercising the lower abdominals is very important to balance the blood/energy flow to and from the genitals. Practice as many of these exercises as you can every day. You can do the Contract-Relax several times a day, even around people without anybody notising. This is a very easy but effective exercise. It’s as simple as it sounds: tense or contract the lower abdominal muscles as though you’re trying to brace for a punch to the abdomen and hold for 5-10 seconds or as long as you can comfortably do so, then relax for 10 seconds and repeat for 6 repetitions (up to 2 minutes). Build to five minutes at a time. Be sure to try to breathe comfortably throughout. To retrain the lower abdominals to work in conjunction with the lower back and open the energy flow, lie on your back with knees bent and feet flat on the floor. Feel free to support your neck with a rolled up towel if that’s more comfortable. Start this exercise with a neutral spine--i.e. if you put your hand just below the small of your back you should feel about an inch of space between your back and the floor. Without contracting the gluteus (buttocks) muscles or pushing your feet into the floor, focus instead on tensing the abdominal muscles to slowly tilt the pelvis backwards. Exhale as you press the lower back into the floor (which will rock the pelvis back) and inhale as you release the back and pelvis to neutral spine position. Repeat for 2-3 sets of 12-15 repetitions. IF you want to provide a little support for the abdominals, wrap your arms around your mid-section and pull slightly inward with your hands to act as a brace. Abdominal 3: Quadruped Bracing This exercise is a great one that combines upper body with core (abdominal and lower back) stability. Position yourself on hands and knees (feel free to place a towel under your knees to provide more support) with hands directly under shoulders and knees under hips. Keep the head neutral, looking straight down at the floor but not dropping below the level of your spine. On an exhale, gently raise your knees 1-2 inches off the floor, hold for 3-5 seconds, then replace the knees to the floor and repeat 8-10 times. Avoid lifting too high or this will be quite easy. Concentrate on tensing the abdominals and making both sides of the body work at the same time. Lie on your back with your hips and knees comfortably bent and your arms folded across your chest (easier) or clasped behind your head (more difficult). Keeping your eyes focused on the ceiling. Clench your lower abdominals as you raise your shoulders and chest 4-6 inches off the floor. Do NOT tuck your chin. Slowly return to the starting position. Lie flat on your back, legs fully extended and tuck your hands under your lower back. Keep your pelvis tilted up and back into the floor. Clench your lower abdominals as you lift both legs off the floor approximately 8 inches and hold them there for 3-5 seconds. Lower both legs to the floor. Keep pelvis and lower back tilted into the floor at all times Lie on your back and clasp your hands behind your head. Bend both knees and raise them towards your chest. Raise your neck and shoulders off the floor. Simultaneously move your right elbow and left knee towards each other while keeping your head, shoulders, and legs off the floor. Repeat with your left elbow and right knee. Never allow shoulders or legs to rest on the floor. Like the Abdominal Exercises, the lower back exercises will balance the energy/blood flow to the genitals. Practice as many of these exercises as you can each day. Lie flat on the floor in a relaxed position. Bring your right knee toward your chest, clasping your hands around the knee. Pull your right knee toward your chest firmly and, at the same time, forcefully straighten the left leg. Hold for three to five seconds. Relax tension. Do five times. Repeat same procedure with opposite leg. Repeat five times or as recommended. Lie on the floor with your knees bent, feet flat on the floor and arms at your sides, palms down. Tighten the muscles of your lower abdomen and buttocks so as to flatten your low back. Slowly raise low back and buttocks from the floor and hold for five seconds. Relax. Do five times or as recommended. Lie on your back with your knees bent, feet flat on the floor, hands at your sides, palms down. Tighten the muscles of your abdomen and buttocks so as to push your low back flat against the floor. Hold for three to five seconds, relax. Do five times or as recommended. Lie on the floor with your knees bent, feet on the floor and arms at your sides. Bring both knees to chest, clasping hands around the knees and pulling firmly towards your chest. Hold for three to five seconds. Relax tension. Do five times or as recommended. These exercises where first discovered by the Lamas in the Himalayas and brought to the western world early 19 th century by an English Gentleman who served over there. These exercises where believed to be the bringers of youth. I'm not sure if that's true, but I know they have been proven very effective when fighting erection dysfunction. The exercises are very simple to work, anybody can do it no matter what kind of physically shape they're. One of the main cause for erection dysfunction are blocks of blood flow around the genital area and the legs. The main thing these exercises do is increase the blood flow in this area. They will also increase the energy flow throughout your whole body and help deal with some secondary causes for erection dysfunction like high blood pressure and over weight. There are however a few simple guidelines you've to follow 1. Take it slowly in the beginning and work your self up to more little by little. There is no gain in pushing your self in the beginning and then ending up getting hurt or giving up. Do only what feels comfortable to you. There is no hurry. 2. For the first week, begin by doing only the first exercise, three times each day, and only if you experience being completely comfortable doing this. If you feel too dizzy or tired, practice the exercise slower or fewer times. Then add more as your strength grows. 3. Add exercise two the second week but again only if you experience being completely comfortable doing it. Begin doing it 3 times a day and then add more as your strength grows. 4. In the same way as before, add exercise 3 the third week, exercise 4 the fourth week and exercise 5 the fifth week. If you need more time, take it. 5. All the exercises will most likely be hard in the beginning. Don't worry about doing them perfectly. If you can only lift your thighs when you do exercise 2 for the first time, then that's what you'll do. Little by little your strength will grow. 6. 21 is the maximum of each exercise you ought to ever do. If you want to enhance your program, do the exercises at a faster pace, though do not so more than 21 of each exercise each day. Doing more than 21 repetitions of each exercise in any day will overdo your metabolism and is capable of creating imbalances in your body. 7. Do the Five. 8. For maximum benefit, do the exercises before breakfast in the morning, if at all possible. If this is not possible do them anytime during the day except make sure you do NOT do them less than 3 hours before going to sleep. 9. The "Five exercises" are very powerful and may stimulate detoxification and sometimes create some unpleasant physical symptoms in the beginning. This is why it is recommended to increase the number of each exercise gradually on a weekly basis. 10. It's essential you've enough energy when doing these exercises. Try to have 3 good meals a day and then some fruits in between. Eating healthy has also been proven to eliminate big part of erection dysfunction symptoms. That's enough of talking, lets get down to the exercises: The first exercise, is a simple one. It is for the express purpose of speeding up the metabolism in your body. It'll also synchronize your balance system. When we were children we used it in our play. It is this: Stand erect with arms outstretched, horizontal with the shoulders. Now slowly spin around 2-3 times, or until you become slightly dizzy. There is only one caution: you must turn from left to right. In other words, if you were to place a clock or watch on the floor face up, you would turn in the same way the hands are moving. Take it very easy in the beginning. 3-6 slow spins is plenty the first days. Speed is not important. As you master this exercise, add more spins but only till you get to the point of slight dizziness. Then sit down and relax for a while before you do anything else. Breathing: Inhale and exhale deeply as you do the spins. After you've mastered this exercise (and it may take years), you could spin with full force 21 times without feeling too dizzy. I recommend limiting it to 12 times tough. Like Exercise Number One, this second one is for further stimulating the Metabolism and the energy flow in the body, especially the genital area. It is even simpler than the first one. In Exercise Number Two, you first lies flat on your back on the floor or on the bed. If you practice on the floor, use a rug or blanket under your self, folded several times in order that your body will not come into contact with the cold floor. Then place the hands flat down alongside Exercise all over again. Breathing: Breathe in deeply as you lift your head and legs and exhale as you lower your head and legs. In the beginning you may be so weak, and decrepit that you can’t possibly lift up both your legs. Don't beat your self up Start out by lifting your thighs until the knees are straight up, letting your feet hang down. Little by little, however, you'll be able to straighten out your legs till at the end you can raise them straight with perfect ease. The third Exercise should be practiced immediately after practicing Exercise Number Two. It, too, is a very simple one. All one needs to do is to kneel on the floor, place your hands on your Exercise all over. Breathing: Inhale as you arch the spine and exhale as you return to an erect position. Begin by doing this exercise only three times and then add more as your strength grows. The first time you try exercise four, it may seem very difficult, but after a week or two, it'll be as simple to do as any of the others. Sit on the floor with the feet stretched out in front. Then place the hands alongside the body. Now raise the body and bend the knees so that the legs, from the knees down, are practically straight up and down. The arms, too, will be, tense every muscle in the body. This will have a tendency to stimulate your soar muscles and get the metabolism going again in them. Breathing: Breathe in as you rise up, hold your breath as you tense the muscles, and breathe out fully as you come down. In the beginning you may feel that unless you can perform this Exercise perfectly, right from the beginning, no good could come from it. That's totally wrong. When starting out, you may just barely be able to get your body off the floor; and not anywhere near a horizontal position. Do the best you can and see just what happened in a month’s time. The results will be more than gratifying. The best way to perform this Exercise is to.. Breathing: Breathe in deeply as you raise the body, and exhale fully as you lower the body. Before the end of the first week you practice this exercise, it'll be one of the easiest ones to perform. If you're overweighted, tough, and have trouble doing this exercise, you may want to skip it for a while and work the other harder till they begin to burn your weight off (and they'll quickly). Please do not underestimate this exercise. I have had clients cure their erection dysfunction in less than a week by only going for a 20-30 minutes power walk every day. Two things happens when you go for a power walk outside: 1. You load your body with fresh oxygen. Erection dysfunction is caused by lack of oxygen filled blood in the penis, so walking outside is extremely important for you. 2. Nothing gets the circulation around the genitals going as well as walking. Most people do not walk enough. To make it clear, I'm going to repeat the directions here: Take a 20-30 minutes power walk every day! Walk as fast as you can. Put power in your steps and swing your hands. Act as frisky and energetic as you can. If you have to fake it, then fake it till you make it (it won't take long). As I talked about in the “Walking Part” of this program, lack of oxygen filled blood in the penis is one of the main cause of erection dysfunction. Another common cause for this condition is stress and anxiety. These breathing exercises will fill your body with fresh oxygen and relax it at the same time. You can practice these exercises whenever you want, especially if you're in a stressful situation or shortly before having sex. The following exercise will teach you how to relax your breathing and to relax your body and mind through deep-breathing techniques. You can practice this breathing exercise virtually anywhere but you may want to start in a calm and quiet place the first few times till you have gotten the hang of it. As we mentioned before, you do not want to be distracted or interrupted. You can perform the breathing exercise one of two ways; sitting or standing. You could try both and decide which works best for you and use that position in the future. ● Begin by taking a deep breath and relaxing your mind. ● Take a moment to focus on your natural breathing rate. ● Now take a deep breath in through your nose and hold it for a few seconds. ● Now release your breath slowly through your mouth. ● Repeat this process slowly, picturing your stomach filling like a big balloon full of air. ● Imagine the air circulating throughout your body, making its way through all your organs. ● Continue your deep slow breaths. As you breathe in deeply, imagine the air relaxing all of your body parts. Do this for as long as you feel like. You may even want to practice it several times a day or any time you are feeling high stress stages. Once you learn this deep breathing method, you can combine it with the other body relaxation exercise, such as relaxing step by step or doing nothing, and to truly reach a deep, relaxed state. Most of us never exhale a big part of the air out of the lungs. By not exhaling completely, your breathing will be shallow and inefficient. You will not be able to fill the lungs with new fresh air and you don't get enough oxygen. We hold on to a lot of tension in our body by holding onto the air in the lungs. Of course you will never be able to empty the lungs completely, but holding onto too much air will prevent you from relaxing and getting enough oxygen. This exercise will help you empty out your lungs, making space for new fresh air. By doing it a few times you will probably notice your breathing becoming more efficient during the day, and night. Bend your body very slightly forward, as if you are about to bow, while exhaling all the breath you have, so your lower abdomen is completely sucked in. Normal longs and diaphragm As you bend over a little let the diaphragm press all the air out of the lungs As soon as the lungs are emptied, straighten up again and let the diaphragm suck the air into the lungs As soon as you feel that you have emptied all your breath, straighten up again while taking an easy and smooth deep breath on an imagined round "ah" sound. Be sure not to inhale too much, as it will make your body rigid. Repeat this exercise six or seven times in succession, once or twice a day. Make sure you don't overdo it. If at any point you start feeling dizzy, stop the exercise and wait a few hours before you do it again. This is an exercise you can do any time during the day, when you feel tension in your body, or emotions you want to get out (like if you need to get frustration out of your system). Sit down. Keep your back straight. Simply breathe through both your mouth and nose at the same time and feel how your breathing passages open up and the energy from overload of oxygen is filling you up. Start by using your belly to breathe like you did in "Exhaling All The Air". Then move your breathing up until you use your shoulders to breathe. Then let all the air out through both your nose and mouth the same way. Start by letting the shoulders breathe out, all the way down to your belly breathing out. Feel how you relax. Repeat a few times. Breathing in and out, through both your nose and mouth at the same time will do two things. You will take in twice the oxygen than only using one gap, and you will completely relax your body and get rid of built up frustration. There are many underlying psychological causes for erection dysfunction. In essence if negativity, worries, stress, overwhelming anger (often unexpressed) and other tough feelings get hold on us, something has go give. And for many men it's the sexual function that gives. If you weren't burdened by negative thoughts or feelings before you began to experience this condition, you would have to be a mega man to keep it away now. These exercises are aimed to lighten your burden. I've had clients who experienced tremendous change after only practicing this part a few times. Especially “Talking Things Out” with an understanding partner. Practice and implant to your life as many of these techniques as you comfortable can every day. Implanting this rule all the time will totally change your life. Not only will it help you to deal with your erection dysfunction, every area in your life will get better. Because you will push away the biggest obstacle in your life, your negative thinking. We think a lot. It is just our human nature. But have you ever noticed that most of our thinking is negative thinking? ● We doubt ourselves. ● We let other people get on our nerves. ● We think about everything that goes wrong, but don't notice what is right. The 1-2 rule is meant to reverse this. The rule goes like this: "It is ok to think something negative, but I always have to match it with two positive things". For example, you might think about somebody: "Man, he is boring." It is okay to think that, but you have to be able to match it with two positive things about that person. You might add: "But, he is a hard worker, and he is loving to his kids". The hardest part for most people is to use this rule about themselves. You might doubt yourself, thinking: "I am not good enough, I will never get this promotion". And it is okay to think this. You are allowed to have this opinion about yourself. But you have to match with two positive things about your self. You might, for example, add: "But, I am popular as a friend in my workplace, and I know I give my work 100%." You will notice two things, if you apply this rule to your daily life. 1. You will feel lighter and happier. 2. You positivity will grow. It will be so much work to always have to stop to look for positive things to think every time you think something negative, but little by little you will train yourself to diminish the negative thinking, and increase the positive. Note that everybody has something positive, everybody. If you can't find anything positive about some person, you really don't want to. In the process of implanting this rule into your life, you will slip, you can be sure of that. There will be days where you simply can't think positively. Your negative thinking will take over. Don't worry about this. Just start the next day with a clean slate. Use the 1-2 rule also talking to people around you. Everywhere you go try to match any negative thing you say with two positive ones. If you are complaining to somebody, you might say: "I love your products, and your sales team is great, but every time I need assistance, I can't reach customer support." People are way more open to assist and make amends if you say something positive to them. This exercise is meant to get you thinking about what you really like in your life, and what you would like to do. Simply rewrite this list and fill in the blanks with your personal choices. Make the answers as short or long as you want. Take time to think about your answers. Allow yourself to dream! 1. My favorite way to spend the day is 2. I often dream of traveling to 3. Choosing between a mystery, novel, or biography, I pick 4. The music I enjoy listening to is 5. If given the choice, I'd build my house in 6. I often dream of having 7. I wish I could feel good about 8. I cry when I feel 9. I laugh when I feel 10. I need to communicate because When you are done with this list, make your own list. Write down, in a simple manner, what you like and what you like to do. What is your reality? If you don't like writing, just make those lists in your own mind. It can be fun to do a similar exercise with your partner. You each make up a question, and then the other answers. You might ask your partner: "If you could choose any place in the world, where would you want to live?" Or, "What in life gives you the biggest joy?" Remember you are never too old to play a game like this one. Do this exercise once a week, or as often as you want. Because you are seeking advice for erection dysfunction, I assume you have a partner. If this is a misunderstanding, and you don't have a partner at the moment, try to get somebody else to do this exercise with you. A good friend can sometimes even be better than a partner. With all couples there is something unspoken floating in the air. There is something both of you are worried about, angry about, or you haven't expressed all the love towards each other, from your heart. These kind of unspoken emotions can lead to erection dysfunction in two ways: 1. Your body will tense up when you have the emotions. For example, if you are angry you may often make a fist without even noticing. When you are scared your shoulders may tense up. When there is lot you are not expressing, anger, fear, love, your genital area will tense up and block the blood flow, leading to erection dysfunction. 2. When you are around somebody who is holding on to unspoken emotions, you will feel it in the same way as if you had it yourself, making you tense up as explained before. You may not feel it as strongly as if you had the emotions yourself, but you will still feel it, causing your to erection dysfunction. So if your partner is not expressing emotions, especially some emotions projected at you, you will feel tense, and that effects your sexual performance. The cure in both of those cases is simply: Talk together! Most couples spend more time in front of the television than talking together. Especially talking about something important. The description of the exercise is short: "Within two or three hours before going to bed, talk together for a half an hour". To make the task a little bit easier, I am going to give you a few rules to follow in the conversation. 1. Talk together for a least half hour, but split it up in few sections. For the first five minutes you get as many things off your chest as you can, and your partner listens. Then your partner get as many things of her/his chest as possible, and you listen. For twenty minutes you take turns to talk, and listen. The last ten minutes are free for you two to talk together, without anyone controlling the time. 2. When talking try to use the 1-2 rule explained before. Try to find two positive things for each negative thing you say. 3. When listening be as non-judgmental, and non-emotional as you can. Your partner is only expressing his or her reality, and maybe the only thing needed is to get it out of one's system. 4. When talking, try to take a grown up stand of responsibility for your feelings and reactions. Although hard to believe, your feelings have nothing to do with your partner's behavior. You are not a victim of your feelings, you can always choose from which point of view you see things. 5. Talk together like you knew your partner would not be alive tomorrow. Like it was the last time you saw each other. This could be true. Especially use the last ten minutes to say everything you wanted to say if you would never see your partner again. Never go to bed with something unspoken. If you do this exercise right, you might feel a huge difference in your sexual energy right away tonight. Most couples though, need quite a few times to get the right flow going. It is okay, just do this exercise constantly every night, hopefully for the rest of your life. And you will not only have better sex life, but also have a way better atmosphere in your home. If the atmosphere is already great, it will only get better! As mention many times before, stress and anxiety are two very underlying causes for erection dysfunction. You may not cure your condition overnight using these exercises but I promise you, you'll feel and sleep a whole lot better. Choose either one of these exercises and practice it daily or as often as you can. This is my favorite exercise. It took a while to get used to it, but now I am addicted to it. :-) It is simple. Sit in your favorite chair, and do nothing for fifteen minutes a day. You might think this is a waste of time, but I assure you it is not. Isaac Newton maybe thought he was wasting his time sitting under the apple tree. But it was there he realized his most famous principle. Taking the time to sit for fifteen minutes, every day, takes an amazing amount of self-discipline. Everything will want to get in your way. But believe me, if you do this, your whole day will be better. You will be way more relaxed, and your stress (the worst enemy of the western world) will diminish tremendously. Stress is one of the main hidden causes for erection dysfunction. It gets all our body tensed up, especially the genital area and blocks the blood flow. If you think you are too busy to sit down for fifteen minutes a day and do nothing, then you probably need to do this exercise. I am going to repeat the directions. Sit in your favorite chair, and do nothing for fifteen minutes a day. If you think you have to do something, let it wait. If there is something very important to think about, do it after the exercise. For fifteen minutes, you don't have to think about anything, don't have to make any decisions, don't have to read anything, don't have to listen to anything, and you don't have to do anything. Out of one thousand four hundred and forty minutes a day, you are going to do absolutely nothing for fifteen minutes. When the fifteen minutes are over, open you eyes and check how you feel. Do you feel the same as when you started, or different? Did you feel temptations to stop the exercise and do something else? Was it always the same temptation which wanted to stop you from doing what you had decided was the most important to do in the moment? It will get easier to do this exercise the more you practice it. The following exercise will teach you how to relax your body and mind. You will want to find a quiet, comfortable spot to practice where you will not be interrupted. You are going to want to totally free your mind and you can not do this if you are worried about things in your surroundings. This means turn off your phone and pager (or put them on silent), turn off your television, anything else that is distracting or may cause interruption. You are going to want to quiet your mind first and then move on to relaxing your entire body. To quiet your mind, you first want to: ● Lie down on your back with your arms by your side in a comfortable spot, use pillows if necessary to make yourself more comfortable. ● Close your eyes. ● You may want to listen to soothing music or relaxation recordings. (Just be sure not to play any music that is distracting or not calming.) ● Free your mind of any daily concerns; don’t worry about that work assignment, feeding the dog or changing the oil in the car. Just let all your worries and concerns slip away for a moment and imagine yourself drifting away. ● Think of yourself as getting lighter, being held up like a feather in the breeze. ● Remain this way for as long as you want. Now, to relax your body, you’re going to want to focus on each and every part of your body. This progressive muscle relaxation is similar to getting a full-body massage. You will begin this muscle awareness exercise in your feet and work your way up slowly. Remember, don’t rush. Just enjoy the time with yourself. While lying down on your back, tense up your toes, hold, and then release. Now do your feet; tense your muscles, hold for a moment and then relax. Slowly continue this up your legs. You are now becoming aware of your body and gaining control of your muscles. Work your way up your lower leg and thighs to your butt and genitals. Focus on those muscles and tensing and releasing them. Breathe naturally as you tense and release the muscles throughout your whole body, one at the time. Pay special attention to the genital area and the lower back and abdomen. I originally made these exercises to deal with premature ejaculation. They became very effective and my one line program (ejaculationmaster.com) is recognized all over the world as the most effective solution to cure premature ejaculation. What I found out was that these exercises were as effective to deal with erection dysfunction. I recommend waiting with this part till you've practiced the other 8 parts for at least 2 weeks. You may want to wait longer or skip it completely that's okay too. There is of course an obvious problem with these exercises. If you can't get hard at all, then you'll not be able to practice them all, that's okay. Do the parts that you can. Little by little, you'll be able to do more and experience more pleasure. Up until this point, the program is basically the same for everybody. But now that you have reached the awareness exercises, you will have the choice to work alone or with your partner. But before you can start practicing the awareness exercises alone or with partner, you will have to learn how to recognize the arousal stages in yourself. You are going to want to become familiar with yourself and with what happens as your arousal level grows till you reach the point of no return when you can't stop your self from ejaculating. Just exactly what is happening when you get turned on? As you get more and more aroused, your body function changes. There are several signs your body shows when you are getting close to orgasm. They are ● Increased breathing rate, possibly even panting ● Blood pressure and heart rate both increase ● Legs and butt muscles tighten up ● Pelvic muscles tense ● Testicles may draw up close to the body ● You become inwardly focused, blocking out the outside world Now let’s look at the exact stages you go through from no arousal to full blasting ejaculation. Ten Stages from Arousal to Ejaculation There are basically ten stages that a man experiences on the road to ejaculation. It’s extremely important to understand these 10 steps and learn to recognize them in yourself as it is the fundamental base for performing the awareness exercises. You will need to study these stages carefully and then study them as you are experiencing them. Then when you are masturbating or having sex, learn to recognize what stage you are at. ∑ Stage 1: Going from un-aroused to feeling a light feeling in the tip of the penis ∑ Stage 2: You will get your first little surges of pleasure ∑ Stage 3: Now you start to get feel-good feelings ∑ Stage 4: Start to experience low stages of arousal ∑ Stage 5: Feeling really good, fully aroused ∑ Stage 6: Feelings of arousal increase ∑ Stage 7: Breathing increases, pleasure spreading all over ∑ Stage 8: Increased pleasure; breathing fast, heart rate increased and face flushed. ∑ Stage 9: Stage of intense pleasure and feelings of elation, ∑ Stage 9.9: Reaching point of no return. ∑ Stage 10: Ejaculation. Learning these stages and recognizing them in yourself is essential when performing the awareness exercises. You want to be able to know your body and your pleasure stages so your body can increase the arousal and therefore get harder, more powerful erection. You will eventually learn how to move up and down the arousal steps at will. Ejaculating Be aware as you begin practicing these exercises that many times you will go over the point and ejaculate when you don’t want to. That is actually great. If you don’t lose it once in a while, you are not pushing the limits enough. So you are doing great. Don’t worry about it or beat yourself up over it. Be happy about it because as I will mention over and over again this only gives you deeper awareness of how far you can go. You may also not be able to get hard firm erection in the beginning. That is okay. Little by little your erection strength will grow and you'll gain both harder erection and ejaculation. Practice Alone Or With Partner? Finally you are ready to practice the awareness exercises. Now it is time for you to choose if you want to start practicing the exercises with your partner or alone, if you choose to practice alone for right now, you can always switch over at any time and start practicing with your partner. If you want to get your partner involved now, move over to the partner awareness exercises part of this section now. Otherwise just keep on reading and follow the guidance for the single awareness exercises. Now that you are beginning the “hands-on” exercises, your privacy is really important. You may even feel shy when you are all alone but it’s okay. Part of the program is learning to let yourself go and be completely relaxed with yourself. You need to feel free to make noises and feel the pleasure. Don’t worry about coming when you don’t want to; if this doesn't happen every now and then, than you are not pushing yourself enough to benefit from the exercises. So go ahead and let yourself go. Take time to pleasure yourself and explore your erotic pleasures. Most of all have fun! Now, start the first exercise and then just follow the step by step guidance how to move on. ● Lie in your bed naked. You can either go quickly through relaxing your body step by step, or do this exercise directly after the relaxing exercise. ● Relax by taking a deep breath and then empty out the lungs completely. Repeat these three times. ● Now as you lay there start touching your self looking for spots that give you pleasure. Do not touch your genitals yet! ● Experience how your body feels when you touch yourself in different spots. ● Feel how your arousal stage goes up a little. Keep the 10steps we talked about before in mind. ● Breathe deeply, close your eyes, and enjoy. ● Make some sounds; let your voice express how good this feels. ● Feel how different kinds of strokes give you different kinds of pleasure. ● Feel your whole body with your hands. Your most sensual spots might be anywhere your arms, shoulders, nipples, face, neck, stomach or legs. You will most likely discover many sensual spots you never realized you had. ● Spend some time touching yourself like this. Take note of your body’s reaction as you touch yourself. Also experience how good it feels in your hands when you touch your self. Discover how good it feels to be doing the touching, not just receiving. You should have a double pleasure. Enjoy as much from the giving hand as the receiving body. ● Continue to practice this for at least fifteen minutes without ever touching your genitals. Go for longer if you feel like it. After at least fifteen minutes of self pleasure you may touch your penis and balls. ● Stoke your penis lightly like you did with the other parts of your body. Move your hand slowly on your penis and feel every touch, every movement. ● Let out the pleasure by making some sounds. Panting is great. Talk to yourself out loud: “this is great”, “this feels good”. The same way that people get turned on by talking during sex, you will get turned on more by talking when you are pleasuring yourself. Don't go into fantasying but try to feel your body sensation deeper and deeper. ● Talking and making sounds also relieves a lot of tension and anxiety. Start practicing making sounds right away. If you think you are too loud, become even louder. This also eliminates lot of sexual shame or timid-ness most people have. ● Do not move too fast, take it very slowly and enjoy the almost overwhelming feeling you may experience. If you get irritated and want to move faster, do the opposite and move slower. You’ve been rushing it your whole life. It’s time to learn not to rush. Take it for as much time as you can stand. ● Now that you’ve soaked up that amazing feeling, relax and feel as your arousal stage rises. You do not have to do anything to control it, just feel it and experience it with joy. ● When you reach ejaculation, feel every pump. Feel the semen come from inside and move up the penis and then out. Explore The Pleasure. Practice this exercise a least five times before you move over to Single Exercise 2. Just like in exercise 1, you should relax for about 15 minutes before beginning the exercise. This is very similar exercise to Single Exercise 1 except now you will learn to let the sexual energy spread all over your body. If done correctly, this will give you a great energy boost. ● Start out like in Single Exercise 1. When you reach the point when you can start touching your penis, visualize how the energy is moving from your genitals and up your spine. Feel how it reaches your Solar Plexus, your heart, and then your forehead. ● Take your time. ● Now feel how it moves from those spots (solar plexus, heart, and forehead) and spreads all over your body. You may see it as colored light or just feel it as a current or surge throughout your body. ● Now add the PC pump. ● Breath in deeply, clench the PC muscles (both front and back), then breathe out and let go of the tension. As you flex the muscles feel the energy flow up the spine and as you release and breathe out, feel the energy flow all around your body. Do not rush through the exercise. Take things slowly and enjoy your pleasure. ● The whole time you are doing the PC pump keep on arousing your penis ● When you finally ejaculate, you will have a fantastic orgasm! Practice this exercise a least five times before you move over to Single Exercise 3. Before you practice this exercise make sure you know the 10 Stages you go through as your arousal rises well. You will need to use them in this exercise. Just like in the other exercises, spend at least 15 minutes relaxing before you begin. Start out like in the two previous exercises until you reach the point when you can touch your penis. ● Start masturbating slowly. Be aware as you move from one stage to another. Take your time and note how you feel. Go slowly and feel the tension as it rises. ● Slowly let your self move up to stage 6. Then stop everything and wait until you have dropped to arousal stage 2. This might take few seconds or few minutes. ● When your arousal stage has dropped down to stage two, start masturbating slowly again. ● When you reach stage 6 again, stop everything and let your arousal stage drop to stage2. ● When you have dropped to arousal stage 2, start masturbating slowly again. This time arouse your self to stage 7. Then stop everything and drop to stage 2. ● Arouse your self up to stage 7 again and then drop to stage 2. ● Now arouse your self to stage 8, and then stop everything and drop to stage 2. ● Arouse yourself to stage 8 and then drop to stage 2. ● Then do the same with stage 9. Arouse your self slowly up to stage 9, then stop everything and drop to stage 2. ● Repeat going to stage 9 and then dropping to stage 2 for about four times. ● Now the most enjoyable step in this exercise. If you haven’t already lost it and ejaculated (it is very likely that you loose it first few times if you press the limits enough) drop your arousal stage down to stage 2. Then masturbate all the way up to stage 9, be aware when you reach stage 9, then go over the line to the point of no return. ● Allow yourself to enjoy the orgasm fully. Try to spot it exactly when you move over to the place of no return. Don’t try to stop it, just notice it. Next time you practice this exercise and are moving to stage 9, try to get as close to this point as you can without crossing the line. Remember crossing the line to The Point Of No Return without wanting to is never a failure. You are only practicing, and every time you reach that point unintentionally you will have clearer feeling of how far you can go. Not only will you have clearer conscious feeling of how far you can go. Your subconscious, which controls your ejaculation anyway, will also learn to recognize this. Playing on the edge of an orgasm for as long as possible will boost your penis with energy and train it to bring on harder and harder erection. Practice this exercise a least five times before you move to Single Exercise 4. You may find you enjoy it and want to practice it often. This exercise is very similar to Single Exercise 3, except now you will not go all the way down to stage 2 but only drop two steps down. As with the other exercises, relax for about 15 minutes or more before beginning. If you are not relaxed, or if you start to feel tense, stop the exercise and go back to your relaxation techniques. The tension will interfere with your arousal process. Practice this exercise like the previous till you reach the point you can touch your penis. ● Masturbate slowly till you reach arousal stage 6. Then stop everything until you have dropped to arousal stage 4. Then arouse your self slowly back to stage 6, and then drop back to stage 4. ● Now masturbate slowly till you reach stage 7. Then stop everything and drop to stage 5. Masturbate to stage 7, then stop everything and drop to stage 5. ● Now arouse yourself up to stage 8, stop everything till you drop to stage 6. When you have dropped to stage 6, arouse your self to stage 8 again, and then drop back to stage 6. ● Now arouse yourself to stage 9 and then drop to stage 7. This time repeat this process from stage 9 to stage 7 four times. Every time try to get closer and closer to the point of no return without crossing it. ● Finally drop your arousal stage all the way down to stage 6 and then arouse yourself to stage 9. Slowly move higher and higher in stage 9 until you feel that you have crossed the point of no return. Then just enjoy a great orgasm. Try to spot exactly the point when you move over to the place of no return. Next time you practice this exercise and are moving to stage 9, try to get as close to this point as you can without crossing the line. Each time you practice the exercise try to get a little closer. If you do the exercise right you will sometimes cross the line of no return without wanting to. If you never do this you are most likely not pressing the limits enough in stage 9. So once again, do not feel back if you come before you finish the exercise. Just enjoy it and then take note of how it felt and how you knew you were crossing over to the point of no return. Repeat this exercise at least five times before you move on to Single Exercise 5. At this point you should have good feeling for the sages and your body, as you move up and down from one stage to another. In this exercise you are supposed to hold back by reversing the process you would normally go through right before you reach the point of no return. Remember the five things that happen with your body as you get close to climax: 1. Breathing speeds up to the point of panting 2. Heart rate and blood pressure increase 3. Legs, butt, and other muscles around the genitals tense up 4. Testicles draw up against your body 5. You have inward focus; the outside world is far away If you can control those five attributes you will be able to last way longer than usually. Let’s look at what you can do to hold yourself back. We will call this THE REVERSE FOCUS. 1. Breathing. You can slow down and deepen your breathing. Make sure you breathe all the way down to your belly, and then breathe all the air out. Breathe in through your nose. Usually when we get excited we breathe through our mouth. If you breathe in through your nose you will change this pattern. 2. When you breathe out make a pleasure full sound. This will release a lot of tension. 3. Tension. You should now have practiced to relax your whole body. Now it is time to use this to relax when you are getting highly aroused. Feel it when your muscles start to tense. Tell them to relax. Try to relax your whole body, even if you are over aroused. 4. Testicles lift. As the testicles start to draw up, use the PC muscles you have been exercising to let them down again. Do the testicle lift, and then release them totally down. Little by little you will get the feeling of how to use the PC muscles to avoid ejaculation. Try out different things. You will cross the line many times, but little by little you get a better hang of it. 5. Inward focus. Open your eyes widely and watch everything around you. Feel the whole room. Touch yourself with your free hand. Feel the touch both with your hand and also where you touch yourself. Listen to whatever sound is around you. You may be playing slow music, or a car might be driving by. This way you will have an outside focus, as an opposite to the inward focus. Now read those steps over again, and understand how you can control your ejaculation by doing the opposite to what you would usually do when you are close to coming. Let’s try this out Again, do your relaxation for at least 15 minutes before beginning and go through the process like in the previous exercises till you reach the point you can start touching your penis. Now, masturbate like you did in the previous exercises until you reach stage seven. Now slow down your stroking, but don’t stop. As you keep on masturbating slowly, deepen your breathing, breathe in from your nose, and make sure you breathe all the way down to your belly. Release all the air out with a moan. Empty out the lungs from the belly up to the shoulders. Do everything else I explained before to reverse the process up the steps of the 10 Stages. ● Breathe deeply ● Make pleasurable sounds ● Relax your whole body ● Perform a testicle lift and then release them totally ● Focus outside your self, not inward focus If you reach stage nine, stop everything and wait until you drop down to stage six again. Start masturbating again like you usually would but when you reach stage eight, get the reverse focus again. Now do the same with stage nine Masturbate as usually until you reach stage nine. When you reach stage nine, slow down and get the reverse focus. ● Breath deeply If you get too close to the point of no return, stop everything and keep the reverse focus tll you drop down to stage seven. Play on the edge. Feel how far you can go with the reverse focus without reaching the point of no return. Feel the energy build up in your penis and how hard it gets the longer you play around the edge. When you have played around on step nine for a while make a conscious decision to cross the line of no return, give in to the orgasm. Breathe like you normally would and feel the inward focus. Feel it as you reach the point of no return. Be aware of what changes and what happens in your body when you make the conscious decision to cross the point of no return and enjoy your orgasm. How do you feel when you do this? What is going on in your body? Repeat this exercise for at least five times before moving on to the next step in the program. You are now at the end of the single exercises. You have 2 choices of how you will decide to move on in the program: 1. You can keep on exercising alone till you have totally mastered the exercises. You will feel a huge difference when you have sex. You can then keep on practicing exercises 5, Reverse Focus, exercise 4, Rocking the Steps and Exercise 2, Spreading the Energy. 2. Your other option is to move on to the partner exercises. If you have a partner, you can start the awareness exercises with her. This is the most recommended choice. If you are ready for that, just keep on reading You have now either worked on the awareness exercises alone for awhile and gotten good control over your ejaculating and rocking the steps and are ready to start exercising with your partner, or you have decided to move right into the awareness exercises with your partner. Whichever method you have chosen, you should still continue to practice the relaxation exercises a least three times a week and practice the PC muscle exercises every day. Before you continue, be sure you have read the introduction to the awareness exercises and that you know the 10 steps by heart. In the next section you may see the phrases “FOR HIM” and “FOR HER”. Whenever you see this, it is a direct message for each partner specified. Before you start the action with your partner, you will need to discuss the program and the exercises to be able to communicate clearly when the tension rises. So it may be a good idea to read through this section with your partner before you begin. As we mentioned before in the program, your partner has to be very supportive or this is not going to work. If your partner is negative about you curing yourself, does not want to believe you can, or is not open to practicing the exercises then you should just exercise alone till she is into it. By now you should have been taking time to talk with your partner a few times a week if you were planning on her participating. You have been sharing your realizations and your progress in the program. She has been sharing her thoughts and concerns. The two of you are developing intimacy as you go through the program. Make sure your partner is familiar with the ten steps you go through as your arousal stage rises. She may not know them as well as you do in the beginning and you will have to tell her if you are getting to close to the final stage but with time, after practicing, she should begin to learn to read your stages. She should also read through the whole program to deepen her understanding about what is going on. Now it is time to get down to business You have to make very clear communication signals between the two of you that you are going to use in the following exercises. Make sure they are short and clear so that they need no more explanation. I recommend the following but you may choose to create your own ● "Stop" – when you wanted her to freeze and stop the arousing. ● "Start" – when wanted to keep on going. ● "Slower" – when you need to slow down. ● "Faster" – when needed to go faster. ● "One" – when you reaching arousal stage 1. ● "Two" – when you reaching arousal stage 2. (And so on up to 10.) ● "Yes" – to answer a question. ● "No" – to answer question. When asking questions during lovemaking agree to make them Yes or No questions. Example) Instead of asking: “How does this feel?” Ask: “Does this feel good?” Also make the questions as short as possible. Go over the communication signals and the arousal steps with your partner every time you exercise the partner awareness exercises. Now you are ready to start the partner lovemaking exercises! This exercise is similar to “Single Exercise 1” except that this time it is your partner that is touching and kissing you. Your responsibility is to guide her lovingly to how and where she can make you feel good. You need to have a least one hour privately with your partner to practice this exercise. Agree that she will pleasure you first for at least twenty minutes without touching your genitals (even if you later on beg her to do so) and without you having to do anything other than guide her on what to do. Later on you will do the same thing for her. DIRECTIONS FOR HIM As she starts to touch you and kiss your body, suggest what you would like her to do. Where would you like her to touch and kiss you and how? Then give her compliments how good it feels what she is doing. Give exact, specific comments about what you want and how you feel. Then you guide her to the parts of your body that you have been experiencing in the single exercises. Take a lot of time doing this. Let her touch you and kiss you where you feel good for longest time before you ask her to move on to another place. You are not allowed to try to pleasure her in any way. This part of the exercise is for your pleasure only. You will have to learn to take in the pleasure from a woman, take in her love. We all have limits to how much pleasure we can take in from someone else before we think we are obligated to do something in return. In this exercise you are going to break those inner limits and take in her love for a longer time than you are probably used to. Don’t be afraid to moan or sigh or make noise to express your pleasure and release tension. Enjoy her pleasing you for at least twenty minutes before she begins to touch your genitals. As she starts to arouse you, either manually or orally be aware in what stage of the 10 Steps you are on. Express that in simple way like stating: “Stage 5” You can also guide her by saying “slower” or “faster”. When you reach and state: “stage 7” she will stop arousing your genitals and just kiss and touch other parts of your body. When you drop down to and state: “stage 5” she will start arousing you again until you come back up to “stage 7” then she will stop touching your penis and just kiss other parts of your body. Remember to always state which stage you are on. She has no way of knowing that unless you tell her. When you have dropped to “stage 6” she will arouse you again until you reach “stage 8” and then stop again until you drop to “stage 6” once again. Now she will arouse you until you reach “stage 9”. As soon as you state “stage 9” she will stop touching your penis until you state “stage 7”. Then repeat this, reach “stage 9” and then stop until you reach “stage 7”. Now we are getting to the risky part. She will arouse you until you state “stage 9”. At this point oral stimulation is much better than manual one. It is just a much closer feeling. When you reach “stage 9” she will slow down so you can feel everything stronger. You want to keep this highest, strongest arousal stage for the longest time possible but you never want to drop down below “stage 9”. So now guide her by the words “slower” and “faster”. Right before you reach the point of no return state “POINT” and she will stop arousing you until you drop back to “stage 8”. When you state “stage 8” she will start again, slowing down again when reaching “stage 9” and taking as long as you can till you are about to reach the point of no return. Then (if you can actually speak by this point of arousal) state “POINT” and she will stop until you reach “stage 8”. This time you are consciously going to cross the point of no return (if you haven’t crossed it already by accident). She will work you up to “stage 9” again and then slow down. You will guide her as before so you can take the longest time on this high intensity stage. When you are just about to cross the point of no return you will state “POINT” but this time she will not stop but keep on going. If you have felt it right, you will reach the strongest orgasm in your life only few seconds later. DIRECTIONS FOR HER Your role to start with is to give pleasure. Later on he will do the same for you but for now, you are there to pleasure him. You should kiss and touch him where he asks you to but take it slowly so he can really enjoy it. You should encourage him to make sounds. You could do this by saying “I love it when you make noise” or “Led me hear how much you love this”. When doing this exercise it is very important that you follow his guidance, because he is stating how he feels, what he likes, and how he can be pleasured more. Kiss and touch him where he tells you to, anywhere except the genitals. If there is something he wants you to do which you feel uncomfortable just tell him. You don’t have to do it now and you can agree to talk about it after the exercise. When you have played with him like that for twenty minutes you can start arousing the genitals. Oral arousing is better because there is deeper connection between the two of you that way but manual stimulation is also good. He will guide you through the stages of arousal as he feels them. For example, he says “stage 7”, when he reaches "stage 7". And "slower" and "faster" if he wants you to arouse him more or less. When you have to stop arousing his genitals directly just kiss and touch other parts of his body. So start orally or manually arousing him. When he reaches and state: “stage 7” stop arousing his genitals and just kiss and touch other parts of his body. When he drops down to and state: “stage 5” start arousing him again until he comes back up to “stage 7” then stop touching his penis and just kiss other parts of his body. When he has dropped to “stage 6” start arousing him again until he reaches “stage 8” and then stop again until he drops to “stage 6” once again. Now arouse him until he reaches “stage 9”. As soon as he states “stage 9” stop touching his penis until he states “stage 7”. Then repeat this, reach “stage 9” and then stop until he reaches “stage 7”. Now we are getting to the risky part. Arouse him until he states “stage 9”. At this point oral stimulation is much better than manual one. It is just a much closer feeling. When he reaches “stage 9” slow down so he can feel everything stronger but don't stop completely. The goal is to keep this highest, strongest arousal stage for the longest time possible without him ever dropping down below “stage 9”. So now he will guide you by the words “slower” and “faster”. Right before he reaches the point of no return he will state “POINT”. Immediately stop arousing him completely until he drops back to “stage 8”. When he states “stage 8” start again, slowing down again when reaching “stage 9” and taking as long as you can until he is about to reach the point of no return. Then (if he can actually speak by this point of arousal) he will state “POINT” and you stop arousing him completely until he reaches “stage 8” again. This time he is consciously going to cross the point of no return (if he hasn't crossed it already). Work him up to “stage 9” again and then slow down. He will guide you as before so he can take the longest time on this high intensity stage. When he is just about to cross the point of no return he will state “POINT” but this time you should not stop but keep on going. If he felt it right, he will reach the strongest orgasm in his life only few seconds later. DIRECTIONS FOR BOTH OF YOU One of the most important things to remember when practicing these exercises is to have fun. The most common cause of most sexual dysfunction is anxiety of some sort and the cure for that is to have true fun. So play together and have fun with it. You may be experiencing each other fully for the first time. Laugh when you reach the point of no return before you want to. It means that you two are stretching the limit to the fullest. If you never come before you want to, most likely you are too careful and won’t benefit fully from the exercise. Plus, it’s fun, right? So enjoy yourself. Practice this exercise a least five times before you move over to Partner Exercise 4. Always make sure that you do Partner Exercise 3 after this one. You don’t have to do it right away, although that is the best method; just make sure you do it. Now it is time for the woman to get her pleasure. You can practice this exercise soon after Partner Exercise 2 or the next day. Just make sure that you do practice this exercise after the other. You might ask why this is part of healing your condition. This exercise does not sound like an exercise to deal with ejaculation or erection dysfunction. It is an exercise for your partner to experience pleasure. But there are several reasons why this exercise is so important. 1. Sexual dysfunctions are most often caused by hidden emotions we are not aware of. You might not be aware that you project anger to your partner and want on some stage to deny her of having a deep sexual pleasure. You might also have guilt about not pleasuring her, or suffer from performance anxiety. By pleasing her fully, you will relieve lot of this tension. 2. Most women have, like men, a lot of sexual shame and problems accepting good sexual energy from a man. This is of course as unconscious as most other emotions we have. Little by little when practicing this exercise a few times women will relax and enjoy sex even more. Many women experience orgasm for the first time practicing this exercise and then enjoy sex even more after that. Having good loving sexual flow between both of you will unconsciously encourage both of you to want to make love for longer time. 3. The most important part is that she deserves it. If she is ready to practice the other partner exercises she is a fantastic woman who deserves to experience the highest stage of pleasure possible. If you don't want to spend his time and energy pleasuring her in this exercise you shouldn't be practicing this program. This program is about mutual love and sexual pleasure, not about just performance or looking good. So let’s start pleasuring her. This exercise is a lot like the previous one except that now he is pleasuring her in a selfless way and there is no rocking the steps. Just remember although following the guidelines is great, the most important thing is to have fun and enjoy this together. Laugh and joke and enjoy the flow. Directions for Him Now it is time for her to experience the great pleasure of you playing with her for the longest time. The rules have switched. Now you are there only to please her sexually. She will guide you to kiss her and touch her at spots on her body that pleasure her. Stay at those spots and do exactly what she asks till she guides you to another spot. Some men have problems with taking directions about sex from a woman. But how else are you going to learn what pleases her the most? And how else is she going to experience what she needs? You can’t read it in books what pleasures your woman; it varies so much from woman to woman. The best way to learn is hands-on. So take her directions to the point and give her the pleasure she is dying for. Later when you are not exercising but just making passionate sex, you will find yourself using what you learned about your partner and taking her to incredible heights in the bedroom. Don’t be offended if she asks you to do things differently, you are learning what pleases her and that is all that matters. So kiss her and play with her in the way she wants without touching the genitals. Do this for at least twenty or thirty minutes. She should be steaming before you get to the genitals. You can kiss her inner thighs and all around the genitals if she asks you, just don’t go into the sacred triangle. Now after twenty or thirty minutes you can move over to the genitals if she is ready and asks for it. She might ask you to put a finger in, kiss the outer lips and clitoris, or use a finger on the clitoris, or something else. You have to listen to her closely and ask simple questions she can answer with “Yes” or “No” like “is this good”. She will also use simple directions like “Faster” and “Slower”. Or short sentences like “Lick the clitoris”. Sometimes touching the clitoris directly is too intense and it is better to kiss and touch around it. Just be aware of this and follow her guidance. Now slowly work her vagina area over, following every guidance she gives you, until hopefully she has the most intense, strongest orgasm in her life. After this exercise talk about what the two of you have experienced together. Talk for at least twenty minutes after you finish the exercise. Often when we experience such a deep intimate connection we want to run away. Be aware of this tendency, but stay. Directions for Her Now the pleasure is for you. Now it is time for him to please you sexually in any way that you want except that for the first twenty to thirty minutes he is now allowed to touch your vagina. Before you practice this exercise it is suggested that you practice the relaxing exercises in the beginning of this program on yourself and maybe even your own take of the single awareness exercises. This will help you become in better touch with yourself making orgasm easier and more enjoyable for you. During the exercise, be sure to tell him specifically what pleases you and what you want. This is not the time to be shy. Let go of that sexual tension and nervousness and ask for what you want. For the first 20-30 minutes you can ask him to do anything except touching the holy triangle around the vagina. After he has pleased your whole body you can direct him down to your vagina and what to do there. The whole time remember to breathe. Breathe deeply all the way down to your belly, especially if you stop feeling aroused or if the arousing is getting overwhelming. At this point you will want to use very short clear commands like “Faster” or “Slower”. You might also guide “On the clitoris” or “Around the clitoris”. It is good to make up clear commands before you practice the exercise and then later when you talk about what you experienced you might want to add to the list or change some commands. Let him stimulate you until you hopefully reach the strongest, most powerful orgasm in your life Before you start this exercise both of you should read the exercise: "Single Exercises 4: The Reverse Focus" because this exercise is absolutely similar to that one. Except now you practice it as a couple. You start out just like in Partner Exercise 2 except that this time the woman will not stop stimulating you when you move to a certain stage, she will only slow down. Again she can choose if she is into oral stimulating or just manual. However like before I recommend oral stimulation. You start as in the previous exercise with the woman kissing and touching the man where he likes, without touching his genitals. At this stage, 10 minutes are enough although you can have it for longer if you want to. Guidance for Him: As soon as you reach arousal stage 7. Voice it out and she will slow down. At the same time use the reverse focus to move away from the higher arousal stage through your nose, focus outside, etc. breathe deeply When you feel you have dropped down to stage 5, voice out "stage 5" and she will increase the arousal again. Guidance for Her: As Soon as he voices out "stage 7", slow down to lessen the arousal. But throughout the whole exercise never stop completely. When he voices "stage 5" start arousing with more tension again. Guidance for Both: Repeat this four times. Now do the same things except this time reach stage 8 and then drop back to stage 6. Again, repeat this four more times. If it happens that you haven’t slipped over the point of no return yet, which is highly unlikely, repeat the process up to "stage 9". And then drop back to "stage 7". Again repeat this four times. Guidance for him: When you are aroused all the way to "stage 9" you might need to use more critical techniques. If you feel like you are flying towards the point of no return, use the PC muscle techniques taught in Chapter 4, to avoid ejaculating or try the testicle pull. But what ever you do, don’t have her stop completely. Direction for both: Now, the toughest task … Direction for him: Have her arouse you as close to the point of no return as you can go without you crossing the line and ejaculating. Direct her with the words "Faster" and "Slower" and test how much you can actually take using the "reverse focus" and the techniques tough in chapter 4 to keep you away from the point of no return. This is of course loosing proposition, because at some point you will cross the line of no return. So enjoy it when that happens. As soon as you feel you have crossed the line voice out "point". Then she will also get the feeling and your connection and awareness of each other will grow stronger. Directions for her: Now you are going to test how long he can keep away from the point of no return, even if you keep on arousing him. You are also going to check how much he can take. So follow his directions carefully as he voices out "faster" or "slower". However don't hesitate to encourage him to take risks and take more arousal than he thinks he can handle. This will just give the two of you the reality about where the point of no return really is and how much you can take. Sooner or later he is of course going to loose it and cross the point of no return. I can’t state enough times that the most important thing to cure any sexual dysfunction is to learn to experience real fun with your sex life. Get rid of any anger and anxiety, fear and dread from your sex life and you will never have to worry about sex again. Repeat this exercise a least 5-6 times over a period of two or three weeks before you move over to next stage. The first time we actually involve intercourse. Now we’ve reached the part you’ve probably been waiting on since the beginning of the program; you can now have vaginal intercourse. But remember, don’t get too excited and forget everything you’ve learned so far. Take it slow. You might want to begin with relaxing exercises. Spend some time pleasuring her and getting her really hot and ready for you by using what you learned in partner exercise 2. Mastering that exercise will really pay off for you now. Have her do the same for you, using what she learned in partner exercise 1. Directions for him: Entering her in a position that will decrease your chances of premature ejaculation until you have mastered this exercise. Try either rear entry or it may be more comfortable to have her on top while you lie flat on your back. Enter her or have her straddle on top of you. If she is on top, you can place your hands on her hips to guide her up and down motions. If she is on top, you will have to guide her like you did in previous exercises by using words like "Stop", "Start", "Slower" and "Faster". It is also great idea to voice every stage as you feel your self reach it. That way she will know exactly what you are going through. Now rock the steps like you did in the previous exercises using the methods you like, for example Move slowly inside of her until you reach “stage 7", then stop completely and drop to "stage 5". You are not really thrusting at this point, just enjoying being inside her. Use "reverse focus" or the techniques taught in chapter 4 if needed to drop your arousal level. If necessary to avoid coming to fast, pull out altogether until you bring yourself back down to a lower stage. Repeat this a few times. Then arouse to "stage 8", stop completely and drop to "stage 6" like before. Repeat few times. Then do the same with "stage 9", stop completely and drop to "stage 7". Now repeat this few times. Finally move slowly inside of her until you get as close to the point of no return as you can. Then stop completely until you drop back to "stage 8". Now repeat this until you "loose it" and have a fantastic orgasm. Or just decide to consciously cross the point of no return and enjoy it. When you are aware that you are crossing the point, voice out "point" so your partner will have the awareness what is going on. Directions for Her: Before he enters you make sure you are sexually aroused enough. If not ask him to make the foreplay longer, using the techniques taught in partner exercise 2. He is going to enter you from a position he feels most comfortable to last longer. Most likely he will ask you to be on top first or he will want to enter you from behind. When practicing this exercise, make sure you follow his guidance to the point. When he says "stop", stop completely and totally freeze. If he is on top or from behind and you feel him stop completely, do the same thing movement and freeze. Tips for evolving the Penetration exercise: Stop every This was the last formal exercise in the program and for special purpose; it is not as precise as the previous exercises. Start by using the simple layout I provided here (which is similar to the rocking the step exercise you trained before) few times. Then, as you grow together, as a couple and your staying power increases, I want you to evolve this exercise to push your self to your personal limit Change the positions you use, the speed and intensity of the arousal, use the "reverse focus" you learned before. Or maybe do something completely different, your own premature ejaculation exercise. Start with any position where the man can not easily thrust is ideal for the beginning until you get better at control. Ideal position to start with is woman on top. Then progress to side by side position or doggy style. And finally advance to missionary position The point here is that you won't stagnate in any one exercise doing things in sudden fixed way. Instead develop the highest level of positive sexual intensity you can experience by pushing your self to the limit all the time. Experiences dry multiple orgasms for him, mind blowing goddess climax for her. Hours and hours of high level intimate pleasure beyond wildest dreams for both of you. So the layout I am presenting in this exercise is not rigid or something you have to follow to the point. But just guidelines you can work from using your previous experiences from the program and you own awareness. If you want to try something else after practicing and evolving this exercise few times, you can practice the techniques to stop your self from ejaculating taught in section 4. You should also go back to Partner Exercise 1: Pleasuring Him and Partner Exercise 2: Pleasuring Her once in a while to develop the knowledge of each others pleasure. Because these pleasure spots can change as you go on. But make sure you come back to Partner Exercise 4: Penetration over and over again and evolve it to push your self to the limit all the time. Mult mai mult decât documente. Descoperiți tot ce are Scribd de oferit, inclusiv cărți și cărți audio de la editori majori.Anulați oricând.
https://ro.scribd.com/doc/54268785/Erection-Master
CC-MAIN-2020-29
refinedweb
15,592
80.82
Hi Friends, I am going to explore a sample application in android ,which gives you an idea , How to select Image from gallery and how to capture image from camera and after it crop it according our use... For this I have used android default camera and android default gallery... Hope this will helps you...... 1- Print Screen of Home Page 2-Android Manifest file <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="" package="camera.test.demo" android:versionCode="1" android: <uses-sdk android: <application android:icon="@drawable/ic_launcher" android: <activity android:name=".SimpleCameraGalleryDemo" android: <intent-filter> <action android: <category android: </intent-filter> </activity> </application> </manifest> 3-SimpleCameraGalleryDemo Code package camera.test.demo; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.Intent; import android.graphics.Bitmap; import android.os.Bundle; import android.provider.MediaStore; import android.view.View; import android.widget.Button; import android.widget.ImageView; public class SimpleCameraGalleryDemo extends Activity { private static final int PICK_FROM_CAMERA = 1; private static final int PICK_FROM_GALLERY = 2; ImageView imgview; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); imgview = (ImageView) findViewById(R.id.imageView1); Button buttonCamera = (Button) findViewById(R.id.btn_take_camera); Button buttonGallery = (Button) findViewById(R.id.btn_select_gallery); buttonCamera.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // call android default camera } } }); buttonGallery.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent intent = new Intent(); // call android default gallery intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); // ********.createChooser(intent, "Complete action using"), PICK_FROM_GALLERY); } catch (ActivityNotFoundException e) { // Do nothing for now } } }); } protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == PICK_FROM_CAMERA) { Bundle extras = data.getExtras(); if (extras != null) { Bitmap photo = extras.getParcelable("data"); imgview.setImageBitmap(photo); } } if (requestCode == PICK_FROM_GALLERY) { Bundle extras2 = data.getExtras(); if (extras2 != null) { Bitmap photo = extras2.getParcelable("data"); imgview.setImageBitmap(photo); } } } } 4-main.xml File <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="" android:layout_width="fill_parent" android:layout_height="fill_parent" android: <TextView android:id="@+id/textViewAddCard" android:layout_width="250dp" android:layout_height="50dp" android:text="Take Image" android:textSize="16dp" android:layout_gravity="center" android:gravity="center" android: <Button android:id="@+id/btn_take_camera" android:layout_width="250dp" android:layout_height="50dp" android:text="Take From Camera" android:layout_marginTop="5dp" android:layout_gravity="center" android: <Button android:id="@+id/btn_select_gallery" android:layout_width="250dp" android:layout_height="50dp" android:text="Select from Gallery" android:layout_marginTop="10dp" android:layout_gravity="center" android: <ImageView android:id="@+id/imageView1" android:layout_gravity="center" android:layout_width="wrap_content" android: </LinearLayout> Just copy above code and save your life... Hi, thank you for your codes! I was wondering how do i edit the codes because i dont need the crop picture function. Can i get your help on this? yes sure! just remove crop image code from your activity- intent.putExtra("crop", "true"); intent.putExtra("aspectX", 0); intent.putExtra("aspectY", 0); intent.putExtra("outputX", 200); intent.putExtra("outputY", 150); Thanks, Hi, thank you alot for your help. I am a student working on a Android Programming Project. I am new on this. Do you mind helping me out with some of my doubts? If you dont mind, do you have an email so I could contact you with? Let me know if you are uncomfortable with it. Thank you. Hi, No issue you can make me a detail mail my id is-manishsri01@gmail.com Thanks, can we use explicit intent for cropping image Hello, I am not sure but it should work. If you did not get anything in bundle or in data is null you should get image path after capture an image and then try to crop it.. Like this- public void callCamera() { Intent cameraIntent = new Intent( android.provider.MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(cameraIntent, CAMERA_REQUEST); } and after that- protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) { Bitmap photo = (Bitmap) data.getExtras().get("data"); /** * crop it... after that how to crop it? i have defined a button named crop in java class itself and i want when the user click on crop then the image should be crop but don't know how to do it,,,because when you make a button in java class you don't have any id of in in R.java file Thanks for sharing. It works! Your welcome, and thanks for positive comment on my post.. hi here in your code i want to change these two lines intent.putExtra("outputX", 200); intent.putExtra("outputY", 150); to intent.putExtra("outputX", 600); intent.putExtra("outputY", 500); but it is not working.I want to change size of output image. Hi, intent.putExtra("outputX", 200); intent.putExtra("outputY", 150) these line not for image size it is just for crop image size in 2:1.5 ratio.. you can increase it using your fingers. My advice is don't fix it to- intent.putExtra("outputX", 600); intent.putExtra("outputY", 500); because everyone don't have high resolution screen device.. if i increase with my fingers for example if i take completes image the output image doesn't contain whole complete image it is cropping automatically and i am not able to see whole image.And in cropping screen,there are two buttons save and cancel.If i want to change text on them how can i change.please help me. For your first problem for crop image I am not sure what have to do because in my case its working fine. Actually it is totally depend upon your device density. For this I suggest you ask question on stackoverflow.com and if you got any answer please put your answer on my blog so I and my other visitor can take help from you. And second question for change save and cancel button. so when we use-intent.putExtra("crop", "true"); this is android default behavior we have no any control or we should override OS. well it will be different text and button on different-different devices. Thank you so much and I am waiting for your comment. is it possible to keep pinch zoom in and zoom out for those images which i have selected from gallery so that i can make zoom in on image and fix in that box and so that i can get full image No I don't think it is possible zoom in after crop image. Better idea don't crop. Just remove crop code hope it will help you. Or search for any android library for crop image in full. thanks i will search if i get solution i will put answer in your blog Thank you so much! i want to know that how that rectangle is coming and how to get size of rectangle. This is depend upon android device density and size- Basically this is Android SDk default behavior we are not going to create any rectangle from our self.. for testing just remove below 2 line from your crop code- intent.putExtra("aspectX", 0); intent.putExtra("aspectY", 0); you will see still its working but rectangle ratio is change now- and yes you can create your own Canvas for crop image in a fix size in any shape some thing like); This comment has been removed by the author. Hi, do you know the reason why i run your app in my android phone (Samsung Galaxy Nexus), it pop up a message saying "unfortunately, your app has stopped running." Hi Jaden can you paste your error log here? Well this camera code have issue with samsung gallexy series mobiles. Actually because of good quality high resolution image data got null in OnActivity Result.. So try to get url of image instead of data..try below code- /** *); // convert bitmap to byte ByteArrayOutputStream stream = new ByteArrayOutputStream(); yourSelectedImage.compress(Bitmap.CompressFormat.PNG,100, stream); byte imageInByte[] = stream.toByteArray(); // Inserting Contacts Log.d("Insert: ", "Inserting .."); db.addContact(new Contact("Android", imageInByte)); Intent intent = new Intent(SQLiteDemoActivity.this,SQLiteDemoActivity.class); startActivity(intent); finish(); } cursor.close(); } 04-26 11:38:06.107: E/Trace(1834): error opening trace file: No such file or directory (2) 04-26 11:38:06.162: D/AndroidRuntime(1834): Shutting down VM 04-26 11:38:06.162: W/dalvikvm(1834): threadid=1: thread exiting with uncaught exception (group=0x40c08600) 04-26 11:38:06.170: E/AndroidRuntime(1834): FATAL EXCEPTION: main 04-26 11:38:06.170: E/AndroidRuntime(1834)::38:06.170: E/AndroidRuntime(1834): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2222) 04-26 11:38:06.170: E/AndroidRuntime(1834): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2356) 04-26 11:38:06.170: E/AndroidRuntime(1834): at android.app.ActivityThread.access$600(ActivityThread.java:150) 04-26 11:38:06.170: E/AndroidRuntime(1834): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1244) 04-26 11:38:06.170: E/AndroidRuntime(1834): at android.os.Handler.dispatchMessage(Handler.java:99) 04-26 11:38:06.170: E/AndroidRuntime(1834): at android.os.Looper.loop(Looper.java:137) 04-26 11:38:06.170: E/AndroidRuntime(1834): at android.app.ActivityThread.main(ActivityThread.java:5193) 04-26 11:38:06.170: E/AndroidRuntime(1834): at java.lang.reflect.Method.invokeNative(Native Method) 04-26 11:38:06.170: E/AndroidRuntime(1834): at java.lang.reflect.Method.invoke(Method.java:511) 04-26 11:38:06.170: E/AndroidRuntime(1834): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795) 04-26 11:38:06.170: E/AndroidRuntime(1834): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562) 04-26 11:38:06.170: E/AndroidRuntime(1834): at dalvik.system.NativeStart.main(Native Method) 04-26 11:38:06.170: E/AndroidRuntime(1834): Caused by: java.lang.ClassNotFoundException: Didn't find class "camera.test.demo.SimpleCameraGalleryDemo" on path: /data/app/camera.test.demo-1.apk 04-26 11:38:06.170: E/AndroidRuntime(1834): at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:65) 04-26 11:38:06.170: E/AndroidRuntime(1834): at java.lang.ClassLoader.loadClass(ClassLoader.java:501) 04-26 11:38:06.170: E/AndroidRuntime(1834): at java.lang.ClassLoader.loadClass(ClassLoader.java:461) 04-26 11:38:06.170: E/AndroidRuntime(1834): at android.app.Instrumentation.newActivity(Instrumentation.java:1054) 04-26 11:38:06.170: E/AndroidRuntime(1834): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2213) 04-26 11:38:06.170: E/AndroidRuntime(1834): ... 11 more 04-26 11:38:08.154: I/Process(1834): Sending signal. PID: 1834 SIG: 9 and this as well ... 04-26 11:39:43.295: E/Trace(1969): error opening trace file: No such file or directory (2) 04-26 11:39:43.318: D/AndroidRuntime(1969): Shutting down VM 04-26 11:39:43.318: W/dalvikvm(1969): threadid=1: thread exiting with uncaught exception (group=0x40c08600) 04-26 11:39:43.318: E/AndroidRuntime(1969): FATAL EXCEPTION: main 04-26 11:39:43.318: E/AndroidRuntime(1969)::39:43.318: E/AndroidRuntime(1969): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2222) 04-26 11:39:43.318: E/AndroidRuntime(1969): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2356) 04-26 11:39:43.318: E/AndroidRuntime(1969): at android.app.ActivityThread.access$600(ActivityThread.java:150) 04-26 11:39:43.318: E/AndroidRuntime(1969): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1244) 04-26 11:39:43.318: E/AndroidRuntime(1969): at android.os.Handler.dispatchMessage(Handler.java:99) 04-26 11:39:43.318: E/AndroidRuntime(1969): at android.os.Looper.loop(Looper.java:137) 04-26 11:39:43.318: E/AndroidRuntime(1969): at android.app.ActivityThread.main(ActivityThread.java:5193) 04-26 11:39:43.318: E/AndroidRuntime(1969): at java.lang.reflect.Method.invokeNative(Native Method) 04-26 11:39:43.318: E/AndroidRuntime(1969): at java.lang.reflect.Method.invoke(Method.java:511) 04-26 11:39:43.318: E/AndroidRuntime(1969): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795) 04-26 11:39:43.318: E/AndroidRuntime(1969): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562) 04-26 11:39:43.318: E/AndroidRuntime(1969): at dalvik.system.NativeStart.main(Native Method) 04-26 11:39:43.318: E/AndroidRuntime(1969): Caused by: java.lang.ClassNotFoundException: Didn't find class "camera.test.demo.SimpleCameraGalleryDemo" on path: /data/app/camera.test.demo-1.apk 04-26 11:39:43.318: E/AndroidRuntime(1969): at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:65) 04-26 11:39:43.318: E/AndroidRuntime(1969): at java.lang.ClassLoader.loadClass(ClassLoader.java:501) 04-26 11:39:43.318: E/AndroidRuntime(1969): at java.lang.ClassLoader.loadClass(ClassLoader.java:461) 04-26 11:39:43.318: E/AndroidRuntime(1969): at android.app.Instrumentation.newActivity(Instrumentation.java:1054) 04-26 11:39:43.318: E/AndroidRuntime(1969): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2213) 04-26 11:39:43.318: E/AndroidRuntime(1969): ... 11 more 04-26 11:39:48.279: I/Process(1969): Sending signal. PID: 1969 SIG: 9 As you can see- Caused by: java.lang.ClassNotFoundException: Didn't find class "camera.test.demo.SimpleCameraGalleryDemo" on path: /data/app/camera.test.demo-1.apk that mean something wrong with your code, have you declare SimpleCameraGalleryDemo in your manifest? or package name or file name is change.. Please copy whole project with same class name and package name.. and one more thing let me know your app crash on open camera or on launch your app? Ok. i will try it out. It crashes when i launch the app. Hi, I am able to crop now but its only select from gallery. However, when i use camera and take a picture and try to crop it, the app crashes. what was the issue? well for camera crash you can try above code what I was comment - String[] filePathColumn = { MediaStore.Images.Media.DATA }; Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null); cursor.moveToFirst() .. Hope it will help you.. It is the package name - SimpleCameraGalleryDemo - name conflicted. I solved it as you said and manage to select from image gallery and crop it. However, when i select camera, it crashes. And for the above code you gave it to me.... where do i place it in my coding? Okay so you can check this comment- logic is that- Samsung Gallexy serise mobile have good quality of camera so their size is also big that's why we got data==null in OnactivityResult. for avoiding this issue get last image capture location in your memory card and convert it into bitmap. Do i add the above given comment code into the OnActivityResult method for camera?? and replace with the old ones that were given in the post? P.S: I apologized, i am just confused about the coding for the camera. just change whole onActivityResult with new one.. Hi see below code in my case I am using on button and dialog box for camera and gallery instead of two button- public class SQLiteDemoActivity extends Activity { Button addImage; private static final int CAMERA_REQUEST = 1; private static final int PICK_FROM_GALLERY = 2; int columnIndex; String picturePath="path"; ListView dataList; int imageId; Bitmap theImage; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); /** * open dialog for choose camera/gallery */ final String[] option = new String[] { "Take from Camera", "Select from Gallery" }; ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.select_dialog_item, option); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Select Option"); builder.setAdapter(adapter, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub Log.e("Selected Item", String.valueOf(which)); if (which == 0) { callCamera(); } if (which == 1) { callGallery(); } } }); final AlertDialog dialog = builder.create(); addImage = (Button) findViewById(R.id.btnAdd); addImage.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { dialog.show(); } }); } /** *);//this is your result } cursor.close(); } /** * open camera method */ public void callCamera() { Intent cameraIntent = new Intent( android.provider.MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(cameraIntent, CAMERA_REQUEST); } /** * open gallery method */ public void callGallery() { Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); intent.putExtra("return-data", true); startActivityForResult(Intent.createChooser(intent, "Complete action using"),PICK_FROM_GALLERY); } } Can you please tell me how to remove the spacing from image, that is when I capture image onResult the image is set but there is spacing in background, so how could I remove it? This spacing because of cropping image I mean suppose you capture an Image size of 480*720 and after that you crop it just half 240*360 that's why you are getting black dark shade in background. For this you should check device resolution and crop image according it.. Well if you got any better solution please let me know and please publish you comment on my blog so other user can get help from you.. Thanks.. hi may i know what is the problem that occurred, when i run your app, everything is fine. Until, after the crop section. The cropped image does not show up at all. Hi yan! Let me know please which device you are using for testing may be it happens because of high resolution image. May be your device memory size is less so you did not got any thing.. and please cross check for camera and gallery in both case you are getting same issue? hi manish, i am using a galaxy nexus. so i guess it is the resolution? but i previous run this codes on my phone but it was fine. but the next day my codes fail to run. My memory size is about 1gb left so i doubt that is the problem yes may be remove some app from your phone and try again..and yes you are right problem is the high resolution image. hmm... tried so but still not able to run the program still Please try to debug code using debugger I think you got null data that's why not able to get image after crop.. Use debugger please.. and one more testing remove crop code from your project then try again.. Remove these lines from your code- intent.putExtra("crop", "true"); intent.putExtra("aspectX", 0); intent.putExtra("aspectY", 0); intent.putExtra("outputX", 200); intent.putExtra("outputY", 150); hi manish, sorry for this. but i am a beginner programmer for android apps. erm.. i did remove the cropping code but it still does not work. now i try checking for null data but it says imagebyte is not used. hi In my code i want to use gallery but one problem is that get images from drawable and crop it and set as wallpaper so can you please help me?? Thanks in advance I think you can't open a crop window for drawable image for that you should use canvas. you can Goggling for that and you can check my below comment it will give you a little idea about it- I got code but when store in sd card image will going to distorting. I have one code but in that when i crop image and store it into sd card then it will be blurry so not able to set as wallpaper. yes dear after crop image it will got blurry in this case I can't help I think don't crop more or try perfect ratio to crop image.. when i click on camera then camera open and take pick and when click on save my apps crashed and showing msg java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=0, data=null} to activity {com.example.cropaftercapture/com.example.cropaftercapture.MainActivity}: java.lang.NullPointerException plz help me and thanks in advance PLZ As you can see your data is null that's why your application got crash.. I think you are using Samsung phone for testing. In High Density device image size is big so we got data==null. for that just capture image and get last path of image and crop it.. Just follow my this comment or do googling - Thanks, protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == PICK_FROM_GALLERY && resultCode == Activity.RESULT_OK) { // code here } } Without "resultCode == Activity.RESULT_OK" this checking, the app forces close on back button press Hi it is becasuse of null data on press back button so please change your code- protected void onActivityResult(int requestCode, int resultCode, Intent data) { if(data!=null){ if (requestCode == PICK_FROM_CAMERA) { Bundle extras = data.getExtras(); if (extras != null) { Bitmap photo = extras.getParcelable("data"); imgview.setImageBitmap(photo); } } Enjoy.. i have a problem, how can i save the image that has been crop into my phone gallery? thank you very much, I have a problem ... on galaxy s with android 2.3.3, after taking the picture and highlight the crop area the image saved without getting back to the app activity, it get back to the camera android the onActivityResult() will not be invoked how to solve this ? I've tried the code on sony xperia s with android 4.0 it works without error. Yes Firas you are right I have also same issue its work on some devices and failed on some.. Error is who==null; I think it is because of high resolution image.. Please try it on google.. Ok thank you for the fast response, I don't think the problem because if high resolution cause the xperia s is 12mp and the galaxy s is 5mp. I will try on google thanx :-) I tested it on HTC 4.0 and Samsung Gallexy S Dues and its working fine.. Please check on google and if got answer please paste here so other people got help from you.. Thanks, Thanks for your code.. but how can get exact path of cropped image. I want upload it to the server Hi I got same question on stackoverflow- search it on google- "stack overflow question number 14534625" Thanks, hi, can you tell me, how to pass the cropped image from one activity to another activity? it showing classcastexception... Hi, where I add bitmap into imageview from there call an intent for next page and put your image something like that- Intent intnt = new Intent(A.this,Bclass); intnt.putExtra("photo", photo); startActivity(intnt); And on activity B- Intent intnt = getIntent(); final Bitmap crop_photo = (Bitmap) intnt.getParcelableExtra("photo"); Thanks, thank u so much.. it's working. i did a small mistake. thanks a lot.. Your welcome! Hey manish, I am done with the path of cropped image.... Now i want cal aspx page from android... do you know how to do this..... use web services follow my below post- hello manish..thanks for sharing a nice tutorial on image cropping in android..im new to android can you help me in my projects...some guidance im stuck up in some parts.. :( Yes sure i you have little issues you can ask.. Hi Manish, How do we crop an image if we have it's path ? In one of your replies () you explained how to get the captured image path, could you please explain how to let the user crop it ? Thanks in advance Hi this is normally not happen so you can use canvas for it. See one of my comment on this post- After cropping image i want to upload to server and get link of that uploaded image. But when crop and press save it just give crop image. How could i upload it? Hi after cropping don't set your image in any imageview, just call web services for upload your image on server.. I ran this code in samsung galaxy y dual(api level 8) I got the output, but when i run it in Celkon(android 4.0) i'm getting error message. Unfortunatuly Gallery is closed.So i removed Intent.putExtra("crop", "true")line then It works fine .Why? can you explain please Yes it is because of High resolution of Image... Do you know how to get the coordinates(X,Y,H,W) of the cropped image? In my knowledge we can't get coordinate of crop image but we can set coordinate. intent.putExtra("crop", "true"); intent.putExtra("aspectX", 0); intent.putExtra("aspectY", 0); intent.putExtra("outputX", 200); intent.putExtra("outputY", 150); Read more: Hi Manish, This is really a great tutorial, I have searched over a lot of websites and finally landed up here. My requirement is to take a picture and crop it and show it on the ImageView. With your code, I am able to take the picture, but upon confirming the picture, the app is crashing. When i commented out the cropping part, its working fine i.e. intent.putExtra("crop", "true"); intent.putExtra("aspectX", 0); intent.putExtra("aspectY", 0); intent.putExtra("outputX", 200); intent.putExtra("outputY", 150); But, The cropping and displaying of image from gallery works fine, though my requirement is to capture and crop the image. Can you please guide me where i went wrong or what is problem? Hi Satish, Thanks for comming here and share your problem with me. Actually you are not doing anything wrong. problem with android OS. In market many size and many company devices and they have their own camera resolution and their own way to override android OS. I also got stuck same code working fine on HTC device and some of Samsung device but some of Samsung device have issue. I am using Samsung gallexy s-dues, HTC Desire and its working fine camera and gallery both but one of my friend have samsung device and I am getting crash on Gallery and on one of my user having crash on Camera.I am really got stuck. I don't know why Android allow to override OS like that. Actually problem is data when you are call camera or gallery Intent and getting in onActivityResult() data came null, that's why application got crash. for that I try many thing like getting direct path and after that crop that image but now this code is working fine on high density device but got crash on lower density devices :) Well If you don't want crop Image you can get it using it's path and display in Imageview. Please discuss your views, sure I will help you. Thanks, Hi Manish, This code looks awesome,do you know how to give overlay points on the image so that image can be cropped as per the points boundary...something like camscanner android application.Do help me with your answer. Hi Robin, I think you should use canvas. It will help you to crop image in custom ratio like-circle,square etc. can you help me,if you have any code Sorry dear I don't have any code. Just see this comment hope it will help you- This comment has been removed by the author. very fine code you upload Thanks Nadir! Hi Manish..i would like to say thanks first for ur post..its helping to me ..but when i m taking image from Camera i am unble to crop it app is crashing ..cuold u please help me.. my code is: } onActivityResults: if(requestCode == PICK_FROM_CAMERA) { Bundle extras = data.getExtras(); if (extras != null) { Bitmap photo = extras.getParcelable("data"); ImageView picView = (ImageView)findViewById(R.id.picture); //display the returned cropped image picView.setImageBitmap(photo); } //imgview.setImageBitmap(photo); }//user is returning from cropping the image hi, how can i get the best result of cropping image, so that the resolution of cropped image same as original ( quality).. thanks Suppose you have imageView of size 200x200 or you want send that image 150x150 size on server so crop that image in that ratio else it will be blur. could you please send me the zip getanoopwayanad@gmail.com Sorry Anoop don't have code. Just copy from above it is very simple code... Thanks! This comment has been removed by the author. ok...i have done this....thank u so much. there is small problem everything work fine but when we press the back button(after the cropping option) on the mobile, appilcation crashes. after cropping when we press save or cancel it is fine.. i think you got my problem......could you please help. Yes yes just check for null data - if (requestCode == PICK_FROM_CAMERA) { if(data!= null) { Bundle extras = data.getExtras(); if (extras != null) { Bitmap photo = extras.getParcelable("data"); imgview.setImageBitmap(photo); } } i am not sure but i think it should work please check and update me.. Thanks! I want to crop an image in my application when it is selected from gallery.My cropping code work from the simulator but not properly work on phones. I set outputX=400 and outputY =487. In my simulator i get the output bitmap with 400 x 487 resolution,but when i cropped the image from gallery i get the output bitmap with 145 x 177 resolution. Why does it happen? it is because of device density. It will be different-different on different devices. My system "photo crop" app working for crop but "Picture Crop" app is not responding when i click on save button... Do u have any solution for it @Override public void onClick(View v) { // TODO Auto-generated method stub switch(v.getId()){ case R.id.buttonCam: try{ Intent it=new Intent(getApplicationContext(),MyCustomCamera.class); startActivityForResult(it, PICK_FROM_CAMERA); }catch(Exception e){ e.printStackTrace(); } break; case R.id.buttonGall: try{ Intent intnt = new Intent(); intnt.setType("image/*"); intnt.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intnt, "Complete action using"), PHOTO_PICKED); }catch(Exception e){e.printStackTrace();} break; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // TODO Auto-generated method stub super.onActivityResult(requestCode, resultCode, data); switch(requestCode){ case 1: if(resultCode==RESULT_OK){ String mydir = data.getExtras().getString("image_path"); File f1=new File(mydir); cropCaptureImage(Uri.fromFile(f1)); } break; case 2: if(resultCode==RESULT_OK){ cropCaptureImage(data.getData()); } break; case 3: if(resultCode==RESULT_OK){ Bundle extras = data.getExtras(); Bitmap thePic = (Bitmap)extras.get("data"); ByteArrayOutputStream baos= new ByteArrayOutputStream(); thePic.compress(CompressFormat.JPEG, 100, baos); byte[] byteArr=baos.toByteArray(); Intent it=new Intent(MainWindow.this,MainActivity.class); it.putExtra("myImage",byteArr); startActivity(it); }else{ return; } break; } } private void cropCaptureImage(Uri picUri) { // TODO Auto-generated method stub try{ Intent cropIntent=new Intent("com.android.camera.action.CROP"); List list = getPackageManager().queryIntentActivities( cropIntent, 0 ); int size = list.size(); if (size == 0) { Toast.makeText(this, "Can not find image crop app", Toast.LENGTH_SHORT).show(); return; } else { cropIntent.setDataAndType(picUri, "image/*"); cropIntent.putExtra("crop", "true"); cropIntent.putExtra("aspectX", 1); cropIntent.putExtra("aspectY", 1); cropIntent.putExtra("outputX", sv.getWidth()); cropIntent.putExtra("outputY", sv.getHeight()); cropIntent.putExtra("scale", true); cropIntent.putExtra("return-data", true); startActivityForResult(cropIntent, 3); } }catch(Exception e){e.printStackTrace();} Hii M.S, I have problem with cropping a large image, its didn't work for more than 600 px image resolution protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_OK) { if(requestCode == FILE){ UrlGambar = data.getData(); performCrop(); } else if(requestCode == PIC_CROP){ Bundle extras = data.getExtras(); thePic = extras.getParcelable("data"); ImageView picView = (ImageView)findViewById(R.id.tampil); picView.setImageBitmap(thePic); TextView text = (TextView) findViewById(R.id.height); TextView text2 = (TextView) findViewById(R.id.focal); TextView text3 = (TextView) findViewById(R.id.sh); Bitmap bMap = thePic; text.setText(Integer.toString(bMap.getHeight())); text2.setText(Float.toString(FocalLength)); } } } how can I get picture Height and Focal length after cropping? private void performCrop(){ try { Intent cropIntent = new Intent("com.android.camera.action.CROP"); cropIntent.setDataAndType(UrlGambar, "image/*"); cropIntent.putExtra("crop", "true"); cropIntent.putExtra("aspectX", 0); cropIntent.putExtra("aspectY", 0); cropIntent.putExtra("scale", true); // cropIntent.putExtra("outputX",1500); //cropIntent.putExtra("outputY", 1500); cropIntent.putExtra("return-data", true); startActivityForResult(cropIntent, PIC_CROP); } catch(ActivityNotFoundException anfe){ //display an error message String errorMessage = "Oops..Perangkat Anda tidak mendukung fungsi CROP!"; Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT); toast.show(); return; } }} This comment has been removed by the author. Hi Manish, Thanx for helping so many with ur code.Ur code worked fine for me.One prob is zoomin/zoomout is not working when resizing the crop frame in gallery picture but the same is working fine when clicking picture from camera upon resizing ZIN/ZOUT option working..Plz help me what can be done..Thanx in advance. Read more: So Simple just setonclicklistner on that imageview and on click open the camera and onActivityResult set image into imagview. Thanx for the reply. I dont get you.. ur answer is not relevant for my question.If u run ur code..u l get to know while cropping image is zoomin/zoomout when u click picture..but when u select picture from gallery ZIN/ZOUT not happening while cropping. We have same croping code for both. So it should function same as well camera and gallery both. Its not working the same way when i exactly copied ur code.U can also try and see. its possible to get the multiple crop option an above code...pls share Hi Manish, I have got problem for crop image. In Samsung galaxy tab , the selected URI give as null pointer exception,Please give me suggestion. try below post- Hi Manish The crop is not working while selecting image from Gallery. After i select the image it does not give me option to crop. Please help me. Thanks Thanks a ton brother ! I don't have words to express my gratitude towards you ! Just thanks a ton again ! Bro. I have just a small query ! if i set an image to this image view created as per your algorithm.. How am I suppose to save it and retrieve it during the app start and app close ?? Could you please help me on this ... eagerly waiting for your answer.. you need to shave your image into sdcard or sqlite, try below link- Hi Srivastava, I have used your code.its working fantastic but In my application i need to upload the image with 100*100 size. How can i crop to this size. thanks & regaurds... Try something this- Bitmap finalImage = Bitmap.createScaledBitmap(srcImage, desiredHeight, desiredWidth, true); and use finalImage for sending image over the server. I am not sure but it should work for you. hiiii manish your code run my samsung galaxy grand but when i run it on other devices like micromax and huwai it crashes while taking images and on save on it. i can't find the croping function when i run it Hi Manish, After capturing image from camera I want to set the same on imageView of resolution 300x246. I have used you code it is working for me but I am not able to use the same as per my requirement. Can you please provide the solution for the same. Hi Manish, Thanks for this brilliant post!! It has really helped me. I've a query which might be out of the context of this development, but I would really appreciate if you could help me with that. I want to change the value / text in the buttons of 'Save', 'Cancel' and 'Crop' after a picture is taken from any Android device (samsung especially) and the result outcome as well. What happens in my app is, when you take a pic, you get the options to Save and Discard (I want to change the Save to Next). Once you Save it, you land on the Crop screen where you crop the intended image and press Crop. After the image is cropped, you again get the options to Crop or Cancel. At this stage, I want the options to be Done rather than the Crop and Cancel. Once Done is pressed, the cropped image is taken to my app screen. I tried looking for this in the Camera API, but couldn't get anything from there. Hope you could help me with this. Awaiting on your expert advice. Thanks!! Hi, this is android manufacture default feature, you can't override it. you need to implement your own surfaceview for custom requirement. you can try any cropping library too. When I run this, the program exit with [gallery has stopped] error. What the problem is ? Hi, When I am using this code on my Galaxy S5 device after image capture I will go to image crop view that's right. But on my Galaxy S5 after image capture I will go to image save option view . Please help.. Thanks Hi, thx for share your work. It's very interesting :) I test it now. I want after I've selected a picture (or taked a picture) to share this with differents services like G+/fb/email/sms/snapchat/twitter/other. I'm not abble to do this alone. Can you help me à little please ? I think I must use: "Intent sharingIntent = new Intent(Intent.ACTION_SEND); Uri screenshotUri = Uri.parse(path); sharingIntent.setType("image/png"); sharingIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri); startActivity(Intent.createChooser(sharingIntent, "Share image using"));" But I don't kno how For me its not Working. camera working but gallery not displaying image. am using Samsung Galaxy GTS5303 Hi, I have executed this code but while I am executing this code I have an error when camera is opened as "Unfortunately stopped". Can suggest anyone on this this is great but how to store that image in sqlite.. thats more imprtant thing Nice Tutorial, but can you tell me why it's forced close everytime I take from camera, but it's works when I import from gallery. Nice Tutorial, but when I select an image from the gallery, the main activity is opened and no cropping option appears. What do I do ? Thanks can you see the image on main activity? If no it's mean you are getting null as data on your onActivityResult. For that I will suggest to use URI and set into Imageview. Thanks Manish :) nice example Thanks bro :) hello manish, nice work,it worked for me,but in my app I have crop an image already there in activity on click of button I have to crop that image.Can u help? I am not getting my image on image view after clicking save button.plz help me out! I want load image from Gallery and Camera or a url. please help for set mSource is in String format. some device not work in crop image. I test motoe and asus.
https://www.androidhub4you.com/2012/07/how-to-crop-image-from-camera-and.html?showComment=1415958119702
CC-MAIN-2020-05
refinedweb
6,393
52.97
Get an SSL certificate for your domain You can obtain an SSL certificate for your site by: - Using a web host that integrates SSL and configures HTTPS for you. - Getting an SSL certificate from a Certificate Authority (CA) Using a web host with SSL Security. A number of web hosts provide SSL certificates and automatically configure webservers to support HTTPS connections. Use a Google website that provides SSL security for free. Google provides SSL security for the sites hosted on the following Google products for free. Google My Business You can create a site through Google My Business and integrate it with your secure namespace domain. - “Create your free website with Google” in the Google My Business help center - “Use your existing domain name for your new site” in the Google My Business help center Blogger You can set up a custom domain name for Blogger to satisfy the security requirements of a domain in a secure namespace (. See “Set up a custom domain” in the blogger help center Use one of our partner web hosts. Google’s web host partners can provide security at a variety of prices, starting from no additional cost. - Bluehost (WordPress) - Shopify - Squarespace - Weebly - Wix See “Web presence” You can also integrate your domain with any other web host that provides SSL security. See “Map your domain to a third-party web host” for a instructions on integrating your domain with several popular web hosts. Read your web host’s help center to make sure it provides SSL. Getting an SSL certificate from a Certificate Authority (CA) You can obtain an SSL certificate for your domain directly from a CA. You will then have to configure the certificate on your web host or on your own servers if hosting it yourself. You can get a free SSL certificate from Let’s Encrypt, a popular CA that provides certificates in the interest of creating a safer Internet: More help on configuring HTTPS:
https://support.google.com/domains/answer/7630973?hl=en&ref_topic=9018335
CC-MAIN-2019-26
refinedweb
326
58.11
German Free Software Group asks Gov't Say No to MS 64 A reader writes "A German free software advocacy group has asked local government officials to halt their agreement with Microsoft to sponsor a new e-commerce center.. The group has made a good arguement, stating that taxpayer dollars are being used to pay for something that can already be obtained for free. The government's current reply is that partnering with Microsoft doesn't preclude involvement from other operating system. Bad Link (Score:3) Working Link to the Story (Score:1) Users balk at German state's deal with Microsoft [cnn.com] MS hope to gain more than they lose (Score:2) The group are entirely correct that the government is, in effect, subsidising Microsoft in this way, even though naively it looks the other way around. End corporate welfare! Something both libetarian socialists and libertarian capitalists should agree on :) I'm Surprised (Score:1) Re:MS hope to gain more than they lose (Score:2) I may be biased, but if there was some cash involved, say some donations, would I be wrong to consider this as corruption? Anti-competitive (Score:1) Link to FFII (Score:2) and the Open Letter [ffii.org] it's not too long and a good read. nmarshall #include "standard_disclaimer.h" R.U. SIRIUS: THE ONLY POSSIBLE RESPONSE Doesn't preclude what? (Score:4) And 'Linux' won't be able to sponsor this, no matter what the government thinks. Linux isn't a corporation. You know, given the German response to this (and the other incident mentioned in the article), I'm surprised that such a movement hasn't taken place in the US. Given Microsoft's funding of school computer labs, one might think that similar organizations here (here being the US) would possibly want schools to also look to alternatives. Maybe Apple's a bit more powerful in these situations or perhaps our country just isn't as open to these new ideas as Europe is. Hmm. see my earlyer post. (Score:1) nmarshall #include "standard_disclaimer.h" R.U. SIRIUS: THE ONLY POSSIBLE RESPONSE 700 signatures (Score:2) I find this quite funny. Methinks that Microsoft can't take nearly universal acceptance of it's product by the public for granted anymore! Re:MS hope to gain more than they lose (Score:1) The idea of deals is that both parties benefit. A Model for other complaints about Govt spending? (Score:2) Gov't shouldn't be speding money on stuff that is available for free. How many other goverment programs feed the evil giant? Can we use a similar attack any of those? what exactly is the project? (Score:1) a) is it a place to demo e-commerce stuff(lots of silly ads and propaganda)? b)is it that the gov. is gonna help small business set-up and host their e-comerce sites? if its option b then that's a cool idea. either way it's too bad microsoft had to get their grubby hands in it. they just can't leave anything alone can they. Re:700 signatures (Score:1) -- Re:700 signatures (Score:1) True. Now if these were all network admins or CTOs or some such thing, then it would be significant. Re:A Model for other complaints about Govt spendin (Score:1) Be prepared for an uphill battle - most people in power are pro-corporate welfare (which this would be considered..) think of your congressman, his first line of defense would probably be "but we NEED to spend money on this, because it keeps all those citizens employed." This would probably work better in other countries, where that particular defense wouldn't work... (for you Canadians reading, try The Canadian Taxpayer Federation [taxpayer.com] Re:Anti-competitive (Score:1) Maybe I missed something, but I don't see your point. I think it's quite appropriate, given Microsoft's long history of abuses, that they be opposed "soley because they are Microsoft." I really don't care if they like it or not, they earned it and made a killing along the way. Just chalk it up to karma. Re:Anti-competitive (Score:1) However, that's not the case here. The people signing the petition are putting forward a valid argument that there are alternatives that are not being properly considered, and that these alternatives are both (1) more stable, and (2) free. Considering that the government in question can get more for less, it seems only right that people would complain that it's squandering their taxes. -Snibor Eoj Where can I find more information / petition? (Score:1) Are there any online information available? Where can I sign the protest letter? Taxpayers demanding intelligent decision making (Score:3) There is also a legitimate philosophy against subsidizing industry in general -- there are numerious ethical as well as economic arguments against this kind of thing (it does, I think anyone would agree, severely distort the free market no matter how it is done, and many people rightly think this is a bad thing irrespective of the ethical arguments pro or con). Subsidizing a monopolistic entity, which has caused such havoc in the IT industry in the last decade is to many a particularly perverse and noxious example of this practice. Re:MS hope to gain more than they lose (Score:1) I think it is more correct if you add 'think they' to the above phrase: The idea of deals is that both parties think they benefit. Did users benefit by getting Dos/Windows preinstalled from 1991 to 1996? They thought so but in reality they were being bound into a contract with Micros~1 in such a way as to tie them to that vendor for the rest of their lives. Perception is at the heart of "the deal". IMHO Re:Where can I find more information / petition? (Score:1) nmarshall #include "standard_disclaimer.h" R.U. SIRIUS: THE ONLY POSSIBLE RESPONSE Re:Alert! Moderator abuse (Score:2) Punish? By moderating down? Boy, I gotta figure out how to be a moderator when I grow up so that I can punish people with a mere click of the mouse! Geez, you'd think a moderator had powers to garnish your wages for making bad posts. If a moderated post is too much of a slap to your ego to bear, you need to get out more. >Go ahead moderate this down. Squash my opinion. Squelch my voice If only I could govmt contracting in general and in Germany (Score:2) A number of posts included some incorrect assumptions about how government contracting, esp outside of the US, works. The idea that government should not support any particular company (ie stand back and let free competition occur) is a peculiarly American idea. Most other nations expect their governments to actively lobby and support favored businessess. This has nothing to do with what business provides the "best" products, and has everything to do with politics and whose hands are in whose pockets. Germany follows an economic model that favors large, established organizations (business, labor groups, etc.) who avoid direct competition with each other but who instead come to agreements via a closed-door decision process. So Germany knows perfectly well what it's getting with Microsoft; the whole point is to get in bed with companies for the long haul, not for one-time contracts. The German govmt couldn't care less about the DOJ/MS case. Much of the world doesn't think very highly of American politics; from their perspective, we get all bent out of shape over things that are common practice elsewhere (Presidential affairs, predatory business practices). R.U. SERIUS (Score:1) School computer administrators (Score:1) at a high school I went to, where there are MANY computers, and have been for a long time, the only linux boxen are the servers (well, except for the Solaris one) becasue a) the faculty guy in charge of this knows squat about it and so b) the students who I think it's more than possible to do. ask at your local hs (mostly) about that, and about helping admin them on a continuing basis, since that is one of the biggest problems. one explanation of why they don't have to just throw out their 386's and can actually run useful software on them (not to mention the lack of expense and the joy of the cs classes) they'll be at least willing to listen. I'm still working on my old school because this is a great place to promote Linux-awareness. Apple knew what they were doing when they equipped all those schools with computers, and Microsoft does now. Lea Re:govmt contracting in general and in Germany (Score:1) putting programmers to work... (Score:1) programmers. By spending more on commercial software, you are actually spending money to bring programmers into the country. If that made any sense. Regardless. Cutting spending w/ out cutting services is what they should be about. How can they be against that? Re:I'm Surprised (Score:1) I'm thinking the German Gov. thinks that M$ is just going to get a slap on the wrist. Personally, it won't effect me too much if the agreement goes through, but I would be interested in knowing if there is anything I (we) could do to attempt to convice the German Gov. that Open Source solutions are more favorable to M$. Combine our voice with that of the German Advocacy (I suck at spelling) group, then perhaps we can convice them to see "the light" At the least, it'd be fun helping out our "overseas brethren" (well, overseas from my point of view).... Re:Silly wabbit! (Score:1) Re:govmt contracting in general and in Germany (Score:1) I agree that it's good to have regulations on govmt contracting -- better than having it unregulated! However, at the practical level, the existence of regulations means only that the contracting process is byzantine. Just because something is "required by law" doesn't mean that the process will genuinely be open, fair, logical, produce the best result, etc. Believe me, as someone who's worked in govmt contracting for years, there are no rules so well-intentioned that they can't be manipulated. The "low bidder" rule being a perfect example -- the games you can play with THAT one... Don't mean to sound cynical, it's just the way business is done -- people will work the system to their best advantage. Implying that everything will work out OK because it's "required by law" is a misleading statement. The best guarantee of a well-managed govmt is an involved citizenry. That's what is encouraging about this particular situation in Germany. BTW the stakeholder method (forget the German term) of corporate governance has been the standard in Germany for decades, it does not relate specifically to contracts (large or small). Re:I'm Surprised (Score:1) The issue for anyone seeking to 'get into bed' with MS isn't isn't whether Gates will lose anything after the DOJ is finished, but whether the company will be able to provide the level of service they can now (supposing you think MS service now is acceptable; personally, I have no opinion about that). It just doesn't strike me as good strategy to get involved in any new venture with MS right now. Maybe the government in that part of Germany doesn't think so, but certainly companies in the US are using the trial to position themselves to kick MS when it's down, and they're much closer to the action. I don't think that the DOJ is going to wipe out MS or Gates, but there's likely to be a lot of internal turmoil if the judge does anything on the order of what MS has given him reason to do (i.e something pretty serious). And that just makes things uncertain, which businessmen and governments tend not to like. Info-may-shun Pro-fesh-un-nulls (Score:1) Once upon a time, the Great Manager deemed a notoriously slow program so important that he would set three of his top staff members to work on it. The first employee, a computer engineer, noted that there were too many bad blocks on the disk plus dodgy memory with parity errors, so swapped out the hardw are. And there was some rejoicing. The second employee, a computer scientist, noted that the algorithm was quartic, and reduced it to one that was merely quadratic. And there was much rejoicing. The third employee, an in-fo-may-shun pro-fesh-un-null, went down to Radio Shack to find out whether the Great Satan had issued a Win95 Resource Kit he could buy. And there was much invoicing. Re:I'm Surprised (Score:1) Actually I'm not really surprised. Most politicians (the German ones are no exception), like most 'ordinary' people, aren't aware of geekish stuff like Linux. All they see is the omnipresence of MS on their computers. The DOJ isn't that big in the German news and even if the outcome doesn't favor MS - what will be the consequences for Rheinland-Pfalz (which btw is just around 10% of Germany anyway)? and Actually... (Score:1) ...I read somewhere recently that he's up to $100 billion; that'd make it %99 before he' down to a measly(sp?) $1 bil. I can't even comprehend how he's even motivated about money! I mean I understand it intellectually (monomania, etc...or is that moneymania chris Depends on where in Europe (Score:2) Is not. >Much of the world doesn't think very highly of American politics; from their perspective, we get all bent out of shape over things that are common practice elsewhere (Presidential affairs, predatory business practices). Ok, but its not true for ALL other countries. Yes, most of the world thinks that presidental affairs is a more a matter between the president and his wife (lying about is under oath is worse though), but if you suggest that only Americans get upset over corruption or predatory business practices, think again. In Sweden, Mona Salin, the woman who was supposed to become the new head of the Social Democracy party and therefore probably the next prime minister, was ripped apart by media after using an official credit card to buy private stuff (I think it was diapers and socks or something banal like that) for around $20, even though she had later paid back the money! She resigned from her post and disappeared from politics. (Though she was forgiven after a while and is back now.) But yes, I have gotten the impression that in southern Europe (France and Italy especially), voters seem to accept corruption quite a lot. This is what has made Scandinavians very sceptic about joining the EU. However, things are moving in the right direction. Remember Edith Cresson (sp?), she was thrown out together with the rest of the European parliament. But maybe I'm prejudiced as well when accusing southern Europe. Look what I found on the net. Take a look at this. The lower the number, the more corruption in the country. Guess which country doesn't even make it into the top ten? Cheers, Lars ***************** Table 1. 1996 Transparency International Corruption Index By Country Country Corruption Ranking New Zealand (NZL) 9.43 Denmark (DNK) 9.33 Sweden (SWE) 9.08 Finland (FIN) 9.05 Canada (CAN) 8.96 Norway (NOR) 8.87 Singapore (SGP) 8.80 Switzerland (CHE) 8.76 Netherlands (NLD) 8.71 Australia (AUS) 8.60 Ireland (IRL) 8.45 United Kingdom (GBR) 8.44 Germany (DEU) 8.27 Israel (ISR) 7.71 United States (USA) 7.66 Austria (AUT) 7.59 Japan (JPN) 7.05 Hong Kong (HKS) 7.01 France (FRA) 6.96 Belgium (BEL) 6.84 Chile (CHL) 6.80 Portugal (PRT) 6.53 South Africa (ZAF) 5.68 Poland (POL) 5.57 Czech Republic (CZE) 5.37 Malaysia (MYS) 5.32 South Korea (ROK) 5.02 Greece (GRC) 5.01 Taiwan (TAI) 4.98 Jordan (JOR) 4.89 Hungary (HUN) 4.86 Spain (ESP) 4.31 Turkey (TUR) 3.54 Italy (ITA) 3.42 Argentina (ARG) 3.41 Bolivia (BOL) 3.40 Thailand (THA) 3.33 Mexico (MEX) 3.30 Ecuador (ECU) 3.19 Brazil (BRA) 2.96 Egypt (EGY) 2.84 Colombia (COL) 2.73 Uganda (UGA) 2.71 Philippines (PHL) 2.69 Indonesia (IDN) 2.65 India (IND) 2.63 Russia (RUS) 2.58 Venezuela (VEN) 2.50 Cameroon (CMR) 2.46 China (CHN) 2.43 Bangladesh (BGD) 2.29 Kenya (KEN) 2.21 Pakistan (PAK) 1.00 Nigeria (NGA) Re:It's not the Rheinland-Pfalzian either ;) (Score:1) Nevertheless you were right about that its just a state... though the one whith the most inhabitants. Re:700 signatures (Score:1) Also, if you take a closer look at who actually signed the petition there are quite a few interesting startup companies (or at least their CEOs) at wich this whole new-media center thing aims. OTOH, I'm not too optimistic about the outcome of this movement, though. Re:It's not the Rheinland-Pfalzian either ;) (Score:1) Re:Info-may-shun Pro-fesh-un-nulls (Score:1) Gates' Wealth (Score:1)
https://slashdot.org/story/99/06/14/175231/german-free-software-group-asks-govt-say-no-to-ms
CC-MAIN-2017-47
refinedweb
2,917
65.93
- Tutoriais - Survival Shooter tutorial - Player Health Player Health Verificado com a versão: 4.6 - Dificuldade: Principiante This is part 6 of 10 of the Survival Shooter tutorial, in which you will program the player's health, which is used in reference by other elements of the game. Player Health Principiante Survival Shooter tutorial Transcrições - 00:01 - 00:03 The next thing we're going to do is look in to - 00:03 - 00:05 player health, so obviously we just created a slider - 00:05 - 00:06 to represent the health, - 00:06 - 00:08 we now want to actually implement that. - 00:08 - 00:10 So we have this HealthUI - 00:10 - 00:13 and the next component to this game - 00:13 - 00:15 that we want to have is we want to - 00:15 - 00:17 have the player have health - 00:17 - 00:19 that is able to be taken away and is able to - 00:19 - 00:21 also interact with our UI that we just created. - 00:21 - 00:23 We also want to have the enemy have - 00:23 - 00:25 the ability to attack the player and thus - 00:25 - 00:27 take that health away. - 00:27 - 00:30 And then from there we're going to reverse the roles, - 00:30 - 00:32 we're going to give the enemy some health and give the player - 00:32 - 00:33 the ability to take that health away. - 00:34 - 00:36 What we're going to do to start is we're going to go - 00:36 - 00:38 to the Scripts folder and we're going to - 00:38 - 00:40 locate the Player folder and - 00:40 - 00:43 we should find a script called PlayerHealth. - 00:44 - 00:46 So we're going to take that and we're going to click - 00:46 - 00:49 and drag that on to the Player game object - 00:49 - 00:51 in our hierarchy. - 00:51 - 00:53 So we will drop there and if we click on the player, - 00:53 - 00:55 we scroll down and we should see - 00:55 - 00:57 Player Health Script as a component. - 00:57 - 00:59 Also we are currently still in this - 00:59 - 01:01 view where we're really zoomed out and we're - 01:01 - 01:04 focused on the canvas and all that stuff - 01:04 - 01:06 so why don't we take a second, we'll come out of 2D - 01:06 - 01:09 view here again by clicking on the 2D button - 01:09 - 01:11 right there, bringing us out of that 2D mode - 01:11 - 01:14 and then if we want to get to the player quickly - 01:14 - 01:16 we can just double click on the player's name in the hierarchy - 01:16 - 01:18 it'll zoom us right in there. - 01:18 - 01:21 It just brings us back to where we were previously - 01:21 - 01:23 We now have the PlayerHealth script on the player - 01:23 - 01:25 so we're going to open it up and take a look at it - 01:25 - 01:27 before we do be sure to save your scene. - 01:28 - 01:30 And let's go ahead and pop this open. - 01:31 - 01:32 Alright, player health. - 01:32 - 01:34 So we start off with our PlayerHealth with a whole - 01:34 - 01:36 bunch of variables so let's just step through and - 01:36 - 01:38 see what each of these are. - 01:38 - 01:40 So the first variable here is our startingHealth, - 01:40 - 01:42 which is a public integer which dictates - 01:42 - 01:44 how much health the player has - 01:44 - 01:46 when the level first starts. - 01:46 - 01:48 Next we have an integer for currentHealth - 01:48 - 01:50 which is how much health a player will have - 01:50 - 01:53 after they've been damaged or just at any given point in the game. - 01:53 - 01:55 We have this healthSlider which - 01:55 - 01:57 is a slider game object - 01:57 - 02:00 which is the reference to that slider UI element - 02:00 - 02:01 that we created earlier. - 02:01 - 02:04 Now a good note right here, we're accessing Slider, - 02:04 - 02:06 which is the new UI. - 02:06 - 02:08 In order to access this we need to - 02:08 - 02:11 include using UnityEngine.uI. - 02:11 - 02:13 If you don't have that line of code at the top - 02:13 - 02:15 using UnityEngine.uI - 02:15 - 02:17 you're not going to be able to use text, images, sliders - 02:17 - 02:19 any of the new UI components. - 02:19 - 02:21 So just keep in mind you have to have that. - 02:21 - 02:23 After the slider we then have a - 02:23 - 02:25 public Image damageImage, - 02:25 - 02:27 which is again a reference to that damage image - 02:27 - 02:28 item we created. - 02:28 - 02:30 We have an audio which is our death clip. - 02:30 - 02:32 So unlike our hurt clip the death clip - 02:32 - 02:35 is going to be what's called a one-shot audio - 02:35 - 02:36 where we basically are saying we're not going to play - 02:36 - 02:38 the hurt sound any more, this is the sound the player makes - 02:38 - 02:39 when the player loses the game. - 02:39 - 02:42 We have a public float flashSpeed which is how - 02:42 - 02:44 quickly the damaged image - 02:44 - 02:46 flashes up on the screen. - 02:46 - 02:48 And then we have flashColour which we have - 02:48 - 02:52 set to (1f, 0f, 0f, 0.1f) which means - 02:52 - 02:54 completely red and a tenth - 02:54 - 02:55 of the way completely opaque. - 02:55 - 02:57 So it's mostly transparent and red. - 02:58 - 03:00 Next we have some private variables, the first - 03:00 - 03:03 is animator anim which again a reference - 03:03 - 03:05 to our animator components. - 03:05 - 03:07 We have a reference to our audio sources which - 03:07 - 03:09 we call payerAudio. - 03:09 - 03:11 We have a reference to the playerMovement scripts - 03:11 - 03:13 So this is the first time we've seen this. - 03:13 - 03:16 We've created a reference to another script - 03:16 - 03:17 that we've already written. - 03:17 - 03:20 We all remember writing PlayerMovement earlier today - 03:20 - 03:22 so now we are actually getting a reference to that - 03:22 - 03:24 script that is on the Player - 03:24 - 03:26 so that we can prevent the player from - 03:26 - 03:28 running around once the player is dead. - 03:28 - 03:30 We have to have a reference to it to do that so - 03:30 - 03:32 you're seeing some script interactivity there. - 03:32 - 03:35 We have 2 boolean values, one is isDead, - 03:35 - 03:37 which will determine whether or not the player is dead. - 03:37 - 03:39 And the other is damaged, which will allow us - 03:39 - 03:41 to know whether or not the player has taken damage. - 03:41 - 03:43 The awake function here is going to be fairly similar - 03:43 - 03:45 to what we've seen before, we're starting - 03:45 - 03:47 by getting a reference component to - 03:47 - 03:49 our animator, we're then getting a - 03:49 - 03:51 reference to our audio source - 03:51 - 03:54 playerAudio = GetComponent - 03:54 - 03:55 This is slightly new, so here we're doing - 03:55 - 03:58 playerMovement = GetComponent - 03:58 - 04:00 And you'll see to get the component of the script - 04:00 - 04:03 we've created we just use the name of that script. - 04:03 - 04:06 Script is called PlayerMovement, I want to reference to it - 04:06 - 04:08 so I GetComponent . - 04:08 - 04:10 Again we have some comments in our code. - 04:10 - 04:12 We'll revisit this script and re-enable that later. - 04:12 - 04:14 And then we're going to say our - 04:14 - 04:16 currentHealth is equal to our startingHealth - 04:16 - 04:18 You'll recall awake gets called right - 04:18 - 04:20 at the beginning when the game first starts up - 04:20 - 04:22 so we're just going to set out currentHealth to it's max - 04:22 - 04:23 value right there. - 04:24 - 04:26 Update method, our update method's really simple. - 04:26 - 04:28 Update is simply concerning itself with - 04:28 - 04:30 whether or not we are flashing that - 04:30 - 04:32 red damaged image, right. - 04:32 - 04:34 And so basically what this function is saying - 04:34 - 04:36 is 'hey, if we are damaged, - 04:36 - 04:38 if damage has been taken, what we are going to do is - 04:38 - 04:40 we are going to set this image - 04:40 - 04:42 to our flashColour', - 04:42 - 04:44 which you'll recall is red with a - 04:44 - 04:46 10% opacity, so that's going to happen - 04:46 - 04:47 immediately, it's going to flash this red. - 04:47 - 04:49 Otherwise, if we're not damaged, - 04:49 - 04:52 what we're concerned with is fading - 04:52 - 04:55 the damaged image away, so it flashes red - 04:55 - 04:57 and then we're going to fade it back to transparent. - 04:57 - 04:59 And we do that again using Lerp. - 04:59 - 05:01 Before we used Vector3.Lerp - 05:01 - 05:04 with the player's movement, so now what we're doing is - 05:04 - 05:06 we're doing a Color.Lerp, - 05:06 - 05:08 which is the exact same concept, - 05:08 - 05:10 we're moving from one to another, - 05:10 - 05:12 but instead of vector3s we're doing color. - 05:12 - 05:14 So we're doing Color.Lerp and we're - 05:14 - 05:16 parsing in the current color - 05:16 - 05:18 of our damaged image and we're - 05:18 - 05:20 parsing the color that we would like, - 05:20 - 05:23 which is completely clear, completely invisible, - 05:23 - 05:26 and then we have our flashSpeed - 05:26 - 05:27 times Time.DeltaTime. - 05:27 - 05:29 Very much like the smoothing that we had on - 05:29 - 05:32 the camera as it would follow the player around. - 05:32 - 05:35 Here we're just smoothing from the - 05:35 - 05:38 color that it is all the way to transparent. - 05:38 - 05:40 And then finally at the end of every update cycle - 05:40 - 05:42 we're setting damaged equal to false. - 05:42 - 05:44 What that basically means is the moment we - 05:44 - 05:47 take damage we're then going to set damage back - 05:47 - 05:49 to false after showing that damaged image. - 05:50 - 05:52 In the next bit here what we have is a - 05:52 - 05:53 called TakeDamage. - 05:53 - 05:55 Now this function is also unique because it is a - 05:55 - 05:58 public function, as such, what this means is - 05:58 - 06:00 other scripts and other components can - 06:00 - 06:01 call this function. - 06:01 - 06:03 Take damage as a special function in the script - 06:03 - 06:06 in that it's not called in this script. - 06:06 - 06:08 Other stuff calls this function, - 06:08 - 06:10 so when the enemies attack the player they - 06:10 - 06:12 call the TakeDamage function and so - 06:12 - 06:14 again that script interactivity is important. - 06:14 - 06:17 It has to be public or else this isn't going to work. - 06:17 - 06:19 The one parameter or argument for this function is - 06:19 - 06:22 int amount, which is how much damage the player has taken. - 06:22 - 06:24 Next what we're going to do is we want to ensure - 06:24 - 06:27 the player flashes that red image. - 06:27 - 06:29 So we do that by saying damaged equals true. - 06:29 - 06:32 We detract the amount of damage from our current health. - 06:32 - 06:34 We do that using a little shorthand here - 06:34 - 06:37 by saying currentHealth -= amount; - 06:37 - 06:39 What that little shorthand means is we're going to say - 06:39 - 06:41 take the current health, remove the amount of damage - 06:41 - 06:43 and then put that back in to current health, - 06:43 - 06:45 so basically it just reduces by that amount. - 06:45 - 06:47 We are then going to take our current health and - 06:47 - 06:50 parse it in to the value of our slider. - 06:50 - 06:52 And so we see the slider slowly - 06:52 - 06:54 shrink as the player takes more damage. - 06:54 - 06:56 Next we're going to play our audio and if we - 06:56 - 06:58 recall we setup an audio source on - 06:58 - 07:00 the player in Unity - 07:00 - 07:03 and we gave it that Player Hurt audio. - 07:03 - 07:05 So basically every time the player takes damage they're - 07:05 - 07:07 going to play that hurt audio. - 07:07 - 07:10 Finally we're going to say 'the player's hurt, - 07:10 - 07:12 is the player dead?'. - 07:12 - 07:14 What we're going to do is say - 07:14 - 07:16 if the current health is now below or - 07:16 - 07:19 equal to 0, and they're not already dead, - 07:19 - 07:21 that's what that and not isDead - 07:21 - 07:23 make them dead, alright, because there's no sense in - 07:23 - 07:25 making them dead if they're already dead. - 07:25 - 07:28 If that happens we're going to call a new function called Death. - 07:28 - 07:30 Death is a function that is in this script. - 07:30 - 07:32 It's not built in to Unity or anything like that. - 07:32 - 07:34 It's actually the very next function we're going to look at. - 07:34 - 07:36 Basically if the health drops below 0 - 07:36 - 07:37 we're going to call this Death function, - 07:37 - 07:39 and here's what the Death function does. - 07:39 - 07:41 The first thing the Death function does is sets - 07:41 - 07:44 isDead equal to true, saying 'yeah, okay, player is dead'. - 07:44 - 07:47 Next we've got some disabled code, we'll come back to that. - 07:47 - 07:50 Next we say anim.SetTrigger ("Die"); - 07:50 - 07:52 remember when we did the Animator Controller - 07:52 - 07:54 in the animator window and we had that second - 07:54 - 07:56 parameter which was Die which was a trigger? - 07:56 - 07:58 This is where we play that animation - 07:58 - 08:00 so we say SetTrigger Die and the character - 08:00 - 08:02 plays their death animation. - 08:02 - 08:04 We then set the audio clip of - 08:04 - 08:07 the audio source to this Death clip - 08:07 - 08:09 and then we play that sound, the sound the player makes - 08:09 - 08:10 when they lose the game. - 08:10 - 08:12 And then finally here's where we access - 08:12 - 08:14 that script, the Player Movement script - 08:14 - 08:15 we added as a component. - 08:15 - 08:18 We say playerMovement.enabled = false; - 08:18 - 08:20 which basically means no more movement. - 08:20 - 08:22 That script component on the object gets - 08:22 - 08:24 disabled, stops reading our inputs, - 08:24 - 08:26 player stops moving. - 08:26 - 08:28 And so this is that script - 08:28 - 08:30 in it's entirety so let's go ahead and - 08:30 - 08:32 close this down here and now we're going to - 08:32 - 08:34 return to the Unity editor. - 08:34 - 08:37 And again I reiterate, make sure if you - 08:37 - 08:39 click on the player in the hierarchy - 08:39 - 08:41 that you see the playerHeath component - 08:41 - 08:43 at the very bottom, which will let you know that you - 08:43 - 08:46 put that script on to the right game object. - 08:47 - 08:49 Now that we are - 08:49 - 08:52 back here and we have this PlayerHeath script component - 08:52 - 08:54 on the player game object what we're - 08:54 - 08:56 going to do is we are going to start - 08:56 - 08:58 filling in some of these values. - 08:58 - 09:00 So we could see Starting Health is 100, that's fine, - 09:00 - 09:01 it's what we want. - 09:01 - 09:03 Current Health is 0, again that doesn't matter - 09:03 - 09:05 it'll be set in the awake function. - 09:05 - 09:07 But here we have this Health Slider property. - 09:07 - 09:09 And it's currently empty. - 09:09 - 09:11 This is where we establish that link between - 09:11 - 09:13 the UI that we created and the - 09:13 - 09:14 script that we've just added. - 09:14 - 09:16 So if we look in the hierarchy - 09:16 - 09:20 we see the HUDCanvas, which we expand - 09:20 - 09:22 and then the healthUI, which we expand, - 09:22 - 09:25 and right here we have our HealthSlider. - 09:25 - 09:27 So if we were to take this health slider and - 09:27 - 09:29 click and drag and drop it in to the - 09:29 - 09:31 Health Slider property that will link - 09:31 - 09:33 the healthSliderUI component - 09:33 - 09:36 with this Player Health script. - 09:36 - 09:39 So now we can update the health via the slider. - 09:39 - 09:41 Next we have this Damage Image, - 09:41 - 09:43 so again I'm going to come up and grab my - 09:43 - 09:46 Damage Image from the HUD and I'm going to click and drag - 09:46 - 09:50 down in to the Damage Image property in the script. - 09:50 - 09:53 And then finally I have this Death Clip, - 09:53 - 09:55 where it currently says None I'm going to click the circle select - 09:55 - 09:57 here and I'm going to look for - 09:57 - 09:59 Player Death and I'm going to double click - 09:59 - 10:02 and we'll see that that gets added there. - 10:02 - 10:03 So the next thing I want to do now, - 10:03 - 10:06 the player has health and the health is interfaced - 10:06 - 10:08 with our UI system, so as the player loses - 10:08 - 10:10 health the UI system reacts, and all that's done. - 10:10 - 10:12 Now what we want to do is we want to give the - 10:12 - 10:14 enemies the ability to actually attack the player - 10:14 - 10:16 and thus we can see that this all works and - 10:16 - 10:19 see the interactivity of our game objects. - 10:19 - 10:21 We want to look in the Scripts folder - 10:21 - 10:23 and we want to locate the Enemy scripts folder - 10:23 - 10:26 and we're going to locate the EnemyAttack script. - 10:27 - 10:29 What we want to do is click - 10:29 - 10:32 and drag that on to the Zombunny. - 10:33 - 10:35 Again when we select the Zombunny afterwards - 10:35 - 10:37 we should see, - 10:38 - 10:39 we should see EnemyAttack - 10:40 - 10:41 at the bottom there. - 10:41 - 10:43 Let's go ahead and open up EnemyAttack. - 10:44 - 10:47 EnemyAttack, a lot of this stuff is going to be - 10:47 - 10:49 very familiar to you by now, - 10:49 - 10:51 but again we're going to start with a few public variables. - 10:51 - 10:54 The first public variable we're interested in is a public float - 10:54 - 10:56 timeBetweenAttacks, - 10:56 - 10:58 which is 0.5. - 10:58 - 11:00 It basically is the amount of time - 11:00 - 11:02 between each of the attacks - 11:02 - 11:05 And then we also have a public integer, which is the attackDamage. - 11:05 - 11:07 So how much damage has each of these - 11:07 - 11:09 attacks done to the player. - 11:09 - 11:11 Then we have our private variables, and again - 11:11 - 11:13 these are very similar, we have an - 11:13 - 11:15 Animator variable named anim which is going to - 11:15 - 11:17 store our reference to our animator component. - 11:17 - 11:20 We have a GameObject parameter which - 11:20 - 11:22 is going to be the player, so again the - 11:22 - 11:24 enemy will be able to attack the player - 11:24 - 11:26 but it needs to have some reference to that player. - 11:26 - 11:29 We have a reference to the PlayerHealth script. - 11:29 - 11:33 This is new, we have the enemy - 11:33 - 11:35 referencing a script that we have created - 11:35 - 11:37 that is on a different game object. - 11:37 - 11:39 So the player has a PlayerHealth script - 11:39 - 11:41 and the enemy has a reference to it - 11:41 - 11:44 so that the enemy can then damage the player. - 11:44 - 11:46 We have a bit of code that is commented out - 11:46 - 11:48 and then we have a boolean value playerInRange. - 11:48 - 11:50 This will be set to true whenever the player gets - 11:50 - 11:52 close enough for the enemy to attack/ - 11:52 - 11:54 It'll be set back to false when the player - 11:54 - 11:56 gets too far away. - 11:56 - 11:58 And then finally we have float timer, - 11:58 - 12:00 and timer is a variable that we're going to use to keep - 12:00 - 12:02 everything in sync, to make sure that the enemy is not - 12:02 - 12:04 not too fast, not too slow. - 12:04 - 12:06 In our awake function, again we're going to be - 12:06 - 12:08 setting up a lot of our stuff so - 12:08 - 12:12 we're doing GameObject.FindGameObjectWithTag ("player"); - 12:12 - 12:15 Which again is going to locate the player for us - 12:15 - 12:17 and store that reference locally. - 12:17 - 12:19 We do this in the awake method and then we store it - 12:19 - 12:21 so that we don't have to do it every frame - 12:21 - 12:22 or every time we need it. - 12:22 - 12:24 This is a fairly inefficient call - 12:24 - 12:26 so we really want to limit the number of time - 12:26 - 12:28 we do that, so by doing it once in the awake function - 12:28 - 12:30 and storing it we're greatly improving - 12:30 - 12:33 the performance of our games and projects. - 12:33 - 12:36 Then we use that player object that we just found - 12:36 - 12:39 and we say player.GetComponent - 12:39 - 12:41 thus pulling the PlayerHealth script off - 12:41 - 12:44 off that player, and again, storing a reference to it. - 12:44 - 12:46 Now with that reference we have the ability to - 12:46 - 12:49 call that public function takeDamage we saw previously. - 12:49 - 12:52 And then finally we do GetComponent - 12:52 - 12:54 to setup a reference to our animator component. - 12:54 - 12:56 Now remember how we created the - 12:56 - 12:58 sphere collider on the enemy that was a trigger - 12:58 - 13:00 and I talked about how triggers are - 13:00 - 13:03 not used for in-scene effects - 13:03 - 13:05 and Will was talking about how we use these - 13:05 - 13:08 for detecting collisions and stuff behind the scenes? - 13:08 - 13:10 If we have a trigger on an object and - 13:10 - 13:12 another object comes in collision with that - 13:12 - 13:16 it doesn't react physically, because it's a trigger. - 13:16 - 13:18 Instead it calls a function - 13:18 - 13:20 and if we have a function in a script - 13:20 - 13:22 that function runs. - 13:22 - 13:24 The function's called OnTriggerEnter - 13:24 - 13:26 and it gets called whenever anything goes - 13:26 - 13:27 in to a trigger. - 13:27 - 13:30 So here we have void OnTriggerEnter - 13:30 - 13:33 and then inside parenthesis we have (Collider other). - 13:33 - 13:35 Other is whatever it is that - 13:35 - 13:37 collider with this collider. - 13:37 - 13:39 If I'm the enemy and something collided with me chances - 13:39 - 13:40 are Other is the player. - 13:40 - 13:42 And so now I know where that is. - 13:42 - 13:44 So the very next line is - 13:44 - 13:47 me making sure that it's the player - 13:47 - 13:49 because we don't want to be able to attack a sofa - 13:49 - 13:51 we want to only attack the player and - 13:51 - 13:53 as such we want to ensure - 13:53 - 13:54 what it is we are attacking, so we're going to say - 13:54 - 13:58 if(other.gameObject == player) - 13:58 - 14:01 and that double equals is an equality operator, it says - 14:01 - 14:03 'are these the same thing?'. - 14:03 - 14:06 So if what we collided with is the player, - 14:06 - 14:08 cool, okay, then we can attack it. - 14:08 - 14:11 If that's true then we set playerInRange to true. - 14:11 - 14:13 Now there's an inverse version of that - 14:13 - 14:16 function called OnTriggerExit. - 14:16 - 14:19 It tells us that something was in the trigger - 14:19 - 14:20 and it has now gone away. - 14:20 - 14:22 Alright, that's just the complete opposite. - 14:22 - 14:24 So again what we're going to say is - 14:24 - 14:27 was the thing that left the trigger the player? - 14:27 - 14:29 If it was the player is no longer - 14:29 - 14:31 in range, so we set that to false. - 14:32 - 14:34 So we just used the trigger to say 'hey, they're close enough' - 14:34 - 14:35 'no, they're not close enough any more'. - 14:35 - 14:37 'Hey they're close enough, no they're not close enough any more'. - 14:37 - 14:39 This isn't actually the attacking part - 14:39 - 14:41 this is just how we determine whether we're close enough. - 14:42 - 14:44 The actual attacking happens in the update. - 14:44 - 14:46 In the update method the first thing we - 14:46 - 14:49 do is we determine how much time has occurred. - 14:49 - 14:51 We start accumulating this time - 14:51 - 14:53 inside the variable Timer. - 14:53 - 14:55 So every time update runs Timer gets a little bit bigger and - 14:55 - 14:59 a little bit bigger and it represents how much time has passed. - 14:59 - 15:01 Then we're going to say - 15:01 - 15:03 if the timer is greater than - 15:03 - 15:06 the time between attacks, so it's been long enough - 15:06 - 15:09 between attacks and the player is close enough, - 15:09 - 15:11 we're going to attack the player. - 15:11 - 15:13 And we can see that we call the function Attack. - 15:13 - 15:15 Then finally we'll look at Attack here in a second. - 15:15 - 15:17 Then finally we say - 15:17 - 15:19 if the player's health is - 15:19 - 15:22 equal to 0, that means the player died, - 15:22 - 15:24 right, our attack killed it and the player died - 15:24 - 15:27 so we're going to do anim.SetTrigger ("PlayerDead"); - 15:27 - 15:31 which as we recall will transition us from the - 15:31 - 15:34 moving state to the idle state. - 15:34 - 15:36 Player is dead so now we just get to sit around and go - 15:36 - 15:37 'well that was fun, now what?'. - 15:37 - 15:40 And so that's how we stop chasing the player around. - 15:40 - 15:42 So if the timer is greater than the time between attacks - 15:42 - 15:45 and the player is in range then we call this aAttack function - 15:45 - 15:47 and this is what the Attack function looks like. - 15:47 - 15:48 The first thing we do is we reset Timer. - 15:48 - 15:51 We're now attacking so Timer is set back to 0. - 15:51 - 15:54 And then we're going to say if the player is alive - 15:54 - 15:56 playerHealth.currentHealth is greater than 0, - 15:56 - 15:58 let's take some of that away. - 15:58 - 16:00 So we say playerHealth.takeDamage - 16:00 - 16:03 and we parse in however much damage this enemy does. - 16:03 - 16:05 And so then the player is going to manage - 16:05 - 16:07 the rest of that and if that happens to kill them - 16:07 - 16:09 the rest of the update will run and we'll - 16:09 - 16:11 transition in to the idle state. - 16:11 - 16:14 And so that is our enemy attack - 16:14 - 16:16 and once we've taken a look at that - 16:16 - 16:18 be sure to save our scene to wrap up - 16:18 - 16:19 what we've just done here. - 16:19 - 16:22 Why not test this? Let's pop back over to Unity. - 16:23 - 16:26 Will, go ahead and get eaten! - 16:28 - 16:30 Oh, and he's taken damage - 16:30 - 16:33 and we see the health slider being reduced in size, - 16:33 - 16:36 we see the screen flashing slightly, - 16:36 - 16:39 and man, that Zombunny is relentless! - 16:39 - 16:41 I don't think he wants to give you hugs. - 16:42 - 16:45 The damage image there is quite faint. - 16:45 - 16:47 But we can play around with that with the - 16:47 - 16:50 Flash Color public variable on PlayerHealth - 16:50 - 16:51 on the player. - 16:51 - 16:53 So if we wanted to make that more apparent - 16:53 - 16:55 we could crank it up a little bit and it would flash - 16:55 - 16:57 a bit more harshly, like that. - 16:57 - 16:59 Again he achieved this just now by increasing - 16:59 - 17:03 the alpha of the color on the Player Health script. - 17:03 - 17:07 Obviously the higher the alpha the stronger the effect - 17:07 - 17:09 and so on and so forth. PlayerHealth Code snippet using UnityEngine; using UnityEngine.UI; using System.Collections; void TakeDamage (int amount) { // (); } } void; } } import UnityEngine.UI; var startingHealth : int = 100; // The amount of health the player starts the game with. var currentHealth : int; // The current health the player has. var healthSlider : Slider; // Reference to the UI's health bar. var damageImage : Image; // Reference to an image to flash on the screen on being hurt. var deathClip : AudioClip; // The audio clip to play when the player dies. var flashSpeed : float= 5f; // The speed the damageImage will fade at. var flashColour : Color = new Color(1f, 0f, 0f, 0.1f); // The colour the damageImage is set to, to flash. private var anim : Animator; // Reference to the Animator component. private var playerAudio : AudioSource; // Reference to the AudioSource component. private var playerMovement : PlayerMovement; // Reference to the player's movement. private var playerShooting : PlayerShooting; // Reference to the PlayerShooting script. private var isDead : boolean; // Whether the player is dead. private var damaged : boolean; // True when the player gets damaged. function Awake () { // Setting up the references. anim = GetComponent (Animator); playerAudio = GetComponent (AudioSource); playerMovement = GetComponent (PlayerMovement); playerShooting = GetComponentInChildren (PlayerShooting); // Set the initial health of the player. currentHealth = startingHealth; } function function TakeDamage (amount : int) { // (); } } function; } EnemyAttack Code snippet"); } } void Attack () { // Reset the timer. timer = 0f; // If the player has health to lose... if(playerHealth.currentHealth > 0) { // ... damage the player. playerHealth.TakeDamage (attackDamage); } } } var timeBetweenAttacks : float = 0.5f; // The time in seconds between each attack. var attackDamage : int = 10; // The amount of health taken away per attack. private var anim : Animator; // Reference to the animator component. private var player : GameObject; // Reference to the player GameObject. private var playerHealth : PlayerHealth; // Reference to the player's health. private var enemyHealth : EnemyHealth; // Reference to this enemy's health. private var playerInRange : boolean; // Whether player is within the trigger collider and can be attacked. private var timer : float; // Timer for counting up to the next attack. function Awake () { // Setting up the references. player = GameObject.FindGameObjectWithTag ("Player"); playerHealth = player.GetComponent (PlayerHealth); enemyHealth = GetComponent(EnemyHealth); anim = GetComponent (Animator); } function OnTriggerEnter (other : Collider) { // If the entering collider is the player... if(other.gameObject == player) { // ... the player is in range. playerInRange = true; } } function OnTriggerExit (other : Collider) { // If the exiting collider is the player... if(other.gameObject == player) { // ... the player is no longer in range. playerInRange = false; } } function"); } } function Attack () { // Reset the timer. timer = 0f; // If the player has health to lose... if(playerHealth.currentHealth > 0) { // ... damage the player. playerHealth.TakeDamage (attackDamage); } } Tutoriais relacionados - Variables and Functions (Lição) - UI Slider (Lição)
https://unity3d.com/pt/learn/tutorials/projects/survival-shooter/player-health
CC-MAIN-2019-35
refinedweb
5,915
74.32
QVariant.canConvert inconsistencies Hi there, following minimized problem: @ #include <QtCore/QCoreApplication> #include <QVariant> #include <QDebug> #include <stdexcept> template <typename Type> Type get(QVariant& source) { if(source.canConvert<Type>()) return source.value<Type>(); else throw std::runtime_error("Invalid type"); } int main(int argc, char *argv[]) { QVariant variant; variant.setValue(QString("blabla")); qDebug() << get<double>(variant); // "0" } @ Obviously, QVariant.canConvert returns true and the string "blabla" gets converted into a double with the value 0 (zero) as the application does not throw an exception. Storing and/or querying other types result in the same value, better say the same "problem" because it seems that nearly any type can be converted into any other type but the return value my be zero (I write nearly because we haven't checked all types) Why? And is there a workaround which gives us a template based posibility to check the stored type. We used boost::lexical_cast before switching to QVariant as we through that QVariant would be the easier solution. greets. an ky canConvert makes a static check, whether the type can be converted, not if the conversion can really be done. nearly everything can be converted to/from a string. Hi Gerolf, is there a way to do dynamic checks? - koahnig Moderators There is also "type": for checks available. AFAIK, QVariant does not offer them. You have to do them on your own. But it will be tricky, becaus: Is a date convertable to a long? yes --> seconds since..., or no ? is a double convertable to an int, if it contains no int values, like 2.567 ?
https://forum.qt.io/topic/9458/qvariant-canconvert-inconsistencies
CC-MAIN-2018-39
refinedweb
263
57.06
- Choppy GUI - My script won't read the room taken up in C:\! - Input Question - IsbIt namespace std - C++ How to Program - Need turotial/help class array/vector - converting LPDWORD to DWORD - maps and populating from a batch? - Force end - I need some help... - OR statement within a "strcmp" - Streams help - I'm stupid. Please help with icons. - Converting Chars to Ints - Compilation problem - Assistance in netwoking program - why isn't my loop working properly? - command line - Segmentation fault - i dont know what is wrong with it (help plz) - code condensing - Is C++.NET worthwhile? - map - search it - Searching File for String - Tough Bitwise Exercise - Pasting data from clipboard - School Mini-Project on C/C++ (Need Your Help).. - Local Function definitions are illegal..... - Need help with an assignment - Exception problem - Templates: VC++ versus C++ standard - Java Runner - Help with classes and addition! - How can I make the base class unable to instantiate? - c++ suggestions - strncpy doesn't seem to work - C# 2.0....better than C++? - Is C++ getting too complex for today's technology? - Easy convert question - simple template question - C++ + Web = ? - using system() and redirection - RSA encryption with 1024 bit keys - Standard Template Library - command line arguments - Trying to save a simple boolean into a data file, and load it - struct is a class??? - simple graphic (dos/consol) - Limitations of DJGPP? (gcc in Windows) - error in resource file
https://cboard.cprogramming.com/archive/index.php/f-3-p-456.html?s=4d00dbf8ad964b76a918f3cc7d9c21d4
CC-MAIN-2017-04
refinedweb
230
67.65
You can subscribe to this list here. Showing 12 results of 12 What will happen to opengl? As far as I know that is already MS property. Whats going to happen to hardware support for 3d accel then? Are we all going to end up using d3d? What are the legal issues around d3d? Can we use it in linux? On Son, 2002-01-20 at 11:09, Philip Brown wrote: > It might be nice to have some sort of "generic 3d card" stub, that > would have certain functions common to all 3d cards. > Nothing too fancy. In fact, NOTHING fancy :-) Sounds like the current DRM template code... > Then it would be a lot easier for someone to come in and do a relatively > small porting effort, to get a new card working. > Right now, for example, most drivers *REQUIRE* that you have the AGP > stuff all happy, and who knows what else. tdfx can't even use AGP, r128 and radeon have PCI GART, and someone posted PCI patches for mga. --=20 Earthling Michel D=E4nzer (MrCooper)/ Debian GNU/Linux (powerpc) developer XFree86 and DRI project member / CS student, Free Software enthusiast Before I start including copyrighted stuff from the existing DRI documentation I would like get permission from the copyright owners. I'm refering to: "Hardware Locking for the Direct Rendering Infrastructure" "The Direct Rendering Manager: Kernel Support for the Direct Rendering Infrastructure" "Direct Rendering Infrastructure, Low-Level Design Document "A Multipipe Direct Rendering Architecture for 3D" "A Security Analysis of the Direct Rendering Infrastructure" "Introduction to the Direct Rendering Infrastructure" "Glossary of common 3D acronyms and terms" "Guide to debugging DRI installation" I don't mind in giving the copyright of this document to VA Linux Systems if that resolves any issue.. Regards, Jose Fonseca _________________________________________________________ Do You Yahoo!? Get your free @yahoo.com address at Hi all, I've finished compiling the the information gathered from the dri-devel archives into the FAQ. Since my university network was again down I was not able to put in my workstation's web server so I took the liberty of attach it in this mail. I'll publish in the same site ( ) in the meanwhile anyway. I hope that you don't get disappointed - it's not yet complete but has several pieces of wisdom. I'm sure that some of the original authors will get nostalgic feelings when reading it.. :-) I would like to get feedback on it. Either personally or to the dri-devel mailing list (to receive peer review). I especially want that you make corrections on: - Incorrect information: e.g., I've taken some assumptions is the questions as right since they were'nt refuted in the answers but that is not necessarily true. - Out of date information: e.g., There are reference to branches which I don't know if they were merged in the trunk. Please don't bother yourself to make comments/suggestions on: - FAQ Structure: There are obviously stuff misplaced but the structure will evolve as I include stuff from the DRI original documents. - Style or typos: Only once the whole information is gathered I will start looking on this. If you have memory of interesting emails in the dri-devel that weren't included please tell me so. You may feel free to give more FAQs (with answers of course!) to include. In summary, now it only matters that the information is _here_ and is _correct_, as much as possible. Regards, Jose Fonseca David Johnson wrote: > Could the DRI experts offer some feedback on the relevence and usefullness > of the following documents. Are the reasonably up to date? Are they > moderately up to date? Are they out of date and not extremely useful with > respect to the current DRI artitecture? I'll throw in my two cents... > 1. Introduction to the Direct Rendering Infrastructure - Brian Paul, August > 2000 > Reasonably up to date. Decent Intro. > 2. Dri term glossary. > I suspect this doesn't need to be changed but is there anything that should > be added? Reasonably up to date--except the author, Nathan, no longer works for VALinux->so his e-mail address is invalid. Useful. > 3. Data flow diagram > Very high level. Good for someone brand new to the concept of direct rendering--we'd use this at trade shows to explain what we are doing at a very high level. > 4. Control flow diagram > This is moderately up to date (and moderately out of date). I find this very useful as a module map of where all the pieces go and how they fit into the big picture. So, I guess this is the "big picture" :-) That's why there is a big version at. A developer interested in writing a new driver should focus on the Red Boxes. Those are the pieces that need to be recreated for each new device. Items that are out of date include: - The modules in the kernel for the DRM. There is no layering and there is not generic driver. There should be a red box labeled "DRM Driver". - The layers at the top of the "OpenGL Compatabile Core Rendering Library" between a 3D client side driver and the application. - Need to deemphasize the MMIO path and make the DMA path easier to follow because all drivers since 3Dfx have used that path. - Consider adding the agp modules to this diagram. > 5. A Multipipe Direct Rendering Artitecture for 3D. Jens Owen, Kevin E. > Martin. September 1998 > Surprisingly, these is moderately up to date. I don't recommend this for somebody wanting to write their first driver--rather, it's a high level design document written before we implemented any of the DRI. It helped us focus on the design tradeoffs we wanted to make. This is somewhat useful to anyone wanting to change the DRI framework. It gives a good idea of our original design goals. > 6. Direct Rendering Infrastructure, Low-Level Design Document. > Kevin E. Martin, Rickard E. Faith, Jens Owen, Allen Akin > This is woefully out of date, and not needed by developers tackling their first driver. This *might* have some value for developers looking to push the infrastructure envelope; however, I think the following docs are more useful... > 7. The Direct Rendering Manager: Kernel Suport for the Direct Rendering > Infrastrucure. Rickard E. Faith > You've got the wrong link here. It should be Although this hasn't been touched since the DRM library was first implemented, this is still a moderately up to date document. It does a decent job of documenting the DRMLib interface (The yellow box labeled "DRMLib" in the control flow diagram). Since the DRMLib interface is used by and supported by a device specific driver suite--it is good reading for first time driver developers. Items that are out of date: - Layering of DRM support, no more layers or generic driver; we now have DRM templates developed by Gareth. - Security Mechanism is slightly different. The flow of approval was reversed--but I don't remember the exact details. - This interface has been extended for some drivers...driver specific IOCTL's added. > 8. Hardware Locking for the Direct Rendering Infrastructure. Rickard E. > Faith, Jens Owen, Kevin E. Martin >. > 9. A Security Analysis of the Direct Rendering Infrastructure. Rickard E. > Faith, Kevin E. Martin > Out of date in that the mechanisms have changed. Also, not very relavant to 1st time driver writer. > 10. DRI Extension for supporting Direct Rendering Protocol Specification. > Jens Owen, Kevin Martin > Reasonably up to date--but only useful to somebody wanting to change the infrastructure. A document describing the API in the DDX drivers that support this extension would be much more useful to the driver developer. Specifically the API defined by the header xc/programs/Xserver/GL/dri/dri.h. This interface is supported by a DDX driver in the X Server and is what makes a DDX driver into a "DRI aware DDX Driver"; the red box in the middle of the control flow diagram. > I believe those are all the important developer and design documents on the > DRI website. Do any others exist anywhere that might help developers? Not that I can think of. > I think the first step might be to clean up the high level design documents > so new developers can quickly see how all the pieces of DRI fit together and > how they are interdependent on each other as well as with XFree86, Mesa and > the kernel. Sounds reasonable. > From there we can develop more detailed documentation on each > part of DRI and the major functions used in each part (this documentation > can be done through extracing in code documentation as others have > suggested). When all is done I would like to have it so that if, for > instance, someone is having a problem getting AGP to work with a Graphics > card ABC and motherboard XYZ and want to fix it they can quickly browse over > the high level documentation which will explain to them the DRI artitecture > and point them to the appropriate place(s) in the source code where AGP > related stuff is handled. I like your intent--I hope it's not over simplified. > Again, I don't think we can demand that Daryll, Paul, Jens, and the other > DRI experts sit down and write documentation or spend 8 hours a week in IRC > chats but if we can get them to point out what is wrong with current > documentation and share some of their knowledge with the rest of us > hopefully the rest of us can take the ball and run with it. I hope my two cents will help. Regards, Jens -- /\ Jens Owen / \/\ _ jens@... / \ \ \ Steamboat Springs, Colorado Mike A. Harris wrote: > >. You've got to be kidding... The P4 docs suggest using a PAUSE insn to reduce the otherwise-huge branch misprediction penalty associated with busy-wait loops like this. It also allows the processor to consume less power, which is handy for mobile platforms. To suggest that a busy-wait loop will cause the processor to overheat (given a functioning -- and attached -- heatsink/fan combo) and kick in the thermal protection is absurd! :-) > Instead of using empty for loops for delays, udelay() should be > used to provide delays. Either way, this is A Good Thing(TM). -- Gareth Philip Brown wrote: > > but I would say that microsoft DOES want to kill OpenGL, > since then they > would control the only useful 3D API. > It's all about creating monopolies. (so he can build hotels?) Allen's original statement made the point that MS considers OpenGL to be dead and buried, period. They've fought that battle, and in their mind, won. If this is the case, suggesting MS is out buying patents to kill off the DRI seems a bit silly... -- Gareth Just wondering where the IRC-based meeting is supposed to take place? #dri on irc.openprojects.net ? Did you people decide on 5PM Pacific Time on Monday? /Andreas. Instead of using empty for loops for delays, udelay() should be used to provide delays. I've sent this patch into the XFree86 patch list as well for application to xf-4_2-branch. Credits to Arjan Van de Ven <arjanv@...> for catching these issues. TIA -- ----------------------------------------------------------------------.net ---------------------------------------------------------------------- ---------- Forwarded message ---------- Date: Sun, 20 Jan 2002 11:06:14 GMT From: Arjan Van de Ven <arjanv@...> To: mharris@... diff -urN Linux/drivers/char/drm/i830_dma.c linux/drivers/char/drm/i830_dma.c --- Linux/drivers/char/drm/i830_dma.c Sun Jan 20 11:04:53 2002 +++ linux/drivers/char/drm/i830_dma.c Sun Jan 20 11:04:25 2002 @@ -36,7 +36,7 @@ #include "drmP.h" #include "i830_drv.h" #include <linux/interrupt.h> /* For task queue support */ - +#include <linux/delay.h> /* in case we don't have a 2.3.99-pre6 kernel or later: */ #ifndef VM_DONTCOPY #define VM_DONTCOPY 0 @@ -60,7 +60,7 @@ do { \ _head = I830_READ(LP_RING + RING_HEAD) & HEAD_ADDR; \ _tail = I830_READ(LP_RING + RING_TAIL) & TAIL_ADDR; \ - for(_i = 0; _i < 65535; _i++); \ + udelay(1); \ } while(_head != _tail); \ } while(0) @@ -375,13 +375,13 @@ } iters++; - if((signed)(end - jiffies) <= 0) { + if(time_before(end,jiffies)) { DRM_ERROR("space: %d wanted %d\n", ring->space, n); DRM_ERROR("lockup\n"); goto out_wait_ring; } - for (i = 0 ; i < 2000 ; i++) ; + udelay(1); } out_wait_ring: @@ -1136,7 +1136,7 @@ current->state = TASK_INTERRUPTIBLE; i830_dma_quiescent_emit(dev); if (atomic_read(&dev_priv->flush_done) == 1) break; - if((signed)(end - jiffies) <= 0) { + if(time_before(end, jiffies)) { DRM_ERROR("lockup\n"); break; } @@ -1170,7 +1170,7 @@ current->state = TASK_INTERRUPTIBLE; i830_dma_emit_flush(dev); if (atomic_read(&dev_priv->flush_done) == 1) break; - if((signed)(end - jiffies) <= 0) { + if(time_before(end, jiffies)) { DRM_ERROR("lockup\n"); break; } Hi folks, Well, I'm very happy to have come back to check my dri mailfolder, and find lots of messages about cleaning docs up for porting purposes :-) If folks really want to make porting easier, then I would make the following suggestion: Change the CODE to make porting easier, also. Right now, part of what makes it somewhat confusing, is that there are so many *DIFFERENT* cards that are supported. It might be nice to have some sort of "generic 3d card" stub, that would have certain functions common to all 3d cards. Nothing too fancy. In fact, NOTHING fancy :-) Then it would be a lot easier for someone to come in and do a relatively small porting effort, to get a new card working. Right now, for example, most drivers *REQUIRE* that you have the AGP stuff all happy, and who knows what else. Once you have basic 3d stuff working, it's a lot easier (and safer!) to add features bit by bit, than it is to try to have to implement everything at once and wonder what you've screwed up. O' course, what with the time pressures on everyone mentioned in the recent discussion, I dont have much hope of seeing this actually materializing. But I thought I'd throw it out there anyway On Fri, Jan 18, 2002 at 04:11:39PM -0800, Gareth Hughes wrote: > ... > The DRI is encompassed by OpenGL (as a whole), and if Microsoft > isn't interested in killing OpenGL because they don't consider > it a threat (*), one would reach the conclusion they don't care > about the DRI either. > .... > (*) but I would say that microsoft DOES want to kill OpenGL, since then they would control the only useful 3D API. It's all about creating monopolies. (so he can build hotels?) Well, scince nobody else announced it, I might as well. It's even on slashdot by now. I was able to snag the patches from 4.1.0 before reached terminal slashdotness. Carl Busjahn
http://sourceforge.net/p/dri/mailman/dri-devel/?viewmonth=200201&viewday=20
CC-MAIN-2016-07
refinedweb
2,434
64
Implicit Intent to view URL call intent android android sms intent intent resolution action-view intent-filter android intent picker what is intent filter verification service I am new to Android, I want to create an Intent to view google website. My String is declared as follows: static private final String URL = ""; and my Intent : Intent browserIntent = new Intent(Intent.ACTION_VIEW); browserIntent.setData(Uri.parse("geo:+URL")); startActivity(browserIntent); This code shows no errors in Eclipse, but I think it might be wrong. You're not building your Uri correctly, when trying to concatenate 2 String, use this : String s = "I'm a string variable"; String concatenated = s + " and I'm another String variable"; Now the content of concatenated is I'm a string variable and I'm another String variable If you do this : String concatenated = "s + and I'm another String variable"; the content of concatenated is s + and I'm another String variable Secondly, why are you using a geo Uri ? This is for viewing locations. To view a website, just use the URL (and don't forget the "http://" part) : String URL = ""; browserIntent.setData(Uri.parse(URL)); android - Implicit Intent to view URL, You're not building your Uri correctly, when trying to concatenate 2 String, use this : String s = "I'm a string variable"; String concatenated = s +� Implicit Intent in Android can invoke other application in the device. We can open a URL in a browser or can make a call. Many other tasks can be performed. Intent has different action that is used with implicit intent. The actions are like Intent.ACTION_VIEW, Intent.ACTION_DIAL, Intent.ACTION_CALL etc. You can create an intent and then set data for it. Intent also has a constructor that takes action String and data URI. Also you need to use geo: when you want to show something on a map. So view an URL in browser you can simply use the website URL. You can pass it to Uri.parse() method to get URI object needed in the intents constructor. You can simply do - Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("")); Intent browserChooserIntent = Intent.createChooser(browserIntent , "Choose browser of your choice"); startActivity(browserChooserIntent ); Common Intents, Implicit Intent in Android can invoke other application in the device. We can Using implicit intent we can open a URL in a browser. Intent. OnClickListener() { public void onClick(View view) { EditText website = (EditText)� An intent allows you to start an activity in another app by describing a simple action you'd like to perform (such as "view a map" or "take a picture") in an Intent object. This type of intent is called an implicit intent because… watch that one, and then the following ones up to the 94, included. However, 2Dee's comment is basically right. You should start by knowing how resources, particullary String resources, work in Android. This is a good start point. Android Implicit Intent Example | Open URL in Browser, In order to launch Google Maps with an intent you must first create an Intent Action: All Google Maps intents are called as a View action — ACTION_VIEW . Example of implicit Android Intent, open a URL, send an email. o7planning. All Tutorials; Java. Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url 2Dee's answer is correct. You can also give the action and set data uri in a single line. To view the website. Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(URL)); startActivity(browserIntent); Google Maps Intents for Android | Maps URLs, public void onBrowseClick(View v) { String url = ""; Uri uri Check if there are no apps on the device that can receive the implicit Intent browserIntent=null, chooser=null; browserIntent= new Intent(Intent.ACTION_VIEW); browserIntent.setData(Uri.parse("")); chooser = browserIntent.createChooser(intent,"Open Website Using..."); if(browserIntent.resolveActivity(getPackageManager()) != null){ startActivity(chooser); } Android, As outlined above, the implicit intent will be created and issued from View; public class ImplicitIntentActivity extends The intent object also includes a URI containing the URL to be displayed.. Android 6 Implicit Intents – A Worked Example, need to use the Intent.ACTION_SENDTO and pass a mailto: URI with the subject and body URL encoded. tab if the app. Take a look at this guide for how to launch this implicit intent. Show location in maps application: Intent intent = new� String url = editText1.getText().toString(); c). Create an Intent object MainActivity.java class to open the webpage. Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); d). The startActivity() method starts to call a webpage for opening specified by the intent. startActivity(intent); Therefore the code snippet for Implicit Intent: Common Implicit Intents, A little known feature in Android lets you launch apps directly from a web page via an Android Intent. One scenario is launching an app when the user lands on a� Android Implicit Intent Example Following is the complete example of implementing an implicit intent in the android application. Create a new android application using android studio and open an activity_main.xml file from \src\main\res\layout path. Android Intents with Chrome, If an implicit intent is sent to the Android system, it searches for all if an intent is triggered when someone wants to view an URL starting with� Intent intent = new Intent(Intent.ACTION_VIEW, webpage); This Intent constructor is different from the one you used to create an explicit Intent . In the previous constructor, you specified the current context and a specific component ( Activity class) to send the Intent . - it might? have you tested it? What is the result? - "geo:+URL" is completely wrong. That is just a string, you're not really using your static field here... - No, you should not leave out the http part, or will end up with an error, use browserIntent.setData(Uri.parse("google.com")); Have a look at this question for details : stackoverflow.com/questions/2201917/… - browserIntent.setData(Uri.parse(URL)); i've put it like this - Mmmh, looks like SO comments system is hiding the http part, sorry, I didn't know about that, just noticed mine was cut as well :) Using Uri.parse(URL) will work just fine.
https://thetopsites.net/article/54731122.shtml
CC-MAIN-2021-25
refinedweb
1,019
56.35
import "github.com/rackspace/gophercloud/pagination" Package pagination contains utilities and convenience structs that implement common pagination idioms within OpenStack APIs. http.go linked.go marker.go null.go pager.go pkg.go single.go var ( // ErrPageNotAvailable is returned from a Pager when a next or previous page is requested, but does not exist. ErrPageNotAvailable = errors.New("The requested page does not exist.") ) func Request(client *gophercloud.ServiceClient, headers map[string]string, url string) (*http.Response, error) Request performs an HTTP request and extracts the http.Response from the result. type LinkedPageBase struct { PageResult // LinkPath lists the keys that should be traversed within a response to arrive at the "next" pointer. // If any link along the path is missing, an empty URL will be returned. // If any link results in an unexpected value type, an error will be returned. // When left as "nil", []string{"links", "next"} will be used as a default. LinkPath []string } LinkedPageBase may be embedded to implement a page that provides navigational "Next" and "Previous" links within its result. func (current LinkedPageBase) GetBody() interface{} GetBody returns the linked page's body. This method is needed to satisfy the Page interface. func (current LinkedPageBase) NextPageURL() (string, error) NextPageURL extracts the pagination structure from a JSON response and returns the "next" link, if one is present. It assumes that the links are available in a "links" element of the top-level response object. If this is not the case, override NextPageURL on your result type. type MarkerPage interface { Page // LastMarker returns the last "marker" value on this page. LastMarker() (string, error) } MarkerPage is a stricter Page interface that describes additional functionality required for use with NewMarkerPager. For convenience, embed the MarkedPageBase struct. type MarkerPageBase struct { PageResult // Owner is a reference to the embedding struct. Owner MarkerPage } MarkerPageBase is a page in a collection that's paginated by "limit" and "marker" query parameters. func (current MarkerPageBase) GetBody() interface{} GetBody returns the linked page's body. This method is needed to satisfy the Page interface. func (current MarkerPageBase) NextPageURL() (string, error) NextPageURL generates the URL for the page of results after this one. type Page interface { // NextPageURL generates the URL for the page of data that follows this collection. // Return "" if no such page exists. NextPageURL() (string, error) // IsEmpty returns true if this Page has no items in it. IsEmpty() (bool, error) // GetBody returns the Page Body. This is used in the `AllPages` method. GetBody() interface{} } Page must be satisfied by the result type of any resource collection. It allows clients to interact with the resource uniformly, regardless of whether or not or how it's paginated. Generally, rather than implementing this interface directly, implementors should embed one of the concrete PageBase structs, instead. Depending on the pagination strategy of a particular resource, there may be an additional subinterface that the result type will need to implement. type PageResult struct { gophercloud.Result url.URL } PageResult stores the HTTP response that returned the current page of results. func PageResultFrom(resp *http.Response) (PageResult, error) PageResultFrom parses an HTTP response as JSON and returns a PageResult containing the results, interpreting it as JSON if the content type indicates. func PageResultFromParsed(resp *http.Response, body interface{}) PageResult PageResultFromParsed constructs a PageResult from an HTTP response that has already had its body parsed as JSON (and closed). type Pager struct { Err error // Headers supplies additional HTTP headers to populate on each paged request. Headers map[string]string // contains filtered or unexported fields } Pager knows how to advance through a specific resource collection, one page at a time. func NewPager(client *gophercloud.ServiceClient, initialURL string, createPage func(r PageResult) Page) Pager NewPager constructs a manually-configured pager. Supply the URL for the first page, a function that requests a specific page given a URL, and a function that counts a page. AllPages returns all the pages from a `List` operation in a single page, allowing the user to retrieve all the pages at once. EachPage iterates over each page returned by a Pager, yielding one at a time to a handler function. Return "false" from the handler to prematurely stop iterating. func (p Pager) WithPageCreator(createPage func(r PageResult) Page) Pager WithPageCreator returns a new Pager that substitutes a different page creation function. This is useful for overriding List functions in delegation. type SinglePageBase PageResult SinglePageBase may be embedded in a Page that contains all of the results from an operation at once. func (current SinglePageBase) GetBody() interface{} GetBody returns the single page's body. This method is needed to satisfy the Page interface. func (current SinglePageBase) NextPageURL() (string, error) NextPageURL always returns "" to indicate that there are no more pages to return. Package pagination imports 9 packages (graph) and is imported by 749 packages. Updated 2018-08-13. Refresh now. Tools for package owners.
https://godoc.org/github.com/rackspace/gophercloud/pagination
CC-MAIN-2019-39
refinedweb
799
57.77
I have to basically write a fuction that does the inmemoized recursion and count the number of times is called..which i did.. the second part is that i dont understand which is to create a global array of 100 and calculate the function using memoization... can some one help..this is the first part import java.util.Scanner; public class Fib{ static int calls; public static void main(String[] args){ int fib; int n; Scanner scan = new Scanner(System.in); System.out.println("Input a number"); n = scan.nextInt(); System.out.println(" " + RecurFib(n) + " " + calls); } int count = 0; public static int RecurFib (int n){ calls ++; if (n<2){ int answer = n; return answer; }else{ int answer = RecurFib(n-1) + RecurFib(n-2); return answer; } }
https://www.daniweb.com/programming/software-development/threads/107882/help-with-memoization-pls
CC-MAIN-2017-09
refinedweb
125
57.98
Full Disclosure mailing list archives There are or at least used to be limits to commandline args in VMS. I seem to recall that for foreign commands the limit is 255 or 256; nothing longer gets passed. This stuff has been in DCL for years. Now, it is possible that recent versions might have extended this limit, but it is very difficult in VMS to have anything of unbounded size...too many internal calls work by descriptor, where a hard limit is enforced, so the odd case that does not tends to be protected somewhat. -----Original Message----- From: full-disclosure-bounces () lists grok org uk [mailto:full-disclosure-bounces () lists grok org uk]On Behalf Of Johnny Lee Sent: Wednesday, January 04, 2006 5:00 PM To: full-disclosure () lists grok org uk Subject: [Full-disclosure] Re: Unzip *ALL* verisons ;)) No one can compile unzip with debug info? :) I looked at this on Windows. Unzip5.52 fixed a buffer overflow in the do_wild() function in all the ports. However, in vms\vms.c, there's still an unbounded strcpy call copying wld to last_wild. I don't know if there are any bounds to command line args in VMS, but if the first arg can be >256 chars, there's a buffer overflow there. In process.c, in process_zipfiles(), there's the following code: char *p = lastzipfn + strlen(lastzipfn); G.zipfn = lastzipfn; strcpy(p, ZSUFX); The fix for the do_wild() buffer overflow was to cap the string at FILNAMSIZ chars. So if we get to this point, then the strcpy of the ZSUFX will cause a slight buffer overflow of lastzipfn which typically points to G.matchname or a static matchname char array. It'd be really hard to exploit too, but I'm just mentioning it. The other possible buffer overflow is the Info macro in unzpriv.h. Code would end up using sprintf() to the slide array which is 32KB if MALLOC_WORK is NOT defined. I can't repro a segfault/access violation in the Win32 version of unzip 5.52 though unless I set the first argument to >32K via code. But you cannot create a Win32 process with a command line longer than 32K for WinXP+, (<= 2K on Win2K). With the Win32 DLL, it'd be possible for an app to pass in an arg that's >32K chars. Maybe on Unix with an arg that is a lot larger than 32K chars. Also a long environment variable may cause a buffer overflow. Updating the Info macro to use snprintf() would be the 'correct' thing to do. But all ports may not support snprintf() and the Info macro is used in many places. Adjusting all the uses of the Info macro to pass in the buffer size would take a long time. Time to whip out your favourite scripting language and write some code. You can use the C runtime (if it's ANSI-compliant) to avoid the Info macro's buffer overflow by passing a precision value for the string args. Here's a quick patch - I arbitrarily chose 512 as the max chars displayed: --- consts.old Sat Mar 23 10:52:48 2002 +++ consts.h Tue Jan 03 16:36:54 2006 @@ -34,9 +34,9 @@ "error: expected central file header signature not found (file #%lu).\n"; ZCONST char Far SeekMsg[] = "error [%s]: attempt to seek before beginning of zipfile\n%s"; -ZCONST char Far FilenameNotMatched[] = "caution: filename not matched: %s\n"; +ZCONST char Far FilenameNotMatched[] = "caution: filename not matched: %.512s\n"; ZCONST char Far ExclFilenameNotMatched[] = - "caution: excluded filename not matched: %s\n"; + "caution: excluded filename not matched: %.512s\n"; #ifdef VMS ZCONST char Far ReportMsg[] = "\ --- process.old Sun Nov 21 19:42:54 2004 +++ process.c Tue Jan 03 16:56:48 2006 @@ -74,20 +74,20 @@ /* do_seekable() strings */ # ifdef UNIX static ZCONST char Far CannotFindZipfileDirMsg[] = - "%s: cannot find zipfile directory in one of %s or\n\ - %s%s.zip, and cannot find %s, period.\n"; + "%s: cannot find zipfile directory in one of %.512s or\n\ + %s%.512s.zip, and cannot find %.512s, period.\n"; static ZCONST char Far CannotFindEitherZipfile[] = - "%s: cannot find or open %s, %s.zip or %s.\n"; + "%s: cannot find or open %.512s, %.512s.zip or %.512s.\n"; # else /* !UNIX */ # ifndef AMIGA static ZCONST char Far CannotFindWildcardMatch[] = - "%s: cannot find any matches for wildcard specification \"%s\".\n"; + "%s: cannot find any matches for wildcard specification \"%.512s\".\n"; # endif /* !AMIGA */ static ZCONST char Far CannotFindZipfileDirMsg[] = - "%s: cannot find zipfile directory in %s,\n\ - %sand cannot find %s, period.\n"; + "%s: cannot find zipfile directory in %.512s,\n\ + %sand cannot find %.512s, period.\n"; static ZCONST char Far CannotFindEitherZipfile[] = - "%s: cannot find either %s or %s.\n"; + "%s: cannot find either %.512s or %.512s.\n"; # endif /* ?UNIX */ extern ZCONST char Far Zipnfo[]; /* in unzip.c */ #ifndef WINDLL J _______________________________________________ - By Date By Thread
http://seclists.org/fulldisclosure/2006/Jan/143
CC-MAIN-2014-42
refinedweb
813
74.29
Hello, I have build a project of three files. First is the main ERIN_TEST_VL53L0X_SENSORS.ino and two other file a .cpp and .h these are all in the same folder and have been included in the project. However when i try to compile the project I get a No such file or Directory error for ERIN_VL53L0X_SENSORS.h top of the main project file ERIN_TEST_VL53L0X_SENSORS.ino is following #include <Arduino.h> #include "ERIN_VL53L0X_SENSORS.h" However if i supply full path it finds the include file #include "D:\NewDev\Robots\Sensors And Drivers\ERIN_TEST_VL53L0X_SENSORS\ERIN_VL53L0X_SENSORS.h" Any ideas please IDE is 1.8.16 compiling for Nano many thanks imk
https://forum.arduino.cc/t/no-such-file-or-directory-cant-find-include-file/921044
CC-MAIN-2021-49
refinedweb
108
79.67
We have just uploaded a new version of the DataGrid that includes a number of bug fixes and a few behavioral breaking changes from the version that shipped with Silverlight 2. Please take the time to read through and understand all of the changes before you decide to upgrade your DataGrid. Following this list of changes is a set of instructions on how to start using the new version. An application that uses the DataGrid will still compile but will no longer work as expected if it was dependent on any of the following behaviors. 1. FrozenColumnCount now takes hidden columns into account. Previously, only the first columns with Visibility set to Visible were included in the range of frozen columns. A column with Visibility set to Collapsed can now be considered frozen even though it isn’t visible. This is to ensure that a column’s DisplayIndex corresponds with the DataGrid’s FrozenColumnCount (i.e. if FrozenColumnCount == 3, columns with DisplayIndex < 3 are considered frozen). 2. The DataGrid’s current cell is now kept in sync with an ICollectionView’s notion of currency. Moving the current position or changing the current item of an ICollectionView will now move the current cell and selected item of a DataGrid, and vice versa. For this to work, the DataGrid’s ItemsSource must be set to a collection that fully implements ICollectionView. 3. A developer can now programmatically reorder a non-frozen column to the frozen column range (and vice versa) by changing a column’s DisplayIndex. The DataGrid used to throw an exception in these cases. An end-user, however, is still unable to do this through the UI by dragging column headers. The following is a list of bugs fixed in the DataGrid since the version released with Silverlight 2. If any application had a workaround for these bugs, the workaround is no longer necessary and should be removed. Its inclusion may cause undesired behavior. 1. Horizontal Gridlines do not show in FillerColumn 2. DragIndicator does not show during reorder when DataGrid is placed inside StackPanel 3. DragIndicatorStyle only exists on the DataGrid level, should also exist at the column level 4. DataGrid doesn't support a disabled state in the main templateBy default, the DataGrid is now grayed out when IsEnabled == false, and includes a new visual state. 7. Changing ItemsSource while in Editing Mode causes Exception to be thrown 8. Row containing focus disappears after sort or ItemsSource changeAny application working around the “disappearing row” issue by manipulating focus within the DataGrid will no longer need to do so, and should be updated. 9. ColumnHeader button pressed visualization should match the new Button pressed visualization 10. SL Designer hits a NullReferenceException while adding an empty HeaderStyle 11. Cells out of view do not always show up when a resize of the DataGrid forces them in view 12. AutoSizedRows keep growing even when the rows are recycled 13. Scrollbar incorrect when ItemsSource changed and DataGrid is on a background Tab 14. Incorrect VerticalScrollbar when setting ItemsSource on DataGrid inside a Popup 15. HorizontalContentAlignment does not have any effect on the DataGridColumnHeader 16. Resizing columns to smaller than column header content removes separator 17. SelectedItem is not updated at the time when the CurrentCellChanged event is raised 18. Sorting or Resetting a CollectionView causes incorrect RemovedItems in SelectionChanged event 19. ScrollColumnIntoView does not align correctly if there are frozen columns 20. Reordering a column should only show DragIndicator for valid reorder positions 21. Adding or removing columns within the frozen column range should not throw exception 22. FrozenColumnCount and the Column’s IsFrozen is getting out of sync when it isn’t visible 23. Exception thrown when sorting a DataGrid that has a list of nullable ints as its ItemsSource 24. CellStyle Background property doesn’t work 25. CellStyle is not applied to Filler Column 26. Setting a DataGrid style that overwrites the template after the original template has been loaded causes an Argument exception 27. Cannot hold editing mode when using a DatePicker or ComboBox in editing template 28. Double-click required on external Buttons when in editing mode 29. Sorting or resetting the ItemsSource does not raise UnloadingRow events 30. Contents of columns out of view do not always show up when the DataGrid is resized such that they are brought into view Visit the Silverlight 2 DataGrid December 2008 Release download page and read the installation instructions carefully. In order to successfully use the new DataGrid you must do the following. 4. For any existing projects, delete the reference to System.Windows.Controls.Data.dll and then re-add the reference. Happy Holidays from the Silverlight DataGrid Team! Does this release also enable mouseover states for single cells (change foreground color for labels inside cells on mouseover). edit: good job btw Regards,Nathan Brouwer "15. HorizontalContentAlignment does not have any effect on the DataGridColumnHeader" YES! I have been waiting for that one, should fix alot of the dynamic resizing now... Now I hafta remove my DataView I made to replace DataGrid. Thanks alot for the update, it was much needed here! The MouseOver, Selected, and Current states on the DataGridCell should be working. Please let us know if you find otherwise. Previously there was a bug where the cell's Background could not be styled, but that was fixed in our mini release. Yifung Lin [MSFT] The short answer is it'll happen automatically. The DataGrid is not part of the Silverlight core package. You got the original dll from the SDK and compiled your app with it. Everything in your app that's not part of the core assemblies is packaged into a xap (including the DataGrid dll) file. That xap file is downloaded by any user viewing your Silverlight page. As a result, as long as you build your app with the new DataGrid dll's, your customers will be using the new version as well. Great thanks! Any idea when there will be datagrid which will support paging? There isn't a concrete date yet but pieces like a pageable data source are being worked on. It is a scenario we will enable in the future Does this release resolve these issues? 1. By default DataGrid's SelectedIndex property is set to "0". While trying to set it to SelectedIndex = -1, doesn't work. No error, but basically it will be ignored and after databinding, SelectedIndex property is still "0". 2. DataGrid's "SelectionChanged" event fires twice for some reason. 1. Unfortunately this issue is not resolved with this update. You could work around it by listening to the SelectionChanged event and setting the SelectedIndex to -1 inside the handler the first time it gets called after setting the ItemsSource. 2. Under what circumstances was the SelectionChanged event being fired twice? Also, was it being raised with the same args? Using the new version, I can confirm that the event is only raised once when selection is changed under normal conditions, but maybe there's some edge scenario I'm not seeing. Congratulations on the release, Brian! Downloading the bits now... For some reason, this just hit my newsreader now. Jeff Wilcox [MSFT]Software Development EngineerSilverlight posting is provided "AS IS" with no warranties, and confers no rights. yifung:The MouseOver, Selected, and Current states on the DataGridCell should be working. Please let us know if you find otherwise. Previously there was a bug where the cell's Background could not be styled, but that was fixed in our mini release. Thanks Brian! Here is the source code. For some reason, everytime Search button is clicked, the dg_SelectionChanged fires twice. XAML Page: <UserControl xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data" x:Class="SQLData.Page" xmlns="" xmlns: <Grid x: <Grid.RowDefinitions> <RowDefinition Height="10" /><!--0 Margin--> <RowDefinition Height="50" /><!--1 Prompts--> <RowDefinition Height="*" /><!--2 DataGrid--> <RowDefinition Height="30" /><!--2 Navigation Buttons--> <RowDefinition Height="10" /><!--3 Margin--> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="10" /><!--0 Margin--> <ColumnDefinition Width="*" /><!--1 Controls--> <ColumnDefinition Width="10" /><!--2 Margin--> </Grid.ColumnDefinitions> > <data:DataGrid x:</data:DataGrid> <StackPanel Grid. <Button Width="60" Height="20" Margin="15,0,0,0" x: <TextBlock Width="60" Height="20" Margin="20,0,0,0" x: <Button Width="60" Height="20" Margin="20,0,0,0" x: </StackPanel> <sd:Detail x:</sd:Detail> </Grid> </UserControl> ------------------------------------ Code Behind: using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; namespace SQLData { public partial class Page : UserControl { public int TotalRows { get; set; } public int PageSize { get; set; } int TotalPages = 0; int PageNo = 1; bool b; ServiceReference1.Service1Client webService = new SQLData.ServiceReference1.Service1Client(); public Page() { InitializeComponent(); PageSize = 10; //Loaded += new RoutedEventHandler(Page_Loaded); Search.Click += new RoutedEventHandler(Search_Click); btnNext.Click += new RoutedEventHandler(btnNext_Click); btnPrevious.Click += new RoutedEventHandler(btnPrevious_Click); webService.GetTotalRecordsCompleted += new EventHandler(webService_GetTotalRecordsCompleted); webService.GetCustomersByLastNameCompleted += new EventHandler(webService_GetCustomersByLastNameCompleted); } void Page_Loaded(object sender, RoutedEventArgs e) { //Search.Click += new RoutedEventHandler(Search_Click); //btnNext.Click += new RoutedEventHandler(btnNext_Click); //btnPrevious.Click += new RoutedEventHandler(btnPrevious_Click); //webService.GetTotalRecordsCompleted += new EventHandler<SQLData.ServiceReference1.GetTotalRecordsCompletedEventArgs>(webService_GetTotalRecordsCompleted); //webService.GetCustomersByLastNameCompleted += new EventHandler<SQLData.ServiceReference1.GetCustomersByLastNameCompletedEventArgs>(webService_GetCustomersByLastNameCompleted); } void Search_Click(object sender, RoutedEventArgs e) { TotalRows = 0; PageNo = 1; TotalPages = 0; webService.GetTotalRecordsAsync(LastName.Text); webService.GetCustomersByLastNameAsync(LastName.Text, PageNo, PageSize); spNavigation.Visibility = Visibility.Visible; b = true; } void webService_GetCustomersByLastNameCompleted(object sender, SQLData.ServiceReference1.GetCustomersByLastNameCompletedEventArgs e) { if (TotalPages == 0) { btnNext.IsEnabled = false; btnPrevious.IsEnabled = false; PageNo = 0; lblPageNo.Text = PageNo.ToString() + " of " + TotalPages.ToString(); dg.ItemsSource =null; } else { if (PageNo == 1) { btnNext.IsEnabled = true; btnPrevious.IsEnabled = false; } else if (PageNo == TotalPages) { btnNext.IsEnabled = false ; btnPrevious.IsEnabled = true; } dg.ItemsSource = e.Result; lblPageNo.Text = PageNo.ToString() + " of " + TotalPages.ToString(); } } void webService_GetTotalRecordsCompleted(object sender, SQLData.ServiceReference1.GetTotalRecordsCompletedEventArgs e) { TotalRows = e.Result; if (TotalRows != 0) { TotalPages = TotalRows / PageSize + 1; } else { TotalPages = 0; } } void btnNext_Click(object sender, RoutedEventArgs e) { PageNo = PageNo + 1; webService.GetCustomersByLastNameAsync(LastName.Text, PageNo, PageSize); if (PageNo == TotalPages) { btnNext.IsEnabled = false; btnPrevious.IsEnabled = true; } } void btnPrevious_Click(object sender, RoutedEventArgs e) { PageNo = PageNo - 1; webService.GetCustomersByLastNameAsync(LastName.Text, PageNo, PageSize); } private void dg_SelectionChanged(object sender, SelectionChangedEventArgs e) { DataGrid grid = sender as DataGrid; if (grid.SelectedItem == null) { b = true; } else { if (b) { DetailsView.Visibility = Visibility.Collapsed; b = false; } else { DetailsView.Visibility = Visibility.Visible; } } } } } So it looks like when the Search button is Pressed, the DataGrid's ItemsSource is changed and that's when you're experiencing multiple SelectionChanged events. I'm assuming the first event says that selection has been removed, and the second event says that the first item has been selected. I believe that the event will only be raised once under these conditions with the new release, so it should be fixed. I don't have the correct bits installed to verify this right now, but I'll try to confirm it when I get a chance. Can you advice or tell if DataGrid December 2008 source code will be made available as the previous MixControls version? I am heavily using DataGrid features and made some derived extension classes which enables to drag and drop cell content between compatible column cells. I ran into some bugs with MixControls DataGrid version which I fixed in order to keep the development going. Anyhow based on these derived classes I am a bit worried to swap into this new version as I am not certain how to mitigate if I would encounter bugs and I would not have source code available. Regards, Alexander We are planning to release updated source code, and unfortunately I don't have a more specific answer than that, as it's still unclear when or how it will be released. I understand your concern, though, and hopefully we can get something out soon. We'll post more information as the plans develop. Hello, Great work.What about filtering? Is it going to be implemented in a future release? Some news about this? Thank you! To do this on the data side today, you would need a datasource that raises INotifyCollectionChanged.Reset when items are filtered. In the SL 3 timeframe, there will be a CollectionView to assist with that. You'll be able to add a Filter to it. The UI side is less predictable. After the data side supports it, it'll likely happen at some point, but it's still up in the air I have a vista system This is what is listed (files listed below under program files) in my computer files. My version was installed in october 2.0 31005.0 I already have a test project in expression blend that does not use this What is the best way to unistall these just go thru that path and unistall ? I really do not need my test project so I may delete this anyway Should I delete data design also?????? Thank you for your help..... billsm: I have a vista system I can not find the proper path Can I just delete this in expression blend I can not seem to find the proper path on my computer ???? PLease advice me thank you...... I would like to install this.... I have a vista system I can not find the proper path Can I just delete this in expression blend I can not seem to find the proper path on my computer ???? PLease advice me thank you...... I would like to install this.... Could you make sure hidden files and folders are shown? In Explorer: Tools (Alt-T)->Folder Options->View->Show hidden files and folders I found this under program files in vista as the article described previously-exactly the same path under programFiles: My files are like this: version 2.0 31005.0 Oct----download yifung ...............................I checked user folder nothing yes I went throught and unchecked hidden folder nothing My path is listed same as described above....Program files etc Please advice How can I delete these off my system..?????? Thank you I made a mistake!!!! I found the proper path users/username/appdata/local I will delete this I will follow the directions above Thank you for this post.......case closed.... desmonduz85:. In Silverlight2, the DataGridColumn.Header cannot be a visual element, only a primitive (string, int, etc.). If you want to add a visual element to the column header, you need to do so in the HeaderStyle. Scott Morrison has a blog post that outlines the breaking changes between the Beta2 version and the first official release. The DataGridTemplateColumn requires a template. You must first define your DataTemplates in XAML, after which you can create the column itself in code and set the corresponding CellTemplate and CellEditingTemplate properties. You can subscribe to events on the elements in the DataTemplates as you would any other element in XAML. DataGridTemplateColumn templateColumn = new DataGridTemplateColumn(); templateColumn.Header = "MyDate"; templateColumn.CellTemplate = LayoutRoot.Resources["cellTemplate"] as DataTemplate; templateColumn.CellEditingTemplate = LayoutRoot.Resources["cellEditingTemplate"] as DataTemplate; dataGrid.Columns.Add(templateColumn); <Canvas.Resources> <DataTemplate x: <TextBlock Text="{Binding MyDate}"/> </DataTemplate> <DataTemplate x: <control:DatePicker </DataTemplate> </Canvas.Resources> Please reply to this thread only for issues related to the December 2008 DataGrid release. General questions about the DataGrid will get better attention if you create a separate post for them. But the real issue is that programmer cannot create the DataTemplate object in code or access its child control. We have to create an DataTemplate with its explicit databinding in XAML. There is no way to do this dynamically. Another method, which constructs the code-generated XAML and parses it, it lacks events. So the elements created in this way cannot be assigned to events. Generally speaking, I cannot understand the trends in Microsoft. Instead of making the layers more loosely connected, they made everything dependent on each other. DB is totally dependent on DataAccess objects, so any change in DB table should be manually replicated in DataAccess layer, then in Presentation layer too, as every columns is specified in DataGrid. I want to create columns dynamically, and I don't know how to create column with buttons where the binding for this column should be set in code, not explicitly in XAML. If you want to set the binding of a control within the DataTemplate, you could subscribe to its Loaded event and set it up in the handler. The control will automatically inherit the Row's DataContext. <Canvas.Resources> <DataTemplate x: <Button Loaded="Button_Loaded"/> </DataTemplate> </Canvas.Resources> private void Button_Loaded(object sender, RoutedEventArgs e) { Button button = sender as Button; if (button != null) { Binding binding = new Binding("MyPropertyName"); binding.Mode = BindingMode.OneWay; button.SetBinding(Button.ContentProperty, binding); } } Usually I can specify the binding while I am adding the columns, because I know which column I am adding right now. In this solution, is it possible to know where this button is loaded? I can have many columns with buttons, but how I can specify the binding for them, as I don't know which button is loaded. As regards the DataGridColumn header, I can only bind the header title to my custom UIControl, but what if I need to bind some more properties, too. For example, I also need to keep the DisplayMemberPath of Column in Tag property of my custom UIControl so it can accomplish some sort or filter operations with database. I would love to use the method above, but please tell me the way how I can identify the current column where the button is loaded. johonline Sorry for the slow response. I just got this release re-installed and it seems to work fine for me. If you're still running into this issue, are there any more details you can provide? When are you calling SelectedItems.Add? Is SelectionMode set to Extended or Single? My SelectionMode is set to Extended (default value), here is the code I use: Day Selector Xaml code: <data:DataGrid x: <data:DataGrid.Columns> <data:DataGridTemplateColumn> <data:DataGridTemplateColumn.CellTemplate> <DataTemplate> <TextBlock Text="{Binding}" /> </DataTemplate> </data:DataGridTemplateColumn.CellTemplate> </data:DataGridTemplateColumn> </data:DataGrid.Columns> </data:DataGrid> Day Selector Initialization code: var days = (from field in typeof(DayOfWeek).GetFields() where field.IsLiteral select field.Name).ToList<string>(); DayMaskList.ItemsSource = days; foreach (object item in DayMaskList.ItemsSource) DayMaskList.SelectedItems.Add(item); With the previous version of the DataGrid, this code allowed me to select all items programmatically. Now, only the last item is selected... The foreach loop does not add anything to the SelectedItems collection. It seems to break our styles for datagrids. Seems like the sort shows up when it didn't before. Here's a screenshot: Noting that CanUserSortColumns is false. Seems like the Datagrid is outputting the sort style for some reason. Noting we're using DataGridTemplateColumn. Here's an example of one: <my:DataGridTemplateColumn <my:DataGridTemplateColumn.HeaderStyle> <Style TargetType="localprimitives:DataGridColumnHeader"> <Setter Property="Padding" Value="0" /> <Setter Property="Margin" Value="0" /> <Setter Property="Height" Value="31" /> <Setter Property="MaxHeight" Value="31" /> <Setter Property="MinHeight" Value="31" /> <Setter Property="Width" Value="122" /> <Setter Property="Background" Value="Transparent" /> <Setter Property="BorderThickness" Value="0" /> <Setter Property="ContentTemplate"> <Setter.Value> <DataTemplate> <Grid Margin="0" MaxHeight="31" MinHeight="31" Height="31" Width="122" Background="#FFFBE4AB" Cursor="Hand" > <Grid.RowDefinitions> <RowDefinition Height="1" /> <RowDefinition Height="24" /> <RowDefinition Height="1" /> <RowDefinition Height="1" /> <RowDefinition Height="1" /> <RowDefinition Height="1" /> <RowDefinition Height="1" /> <RowDefinition Height="1" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="*" /> </Grid.ColumnDefinitions> <Rectangle Grid. <Grid Background="Black" Grid. <TextBlock Text="{Binding}" Foreground="White" MouseLeftButtonDown="Sort_Click" Tag="Country" Margin="3,4,0,0" VerticalAlignment="Center" FontWeight="Normal" /> </Grid> <Rectangle Grid. <Rectangle Grid. <Rectangle Grid. <Rectangle Grid. <Rectangle Grid. <Rectangle Grid. </Grid> </DataTemplate> </Setter.Value> </Setter> </Style> </my:DataGridTemplateColumn.HeaderStyle> <my:DataGridTemplateColumn.CellTemplate> <DataTemplate> <TextBlock Text="{Binding Country}" Margin="4" VerticalAlignment="Top" TextWrapping="Wrap" /> </DataTemplate> </my:DataGridTemplateColumn.CellTemplate> </my:DataGridTemplateColumn> p.s. This is for an internal project for Microsoft themselves, so not good if I need to hack this datagrid even more than I've had to to make things work :) Yes, the new header style always leaves room for the sort icon. You'll have to retemplate the header itself (not just it's ContentTemplate) to remove it. For example, you could make the header's style only consist of the content by adding the following setter to your header style: <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="localprimitives:DataGridColumnHeader"> <ContentPresenter Content="{TemplateBinding Content}" Cursor="{TemplateBinding Cursor}" /> </ControlTemplate> </Setter.Value> </Setter> Since we had set column widths we had to hack the setter properties:<Setter Property="Width" Value="122" />...we had to add 15 to this width in order to "push" this sort thing behind the other column so it isn't viewable anymore. Not sure what you mean by "new header style". New as to this release? Not sure why it isn't in the list of "breaking changes" then if it is. My current styles in the app.xaml have no sorting rectangle in there whatsoever. It seems like our DataGridTemplateColumn.HeaderStyle is getting some default sorting thing in there as you can see in the flickr image. Not sure where this is coming from, since it's not in our styles from before. Edit: So you're saying, even though we have the DataTemplate in there, I need to add your ControlTemplate code in as well to remove the sorting thing? I see where you're going, but I have CanSort as False in each of the columns themselves, and the entire grid, should setting sorting to "no" stop this sorting rectangle from rendering? What you say in your edit is correct; that's what I meant, sorry if I wasn't very clear. The header template essentially has three main components: the content presenter (which can be re-templated through the ContentTemplate), the sort icon, and the vertical separator. Currently, in order to remove the sort icon you have to remove it from the header template itself. I understand what you're saying about leaving the space there for the sort icon even though CanSort is false. We had decided to always leave room there in order to avoid having to dynamically change the column's width when the sort icon appears or the value of CanSort changes during runtime. I'll discuss this with my team and see if we should remove the extra space when CanSort is false, but the only way around this (at least for right now) is to re-template the header. But I also already have the ControlTemplate in my App.xaml for my DataGridColumnHeader, all I'm doing in the DataGrid is setting the DataTemplate. Should the ContentTemplate not trickle down, or when you do things like overriding the DataGridTemplateColumn.HeaderStyle is the rul that you need to override everything, including the ControlTemplate. This is what I would expect, unless it's a Silverlight limitation to do so. Having the exact same issue as johonline where in some cases, adding items to the selecteditems collection does not do anything as DataGrid.SelectedItems.Count returns 0 after calling Add() and the last object in our loop is all that is selected. We aren't trying to select all items as in johonline's case but this is still proving to be a MAJOR headache for us. It seems to work all but the first time we try it. Has there been any workaround to this issue or is it a confirmed bug that is being worked on? This is not a bug we have been aware of prior to this discussion. It sounds pretty serious, though, so I'll continue to try and reproduce it. Thanks for bringing it to our attention. I'll post something when I figure out what's wrong. I was just able to reproduce this locally. It looks like it occurs if you try to select items during the initialization phase. I have an idea of what might be causing this so I'll try to get it fixed for the next version. There is something you can do to workaround this issue in the meantime. If you delay your selection code so that it doesn't run until after the rows have loaded, it should fix this problem. One way to do this is to wrap your selection code in a call to Dispatcher.BeginInvoke. Let me know if that works as a temporary solution. Thanks again for bringing this to our attention. Dispatcher.BeginInvoke(delegate { for (int i = 0; i < 15; i++) { this.dataGrid.SelectedItems.Add(data[ i ]); } }); The December release fixed a lot of issues I was having, but there is still a persistant problem with having the DataGrid appear within a Popup. What I am finding is that the moment the Popup appears away from the top left corner (0 x, 0 y), the column resize functionality overrides the column sort and reorder functionality. Basically you have the WE cursor over the entire column header, so theres no way to reorder columns or click through to the sort option. Looking at the source code thrown up by Reflector, it appears that the resize function uses the header width minus the mouse x position to determine whether or not the mouse is < 5 pixels from the header's edge. If so the resize cursor and function is shown/enabled. I think because the datagrid is in a popup, the mouse co-ordinates it is using in the above resize enabling function are actually relative to the Silverlight host within the browser window, rather than being relative to the Popup. e.g. if the Popup is 500 pixels from the left, then mouse x position is always > 500.Thus the resulting column header size minus mouse x position calculation is always less than 5 pixels (think -400), and the resize is permanently enabled. Anyhow this should be easy to fix - hope this can happen! tsmooth: Yeah, you're right that the workaround won't fix the issue if the DataGrid isn't visible. You'll have to tweak it a little bit by setting selection when the DataGrid becomes visible (you might also have to BeginInvoke the selection code here as well) -- as long as you're in control of when the visibility changes, or can find out when it happens. The reason the workaround doesn't work in this case (if you're curious) is that adding multiple items to the DataGrid is broken while the rows are being loaded. There's a time period between when you set the ItemsSource and the DataGrid finishes loading all of the visual elements. It's this time period in which you can't properly set selection -- that's the bug. The original workaround works in most cases because the BeginInvoke pushes the selection code to the end of the queue so that it doesn't run until after the DataGrid has been arranged/measured completely, but it won't work if it isn't visible because the rows won't finish loading until they're actually rendered. For SelectedItems, I'll bring it to the attention of the feature crew, but it's currently a readonly property and making it bindable could add some complications. Thanks for the tip, it solved our issue. i have followed those steps exactly,(btw the 4 toolbox files where hidden ) now in my silverlight project oolbox i have no controls :S i only have the grid and the datepicker. the others controls are there but only when i sleect show all(inactive). i tried with devenv /resetskipkgs and /resetsettings and /setup, but nothings happens. whats worng???. now im installing the silverlight 3 beta toolbox to see if this get repaired, thanks. Does the RIA Serivces Announcement give us a rough timeline as to when virtual mode for the DataTable will be ready? Is there any expected relation between the two? Chris Did silverlight 3 beta fix your problem? Yes, silveright 3 solved my problems, buyt added a few ones, like i have to rebuild the solution to have debug available. Hi, It seems the datagrid is very slow to display data, even with a reasonnable amount of lines (50 lines, 5 to 10 columns). It takes more than one second to display a collection (binded by setting itemsource property), with listbox it only takes 400 to 500 ms. And with 10 years old asp 3 it takes less than 100 ms ;) Maybe I missed something but It seems to be a known issue (,), can we expect improvements ? Thanks, I personally think that the instructions on the download page are BS. You are making folks remove all of their toolbox mappings for every stinking control that they use? This was a very lazy approach to pushing out these changes, IMHO. It should have been delivered with an MSI, but I guess I should expect nothing less than mediocrity from Microsoft. Alan Gengis - There isn't much more I can add than what Yifung has said in the threads you reference. The DataGrid is a more complex control than ListBox, and chances are that there are many more visuals being created when it loads. A DataGrid with 50 rows and 10 columns is like having 10 ListBoxes with 50 items each. One benefit of the DataGrid, however, is that it virtualizes its rows, so the initial load time is dependent on the number of visible elements rather than the number of items in the ItemsSource -- the ListBox will create visual elements for all of its items, even if they are scrolled out of view. Having said all of that, though, the SL3 DataGrid should have faster load times than it did with SL2. Have you had a chance to try the SL3 beta yet? Alan - I'm sorry you had to lose your toolbox mappings when you upgraded the DataGrid. We wanted to get a new version out for you guys quickly, and I apologize if it was inconvenient. Thanks for the feedback. Brian : I followed Yifung's suggestion, putting the datagrid in a grid (with Grid.Row and Grid.Column) is cleary better than putting it in a StackPanel. Not as fast as a listbox but not so far. I think that mixing StackPanel and DataGrid should be more clearly discouraged. Maybe it's off topic but I do not understand why SL still does not meet all the basic needs of a business application, trivial feature like 'field validation' or 'having a first item blank in a ComboBox' or 'handling wcf exceptions or fault' are not provided out of the box. When you come from asp.net it is a bit confusing to see that such simple features are missing, for each of them you waste time at searching on the web if you did not miss something and then you waste time at implementing them yourself in the less ugly manner. Does anyone know if the System.Windows.Data.CollectionView class is included with Silverlight 3? I don't see it in the Beta documentation. That will be a shame if it's still missing in Silverlight 3 RTM. In Silverlight 3, there is a PagedCollectionView that is a CollectionView implementation that does paging as well. In the SL 3 Beta, it is in the System.ComponentModel.dll that comes with the SDK; however, in the RTM release of SL 3, it will be in the System.Windows.Data.dll. Field validation is available in Silverlight 3 using the same DataAnnotations attributes that are available for ASP.NET. I thought the ComboBox already has nothing selected (blank item) by default. @yifung : the blank list item is selected by default but as soon as you select another item (one provided by in the ItemsSource) it becomes unavailable. So you have to insert a new instance at the first position of your list before setting the items source. Concerning the validation : do you consider an alternative to the DataAnnotations ? How would you apply validation when entities are local representations of remote objects (typically in a silverlight <=> wcf application) ? Would you directly work on the generated classes (in reference.cs) ?! In this case validation through xaml control (like requiredFiledValidator) seems more suitable. And by the way thanks for Fault support and binaryHttpBinding. Thanks for this update, I was having the issue when removing rows from my DataGrid that empty rows would appear and this fixed it! Justin TothToth SolutionsJustin Toth's Blog
http://silverlight.net/forums/t/59990.aspx
crawl-002
refinedweb
5,395
57.57
#include "stdio.h" #include "sys/mman.h" int main() { void* p = mmap( NULL, 4096, PROT_READ | PROT_WRITE, MAP_FIXED | MAP_PRIVATE | MAP_ANON, -1, 0); if (p == NULL) printf("*(NULL) = %x.\n", *((int*) NULL)); else perror("mmap(2)"); return 0; }The program, when run on Linux and Mac OS X, prints *(NULL) = 0, and that's the result of the program doing a NULL pointer reference. This doesn't work on AIX. Thursday, January 8, 2009 Making NULL-pointer reference legal Normally, NULL pointer reference results in access violation and is illegal. However, it is possible to make NULL pointer reference legal on several operating systems. There are two ways to do that: (a) using mmap(2) with MAP_FIXED flag (works on Linux and Mac OS X), and (b) using shmat(2) with the SHM_RND flag (works on Linux). Consider the following program: Posted by Likai Liu at 4:42 PM Labels: correctness, system
http://lifecs.likai.org/2009/01/making-null-pointer-reference-legal.html
CC-MAIN-2017-26
refinedweb
150
62.58
", /* tls_slot_index 0 or 1, if 1 asks the Acldll to create its own thread-local index. See thread-local note below. This argument was 'quiet' in releases prior to 8.1 but not used. */ 0, /* Win32app flag; on UNIX, must be 0 */ 0, /* global variable containing prelinked library list; defined by shlibs.h include file */ linked_shared_libraries ); } void my_exit( int n ) { fprintf( stderr, "my exit code can run here\n" ); exit( n ); } As of 8.1, lisp thread-local values will be stored directly in the threads, rather than in the global table as they now are (thus requiring them to be moved in and out as threads are switched). This requires that Allegro CL be able to get one thread-local slot from the operating system (because thread-local storage is limited in count on some systems, we only require that one slot be provided, and we then manage that slot in the lisp). Some systems don't even provide for thread-local slots, or their provision has not been exploited yet; these systems are marked with :no-os-tls in the *features* list (this name means "no operating-system supplied thread-local storage"). These architectures can supply a 0 or a 1 to the tls_slot_index argument. Also, most architectures can get a tls slot from within the acl shared library, though on some architectures there are very strict linking rules needed in order to do so. On the HP 64-bit port, which has tls, but whose shared-library cannot generate a tls slot, the tls_slot_index function pointer must be passed in. The example is given in examples/linkacl/fact.c (on Unix machines, related example in examples/dll/fact.c on Windows). For HP, and for any other architecture which supports the relatively new __thread construct in C/C++, the code would look something like this: #ifdef NeedTls __thread nat tls_dummy_slot; nat tls_slot_index() { return (nat)&tls_dummy_slot; } #endif and in the actual lisp_init, call where the quiet flag used to be: lisp_init( lnk_argc, lnk_argv, lnk_envp, /* argc, argv, envp */ 0, /* exit routine */ dir_buf, /* system directory */ (char*)LIBACL_NAME, 0, (char*)"fact.dxl", /* image name */ #ifdef NeedTls &tls_slot_index, #else (nat(*)())1, /* quiet flag (old) */ #endif 0, /* unused on Unix */ linked_shared_libraries ); For windows, the definition of tls_slot_index would be nat tls_slot_index() { return ((nat)(TlsAlloc())); } -2012, Franz Inc. Oakland, CA., USA. All rights reserved. Documentation for Allegro CL version 9.0. This page was not revised from the 8.2 page. Created 2012.5.30.
http://franz.com/support/documentation/current/doc/main.htm
CC-MAIN-2014-10
refinedweb
411
60.75
Consider the following C program #include <stdio.h> typedef struct s { int x; } s_t; int main() { int x; s_t a; scanf("%d", &x); if (x > 0) { s_t a; a.x = x; } printf("%d\n", a.x); } The a struct variable in the if branch clearly shadows the a struct variable in main. One would expect that the output in printf would be undefined, but with GCC the scoped variable seems to equal the main variable. For example gcc test.c -o test echo 10 | ./test will output 10. On the other hand, running this through clang, does as expected clang test.c -o test echo 10 | ./test outputs -2145248048. Is this a GCC bug or is there some sort of undefined behaviour that this is triggering? gcc 4.8.2 clang 3.4
http://www.howtobuildsoftware.com/index.php/how-do/clV/c-gcc-struct-clang-scoping-scoping-rules-for-struct-variables-in-gcc
CC-MAIN-2019-09
refinedweb
133
87.31
This class is an abstraction for the packet concept. More... #include <gcs_internal_message.h> This class is an abstraction for the packet concept. It is used to manipulate the contents of a buffer that is to be sent to the network in an optimal way. The on-the-wire layout looks like this: +-----------—+--------------—+-------------—+--------—+ | fixed header | dynamic headers | stage metadata | payload | +-----------—+--------------—+-------------—+--------—+ These constructors are to be used when move semantics may be needed. Constructor called by make_to_send. Constructor called by make_from_existing_packet. Constructor called by make_from_serialized_buffer. Allocates the underlying buffer where the packet will be serialized to using serialize. Decode the packet content from the given buffer containing a serialized packet. Create a string representation of the packet to be logged. Return the cargo type. Retrieve this packet's dynamic headers. Retrieve this packet's header. Return the value of the maximum supported version. Return the payload length. Retrieve this packet's stage metadata. Return the total length. Return the value of the version in use. This factory method is to be used when modifying a packet. This builds a packet with all the same headers, metadata, and state of original_packet. It is used, for example, by: This factory method is to be used when receiving a packet from the network. This factory method is to be used when sending a packet. Encode the packet content into its serialization buffer, and release ownership of the serialization buffer. This method must only be called on a valid packet, i.e. a packet for which allocate_serialization_buffer was called and returned true. The XCom synode in which this packet was delivered. List of dynamic headers created by the stages by which the packet has passed through and changed it. Fixed header which is common regardless whether the packet has been changed by a stage or not. Index of the next stage to apply/revert in both m_dynamic_headers and m_stage_metadata. The buffer containing all serialized data for this packet. The capacity of the serialization buffer. The offset in m_serialized_packet where the application payload starts. The size of the serialized application payload in m_serialized_packet. The size of the serialized m_stage_metadata in m_serialized_packet. List of stage metadata created by the stages by which the packet has passed through. This list always has the same length as m_dynamic_headers, and the following holds: For every i, m_stage_metadata[i] and m_dynamic_headers[i] correspond to the same stage.
https://dev.mysql.com/doc/dev/mysql-server/latest/classGcs__packet.html
CC-MAIN-2021-31
refinedweb
395
52.15
Flag Attributes in Android — How to Use Them I’m sure you have seen something like the following line very often while writing the XML attributes for your views or layouts. attribute="option1|option2" Notice the | between the options. It is not only a fancy separator, it is a bitwise operator merging the two options into one single value. The following will explain what exactly Bit Flags are, how to declare custom XML flag attributes and how to read and work with them in the code. What Are Bit Flags? Generally you can see Bit Flags as a number of boolean values stored in one single value. In the binary system a bit has two states: on and off. Now think about a row of bits where every bit is an indicator for one of your options. When the option is set, the bit has the value 1. If not, it has the value 0. 110 We read this from right to left. The bit for our first option is 0. That means the option is not set. Whereas the bits for the second and third options are 1. This means they are set. Every integer value has a representation in the binary system and and vice versa. 0 = 0*2³ + 0*2² + 0*2¹ + 0*2⁰ = 0000 1 = 0*2³ + 0*2² + 0*2¹ + 1*2⁰ = 0001 2 = 0*2³ + 0*2² + 1*2¹ + 0*2⁰ = 0010 4 = 0*2³ + 1*2² + 0*2¹ + 0*2⁰ = 0100 8 = 1*2³ + 0*2² + 0*2¹ + 0*2⁰ = 1000 This means we can store our Bit Flag value as a plain integer value. And we can use the bitwise operators (more about them later) directly on integer values. Declaring XML Flag Attributes Now, let’s assume that we want to create a custom view called MyView which can draw a border around itself, and that we want to specify on which sites (top, right, bottom, left) it should draw the borders using an XML flag attribute. I will not explain how to actually draw something, I will only explain how to work with flags. We can declare XML flag attributes like any other attribute. You can find an official documentation here. In our values/attrs.xml file we declare the new attribute called drawBorder for our view called MyView. <resources> <declare-styleable <attr name="drawBorder"> <flag name="none" value="0" /> <flag name="top" value="1" /> <flag name="right" value="2" /> <flag name="bottom" value="4" /> <flag name="left" value="8" /> <flag name="all" value="15" /> </attr> ... </declare-styleable> </resources> Look exactly at the values we have set for the options. We essentially have 4 options (top, right, bottom, left). The other two options are used to specify that no option is set or that all options are set. The values for the 4 options are chosen, so that when you write them in the binary system, these two statements are fulfilled: - Every value has exactly one bit which is set to 1. All other bits are 0. - None of the values have the same bit set to 1. The option none is used to indicate that none of the 4 options is set. And the option all is the sum of the values of the 4 options and indicates that all of the 4 options are set. We can now use our custom attribute like this in our custom View: <my.package.name.MyView android: Read XML Flag Attributes Let’s start with the basic class for our custom View. We should declare a constant for each of our options with an equal value as declared above. And a variable for the value that we get from reading the XML attribute. You can have a look about how to read attributes here. public MyView extends View{ // Constants for the flags private static final int BORDER_NONE_DEFAULT = 0; private static final int BORDER_TOP = 1; private static final int BORDER_RIGHT = 2; private static final int BORDER_BOTTOM = 4; private static final int BORDER_LEFT = 8; // Variable for the current value private int mDrawBorder = BORDER_NONE_DEFAULT; public MyView(Context context){ // Delegate to next constructor this(context, null); } public MyView(Context context, AttributeSet attrs){ // Delegate to next constructor this(context, attrs, 0); } public MyView(Context context, AttributeSet attrs, int defStyleAttr){ super(context, attrs, defStyleAttr); // Read attributes TypedArray a = context.getTheme().obtainStyledAttributes( attrs, R.styleable.MyView); try { mDrawBorder = a.getInteger( R.styleable.MyView_drawBorder, BORDER_NONE_DEFAULT); } finally { a.recycle(); } } ... } We have now assigned the value specified in the XML layout file to the mDrawBorder variable. If the attribute does not exists in the layout the BORDER_NONE_DEFAULT value is used.. Let’s have a look at them: | (bitwise logically or) Example: 100 | 001 = 101 The result has a 1 on the position where at least one value has a 1.& (bitwise logically and) Example: 100 & 101 = 100 The result has a 1 on the position where both values have a 1.~ (bitwise inverse) Example: ~100 = 011 All bits get inverted.^ (bitwise exclusive or) Example: 100^101 = 001 The result has a 1 on the position where one value has a 1 whereas the other value has a 0. Let’s assume we have used the attribute in the following two ways. Yes, technically they are correct, but they may look weird 😵. Example 1: app:drawBorder="none|top" In this first example the values of none (0 = 000) and top (1 = 001) get combined by the logically or-operator | to the value (001 = 1). The result still contains the flag value for top (which is 1). And also for none (which is 0) because every flag-set contains the 0-flag at every time. Example 2: app:drawBorder="bottom|all" In this second example the values of bottom (3 =0011) and all (15 = 1111) get combined to (1111 = 15). The result still contains the flag for bottom since all enables the bits for all of the 4 options. Check If a Flag is Contained in The Set Now we need to check which option is contained in the value of the mDrawBorder variable. We do this by calling the following method: private boolean containsFlag(int flagSet, int flag){ return (flagSet|flag) == flagSet; }// Method call boolean drawBorderTop = containsFlag(mDrawBorder, BORDER_TOP); We try to add the flag to the existing flag-set and if the value of the flag-set does not change, we can combine that the flag was already contained. Add a Flag to The Set Adding a flag is pretty simple. We use the same operator (The logically or-operator) like in the XML attributes: private int addFlag(int flagSet, int flag){ return flagSet|flag; }// Method call mDrawBorder = addFlag(mDrawBorder, BORDER_LEFT); We do not need to check if the flag-set already contains the flag that we want to add. When it is already contained, the value simply stays the same. Toggle a Flag in The Set Toggling is also very simple. private int toggleFlag(int flagSet, int flag){ return flagSet^flag; }// Method call mDrawBorder = toggleFlag(mDrawBorder, BORDER_LEFT); Since the exclusive or-operator ^ only keeps the bits where both bits are different, it will remove the bits that are set in the flag when they are also already set in the flag-set. And it will add them if they are not set in the flag-set. Example 1: 110^010 = 100 (Binary) 6 ^ 2 = 4 (Decimal)Example 2: 100^010 = 110 (Binary) 4 ^ 2 = 6 (Decimal) Remove a Flag From the Set Removing a flag is a bit more complicated (we need two bitwise operators), but still easy. private int removeFlag(int flagSet, int flag){ return flagSet&(~flag); }// Method call mDrawBorder = removeFlag(mDrawBorder, BORDER_LEFT); First we invert the flag that we want to remove. Then we combine this with the current flag-set. This means only where the bit in the flag was set, we now have a 0. And that’s why we also have a 0 at this position in the final result. The rest of the result is the same as in the original flag-set. Have a look at this example: 110&(~010) = 110&101 = 100 (Binary) 6 &(~ 2 ) = 6 & 5 = 4 (Decimal) Bit Flags are also a good alternative if you have a lot of boolean values and especially if you want to store them somehow. Instead of saving a lot of booleans you only need to save one integer value. You should now be able to define your own flag attributes and work with them in your application. You should also be able to use Bit Flags as an alternative to a number of booleans. When you found this tutorial useful feel free to hit the 💚. If you have any suggestions on how to improve this tutorial or found a mistake, you can leave a private note at the specific position. Happy coding 💻.
https://medium.com/@JakobUlbrich/flag-attributes-in-android-how-to-use-them-ac4ec8aee7d1
CC-MAIN-2019-22
refinedweb
1,467
69.82
wxPython – Redirecting stdout / stderrPosted by Mike on January 1st, 2009 filed in Cross-Platform, Python, wxPython New programmers start using Python and wxPython each week. So it follows that every few months, I see people asking how to redirect stdout to a wx.TextCtrl on comp.lang.python or the wxPython mailing list. Since this is such a common question, I thought I would write an article about it. Regular readers will know that I have mentioned this concept before in a previous post. First off, we’ll need to create a class that can duck-type the writing API of a wx.TextCtrl. Notice that I use the so-called “new style” class that subclasses object (see code below). class RedirectText(object): def __init__(self,aWxTextCtrl): self.out=aWxTextCtrl def write(self,string): self.out.WriteText(string) Note that there’s only one method in this class. It allows us to write the text from stdout or stderr to the text control. It should be noted that the write method is not thread-safe. If you want to redirect text from threads, then change the write statement like this: def write(self, string): wx.CallAfter(self.out.WriteText, string) Now let’s dig into the wxPython code we’ll need: import sys import wx class MyForm(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, wx.ID_ANY, "wxPython Redirect Tutorial") # Add a panel so it looks the correct on all platforms panel = wx.Panel(self, wx.ID_ANY) log = wx.TextCtrl(panel, wx.ID_ANY, size=(300,100), style = wx.TE_MULTILINE|wx.TE_READONLY|wx.HSCROLL) redir=RedirectText(log) sys.stdout=redir def onButton(self, event): print "You pressed the button!" # Run the program if __name__ == "__main__": app = wx.PySimpleApp() frame = MyForm().Show() app.MainLoop() In the code above, I create a read-only multi-line text control and a button whose sole purpose is to print some text to stdout. I add them to a BoxSizer to keep the widgets from stacking on top of each other and to better handle resizing of the frame. Next I instantiate the RedirectText class by passing it an instance of my text control. Finally, I set stdout to the RediectText instance, redir (i.e. sys.stdout=redir). If you want to redirect stderr as well, then just add the following right after “sys.stdout=redir”: sys.stderr=redir And that’s all there really is to it. Improvements could be made to this, namely color coding (or pre-pending) which messages are from stdout and which are from stderr, but I’ll leave that as an exercise for the reader. Download the Source - Adam Fraser - Adam Fraser - mgag - mgag - mgag - mgag - Anonymous - Anonymous
http://www.blog.pythonlibrary.org/2009/01/01/wxpython-redirecting-stdout-stderr/
CC-MAIN-2015-27
refinedweb
450
67.76
A UICollectionViewLayout subclass, used as the layout object of a UICollectionView. QuiltView can be used with iOS and tvOS, is developed in Swift, and based on the Objective-C RFQuiltLayout library. QuiltView is a Swift port of RFQuiltLayout, but not all features are necessarily ported and some additional features have been added. Installation - Add QuiltView to your Podfile: pod QuiltView - Install the pod using pod install Add the layout as the subclass of your UICollectionView. To do that you set the Layout value to Custom and then select QuiltViewas the Class and Module - Import QuiltView into your controller: import QuiltView Set the QuiltViewDelegateon the Controller hosting the UICollectionView. Next, depending on how you want the cells to appear you can set the width and height of them. You can set the width and heights to different values to create rectangular shapes or you can set the width and height to the same values to create squares. extension ViewController : QuiltViewDelegate { func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, blockSizeForItemAtIndexPath indexPath: IndexPath) -> CGSize { // get random width and height values for the cells let width = self.numberWidths[indexPath.row] let height = self.numberHeights[indexPath.row] return CGSize(width: width, height: height) } // Set the spacing between the cells func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetsForItemAtIndexPath indexPath: IndexPath) -> UIEdgeInsets { return UIEdgeInsets(top: 2, left: 2, bottom: 2, right: 2) } } Overrides The following code shows how to override the default settings of QuiltView let layout = self.collectionView?.collectionViewLayout as! QuiltView // Set the layout to .horizontal if you want to scroll horizontally. // This setting is optional as the default is Vertical layout.scrollDirection = UICollectionViewScrollDirection.vertical // This sets the block or cell size. When the sizes are equal squares will be created. // When the sizes are different, rectangular cells will be created. The default size // set by the library is 314 x 314. layout.itemBlockSize = CGSize( width: 75, height: 75 ) NOTE: All delegate methods and properties are optional Screen Shots License QuiltView is available under the MIT license. See the LICENSE file for more info. Changelog Refer to the Releases page. Latest podspec { "name": "QuiltView", "version": "0.1.4", "summary": "QuiltView is a subclass of UICollectionViewLayout that positions various sized cells in a quilt like pattern.", "description": "QuiltView will layout CollectionView cells with various widths and heights on the page. The cells are positioned in a quilt style layout so each cell fits next to the other cell, leaving only the space defined by the UIEdgeInsets. You can provide widths and heights that are not equal creating rectangular shapes or you can specify a width and height that matches to ensure the cells are square. This library is a port of the RFQuiltLayout developed by Bryce Redd. That project can be found here:", "homepage": "", "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "jgroh9": "[email protected]" }, "source": { "git": "", "tag": "0.1.4" }, "social_media_url": "", "platforms": { "ios": "10.2", "tvos": "10.1" }, "source_files": "QuiltView/Classes/*", "pushed_with_swift_version": "3.0" } Thu, 02 Feb 2017 04:20:05 +0000
https://tryexcept.com/articles/cocoapod/quiltview
CC-MAIN-2019-43
refinedweb
493
56.15
. A simple test Let’s start with what I used to think was the simplest and most obvious example of how const can make C code faster. First, let’s say we have these two function declarations: void func(int *x); void constFunc(const int *x); And suppose we have these two versions of some code: void byArg(int *x) { printf("%d\n", *x); func(x); printf("%d\n", *x); } void constByArg(const int *x) { printf("%d\n", *x); constFunc(x); printf("%d\n", *x); } To do the printf(), the CPU has to fetch the value of *x from RAM through the pointer. Obviously, constByArg() can be made slightly faster because the compiler knows that *x is constant, so there’s no need to load its value a second time after constFunc() does its thing. It’s just printing the same thing. Right? Let’s see the assembly code generated by GCC with optimisations cranked up: $ gcc -S -Wall -O3 test.c $ view test.s Here’s the full assembly output for byArg(): byArg: .LFB23: .cfi_startproc pushq %rbx .cfi_def_cfa_offset 16 .cfi_offset 3, -16 movl (%rdi), %edx movq %rdi, %rbx leaq .LC0(%rip), %rsi movl $1, %edi xorl %eax, %eax call __printf_chk@PLT movq %rbx, %rdi call func@PLT # The only instruction that's different in constFoo movl (%rbx), %edx leaq .LC0(%rip), %rsi xorl %eax, %eax movl $1, %edi popq %rbx .cfi_def_cfa_offset 8 jmp __printf_chk@PLT .cfi_endproc The only difference between the generated assembly code for byArg() and constByArg() is that constByArg() has a call constFunc@PLT, just like the source code asked. The const itself has literally made zero difference. Okay, that’s GCC. Maybe we just need a sufficiently smart compiler. Is Clang any better? $ clang -S -Wall -O3 -emit-llvm test.c $ view test.ll Here’s the IR. It’s more compact than assembly, so I’ll dump both functions so you can see what I mean by “literally zero difference except for the call”: ; Function Attrs: nounwind uwtable define dso_local void @by @func } ; Function Attrs: nounwind uwtable define dso_local void @constBy @constFunc } Something that (sort of) works Here’s some code where const actually does make a difference: void localVar() { int x = 42; printf("%d\n", x); constFunc(&x); printf("%d\n", x); } void constLocalVar() { const int x = 42; // const on the local variable printf("%d\n", x); constFunc(&x); printf("%d\n", x); } Here’s the assembly for localVar(), which has two instructions that have been optimised out of constLocalVar(): localVar: .LFB25: .cfi_startproc subq $24, %rsp .cfi_def_cfa_offset 32 movl $42, %edx movl $1, %edi movq %fs:40, %rax movq %rax, 8(%rsp) xorl %eax, %eax leaq .LC0(%rip), %rsi movl $42, 4(%rsp) call __printf_chk@PLT leaq 4(%rsp), %rdi call constFunc@PLT movl 4(%rsp), %edx # not in constLocalVar() xorl %eax, %eax movl $1, %edi leaq .LC0(%rip), %rsi # not in constLocalVar() call __printf_chk@PLT movq 8(%rsp), %rax xorq %fs:40, %rax jne .L9 addq $24, %rsp .cfi_remember_state .cfi_def_cfa_offset 8 ret .L9: .cfi_restore_state call __stack_chk_fail@PLT .cfi_endproc The LLVM IR is a little clearer. The load just before the second printf() call has been optimised out of constLocalVar(): ; Function Attrs: nounwind uwtable define dso_local void @localVar() local_unnamed_addr #0 { %1 = alloca i32, align 4 %2 = bitcast i32* %1 to i8* call void @llvm.lifetime.start.p0i8(i64 4, i8* nonnull %2) #4 store i32 42, i32* %1, align 4, !tbaa !2 %3 = tail call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([4 x i8], [4 x i8]* @.str, i64 0, i64 0), i32 42) call void @constFunc(i32* nonnull %1) #4 %4 = load i32, i32* %1, align 4, !tbaa !2 %5 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([4 x i8], [4 x i8]* @.str, i64 0, i64 0), i32 %4) call void @llvm.lifetime.end.p0i8(i64 4, i8* nonnull %2) #4 ret void } Okay, so, constLocalVar() has sucessfully elided the reloading of *x, but maybe you’ve noticed something a bit confusing: it’s the same constFunc() call in the bodies of localVar() and constLocalVar(). If the compiler can deduce that constFunc() didn’t modify *x in constLocalVar(), why can’t it deduce that the exact same function call didn’t modify *x in localVar()? The explanation gets closer to the heart of why C const is impractical as an optimisation aid. C const effectively has two meanings: it can mean the variable is a read-only alias to some data that may or may not be constant, or it can mean the variable is actually constant. If you cast away const from a pointer to a constant value and then write to it, the result is undefined behaviour. On the other hand, it’s okay if it’s just a const pointer to a value that’s not constant. This possible implementation of constFunc() shows what that means: // x is just a read-only pointer to something that may or may not be a constant void constFunc(const int *x) { // local_var is a true constant const int local_var = 42; // Definitely undefined behaviour by C rules doubleIt((int*)&local_var); // Who knows if this is UB? doubleIt((int*)x); } void doubleIt(int *x) { *x *= 2; } localVar() gave constFunc() a const pointer to non- const variable. Because the variable wasn’t originally const, constFunc() can be a liar and forcibly modify it without triggering UB. So the compiler can’t assume the variable has the same value after constFunc() returns. The variable in constLocalVar() really is const, though, so the compiler can assume it won’t change — because this time it would be UB for constFunc() to cast const away and write to it. The byArg() and constByArg() functions in the first example are hopeless because the compiler has no way of knowing if *x really is const. Update (and digression): Quite a few readers have correctly pointed out that with const int *x, the pointer itself isn’t qualified const, just the data being aliased, and that const int * const extra_const is a pointer that’s qualified const “both ways”. But because the constness of the pointer itself is independent of the constness of the data being aliased, the result is the same. *(int*const)extra_const = 0 is still UB only if extra_const points to an object that’s defined with const. (In fact, *(int*)extra_const = 0 wouldn’t be any worse.) Because it’s a mouthful to keep distinguishing between a fully const pointer and a pointer that may or may not be itself constant but is a read-only alias to an object that may or not be constant, I’ll just keep referring loosely to “ const pointers”. (End of digression.) But why the inconsistency? If the compiler can assume that constFunc() doesn’t modify its argument when called in constLocalVar(), surely it can go ahead an apply the same optimisations to other constFunc() calls, right? Nope. The compiler can’t assume constLocalVar() is ever run at all. If it isn’t (say, because it’s just some unused extra output of a code generator or macro), constFunc() can sneakily modify data without ever triggering UB. You might want to read the above explanation and examples a few times, but don’t worry if it sounds absurd: it is. Unfortunately, writing to const variables is the worst kind of UB: most of the time the compiler can’t know if it even would be UB. So most of the time the compiler sees const, it has to assume that someone, somewhere could cast it away, which means the compiler can’t use it for optimisation. This is true in practice because enough real-world C code has “I know what I’m doing” casting away of const. In short, a whole lot of things can prevent the compiler from using const for optimisation, including receiving data from another scope using a pointer, or allocating data on the heap. Even worse, in most cases where const can be used by the compiler, it’s not even necessary. For example, any decent compiler can figure out that x is constant in the following code, even without const: int x = 42, y = 0; printf("%d %d\n", x, y); y += x; printf("%d %d\n", x, y); TL;DR: const is almost useless for optimisation because - Except for special cases, the compiler has to ignore it because other code might legally cast it away - In most of the exceptions to #1, the compiler can figure out a variable is constant, anyway C++ There’s another way const can affect code generation if you’re using C++: function overloads. You can have const and non- const overloads of the same function, and maybe the non- const can be optimised (by the programmer, not the compiler) to do less copying or something. void foo(int *p) { // Needs to do more copying of data } void foo(const int *p) { // Doesn't need defensive copies } int main() { const int x = 42; // const-ness affects which overload gets called foo(&x); return 0; } On the one hand, I don’t think this is exploited much in practical C++ code. On the other hand, to make a real difference, the programmer has to make assumptions that the compiler can’t make because they’re not guaranteed by the language. An experiment with Sqlite3 That’s enough theory and contrived examples. How much effect does const have on a real codebase? I thought I’d do a test on the Sqlite database (version 3.30.0) because - It actually uses const - It’s a non-trivial codebase (over 200KLOC) - As a database, it includes a range of things from string processing to arithmetic to date handling - It can be tested with CPU-bound loads Also, the author and contributors have put years of effort into performance optimisation already, so I can assume they haven’t missed anything obvious. The setup I made two copies of the source code and compiled one normally. For the other copy, I used this hacky preprocessor snippet to turn const into a no-op: #define const (GNU) sed can add that to the top of each file with something like sed -i '1i#define const' *.c *.h. Sqlite makes things slightly more complicated by generating code using scripts at build time. Fortunately, compilers make a lot of noise when const and non- const code are mixed, so it was easy to detect when this happened, and tweak the scripts to include my anti- const snippet. Directly diffing the compiled results is a bit pointless because a tiny change can affect the whole memory layout, which can change pointers and function calls throughout the code. Instead I took a fingerprint of the disassembly ( objdump -d libsqlite3.so.0.8.6), using the binary size and mnemonic for each instruction. For example, this function: 000000000005d570 <sqlite3_blob_read>: 5d570: 4c 8d 05 59 a2 ff ff lea -0x5da7(%rip),%r8 # 577d0 <sqlite3BtreePayloadChecked> 5d577: e9 04 fe ff ff jmpq 5d380 <blobReadWrite> 5d57c: 0f 1f 40 00 nopl 0x0(%rax) would turn into something like this: sqlite3_blob_read 7lea 5jmpq 4nopl I left all the Sqlite build settings as-is when compiling anything. Analysing the compiled code The const version of libsqlite3.so was 4,740,704 bytes, about 0.1% larger than the 4,736,712 bytes of the non- const version. Both had 1374 exported functions (not including low-level helpers like stuff in the PLT), and a total of 13 had any difference in fingerprint. A few of the changes were because of the dumb preprocessor hack. For example, here’s one of the changed functions (with some Sqlite-specific definitions edited out): #define LARGEST_INT64 (0xffffffff|(((int64_t)0x7fffffff)<<32)) #define SMALLEST_INT64 (((int64_t)-1) - LARGEST_INT64) static int64_t doubleToInt64(double r){ /* ** Many compilers we encounter do not define constants for the ** minimum and maximum 64-bit integers, or they define them ** inconsistently. And many do not understand the "LL" notation. ** So we define our own static constants here using nothing ** larger than a 32-bit integer constant. */ static const int64_t maxInt = LARGEST_INT64; static const int64_t minInt = SMALLEST_INT64; if( r<=(double)minInt ){ return minInt; }else if( r>=(double)maxInt ){ return maxInt; }else{ return (int64_t)r; } } Removing const makes those constants into static variables. I don’t see why anyone who didn’t care about const would make those variables static. Removing both static and const makes GCC recognise them as constants again, and we get the same output. Three of the 13 functions had spurious changes because of local static const variables like this, but I didn’t bother fixing any of them. Sqlite uses a lot of global variables, and that’s where most of the real const optimisations came from. Typically they were things like a comparison with a variable being replaced with a constant comparison, or a loop being partially unrolled a step. (The Radare toolkit was handy for figuring out what the optimisations did.) A few changes were underwhelming. sqlite3ParseUri() is 487 instructions, but the only difference const made was taking this pair of comparisons: test %al, %al je <sqlite3ParseUri+0x717> cmp $0x23, %al je <sqlite3ParseUri+0x717> And swapping their order: cmp $0x23, %al je <sqlite3ParseUri+0x717> test %al, %al je <sqlite3ParseUri+0x717> Benchmarking Sqlite comes with a performance regression test, so I tried running it a hundred times for each version of the code, still using the default Sqlite build settings. Here are the timing results in seconds: Personally, I’m not seeing enough evidence of a difference worth caring about. I mean, I removed const from the entire program, so if it made a significant difference, I’d expect it to be easy to see. But maybe you care about any tiny difference because you’re doing something absolutely performance critical. Let’s try some statistical analysis. I like using the Mann-Whitney U test for stuff like this. It’s similar to the more-famous t test for detecting differences in groups, but it’s more robust to the kind of complex random variation you get when timing things on computers (thanks to unpredictable context switches, page faults, etc). Here’s the result: The U test has detected a statistically significant difference in performance. But, surprise, it’s actually the non- const version that’s faster — by about 60ms, or 0.5%. It seems like the small number of “optimisations” that const enabled weren’t worth the cost of extra code. It’s not like const enabled any major optimisations like auto-vectorisation. Of course, your mileage may vary with different compiler flags, or compiler versions, or codebases, or whatever, but I think it’s fair to say that if const were effective at improving C performance, we’d have seen it by now. So, what’s const for? For all its flaws, C/C++ const is still useful for type safety. In particular, combined with C++ move semantics and std::unique_pointers, const can make pointer ownership explicit. Pointer ownership ambiguity was a huge pain in old C++ codebases over ~100KLOC, so personally I’m grateful for that alone. However, I used to go beyond using const for meaningful type safety. I’d heard it was best practices to use const literally as much as possible for performance reasons. I’d heard that when performance really mattered, it was important to refactor code to add more const, even in ways that made it less readable. That made sense at the time, but I’ve since learned that it’s just not true.
https://theartofmachinery.com/2019/08/12/c_const_isnt_for_performance.html
CC-MAIN-2020-24
refinedweb
2,587
59.23
AWS Amplify is a JavaScript library that brings their backend services to web and mobile apps. At first glance, it appears to be a simple wrapper for their cloud services. In reality, it’s so much more: a curated set of backend features that make getting started with AWS much easier than ever before. With a few simple CLI commands, you can easily supercharge your app with: - Messaging - Analytics - User sign-in, sign-out, forgot password - Databases - Static website hosting (PWAs, anyone?!) - File storage Getting Started The Amplify team recently published a guide on how to build an Ionic 4 app with AWS Amplify. By following along, you’ll build a complete ToDo app. It’s not just any ordinary ToDo app though: the user must sign into the app before creating todos. Also, the todos are saved in the cloud using services such as Amazon Cognito, DynamoDB, Lambda. I won’t rehash the guide here; instead, let’s take a look at what I liked and disliked about my initial experience, as well as the impact that adding AWS Amplify to your Ionic 4 app can have. The first part of the guide involves the creation of an Ionic 4 app that uses Ionic’s tabs starter project. Three pages are provided: “Home”, “About”, and “Contact.” The ToDo model and UI TypeScript classes are created next, with full Angular code samples provided for reference. The ability to add and remove items in the list are added as well. The interesting twist here is the inclusion of an authentication-based route guard service, which essentially blocks the user from viewing the ToDo list until after they have signed into the app via AWS. The purpose for doing so becomes clearer as you go through the guide – you’ll eventually add a user sign-in experience. The resulting ToDo list page looks very nice: To add the sign-in experience and store ToDo items in the cloud, there’s more work to be done. This is where the magic of AWS starts to shine! Working with the AWS Mobile CLI Similar to Ionic, AWS Amplify puts heavy emphasis on their command line interface tool (CLI), used to create and manage all AWS backend resources. Available commands are mostly intuitive, such as “init”, which walks you through creating a backend project. I was a bit confused at first about some of the prompts regarding what to provide for source and distribution directories, but fortunately the guide provides suggested answers: Another concern arose quickly at the start of using the CLI. In order to provision AWS resources, you must configure an Identity Access Management (IAM) user. IAM is still a source of confusion for me. Given the dozens of policies available, I’m always worried that I won’t select the correct permissions. Fortunately, the steps are quite clear and connecting the user to the CLI is a one-time step. With the CLI installed and after running a couple of npm install commands, it’s easy to add Amplify to an Ionic 4 app. We simply import Amplify into the project in src/main.ts: import { enableProdMode } from '@angular/core'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app/app.module'; import { environment } from './environments/environment'; // Add AWS Amplify import Amplify, { Analytics } from 'aws-amplify'; import aws_exports from './aws-exports'; Amplify.configure(aws_exports); if (environment.production) { enableProdMode(); } platformBrowserDynamic().bootstrapModule(AppModule) .catch(err => console.log(err)); Adding Authorization/User Sign-in With the boilerplate configuration in place, it’s time for the best part: adding Amplify-specific features to our ToDo app such as a user sign-in experience. The first feature, authorization, uses Amazon Cognito behind-the-scenes. To enable it is quite straightforward: awsmobile user-signin enable awsmobile push There’s a lot to unpack in those two lines that isn’t necessarily obvious. For one, there’s no mention of the underlying services. Rather, a friendly name is used instead: “user-signin.” This is a common pattern among all Amplify services: the AWS technology that powers the feature is abstracted away from the developer. This is certainly great for the beginner, but more advanced users may be put off as they try to figure out how to perform advanced configurations. The second command, referencing “push”, seems a bit strange. What are we pushing? As it turns out, when you run “awsmobile feature enable”, changes are only made to your local project – the aws-exports.js file. It’s only after you “push” that this file is synced to the AWS cloud, in effect enabling the feature on the backend. This makes sense once you understand how it works, but I initially assumed that enabling features from the CLI immediately enabled them on the backend. This confusion led me to log into the AWS Mobile Hub, a section of the AWS console that allows you to view and configure the enabled backend features. I love the simplicity and clarity it provides: Once your backend feature is enabled, you can also use the AWS console for the related service to customize your backend, e.g., using Amazon Cognito for the User Sign-in feature. After adding a couple more bits of Angular code to our app, authentication is available on the Home tab: Now this is wicked cool! AWS Amplify provides several Angular UI components, including the full sign-in experience above. Adding a simple one-liner to this page, optionally styled with Ionic UI components, results in a ton of development time saved! <amplify-authenticator</amplify-authenticator> The default UI looks pretty good out-of-the-box and is fully responsive. As briefly mentioned in the guide, you can change the look and feel of the UI rather easily. Storing ToDo Items via Amazon DynamoDB At this point in the guide, we’ve got a ToDo list that users must sign-in to access, but the items aren’t saved anywhere – they’ll disappear after the app is closed. As it turns out, storing them in a cloud database is easy enough. With just a handful of awsmobile CLI commands, a DynamoDB NoSQL database is created and available immediately. We have a cloud database now, but we need to somehow add the ability to add, update, and remove todos from within our app. The next step in the guide is perhaps the most impressive: Automatic creation of a CRUD (create/read/update/delete) API for the ToDoItems database is a huge time saver. Behind the scenes, AWS hosts the backend API in AWS Lambda, their “serverless” service that runs code on-demand, without a provisioned server. Over in the Ionic 4 app, boilerplate JavaScript code is added to the project that exposes simple API endpoints. Here’s the Save method, for example: save(list){ // Use AWS Amplify to save the list... this.amplifyService.api().post('ToDoItemsCRUD', '/ToDoItems', {body: list}) .then((i) => { // and to get the list after you save it. this.getItems(); }) .catch((err) => { console.log(`Error saving list: ${err}`); }); } With that final touch, the ToDo app is complete. Todo items are now saved in the cloud under each unique users’ account. Check out the full app experience: Final Thoughts AWS Amplify is a killer service that allows you to quickly add backend cloud features to your mobile app. Overall, I think it is a solid solution for Ionic developers looking to incorporate a cloud backend into their app. There are some improvements that could be made, mostly around providing better visibility into the costs of enabling each Amplify service. If my experience piqued your interest, check out Amazon’s complete guide to building Ionic 4 apps with AWS Amplify. When you pair the Amplify backend with an Ionic starter app, you’ll have a working full stack solution in no time. We 💙 great cloud backends at Ionic. We’re continuing to work with the AWS team to provide feedback on making the Ionic + AWS experience better. What cloud features and integrations would you like to hear more about?
https://ionicframework.com/blog/adding-aws-amplify-to-an-ionic-4-app/
CC-MAIN-2022-21
refinedweb
1,340
61.97
Issue with "auto-logout"Tom Whitner Feb 21, 2011 2:28 PM I just discovered that a commented out commandlink with action\="\#{identity.logout()}" on an xhtml page will cause Seam to logout the user every time the page is processed. <html xmlns="" xmlns: <body> <h2>Welcome</h2> <h:form> <!-- <h:commandLinkLogout</h:commandLink> --> </h:form> <h:form> <div> <h:outputText <h:inputText <h:inputSecret </div> <div> <h:commandButton </div> <h:messages </h:form> </body> </html> I have created a small sample with the following for my authenticator @Stateless @Name("login") public class LoginAction implements Login { @Logger private Log log; public boolean login() { return true; } @Observer("org.jboss.seam.security.loginSuccessful") public void onSuccessfulLogin() { log.info("Login successful."); } @Observer("org.jboss.seam.security.loggedOut") public void onLogout() { log.info("User Logged Out."); } } With the command link uncommented, I see 2011-02-21 14:17:48,924 INFO [session.LoginAction] (http-127.0.0.1-8080-1) Login successful. 2011-02-21 14:17:59,267 INFO [session.LoginAction] (http-127.0.0.1-8080-1) User Logged Out. Note the 11 second delay before I pressed the logout button. When I comment out the command link (as in the example above), I see the following: 2011-02-21 14:20:40,948 INFO [session.LoginAction] (http-127.0.0.1-8080-1) Login successful. 2011-02-21 14:20:40,979 INFO [session.LoginAction] (http-127.0.0.1-8080-1) User Logged Out. Note that I did NOT push the logout button, and the logout happens 21 ms after I pressed login. Somehow the EL is being processed when the commandlink element is commented out. I think this is a defect/bug. Has anyone seen this? Is this a know issue? If so, please point me to more information (Jira, doc, etc.). Otherwise, I will open an issue in Jira. Thanks, Tom 1. Re: Issue with "auto-logout"Tim Evers Feb 21, 2011 8:00 PM (in response to Tom Whitner) If you are using facelets do you have this in your web.xml <context-param> <param-name>facelets.SKIP_COMMENTS</param-name> <param-value>true</param-value> </context-param> If you are not using facelets then....I'd have to have a bit more of a think about this :P But, out of curiosity, try the page with just one form and not 2. 2. Re: Issue with "auto-logout"Shervin Asgari Feb 25, 2011 5:06 AM (in response to Tom Whitner)Yes I agree. It must be this. Its best to uncomment the <h:form> also, and not just the button 3. Re: Issue with "auto-logout"Tom Whitner Feb 25, 2011 3:30 PM (in response to Tom Whitner) Thanks. I am using facelets and this did the trick... <context-param> <param-name>facelets.SKIP_COMMENTS</param-name> <param-value>true</param-value> </context-param> but it seems to me this should be the default (and maybe only) behavior. Why is is facelets processing HTML comments and executing the EL it finds there? 4. Re: Issue with "auto-logout"Tom Whitner Feb 25, 2011 3:31 PM (in response to Tom Whitner) BTW, the reason for the two forms was that in the original application that I was debugging, I had the logout button in a template which requried the second form. 5. Re: Issue with "auto-logout"Tim Evers Feb 27, 2011 7:07 PM (in response to Tom Whitner) Multiple forms can get really nasty to deal with. If it is early enough in the dev cycle to change to one form I would recommend that. If not, oh well....fun times are ahead :)
https://developer.jboss.org/message/711434
CC-MAIN-2019-22
refinedweb
609
59.19
(A quine is a program that produces its own source as its output, typically to a file.) import sys ifile = sys.argv[0] counter = 0 istream = open(ifile) source = istream.readlines() source[2] = 'counter = ' + str(counter + 1) + '\n' if counter == 0: original = str(ifile) source.insert(5, 'original = r\'' + str(original) + '\'\n') istream.close() ofile = list(original) ofile.insert(-3, str(counter)) ofile = ''.join(ofile) ostream = open(ofile, 'w') ostream.writelines(source) ostream.close() It is a naive implementation in that it depends on code that assumes that the new executables are created in and stay in the same directory as the original executable. Moving the new executable or altering any executable to store the executable in a different directory will break the chain. The first step to improving the code would be to alter the code so that it can function regardless if it is moved. After that, I'd like to include code that would automatically execute the new executable. (This is dangerous code that could be considered a form of virus in that it replicates until it consumes all hard disk space. I'll be sure to write a warning against executing the program or remove the code if I am told to cease and desist by moderators.)
https://www.daniweb.com/programming/software-development/threads/250906/naive-quine-that-i-wrote
CC-MAIN-2017-43
refinedweb
211
66.23
I have been successfully using the org.apache.commons.net.telnet package with my android app, but i have run into a problem. I have an instance of TelnetClient, which works fine, but when i call TelnetClient.disconnect it just hangs and nothing happens at all. A small test case...hangs when disconnect is called. Works fine on my home machine but not on the emulator. Please help as Im not sure whats happening here... Thanks, (code below) Using java Syntax Highlighting - private TelnetClient telnet = new TelnetClient(); - private InputStream in; - private PrintStream out; - public class Test{ - public Test(){ - try { - telnet.connect( ipAddress, port ); - // Get input and output stream references - in = telnet.getInputStream(); - out = new PrintStream( telnet.getOutputStream() ); - Log.d(TAG, "test disconnect"); - telnet.disconnect(); //HERE - Log.d(TAG, "test disconnected"); - } catch (SocketException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - }
http://www.anddev.org/other-coding-problems-f5/problem-using-org-apache-commons-net-with-android-t10015.html
CC-MAIN-2014-10
refinedweb
150
54.08
In the previous post, methods clone_node and indent_node were described. Next method we are going to describe is dedent_node or moving node left. Method dedent_node Method dedent_node(pos) moves node at the given position to left, i.e. to its grand-parent just after its current parent. This operation can change size of model by deleting some positions. Here is the image showing dedent_node in action. We are using outline from our last experiment. ![ Here is the definition of this method: def dedent_node(self, pos): '''Moves node left''' (positions, nodes, attrs, levels, expanded, marked) = self.data # this node i = positions.index(pos) if levels[i] == 1: # can't move left return gnx = nodes[i] # parent node pi = up_level_index(levels, i) pp = positions[pi] pgnx = nodes[pi] psz = attrs[pgnx].size h, b, mps, chn, sz0 = attrs[gnx] # grandparent node gpi = up_level_index(levels, pi) gpp = positions[pi] gpgnx = nodes[gpi] di0 = i - gpi di1 = di0 + sz0 di2 = pi - gpi di3 = di2 + psz def movedata(j, ar): ar[j+di0: j+di3] = ar[j+di1:j+di3] + ar[j+di0:j+di1] def decrease_levels(j): a = j + di0 b = j + di1 levels[a:b] = [x-1 for x in levels[a:b]] donepos = [] for gxi in gnx_iter(nodes, gpgnx, attrs[gpgnx].size): donepos.append(positions[gxi + di2]) decrease_levels(gxi) if di1 != di3: # this node is not the last child of its parent # we need to move data to the end of parent block movedata(gxi, positions) movedata(gxi, nodes) movedata(gxi, levels) for pxi in gnx_iter(nodes, pgnx, psz-sz0): if positions[pxi] not in donepos: a = pxi + di0 - di2 b = a + sz0 del positions[a:b] del nodes[a:b] del levels[a:b] update_size(attrs, pgnx, -sz0) update_size(attrs, gpgnx, sz0) # replace parent with grandparent mps[mps.index(pgnx)] = gpgnx self._update_children(pgnx) self._update_children(gpgnx) First lines 7-9 prevents dedenting top level nodes (at level 1). Then we collect necessary data about this node, its parent and grand parent node (lines 11-24). Then we calculate the distances of data blocks in lines (26-29). The data block [di0:di1] relative to grand-parent index represents the node being moved. The data block [di2:di3] represents parent node. Then we define two helper functions: movedata and decrease_levels. The movedata method moves block of this node at the end of its current parent node. For example if we look at the left side of the above picture and let’s consider moving node at position P9 left. We would have the following situation (see lines 26-29): i, pi, gpi = 9, 8, 0 sz0, psz = 4, 11 di0 = i - gpi = 9 di1 = di0 + sz0 = 13 di2 = pi - gpi = 8 di3 = di2 + psz = 19 In this case there is only one grand parent at index 0 (root node). We would then be moving blocks of data as follows (see line 33): Look at the above image, left side to see which nodes are moved where. The other helper function decrease_levels decreses levels of this node and its subtree by one. If di1 == di3 (end of this node is equal to the end of its parent, i.e. this node is the last child of its parent), we don’t need to move data blocks because they are already where they need to be (see lines 44-46). Then we visit every occurrence of grand parent node (for loop lines 40-49) and each time we decrease levels, then if necessary move this node at the end of its parent. Each position of parent node is marked as done, so that we don’t process it again. In the loop (lines 51-57) we are visiting every occurrence of parent node and if it is not already processed we delete child node that was dedented. Then we update sizes of parent and grand parent ancestors nodes (lines 62-63). Then we change link to parent node to point to the grand parent node in line 63. Finally in lines 65-66 we update lists of children for the parent node and grand parent node.
https://computingart.net/leo-tree-model-7.html
CC-MAIN-2021-49
refinedweb
683
69.92
Some time ago I played with Olimex STM32-P152 board and wrote some posts about it: - Olimex STM32-P152 board arrived - JTAG connection with OpenOCD and FTDI cable - Flashing the STM32-P152 board with OpenOCD - Debugging the STM32-P152 board with GDB I wanted to extend this setup by using an IDE, and I chose Eclipse because it seems to have the right plugins and resources. In particular I have been inspired by this post for developing on STM32F3Discovery on Mac OS X using Eclipse and this post for Windows. I suppose there are many alternatives that are probably simpler and lighter (Eclipse is quite large and complicated), but here’s what I did. I am certain that the steps that I follow here can be modified to work with many other Cortex-M targets and many other JTAG adapters/emulators, so this guide can be useful to people who are developing on something different from the STM32-P152 and have a different cable than the C232HM-EDHSL-0. Installation I follow basically the same steps as the post mentioned above, so use that as a reference, but I have a few differences: - OpenOCD: I have a Debian testing (jessie) PC so I simply ran as root “ aptitude install openocd” and it installed version 0.7.0-2 of the tool. - GCC ARM Embedded toolchain: I extracted GCC ARM Embedded 4.8-2013-q4-major (linux version) in /opt - Eclipse: I installed Keplero for C/C++ Developers (Linux 32-bit version) in a subfolder of my home directory (once I had problem installing plugins by installing it in system folders) - Eclipse plugins: I only installed Eclipse CDT plugin and GCC ARM plugin, I did not need to install Zylin embedded CDT because recently they added OpenOCD debugging to GCC ARM plugin so I had everything I needed. Create and build the program Inside Eclipse, click File -> New -> C Project. Choose Project Type -> Executable -> Hello World ARM Cortex-M3 C Project -> Cross ARM GCC and give a name to the project. I gave it the name “ blink-152” because I already had a program that blinked a LED and the program runs on STM32-P152 and it has no connection whatsoever with a certain rock band. In next page, remove Linker semi-hosting options. Click Next until you reach the Toolchain option, and complete the path to the toolchain, in my case “ /opt/gcc-arm-none-eabi-4_8-2013q4/bin“. A “Hello world” project will be created. It contains a main C file, the assembly code for startup and the linker scripts. The STM32L152 has 128KiB of Flash and 16KiB of RAM, so I changed the “ ldscripts/mem.ld” to reflect it: MEMORY{ FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 128K RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 16K } Then I filled the “ src/main.c” file with the program that I already created in previous posts: #include <stdint.h> STAT4_PIN 11 #define STAT4_PIN_MASK (1UL<<STAT4_PIN) #define RCC_BASE 0x40023800 #define RCC_AHBENR REG32(RCC_BASE + 0x1C) #define RCC_AHBENR_GPIOEEN 0x10 static void delay(int nops) { while(nops > 0) { asm ("nop"); nops--; } } } int main(void) { RCC_AHBENR |= RCC_AHBENR_GPIOEEN; // enable GPIOE clock GPIOE_OTYPER |= STAT4_PIN_MASK; // open-drain set_gpioe_moder(STAT4_PIN, 1); // general purpose output while(1) { GPIOE_ODR |= STAT4_PIN_MASK; // output pin high-z -> LED OFF delay(1000000); GPIOE_ODR &= ~STAT4_PIN_MASK; // output pin low -> LED ON delay(1000000); } }); } } void _exit(int code) { while(1); } I can finally run Project -> Build All (Ctrl-B) and the executable “ Debug/blink-152.elf” is created. Write in flash In order to write the program in flash like I did last time, I wanted a raw binary image of the executable. The project by default creates an Intel HEX image in “Debug/blink-152.hex”, so I changed that option by going in Project -> Properties, then choosing C/C++ Build -> Settings, then under Cross ARM GNU Create Flash Image -> General I changed the Output file format to Raw Binary. On next build (Ctrl-B) Eclipse will create “Debug/blink-152.bin”. This image will be written in flash by OpenOCD, but we need the configuration files for it. I created a new folder “ blink-152/openocd” in Eclipse to contain them, and then I created inside it the file “ c232hm-edhsl-0.cfg” containing: interface ft2232 ft2232_layout usbjtag ft2232_vid_pid 0x0403 0x6014 adapter_khz 1000 I downloaded “ stm32l.cfg” from Olimex website into “ blink-152/openocd” folder, and then I created a last file called “ flash_blink.cfg“: init reset init halt flash write_image erase Debug/blink-152.bin 0x08000000 shutdown Now I have all the files I need. A crucial point is to connect the board, and I repeated exactly the same passages as in this post: - Then I set the board jumpers to B0_1 and B1_1 positions to make STM32 boot from RAM. Now I created a new external tool that takes care of flashing by calling OpenOCD: - Click Run -> External Tools -> External Tools Configuration… - Click Program -> New - Put in Name: Flash Program - Put in Location: /usr/bin/openocd - Put in Working Directory: ${workspace_loc:/blink-152} - Put in Arguments: -f ${workspace_loc:/blink-152/openocd}/c232hm-edhsl-0.cfg -f ${workspace_loc:/blink-152/openocd}/stm32l.cfg -f ${workspace_loc:/blink-152/openocd}/flash_blink.cfg Clicking Run will launch OpenOCD and in the Console below the log will display the job done, ending with: ... Info : STM32L flash size is 128kb, base address is 0x8000000 wrote 4096 bytes from file Debug/blink-152.bin in 0.526960s (7.591 KiB/s) shutdown command invoked By re-configuring the jumpers in B0_0 and B1_0 positions and pressing the reset button the board should start to blink STAT4 LED. Attach debugger It’s also possible to attach Eclipse debugger to the board and see the program execution and the internal state of the core. - Click Run -> Debug configurations - Add new GDB OpenOCD Debugging - Go to Debugger tab - Put in Executable: /usr/bin/openocd - Put in Other options: -f ${workspace_loc:/blink-152/openocd}/c232hm-edhsl-0.cfg -f ${workspace_loc:/blink-152/openocd}/stm32l.cfg - Tick option Connect to running target Be aware that when you debug you have to make sure that the board is flashed with the same executable that you are debugging. Click Debug and the Eclipse Debug Perspective opens. The program is still running so you need to click the “suspend” button to pause the execution and examine the state. The “Reset target and restart debugging” button can also be used to run the program from the beginning. Be aware that when you disconnect from the target it will remain in a paused state and you need to reset the board to make it run again. Conclusions In this post I showed how to use Eclipse to create a simple “blink” program, flash it on a STM32-P152 board and attach to it with a debugger. This has been possible with the help of Eclipse plugins, GCC ARM Embedded toolchain, OpenOCD, C232HM FTDI JTAG cable. This approach can be adapted to many Cortex-M targets and many JTAG adapters mainly by changing access to hardware registers, changing the linker script memory map, and OpenOCD configuration files. Posted on 2014/02/23 0
https://balau82.wordpress.com/2014/02/23/stm32-p152-development-with-eclipse-on-linux/
CC-MAIN-2017-47
refinedweb
1,187
66.67
This action might not be possible to undo. Are you sure you want to continue? Contents Important Changes for 1995.................................... 2 2 3 3 3 4 4 4 4 5 6 6 6 7 7 8 8 8 8 Publication 3 Cat. No. 46072M Introduction................................................................ Gross Income ............................................................. Includible Items ....................................................... Excludable Items..................................................... Missing Status ......................................................... Foreign Earned Income .......................................... Community Property ............................................... Adjustments to Income........................................... Combat Zone Exclusion ........................................... Combat Zone........................................................... Serving in a Combat Zone ...................................... Amount of Exclusion ............................................... Alien Status................................................................. Resident Aliens ....................................................... Nonresident Aliens.................................................. Dual-Status Aliens .................................................. Dependency Exemptions......................................... Dependents ............................................................. TaxInformation for Military Personnel (Including Reservists Called to Active Duty) For use in preparing 1995 Returns Sale of Home .............................................................. 9 Replacement Period ............................................... 9 Special Situations ................................................... 12 Itemized Deductions................................................. 13 Miscellaneous Itemized Deductions...................... 13 Tax Liability ................................................................ 14 Earned Income Credit............................................. 14 Decedents................................................................... Combat Zone Forgiveness..................................... Terroristic or Military Action Forgiveness.............. Claims for Tax Forgiveness.................................... Filing Returns ............................................................. Where to File ........................................................... When to File............................................................. Extensions ............................................................... Signing Returns....................................................... Refunds ................................................................... 17 18 18 18 19 19 19 19 20 21 Extension of Deadline .............................................. 21 Filing Returns for Combat Zone Participants ............................................................................. 23 Important Changes for 1995 Earned income credit. Beginning with 1995 tax returns, the following changes are in effect: ● Useful Items You may want to see: Publication □ 54 Tax Guide for U.S. Citizens and Resident Aliens Abroad □ 463 Travel, Entertainment, and Gift Expenses □ 501 Exemptions, Standard Deduction, and Filing Information □ 508 Educational Expenses □ 516 Tax Information for U.S. Government Civilian Employees Stationed Abroad □ 519 U.S. Tax Guide for Aliens □ 521 Moving Expenses □ 523 Selling Your Home □ 527 Residential Rental Property □ 529 Miscellaneous Deductions □ 553 Highlights of 1995 Tax Changes □ 555 Federal Tax Information on Community Property □ 559 Survivors, Executors, and Administrators □ 570 Tax Guide for Individuals With Income From U.S. Possessions □ 590 Individual Retirement Arrangements (IRAs) □ 596 Earned Income Credit □ 945 Tax Information for Those Affected by Operation Desert Storm Form (and Instructions) □ 1040X Amended U.S. Individual Income Tax Return □ 1310 Statement of Person Claiming Refund Due a Deceased Taxpayer □ 2848 Power of Attorney and Declaration of Representative □ 4868 Application for Automatic Extension of Time To File U.S. Individual Income Tax Return □ 2688 Application for Additional Extension of Time To File U.S. Individual Income Tax Return □ 8822 Change of Address □ 9465 Installment Agreement Request Ordering publications and forms. To order free publications and forms, call 1–800–TAX–FORM (1–800–829– 3676). You can also write to the IRS Forms Distribution Center nearest you. Check your income tax package for the address. The amount you can earn has increased to $9,230 with no qualifying children, $24,396 with one qualifying child, and $26,673 with two or more qualifying children. The credit amount has increased for all three categories listed above. Military personnel stationed outside the United States on extended active duty are considered to live in the United States for purposes of the credit. Taxpayers claiming the credit on their 1995 tax returns must provide a social security number for each qualifying child born before November 1, 1995. Qualifying children born between November 1 and December 31, 1995, must have social security numbers for tax year 1996. Untaxed earned income, such as BAQ, BAS, combat pay, and certain in-kind equivalents, will be shown on the W-2s of military personnel in box 13. A nonresident alien must be married to a citizen or resident of the United States and agree to be treated as a U.S. resident for U.S. tax purposes to be eligible for the credit. ● ● ● ● ● Note: Beginning in 1996, taxpayers who have more than $2,350 in investment income not qualify for the credit. For more information on the EIC, see Publication 596, Earned Income Credit. Introduction This publication covers the special tax situations of active members of the U.S. Armed Forces. It does not cover military retirees’ or veterans’ benefits or give the basic tax rules that apply to all taxpayers. If you need the basic tax rules or information on a subject not covered here, you can check our other free publications. At the time we went to print, the area designated by the President as a combat zone was still in effect. If you receive a notice about tax collection or examination from the Internal Revenue Service and you are serving in the U.S. military in the area still designated as a combat zone, you have been granted relief. Simply mark your notice ‘‘Desert Storm’’ and return it to the IRS. See Extension of Deadline, later. In the event the area ceases to be a combat zone (by Presidential Executive Order), we will do our best to notify you. Many of the relief provisions will end at that time. Page 2 If you have access to a personal computer and a modem, you can also get many forms and publications electronically. See How To Get Forms and Publications in your tax package for details. Free tax help. You can get free tax help from IRS throughout the year. Publication 910, Guide to Free Tax Services, describes many of the free tax information and services you can receive, including telephone help, next. Telephone help. You can call the IRS with your tax questions Monday through Friday during regular business hours. Check your telephone book for the local number or you can call 1–800–829–1040. Telephone help for hearing-impaired persons. If you have access to TDD equipment, you can call 1–800– 829–4059 with your tax questions or to order forms and publications. See your tax package for the hours of operation.. Diving duty, Foreign duty (for serving outside the 48 contiguous states and the District of Columbia), Hazardous duty, Imminent danger, Medical and dental officers, Nuclear-qualified officers, and Special duty assignment pay. Bonuses for such items as: Enlistment, and Re-enlistment. Payments for such items as: Accrued leave, Mustering-out payments, Personal money allowances paid to high-ranking officers, Scholarships such as the Armed Forces Health Professions Scholarship Program (AFHPSP) and similar programs, and Student loan repayment from programs such as the General Educational Loan Repayment Program. Excludable Items Gross Income Members the sections Combat Zone Exclusion and Extension of Deadline. Includible Items These items are includible in gross income, unless the pay is for service in a combat zone declared by an Executive Order of the President. Basic pay for such items as: Active duty, Attendance at a designated service school, Back wages, Drills, Reserve training, and Training duty. Special pay for such items as: Aviation career incentives, These items are excludable from gross income. The exclusion applies whether the item is furnished in-kind or is a reimbursement or allowance. There is no exclusion for the personal use of a government-provided vehicle. Living allowances for: BAQ (Basic Allowance for Quarters). You can deduct mortgage interest and real estate taxes on your home even if you pay these expenses with money from your BAQ, BAS (Basic Allowance for Subsistence), Housing and cost-of-living allowances abroad whether paid by the U.S. Government or by a foreign government, and VHA (Variable Housing Allowance). Family allowances for: Certain educational expenses for dependents, Emergencies, Evacuation to a place of safety, and Separation. Death allowances for: Burial services, Death gratuity payments to eligible survivors, and Travel of dependents to burial site. Moving allowances for: Dislocation, Page 3 Move-in housing, Moving household and personal items, Moving trailers or mobile homes, Storage, and Temporary lodging and temporary lodging expenses. Travel allowances for: Annual round trip for dependent students, Leave between consecutive overseas tours, Reassignment in a dependent-restricted status, and Transportation for you or your dependents during ship overhaul or inactivation. Other payments for: Defense counseling, Disability, Group-term life insurance, Professional education, ROTC educational and subsistence allowances, Survivor and retirement protection plan premiums, Uniform allowances paid to officers, and Uniforms furnished to enlisted personnel. In-kind military benefits such as: Legal assistance, Space-available travel on government aircraft, Medical/dental care, and Commissary/exchange discounts. the U.S. Government. U.S. Government employees include those, Tax Guide for U.S. Citizens and Resident Aliens Abroad.. Community Property, Federal Tax Information on Community Property. Missing Status Compensation is excluded from income if it is received for active service as a member of the U.S. Armed Forces or as a civilian federal employee while in a missing status because of the Vietnam conflict. The full exclusion is allowable to commissioned officers as well as to enlisted personnel and civilian employees. An individual is in a missing status because of the Vietnam conflict if immediately before being declared missing, the individual was performing service in Vietnam or in Southeast Asia in direct support of military operations in Vietnam. The status continues as long as the member or employee is officially carried as missing. Missing status does not include any period a member of the Armed Forces is officially absent from a post of duty without authority. Adjustments to Income There are certain adjustments to income you can take. For purposes of a deduction for contributions to an Individual Retirement Arrangement (IRA), Armed Forces members (including reservists on active duty for more than 90 days) are considered to be active participants in an employer-maintained retirement plan. Individuals serving in the U.S. Armed Forces or in support of the U.S. Armed Forces in designated ‘‘combat zones’’ have additional time to make a qualified retirement contribution to an IRA. For more information on this extension of deadline provision, see Extension of Foreign Earned Income Certain taxpayers can exclude up to $70,000 of income earned in each year in foreign countries. However, this foreign earned income exclusion does not apply to the wages and salaries of military and civilian employees of Page 4 Deadline, later. For information on IRAs, get Publication 590, Individual Retirement Arrangements (IRAs). Do not deduct any expenses for moving services that were provided by the government, or that were reimbursed to you, that you did not include in income. Deductible moving expenses. You can deduct only reasonable unreimbursed moving expenses that are incurred by you and members of your household. A member of your household is anyone who has both your former and your new home as his or her home. It does not include a tenant or employee, unless you can claim that person as a dependent. You cannot deduct costs for unnecessary side trips or lavish and extravagant lodging. You can deduct expenses (if not reimbursed or furnished in-kind) for: 1) Moving household goods and personal effects, including expenses for hauling a trailer, packing, crating, in-transit storage, and insurance. You cannot deduct expenses for moving furniture or other goods you bought on the way from the old home to the new home. 2) Reasonable travel and lodging expenses from the old home to the new home, including automobile expenses (either actual expenses or 9¢ a mile), and air fare. You cannot deduct any expenses for meals. Foreign moves. A foreign move is one from the United States or its possessions to a foreign country, or from one foreign country to another foreign country. It is not a move from a foreign country to the United States or its possessions. For a foreign move, the deductible moving expenses described earlier include the reasonable expenses of: 1) Moving your household goods and personal effects to and from storage, and 2) Storing these items for part or all of the period during which the new place of work continues to be your principal place of work. Moving Expenses To deduct moving expenses, you must generally meet certain time and distance tests. However, members of the Armed Forces who move because of a permanent change of station do not have to meet these tests. In addition, unlike civilian employees, members of the Armed Forces do not report the value of moving reimbursements unless the reimbursements are more than the expenses. Moving expenses are reported on Form 3903, Moving Expenses, or Form 3903–F, Foreign Moving Expenses. Permanent change of station. A permanent change of station includes: 1) A move from home to the first post of active duty, 2) A move from one permanent post of duty to another, and 3) A move from the last post of duty to your home or to a nearer point in the United States if you move within one year of ending active duty or according to the Joint Travel Regulations. Desertion, imprisonment, or death. If a member of the Armed Forces deserts, is imprisoned, or dies, a permanent change of station for the spouse or dependent includes a move to the place of enlistment or to the member’s, spouse’s, or dependent’s home of record or nearer point in the United States. Separate moves. If the government moves you and your spouse or dependents to or from separate locations, the moves are considered a single move to your post of duty. All expenses are combined. Reimbursements. Do not include in income the value of moving and storage services provided by the government in connection with a permanent change of station. Similarly, do not include in income amounts received as a dislocation allowance, temporary lodging expense, temporary lodging allowance, or move-in housing allowance. Because these allowances are excluded from gross income, you may not deduct the expenses incurred in connection with a permanent change of station if you paid them from an excluded allowance. You may still deduct other nonreimbursed moving expenses. However, if you receive reimbursements or allowances (other than those mentioned above) from the government that are more than your actual moving expenses, include the excess in. Reporting moving expenses. Figure moving expense deductions on Form 3903 for moves to a home in the United States or its possessions, even if you are moving from a location overseas. Use Form 3903–F if the home to which you are moving is outside the United States or its possessions. Carry the deduction from Form 3903 or Form 3903–F to line 24, Form 1040. For more information, get Publication 521 and see the Form 3903 instructions. Combat Zone Exclusion If you are a member of the U.S. Armed Forces who serves in a combat zone (defined later), you may exclude certain pay from your income. You do not have to receive the pay while in a combat zone, while you are Page 5 hospitalized, or in the same year of service in a combat zone. However, your entitlement to the pay must have fully accrued in a month during which you served in the combat zone or were hospitalized as a result of wounds, disease, or injury incurred while serving in the combat zone. Enlisted personnel, warrant officers, and commissioned warrant officers exclude the following amounts from their income (officer personnel are discussed later). 1) Active duty pay earned in any month you served in a combat zone. 2) A dislocation allowance if the move begins or ends in a month you served in a combat zone. 3) A reenlistment bonus if the voluntary extension or reenlistment occurs in a month you served in a combat zone. 4) Pay for accrued leave earned in any month you served in a combat zone. The Department of Defense must determine that the unused leave was earned during that period. 5) Pay received for duties as a member of the Armed Forces in clubs, messes, post and station theaters, and other nonappropriated fund activities. The pay must be earned in a month you served in a combat zone. 6) Awards for suggestions, inventions, or scientific achievements you are entitled to because of a submission you made in a month you served in a combat zone. Retirement pay and pensions do not qualify for the combat zone exclusion. Serving in a Combat Zone Service is performed in the Persian Gulf area combat zone only if it is performed on or after January 17, 1991. Service in the combat zone includes any periods you are absent from duty because of sickness, wounds, or leave. If, as a result of serving in a combat zone, a person becomes a prisoner of war or is missing in action, that person is considered to be serving in the combat zone as long as he or she keeps that status for military pay purposes. Qualifying service outside combat zone. Military service outside a combat zone is considered to be performed in a combat zone if: 1) The service is in direct support of military operations in the combat zone, and 2) The service qualifies you for special military pay for duty subject to hostile fire or imminent danger. Military pay received for this service will qualify for the combat zone exclusion if the other requirements are met. Nonqualifying presence in combat zone. The following military service does not qualify as service in a combat zone. 1) Presence in a combat zone while on leave from a duty station located outside the combat zone. 2) Passage over or through a combat zone during a trip between 2 points that are outside a combat zone. 3) Presence in a combat zone solely for your personal convenience. Combat Zone A combat zone is any area the President of the United States designates by Executive Order as an area in which the U.S. Armed Forces are engaging or have engaged in combat. An area becomes a combat zone and ceases to be a combat zone on the dates the President designates by Executive Order. The President has designated by Executive Order 12744 the following locations (including airspace) as a combat zone beginning January 17, 1991: ● ● ● ● Amount of Exclusion. Hospitalized while serving in the combat zone. If you are hospitalized while serving in the combat zone, the wound, disease, or injury causing the hospitalization will be presumed to have been incurred while serving in the combat zone unless there is clear evidence to the contrary. Example. You are hospitalized for a specific disease after serving in a combat zone for 3 weeks, and the disease for which you are hospitalized has an incubation. ● ● This combat zone is referred to in this publication as the Persian Gulf area combat zone. Page 6 period of 2 to 4 weeks. The disease is presumed to have been incurred while you were serving in the combat zone. On the other hand, if the incubation period of the disease is one year, the disease would not have been incurred while you were serving in the combat zone. Hospitalized after leaving the combat zone. In some cases the wound, disease, or injury may have been incurred while you were serving in the combat zone even though you were not hospitalized until after you left. areas should contact their taxing authority with their questions., just like U.S. citizens, and file the same forms as U.S. citizens. Treating nonresident alien spouse as resident alien. A nonresident alien spouse can be treated as a resident alien if all the following conditions are met: 1) One spouse is a U.S. citizen or resident alien at the end of the tax year. 2) That spouse is married to the nonresident alien at the end of the tax year. 3) You both choose to treat the nonresident alien spouse as a resident alien. Example. You were hospitalized for a specific disease 3 weeks after you left the combat zone. The incubation period of the disease is from 2 to 4 weeks. The disease is presumed to have been incurred while serving in the combat zone. Officers. If you are a commissioned officer (other than a commissioned warrant officer), you may exclude your pay according to the rules just discussed. However, the amount of your exclusion is limited to $500 of your military pay for each month during any part of which you served in a combat zone or were hospitalized as a result of your service there. If you are a commissioned warrant officer, you are considered to be an enlisted person and your exclusion is not limited. Form W–2. The wages shown in box 1 of your 1995 Form W–2, Wage and Tax Statement, should not include military pay excluded from your income under the combat zone exclusion provisions. Making the choice. You must both sign a statement and attach it to your joint return for the first tax year for which the choice applies. Include on the statement: 1) A declaration that one spouse was a nonresident alien and the other was a U.S. citizen or resident alien on the last day of the year. 2) A declaration that both spouses choose to be treated as U.S. residents for the entire tax year. 3) The name, address, and social security number of each spouse. Alien Status For tax purposes, an alien is an individual who is not a U.S. citizen. An alien is in one of three categories: resident, nonresident, or dual-status. Determining the correct status is crucial in determining what income to report and what forms to file. For details about alien status other than the information given next, get Publication 519, U.S. Tax Guide for Aliens. Most members of the Armed Forces are U.S. citizens or resident aliens. However, if you have questions about your alien status or the alien status of your dependents or spouse, you should read the following section. residence outside the United States are nonresident aliens. Guam and Puerto Rico have special rules. Residents of those Once you make this choice, the nonresident alien spouse’s worldwide income is subject to U.S. tax. If the nonresident alien spouse has substantial foreign income, there may be no advantage to making this choice. Ending the choice. Once you make this choice, it applies to all later years unless one of the following situations occurs: 1) You or your spouse revokes the choice. 2) You or your spouse dies. 3) You and your spouse become legally separated under a decree of divorce or separate maintenance. 4) The Internal Revenue Service ends the choice because of inadequate records. For specific details on these situations, get Publication 519. If the choice is ended for any of these reasons, neither spouse can make a choice for any later year. This applies to a divorced individual who previously made the choice and later remarries. Choice not made. If you and your nonresident alien spouse do not make this choice: Page 7 ● ● ● ● (see Dependency Exemptions, later).. list an incorrect number, you may be subject to a $50 penalty. This penalty may be waived if you can show reasonable cause for not providing your dependent’s social security number. Dependents A person is your dependent if all 5 of the following tests are met: ● ● ● ● ● Member of household or relationship test, Citizenship test, Joint return test, Gross income test, and Support test. Nonresident Aliens A nonresident alien is an individual who does not meet the requirements for being considered a resident alien as discussed earlier. If required to file a federal tax return, nonresident aliens must file either Form 1040NR, U.S. Nonresident Alien Income Tax Return, or Form 1040NR–EZ, U.S. Tax Return for Certain Nonresident Aliens with No Dependents . See the form instructions for information on who must file and filing status. Nonresident aliens generally must pay tax on income from sources in the United States. A nonresident alien’s income that is from conducting a trade or business in the United States is taxed at regular U.S. tax rates. Other income from U.S. sources is taxed at a 30% rate or a lower treaty rate, if it applies. For example, dividends from a U.S. corporation paid to a nonresident alien generally are subject to a 30% (or lower treaty) rate. For specific information on these tests, get Publication 501, Exemptions, Standard Deduction, and Filing Information. For the member of household or relationship test, the person must be related to you or be a member of your household for the entire year. For the joint return test, the person generally cannot file a joint return. For the gross income test, the person must have gross income of less than $2,500. This test does not apply if the person is your child and is under age 19 or is a full-time student under age 24. The citizenship test and the support test are of special interest to members of the Armed Forces. They are discussed next. Citizenship Test Dual-Status Aliens An alien may be both a nonresident and resident alien during the same tax year, usually the year of arrival or departure. Dual-status aliens are taxed on income from all sources for the part of the year they are resident aliens. Generally, they are taxed only on income from sources in the United States for the part of the year they are nonresident aliens. Aliens, earlier) and the child was born in a foreign country. Child living abroad. You can claim your child’s exemption if the child is a U.S. citizen and meets the other dependency tests. It does not matter if the child lives abroad with the nonresident alien parent. Legal adoption. If you legally adopt a child who is not a U.S. citizen, you can claim the child’s exemption if the other dependency tests are met and the child has your home as his or her main home and is a member of your household for the entire year. Example. Sergeant John Smith is a U.S. citizen and has been in the U.S. Army for 16 years. He is stationed in Germany. He and his wife, a German citizen, have a 2year-old son who was born in Germany and who has dual citizenship — U.S. and German. Sgt. Smith’s stepdaughter, a German citizen whom Sgt. Smith has not Dependency Exemptions Exemptions reduce your income subject to tax. For 1995, you generally can deduct $2,500 for each exemption you claim for yourself, your spouse, and each person who qualifies as your dependent . If another taxpayer can claim an exemption for you or your spouse, you cannot also claim the exemption on your tax return. If you can claim an exemption for a dependent, that dependent cannot claim a personal exemption on his or her own tax return. To claim a dependent on your tax return, you must list the social security number for dependents born before November 1, 1995. If you do not provide a dependent’s social security number when the form asks for it, or if you Page 8 adopted, also lives with them. Only his son can be considered a U.S. citizen for whom a dependency exemption can be claimed. His stepdaughter does not qualify as a U.S. citizen or resident. Sale of Home If you sell your home, get Publication 523, Selling Your Home. The rules discussed in that publication apply to all taxpayers. You may have to pay tax on all or part of the gain from the sale of your home. But you must postpone paying tax on some or all of the gain if you meet certain requirements. One requirement is that you buy and live in a new home within the replacement period. As a member of the Armed Forces, your replacement period after the sale of your old home is suspended for a limited time if you are on extended active duty. An even longer suspension period may apply if you are on an overseas assignment. These replacement periods are discussed next. The other requirement depends on the cost (including construction costs) of the new home and the sales price of the old home. This is discussed in detail in Publication 523. If you sell your home, you must file Form 2119, Sale of Your Home, even if you are postponing the payment of tax on the gain. Support Test To be considered your dependent, the person must receive more than half of his or her support from you during the year. To figure if you provided more than half members of the household. If the item is property or lodging, the amount of such item provided by you in figuring whether you provide more than half the dependent’s support. If an allotment is used to support persons other than those you name, you can claim their exemptions if they otherwise qualify as your dependents. Replacement Period When you sell your home and replace it with another, you must buy (or build) and live in the new home within a specified period of time (replacement period) to be able to postpone tax on any gain from the sale of the old home. The normal replacement period is 2 years before or 2 years after the date of sale of the old home. This replacement period is suspended for members of the Armed Forces, as described under Extended active duty, Overseas assignment, or Operation Desert Shield/ Desert Storm, later. If you have a gain on the sale of your old home and do not replace it within the replacement period, you have no more time to do so. This is true even if the delay is from conditions beyond your control, such as a military requirement to live in government quarters for a period that is longer than the suspended replacement period. Caution: If you sell your old home and do not plan to replace it, you must include the gain in income for the year of sale. If you later buy (or build) and live in another home within the replacement period and meet the requirements to postpone gain, you will have to file an amended return (Form 1040X) for the year of the sale to claim a refund. An amended return can be filed by the later of: 1) 3 years from the date the return was filed, or 2) 2 years from the date the tax was paid. A return filed before the due date is treated as filed on the due date. You may be entitled to additional time beyond the normal replacement period if you: 1) Serve on extended active duty (discussed later), Page 9 Example. Army Sergeant Jeff Banks authorizes an allotment for his widowed mother. She uses the money to support herself and Jeff’s 10-year-old sister. If that amount provides more than half of their support, Jeff can claim an exemption for each of them, even though he only authorized the allotment for his mother. Dependent in the Armed Forces. Generally, a person who is in the Armed Forces or is at one of the Armed Forces academies for the entire year cannot be claimed as a dependent because the support test will not have been met. However, if your dependent receives only partial support from the Armed Forces, you can still claim the exemption if you provided more than half of his or her support and the other dependency tests are met. Example. Leslie James is 18 and single. She graduated from high school in June 1995 and entered the U.S. Air Force in September 1995. Leslie provided $4,400 (her wages of $3,400 and $1,000 for other items of support provided by the Air Force) for her support that year. Her parents provided $4,100. Her parents cannot claim a dependency exemption for her for 1995 because they did not provide more than half of her support. Page 10 2) Serve a tour of duty outside the United States (discussed later), or 3) Served in the Persian Gulf area combat zone (discussed later). This extended replacement period may cause difficulties if you have already paid the tax on the gain from the sale of your old home. If you are entitled to any of the extended replacement periods (listed above), the replacement period may go beyond the last date you can file an amended return claiming a refund for the year of sale. If a possibility exists that you may purchase another home during the extended replacement period, you should file a protective claim for refund. You should file this claim at the time the return for the year of sale is filed or anytime within the period allowed for filing an amended return for the year of sale. Publication 523 explains how to file a protective claim. You must physically live in the new home as your main home within the required period. If you move furniture or other personal belongings into the new home but do not actually live in it, you do not meet this requirement. Extended active duty. This means you are called or ordered to duty for an indefinite period or for a period of more than 90 days. If you are on extended active duty, your replacement period after the sale of your old home is suspended. The suspension applies only if your extended active duty begins before the 2-year period after the sale ends. Your replacement period plus any period of suspension is limited to 4 years from the sale of your old home. If your duty is outside the United States, see Overseas assignment or Operation Desert Shield/Desert Storm, next. Example 1. John Guy sold his home on April 2, 1995. On July 2, 1995, he entered the Armed Forces on active duty, and he will be released on July 1, 1999. He must replace his home by April 2, 1999. This is a total replacement period of 4 years (3 months before he joined the Armed Forces, plus 3 years and 9 months of the time he was on active duty). The replacement period cannot exceed 4 years. Example 2. Use the same facts as in the previous example except that John will be released on January 1, 1997. He must replace his home by October 2, 1998. This is a total replacement period of 31/ 2 years (3 months before he joined the Armed Forces, plus the 1 year and 6-month suspension while he was on active duty, plus the 1 year and 9 months after his discharge). Overseas assignment. If you are on extended active duty outside the United States, your replacement period is suspended while you are overseas and up to 1 year after the last day you are stationed overseas. However, your total replacement period cannot be more than 8 years after you sell your old home. Example. Lieutenant Virginia Rogers sells her condominium on July 1, 1991. From January 1, 1993, to March 31, 1999, she is on an overseas assignment. She must replace her home by July 1, 1999. This is a total replacement period of 8 years (11/ 2 years before she left on an overseas assignment, plus the 6-year and 3-month suspension while she was on an overseas assignment, plus 3 months after she returned from her overseas assignment). She does not have 1 full year after returning from overseas because the total replacement period cannot be more than 8 years. Remote site. If you return from an overseas assignment and must live in on-base quarters because adequate off-base housing is unavailable at the remote site, your replacement period is suspended while you must live in these quarters and up to 1 year after the last day you had to live in these quarters. To qualify for this provision, the Secretary of Defense must determine that adequate off-base housing is unavailable at the remote site. However, the total replacement period, including the time you are overseas and at the remote site, cannot be more than 8 years after you sell your old home. Example. Lieutenant Sam Green sells his home on August 1, 1991. He was on an overseas assignment from January 1, 1992, to May 31, 1995. On returning to the United States, he is stationed at a remote site and must live in on-base housing until December 31, 1996, because off-base housing is not available. He must replace his home by July 31, 1999. This is a total replacement period of 8 years (5 months before he left on an overseas assignment, plus the 3-year and 5-month suspension while he was on an overseas assignment, plus the 1-year and 7-month suspension while he had to live in on-base quarters at the remote site after returning from his overseas assignment, plus the 1-year suspension after the last day he had to live in on-base quarters, plus 1 year and 7 months). Operation Desert Shield/Desert Storm. The running of the replacement period (including any period of suspension) is suspended for any period you served in the Persian Gulf area combat zone. For this suspension, the designation of the area as a combat zone is effective August 2, 1990. If you performed military service in an area outside the combat zone but in direct support of military operations in the combat zone and you received special pay for duty subject to hostile fire or imminent danger, you are treated as if you served in the combat zone. This suspension ends 180 days after the later of: 1) The last day you were in the combat zone (or if earlier, the last day the area qualified as a combat zone), or 2) The last day of any continuous hospitalization (limited to 5 years if hospitalized in the U.S.) for an injury sustained while serving in the combat zone. Example. Sergeant James Smith, on extended active duty in an Army unit stationed in Virginia, had a gain from the sale of his home on June 4, 1991. He had not yet purchased a replacement home when he entered Page 11 the Persian Gulf area combat zone on September 4, 1991. He left the combat zone on May 4, 1992, and returned with his unit to Virginia. He remains on active duty in Virginia. Sergeant Smith’s replacement period began on June 4, 1991, the date he sold the home. His replacement period would have ended 4 years later on June 4, 1995. When he entered the combat zone on September 4, 1991, Sergeant Smith had used 3 months of the replacement period. The replacement period was then suspended for the time he served in the combat zone plus 180 days. The replacement period started again on November 1, 1992, after the end of the 180 day period (May 5, 1992, to October 31, 1992) following his last day in the combat zone. Sergeant Smith then has 45 months remaining in his replacement period (4 years minus the 3 months already used). His replacement period will end July 31, 1996 (45 months after October 31, 1992). For information on other tax benefits available to those who served in a combat zone, get Publication 945, Tax Information for Those Affected by Operation Desert Storm. Spouse. This suspension generally applies to your spouse (even if you file separate returns). However, any suspension for hospitalization within the U.S. does not apply to your spouse. Also, the suspension for your spouse does not apply for any tax year beginning more than 2 years after the last day the area qualified as a combat zone. Married taxpayers. As long as one spouse is a member of the Armed Forces, the suspension of the replacement period applies whether the old home is owned by one of the spouses or by both spouses. However, both the old home and the new home must be used by both spouses as their main home. If you are divorced or separated during the suspension period, the suspension period ends for the nonmilitary member spouse on the day of the divorce or separation. house, and Ellen does so while still trying to sell it. Eight months later, the house is sold. The house in San Diego is her old home, not rental property, so Ellen can postpone paying tax on any gain on the sale. Property used for business. Some taxpayers use part of their home for business. For example, a military member’s spouse uses a room of their house for a petgrooming business. If the house is sold, the rules for postponing the tax apply only to the part used as a home. Rules for the sale of business property apply to the part used for business. To determine what part of the gain to treat each way, see Property used partly as your home and partly for business or rental, under Old Home, in Publication 523. More than one main home. If you buy more than one main home during the normal replacement period, only the last home bought can qualify as your new home for the purpose of postponing the tax. All other homes bought and sold during the replacement period are subject to the regular capital gain and loss rules. However, see Exception for work-related move, next. Exception for work-related move. If you sell your main home because of a work-related move for which moving expenses are deductible (see Deductible Moving Expenses, earlier), you can postpone paying tax on the gain on the sale of more than one home during the replacement period. Example. Sergeant Steve Foster sold his home in Washington, D.C., in November 1994 for $120,000 when he was transferred to Salem, Massachusetts. In December 1994, he bought a home in Salem for $135,000. In June 1995, he was transferred to Jacksonville, Florida. He then sold his home in Salem for $140,000 before purchasing one in Jacksonville for $145,000. He postponed paying tax on the gain on the sale of the Washington home based on the purchase price of the replacement home in Salem, and he postponed paying tax on the gain on the sale of the Salem home based on the purchase price of the home in Jacksonville. Special Situations Some special situations about home ownership can affect military personnel. Rental. If you temporarily rent out either your old home before selling it or your new home before moving into it (for convenience or for some other nonbusiness purpose), you can still postpone paying tax on the gain under the rules just discussed. If you own rental property, even if it once was your main home, get Publication 527, Residential Rental Property. Example. Chief Petty Officer Ellen Glynn transfers from San Diego to Norfolk. She engages a real estate agent to sell her house and moves to Norfolk. Three months later, the house in San Diego has not been sold. The real estate agent suggests renting the San Diego Page 12 Caution. As this publication was being prepared for print, Congress was considering tax law changes that could affect your 1995 tax return and 1996 estimated taxes. These changes include the sale of your home. See Publication 553, Highlights of 1995 Tax Changes for further developments. Information on these changes will also be available electronically through our bulletin board or via Internet (see page 34 of the Form 1040 instructions). Itemized Deductions To figure your taxable income, you must subtract either your standard deduction or your itemized deductions from adjusted gross income. For information on the standard deduction, get Publication 501, Exemptions, Standard Deduction, and Filing Information. Item, Nonbusiness Disasters, Casualties, and Thefts Publication 550, Investment Income and Expenses 1) You were not reimbursed for your expenses, or if you were reimbursed, the reimbursement was included in your income in box 1 of your Form W-2. 2) If you claim car expenses, you use the standard mileage rate. Travel expenses. You can deduct unreimbursed travel expenses only if they are incurred while traveling away from home . To be deductible, your travel expenses must be work related. You cannot deduct any expenses for personal travel, such as visits to family while on furlough, leave, or liberty. Away from home. Home is your permanent duty station (which can be your ship or base), regardless of where you or your family live. You are away from home if you are away from your permanent duty station substantially longer than an ordinary day’s work, and you need to get sleep or rest to meet the demands of your work while away from home. Common travel expenses include: 1) Expenses for meals (subject to the 50% limit), lodging, taxicabs, business telephone calls, tips, laundry, and cleaning while you are away from home on temporary duty or temporary additional duty, 2) Expenses of carrying out official business while on ‘‘No Cost’’ orders. Miscellaneous Itemized Deductions Most miscellaneous itemized deductions are deductible only if they total more than 2% of your adjusted gross income. For information on deductions that are not subject to the 2% limitation, get Publication 529, Miscellaneous Deductions. Note: You must reduce deductible expenses by any allowance or reimbursement you receive to pay for them. Employee Business Expenses Beginning in 1995, the standard mileage rate has been increased to 30 cents for each mile of business use. Deductible employee business expenses are miscellaneous itemized deductions subject to the 2% limit. For information on employee business expenses, get Publication 463, Travel, Entertainment, and Gift Expenses , and Publication 917, Business Use of a Car. Generally, you must file Form 2106, Employee Business Expenses, or Form 2106–EZ, Unreimbursed Employee Business Expenses, to claim these expenses. You do not have to file Form 2106 or Form 2106–EZ if you are claiming only expenses for uniforms, professional society dues, and work-related educational expenses (all discussed later). You can deduct these expenses directly on Schedule A (Form 1040). Reimbursement. Generally, to receive reimbursement, per diem, or another allowance from the government, you must adequately account for your expenses and return any excess reimbursement. Therefore, the amount you receive is not included on your Form W–2 and the expenses for which you receive this reimbursement are not deductible. If your expenses exceed your reimbursement, the excess expenses are deductible (subject to the 2% limit) if you can substantiate them. If this is your situation, you must file Form 2106. You may be able to use Form 2106-EZ if you meet both of the following conditions. Note. You cannot deduct any expenses for travel away from your tax home if the period of temporary employment is more than one year. For more information, see Publication 463 and Form 2106 instructions. Reservists. You can deduct travel expenses if you are under competent orders, with or without compensation, and BAQ and BAS. Transportation expenses. Transportation expenses are the costs incurred of getting from one workplace to another while not traveling away from home. These expenses include the costs of operating and maintaining a car, but not meals and lodging. If you must go from one workplace to another while on duty (for example, as a courier or messenger or to attend meetings or briefings) without being away from home, your unreimbursed transportation expenses are deductible. If you must use your own vehicle, you can deduct the expenses of using it. However, the expenses of getting to and from your regular place of work are not deductible. Temporary work location. If you have a regular place of business and commute to a temporary work location, you can deduct the expenses of the daily roundPage 13 trip transportation between your residence and the temporary location. A temporary location is one where you work on an irregular or short-term basis (generally a matter of days or weeks). If you do not have a regular place of business, but you ordinarily work in the metropolitan area where you live, you can deduct daily transportation expenses between your home and a temporary worksite outside your metropolitan area. However, you cannot deduct daily transportation costs between your home and temporary worksites within your metropolitan area. Uniforms. You usually cannot deduct the expenses for uniform cost and upkeep. Generally, you must wear uniforms when on duty and you can wear them when off duty. If military regulations prohibit you from wearing certain uniforms off duty, you can deduct their cost and upkeep, but you must reduce the expenses by any allowance or reimbursement you receive. Expenses for the cost and upkeep of the following articles are deductible. 1) Military fatigue uniforms if you cannot wear them off duty, 2) Articles not replacing regular clothing, including insignia of rank, corps devices, epaulets, aiguillettes, and swords, and 3) Reservists’ uniforms if you can wear the uniform only while performing duties as a reservist. Professional dues. You can deduct dues paid to professional societies directly related to your military position. For example, Lt. Margaret Allen, an electrical engineer at Maxwell Air Force Base, can deduct professional dues paid to the American Society of Electrical Engineers. However, you cannot deduct amounts paid to an officers’ club or a noncommissioned officers’ club. Educational expenses. You can deduct educational expenses if they meet certain rules. You cannot deduct the cost of travel that is itself a form of education. However, if your educational expenses qualify for a deduction, travel for that education, including transportation, meals (subject to the 50% limit), and lodging, can be deducted. Educational services provided in kind, such as base-provided transportation to or from class, are not deductible. Qualifications. You can deduct educational expenses if the education: 1) Is required by your employer or by law or regulations for you to keep your salary, status, or job, or 2) Maintains or improves the skills required in your present work. Even if the above requirements are met, you cannot deduct educational expenses if the education is necessary to meet the minimum educational requirements needed to qualify you in your trade or business or is part Page 14 of a course of study that will qualify you for a new trade or business, even if you have no plans to enter that trade or business. Example 1. Lieutenant Commander Mason has a degree in financial management and is in charge of base finance at her post of duty. She incurred educational expenses to take an advanced finance course. She can deduct educational expenses that are more than the educational allowance she received because she already meets the minimum qualifications of her job. By taking the course, she is improving skills in her current position. The course does not qualify her for a new trade or business. Example 2. Major Williams worked in the military base legal office as a legal intern. He was placed in ‘‘excess need more information on educational expenses, get Publication 508, Educational Expenses. Tax Liability Now that you have determined your gross income, exemptions, and deductions, you can figure your taxable income and tax liability. You can also determine any tax credits you are entitled to. Most tax credits do not have special rules for members of the Armed Forces. However, the earned income credit, discussed next, may be of some interest to you. Earned Income Credit The earned income credit (EIC) is a special credit for certain persons who work. The credit reduces the amount of tax you owe (if any) and is intended to offset some of the increases in living expenses and social security taxes. Persons With A Qualifying Child If you have a qualifying child, you must meet all of the following rules to claim the earned income credit: 1) You must have a qualifying child who lived with you in the United States for more than half the year (the whole year for an eligible foster child). U.S. military personnel stationed outside the United States on extended active duty are considered to live in the United States. To determine if you have a qualifying child, see Qualifying Child, later. See Social security number and Birth or death of a child, later, for more information. 2) You must have earned income during the year. 3) Your earned income and adjusted gross income must each be less than ● ● $24,396 if you have one qualifying child, or $26,673 if you have more than one qualifying child. If you do not have a qualifying child and earn less than $9,230, see Persons without a qualifying child. 4) Your filing status can be any filing status EXCEPT married filing a separate return. See Married persons, later, for an exception. 5) You cannot be a qualifying child of another person. 6) Your qualifying child cannot be the qualifying child of another person whose adjusted gross income is more than yours. 7) You usually must claim a qualifying child who is married as a dependent. 8) You did not file Form 2555, Foreign Earned Income (or Form 2555–EZ, Foreign Earned Income Exclusion) to exclude from your gross income any income earned in foreign countries, or deduct or exclude a foreign housing amount. See Publication 54, Tax Guide for U.S. Citizens and Resident Aliens Abroad, for more information. 9) You must be married to a U.S. citizen or resident if you are a nonresident alien. In addition, you must choose to be treated as a resident alien for the entire year. See Publication 519 for more information. Refund could be delayed. If you did not provide correct and valid SSNs, the processing of your tax return will be delayed. If the filing deadline is approaching and you still don’t have an SSN, you can: 1) Request an automatic extension to August 15 (Form 4868). This extension does not give you extra time to pay any tax owed. You should pay any amount you expect to owe to avoid interest or penalty charges (see the instructions for Form 4868), or 2) File the return on time without Schedule EIC and file an amended return (Form 1040X) after receiving the SSN. Married persons. Married persons living apart usually must file a joint return to claim the earned income credit. Even though you are married, you may file as head of household and claim the credit on your return if: 1) Your spouse did not live in your home at any time during the last 6 months of the year, 2) You paid more than half the cost to keep up your home for the entire year, and 3) You and your child lived in the same main home for more than half the year. You must also be entitled to claim your child as your dependent. You will meet (3), even if you cannot claim your child as your dependent, if: ● You released your claim in writing to the other parent, or ● There is a pre-1985 agreement (decree of divorce or separate maintenance or written agreement) granting the exemption to your child’s other parent. Important Note. If you meet all these rules, fill out Schedule EIC and attach it to either Form 1040 or Form 1040A. Also complete a separate EIC Worksheet to figure the amount of your credit. If you have a qualifying child, you cannot claim the credit on Form 1040EZ. Enter ‘‘NO’’ next to line 57 (Form 1040) or line 29c (Form 1040A) if you cannot claim the credit because: 1) Your total taxable and nontaxable income was $24,396 or more if you have one qualifying child (or $26,673 or more if you have more than one qualifying child), 2) You were a qualifying child for another person in 1995, or 3) Your qualifying child was also the qualifying child of another person whose adjusted gross income is higher than yours. Social security number. You must provide a correct and valid social security number (SSN) for each qualifying child born before November 1, 1995. Qualifying children born between November 1 and December 31, 1995, must have SSNs for 1996. If you need to get an SSN, apply for one by filing Form SS–5 with your local Social Security Administration office. It takes approximately two weeks to receive an SSN. Qualifying Child You have a qualifying child if your child meets three tests: 1) Relationship, 2) Residency, and 3) Age. Each test has separate rules. Important Note. If you do not have a qualifying child and you earned less than $9,230, you may be able to take the credit. See Persons without a qualifying child, later. Relationship test. To meet the relationship test, the child must be your: ● Son, daughter, or adopted child (or a descendant of your son, daughter, or adopted child—for example, your grandchild), ● Stepson or stepdaughter, or ● Eligible foster child. Page 15 Residency test. To meet the residency test: ● A qualifying child must have lived with you for more than half the year (for the whole year if your child is an eligible foster child), and The home must be in the United States (one of the 50 states or the District of Columbia). U.S. military personnel stationed outside the United States on extended active duty are considered to live in the United States. ● meet all the rules to claim the credit. Adjusted gross income is the amount on line 31, Form 1040 or line 16, Form 1040A. Qualifying child of another person. If you are a qualifying child of another person, you cannot claim the credit—no matter how many qualifying children you have. Persons without a qualifying child. If you do not have a qualifying child and want to take the credit, you must meet all of the following rules: 1) You must have earned income during 1995. 2) Your earned income and adjusted gross income must each be less than $9,230. 3) Your filing status can be any filing status except married filing a separate return. See Married persons, discussed earlier, for an exception. 4) You cannot be a qualifying child of another person. See Qualifying child of another person, earlier. 5) You (or your spouse, if filing a joint return) must be at least age 25 but under age 65 at the end of your tax year. 6) You cannot be eligible to be claimed as a dependent on anyone else’s return. 7) Your main home must be in the United States for more than half of the year. U.S. military personnel stationed outside the United States on extended active duty are considered to live in the United States. 8) You did not file Form 2555, Foreign Earned Income, or Form 2555–EZ, Foreign Earned Income Exclusion. 9) You must be married to a U.S. citizen or resident if you are a nonresident alien. In addition, you must choose to be treated as a resident alien for the entire year. If you meet all these rules, fill out the EIC Worksheet to figure the amount of your credit. Enter ‘‘NO’’ next to line 57 (Form 1040), line 29c (Form 1040A), or line 8 (Form 1040EZ) if you cannot claim the credit because: 1) Your total taxable and nontaxable earned income was $9,230 or more, 2) You (and your spouse if filing a joint return) were under age 25 or over age 64, 3) Your home was not in the United States for more than half the year, or 4) You were a qualifying child of another person in 1995. Birth or death of a child. You will meet the rule for a child living with you for more than one-half of the year if: ● The child was alive for one-half of the year or less, and The child lived with you for the part of the year he or she was alive. ● If your qualifying child is an eligible foster child, you will meet the rule for a child living with you for the entire year (12 months) if: ● ● The child was born or died during the year, and The child lived with you for the part of the year he or she was alive. Temporary absences. You will meet the residency test if you or the qualifying child is away from home on a temporary absence due to a special circumstance. Examples of a temporary absence include: ● ● ● ● ● Illness, Attending school, Business, Vacation, or Military service. Note: You may be eligible for the earned income credit if you are absent temporarily only because of military service. To be eligible for the credit, you must plan to return to your main home where your qualifying child lives at the end of your assignment. Service in the Persian Gulf area combat zone is a temporary absence. Age test. The age test is met if your child is: 1) Under age 19 at the end of the year, 2) A full-time student under age 24 at the end of the year, or 3) Permanently and totally disabled at any time during the tax year, regardless of age. Qualifying child of more than one person. If you and someone else have the same qualifying child, only the person with the higher adjusted gross income may be eligible to take the credit. This is true even if the person with the higher adjusted gross income does not Page 16 Earned Income For purposes of the earned income credit, earned income includes: ● ● Wages, salaries, tips, Long-term disability benefits you received prior to minimum retirement age, Voluntary salary deferrals, Quarters and subsistence allowances and in-kind equivalents received by military members, Pay for service in a combat zone, Net earnings from self-employment, and Anything else of value, even if not taxable, that you received for providing services. your legal assistance office or unit tax advisor if you need additional help. ● ● Advance Earned Income Credit You must meet the following rules to qualify for the advance earned income credit in 1996: 1) Work and earn less than a certain amount. The amount in 1995 was $24,396. The amount for 1996 will be higher (see Form W–5 for the 1996 amount), 2) Have a qualifying child, 3) Meet all the rules explained in the instructions for Form W–5, Earned Income Credit Advance Payment Certificate, and 4) Have investment income of not more than $2,350. If you expect to qualify for the earned income credit for 1996, you can choose to get part of the credit in advance by giving a completed Form W–5 to your appropriate finance office. The credit will be included regularly in your pay. The advance payment is only available if you have a qualifying child. If you received advance earned income credit payments in 1995, you must file either Form 1040 or 1040A for 1995 to report the payments. How to claim the credit and report the advance payment. To receive your credit, you must file a tax return. You can use either Form 1040 or Form 1040A and attach Schedule EIC. If you file a tax return because you met the gross income filing requirements, had taxes withheld from your wages, or received advance earned income credit payments, enter your earned income credit on line 57, Form 1040 (or line 29c, Form 1040A). Include any advance earned income credit payments you received during the year on line 52, Form 1040 (or line 26, Form 1040A). Form W–2, box 9, shows the amount of advance payments you received during 1995. IRS will figure your credit for you. There are certain instructions you must follow before the IRS can figure the credit for you. These instructions are in Publication 596. ● ● ● For purposes of the earned income credit, the term ‘‘quarters and subsistence allowances’’ means the Basic Allowance for Quarters (BAQ) and the Basic Allowance for Subsistence (BAS) received by military personnel (with respect to grade and status) and the value of meals and lodging furnished in-kind to military personnel residing on military bases. To calculate the value of meals and lodging furnished in-kind, you may assume that the value is equal to the combined BAQ and BAS that the military member would have received had he or she been entitled to the allowance. Beginning in 1995, earned income that is not taxable, such as combat pay, BAQ, BAS, and certain in-kind equivalents, will be reported in box 13 of Form W-2. Earned income does not include: ● ● ● ● ● ● ● ● Interest and dividends, Social security payments, Welfare benefits, Pensions or annuities, Veterans’ benefits, Variable housing allowances, Workers’ compensation, or Unemployment compensation. Example 1. Corporal John Andrews and his wife Doris file a joint return for 1995. They have 2 children— Mark who is age 3, and Connie who was born in May of 1995. Their total earned income is $22,227 (basic pay $15,264, BAQ $4,450, BAS $2,513). John and Doris qualify for the earned income credit. Example 2. Staff Sgt. Brad Wilson and his wife Judy file a joint return for 1995. They have two children—Angela who is 6 years old and Eric who is 4 years old. Their total earned income is $29,228 (basic pay $21,023, which includes $7,408 nontaxable pay for service in a combat zone, plus BAQ $5,692 and BAS $2,513). Even though the Wilsons’ adjusted gross income is $13,615, they do not qualify for the earned income credit because their total earned income is not less than $26,673. Military members should receive a Leave and Earnings Statement at the end of the year that includes some of the pertinent allowance information. You should refer to that statement or your Form W-2 when determining earned income for EIC purposes. You can also contact Decedents If a member of the Armed Forces dies, a surviving spouse or personal representative handles such duties as filing any tax returns and claims for refund of withheld tax or estimated tax. A personal representative can be an executor, administrator, or anyone who is in charge of the decedent’s assets. This section discusses the special tax forgiveness provisions that apply to individuals who: Page 17 1) Die while serving in a combat zone or from wounds, disease, or injury incurred while serving in a combat zone, or 2) Die from wounds or injury incurred in a terroristic or military action outside the United States while a U.S. employee. This section also explains how to claim this special tax forgiveness. For other information concerning decedents, get Publication 559, Survivors, Executors, and Administrators. Forces resulting from violence or aggression (or the threat of violence or aggression) against the United States or its allies. Any multinational force in which the United States participates is considered an ally of the United States. Example. Army Private John Kane died in 1995 of wounds incurred outside the United States in a terroristic attack in 1994. His income tax liability is forgiven for all tax years from 1993 through 1995. Refunds are allowed for the tax years for which the period for filing a claim for refund has not ended. Combat Zone Forgiveness If a member of the U.S. Armed Forces dies while on active service in a combat zone or from wounds, disease, or other injury received in a combat zone, the decedent’s entire income tax liability is forgiven for the year death occurred, and for any earlier tax year beginning with the year before the year in which the wounds, disease, or other injury occurred. That tax liability is also forgiven for any earlier tax year in which the member served at least one day in a combat zone. Any forgiven tax liability that has already been paid will be refunded, and any unpaid tax liability at the date of death will be forgiven. In addition, any unpaid taxes for prior years will be forgiven and any prior year taxes that are paid after date of death will be refunded. This forgiveness provision also applies to a member of the Armed Forces serving outside the combat zone if the service: 1) Was in direct support of military operations in the zone, and 2) Qualified the member for special military pay for duty subject to hostile fire or imminent danger. For a description of the combat zone, see Combat Zone, earlier.. Claims for Tax Forgiveness If either of these tax-forgiveness provisions applies to a prior year’s tax that has been paid and the period for filing a refund claim has not ended, the tax will be refunded. If any tax is still due, it will be canceled. The normal in a terroristic or military action, use the following procedures in filing a claim for tax forgiveness: 1) File Form 1040 if a Form 1040, 1040A, or 1040EZ has not been filed for the tax year. Form W–2, Wage and Tax Statement, must accompany the return. 2) File Form 1040X if a Form 1040, 1040A, or 1040EZ has been filed. A separate Form 1040X must be filed for each year in question. These returns and claims must be filed with the Internal Revenue Service Center, P.O. Box 267, Covington, KY 41019, Attn: Stop 28, Desert Storm—KIA (or KITA, if it is not associated with the Persian Gulf area combat zone). All returns and claims must be identified by writing ‘‘Desert Storm — KIA’’ (or ‘‘KITA’’) in bold letters on the top of page 1 of the return or claim. On Forms 1040 and 1040X, the phrase ‘‘Desert Storm — KIA’’(or ‘‘KITA’’) must be written on the line for ‘‘Total tax.’’ An attachment that includes a computation of the decedent’s tax liability before any amount is forgiven and the amount that is to be forgiven should accompany any return or claim . For joint returns, see Joint returns, later. Necessary documents. The following documents must accompany all returns and claims for refund: 1) Form 1310, Statement of Person Claiming Refund Due a Deceased Taxpayer. 2) A certification from the Department of Defense or the Department of State. Terroristic or Military Action Forgiveness Tax liability is forgiven for an individual who: 1) Is a military or civilian U.S. employee at death, and primarily directed against the United States or its allies or any military action involving the U.S. Armed Page 18 For military employees and civilian employees of the Department of Defense, certification must be made by that Department on Form DOD 1300, REPORT OF CASUALTY. For civilian employees of all other agencies, certification must be a letter signed by the Director General of the Foreign Service, Department of State, or his or her delegate. The certification must include the deceased individual’s name and social security number, the date of injury, the date of death, and a statement that the individual died in a combat zone or from a terroristic or military action outside the United States. If the individual died as a result of a terroristic or military action, the statement must also include the fact that the individual was a U.S. employee at the date of injury and at the date of death. If the certification has been received, but there is not enough tax information to file a timely claim for refund, Form 1040X must be filed along with Form 1310 and a statement that an amended claim will be filed as soon as the necessary tax information is available. Filing Returns This section discusses the special problems military personnel encounter when filing federal tax returns. For information on filing returns for those involved in the Persian Gulf area combat zone, see Extension of Deadline, later. Where to File Send your federal return to the Internal Revenue Service Center for the place where you reside. 19255. When to File Joint returns. Only the decedent’s part of the joint income tax liability is eligible for the refund or tax forgiveness. To determine the decedent’s part, the person filing the claim must: 1) Figure the income tax for which the decedent would have been liable as if a separate return had been filed. 2) Figure the income tax for which the spouse would have been liable as if a separate return had been filed. 3) Multiply the joint tax liability by a fraction. The top number of the fraction is the amount in (1), above. The bottom number of the fraction is the total of (1) and (2).. For 1995 tax returns, the due date is April 15, 1996. Extensions You can receive an extension of time to file your return. Different rules apply if you live within the United States or outside the United States. Within the United States. You can receive an automatic 4-month extension to file your return by filing Form 4868, Application for Automatic Extension of Time To File U.S. Individual Income Tax Return. File the application by the normal due date for the return with the service center where you will file your return. You cannot use the automatic extension if: You choose to have IRS figure the tax, or You are under a court order to file your return by the regular due date. The extension of time to file is automatic, and you will not receive any notice of approval. However, if you file Form 4868 late, your request for extension will be denied. The IRS will inform you of the denial. Having an extension to file does not mean you have an extension to pay any tax due. On Form 4868, you must estimate your tax, taking into account any tax withheld or estimated tax payments. You should (but do not have to) send in any tax due when you file Form 4868. However, if you pay the tax due after the original due date, interest will be charged from the original due date to the date the tax is paid. Enter any amount you send on line 58, Form 1040, add the Page 19 The amount in (3) is the decedent’s tax liability that is eligible for the refund or tax forgiveness. If you are unable to complete this process, you should attach a statement of all income and deductions, indicating which belongs to each spouse, and the IRS will make the proper division. Residents of community property states. If the member of the Armed Forces was domiciled in a community property state and the spouse reported half of the military pay on a separate return, the spouse can get a refund of taxes paid on his or her share of the pay for the years involved. The forgiveness of unpaid tax on such military pay would also apply to the half owed by the spouse for the years involved. amount to the total on line 29d, Form 1040A, or include in the total on line 9, Form 1040EZ. You will have to pay a late payment penalty unless you pay at least 90 percent of your tax liability by the original due date of the return. This can be paid through withholding, estimated tax payments, or payment accompanying Form 4868. If you are unable to pay the tax owed by the end of the automatic 4-month extension period, you should attach Form 9465, Installment Agreement Request, to your return. The IRS will attempt to arrange an installment payment agreement that reflects your ability to pay the tax owed. In addition, you will have to pay interest on any tax due when you file your return. For more details, see the instructions on Form 4868. Outside the United States and Puerto Rico. If you are a U.S. citizen or resident, you can qualify for an automatic extension of time until June 15 without filing Form 4868 if: 1) You live outside the United States and Puerto Rico and your main place of business or post of duty is outside the United States and Puerto Rico. 2) You are in military or naval service on an assigned tour of duty outside the United States and Puerto Rico for a period that includes the entire due date of the return. Interest will be charged. To obtain the additional extension, write ‘‘Taxpayer Abroad’’ in the top margin of the Form 4868. Joint returns. For married persons filing a joint return, only one spouse needs to meet the requirements to take advantage of the automatic extension to June 15. Separate returns. For married persons filing separate returns, only the spouse who met the requirements qualifies for the automatic extension. Additional extension beyond August 15. You can request an extension beyond the 4-month period by filing Form 2688, Application for Additional Extension of Time To File U.S. Individual Income Tax Return , or by letter. Except in undue hardship cases, this additional extension will be granted only if Form 4868 has already been filed. Form 2688 or your letter will not be considered if filed after the extended due date. If you file Form 2688 and an extension is granted, and later it is discovered that the information you gave was false or misleading, the extension is void. You may then be subject to a penalty for filing late. Generally, you must sign your return. However, if you are overseas or incapacitated, you may grant a power of attorney to an agent to file and sign your return. A power of attorney can be granted by filing Form 2848, Power of Attorney and Declaration of Representative. In Part I of the form, you must be sure to indicate that you are granting the power to sign the return, the form number, and the tax year for which the form is being filed. Attach the power of attorney to the tax return. If you are acting on behalf of someone serving in the Persian Gulf area combat zone, see Filing Returns for Combat Zone Participants, later. Joint returns. Generally, joint returns must be signed by both spouses. In some cases, however, one spouse may not be able to sign—for example, when a spouse is overseas, in a missing status, incapacitated, or deceased. In some of these situations, a power of attorney may need to be granted for a joint return to be filed. Spouse overseas. If one spouse is overseas on military duty, there are two options when filing a joint return. One spouse can prepare the return, sign it, and send it to the other spouse to sign early enough so that it can be filed by the due date. Or, the spouse who expects to be overseas on the due date of the return can file Form 2848, specifically designating that the spouse who remains in the United States can sign the return for the absent spouse.. The 2-year limit does not apply to combat zone activities in Vietnam. A joint return filed under these conditions is valid even if it is later determined that the missing spouse died before the year covered by the return. Spouse incapacitated. your return. The statement should include the number of the return you are filing, the tax year, the reason your spouse could not sign, and that your spouse has agreed to your signing for him or her. Spouse deceased. If one spouse is deceased, the remaining spouse can file a joint return for the year of death, writing in the signature area, ‘‘Filing as surviving spouse.’’ If an executor or administrator has been appointed, he or she and the surviving spouse must sign the return filed for the decedent. Page 20 Refunds In general, military personnel follow the same rules as other taxpayers concerning tax refunds. See the instructions for your tax form for information on not receiving an expected refund or calling to check on your refund status. Note: Use Form 8822, Change of Address, to notify the IRS if you move or change your address after filing your return. This form is available by calling 1–800–829– 3676 or by writing to the IRS Forms Distribution Center for your area. Extension of Deadline Note. Certain periods of time are disregarded in determining whether certain tax matters are taken care of on time. For ease of understanding, this publication refers to such provisions as extensions of deadlines. These ‘‘deadline extensions’’ should not be confused with other parts of the tax law that refer to extensions of time for performing acts. Extension. The deadline for filing tax returns, paying taxes, filing claims for refund, and taking other actions with the IRS is extended if you serve in the Armed Forces in a combat zone. The deadline for IRS to take certain actions, such as collection and examination actions, is also extended. See the earlier description of a combat zone. However, for purposes of the deadline extension provision, combat zone service is performed in the Persian Gulf area if performed on or after August 2, 1990. Your deadline for taking actions with the IRS is extended for at least 180 days after the later of: 1) The last day you are in a combat zone (or the last day the area qualifies as a combat zone), or 2) The last day of any continuous qualified hospitalization (defined later) for injury from service in the combat zone. Time in a missing status (missing in action or prisoner of war) counts as time in a combat zone. In addition to the 180 days, your deadline is also extended by the number of days 31/ 2 months (Jan. 1 – Apr. 17, 1995) to file your 1994 tax return. Any days of this 3 1/ 2 month period that were left when you entered the combat zone (or the entire 31/ 2 months if you entered the combat zone by January 1) are added to the 180 days to find the last day allowed for filing your 1994 tax return. Example 1. Capt. Margaret Jones entered Saudi Arabia on December 1, 1993. She remained there through March 31, 1995, when she departed for the United States. She was not injured and did not return to the combat zone. The deadlines for filing Capt. Jones’ 1993, 1994, and 1995 returns are figured as follows: The 1993 tax return deadline is January 10, 1996. Capt. Jones has 285 days (180 plus 105) after her last day in the combat zone, March 31, to file her 1993 income tax return. The 105 additional days are the number of days in the 31/ 2 month filing period that were left when she entered the combat zone (Jan. 1 – Apr. 15). There are 105 days in the 1994 filing period. The 1994 tax return deadline is January 10, 1996. Capt. Jones has 285 days (180 plus 105) after her last day in the combat zone, March 31, to file her 1994 income tax return. There are 107 days in the 1995 filing period. The 1995 tax return deadline is not extended because the 180-day extension period after March 31, 1995, ends on September 27, 1995, which is before the start of the filing period for her 1995 return. Example 2. Petty Officer Leonard Brown’s ship entered the Persian Gulf on January 5, 1994. On February 15, 1994, Leonard was injured and flown to a U.S. hospital. He remained in the hospital through April 21, 1995. The deadlines for filing Petty Officer Brown’s 1993, 1994, and 1995 returns are figured as follows: The 1993 tax return deadline is January 27, 1996. Petty Officer Brown has 281 days (180 plus 101) after his last day in the hospital, April 21, 1995, to file his 1993 return. The 101 additional days are the number of days in the 31/ 2 month filing period that were left when he entered the combat zone (Jan. 5 – Apr. 15). There are 105 days in the 1994 filing period. He has until January 29 to file his return because January 27 falls on a Saturday. The 1994 tax return deadline is January 31, 1996. Petty Officer Brown has 285 days (180 plus 105) after April 21, 1995, to file his 1994 tax return. The 1995 tax return deadline is April 15, 1996. The 180-day period after April 21, 1995, ends October 18, 1995, which is before the start of the filing period for his 1995 return. Leonard has until the normal due date to file his 1995 tax return. Example 3. Maj. Rob Willard served in the combat zone from January 1 through July 31, 1995, and was not injured. He has 285 days (180 plus 105) after his last day in the combat zone, July 31, to file his 1994 income tax return. The 105 additional days are the days that were left in the 3 1/ 2 month filing period when he entered the combat zone (January 1 – April 15). His 1994 tax return is due by May 11, 1996. He has until May 13 to file his return because May 11 falls on a Saturday. Page 21 The due date of Maj. Willard’s 1995 return is also extended because part of the 180-day extension period falls within the filing period for his 1995 return. He has 285 days (180 plus 105) after his last day in the combat zone, July 31, 1995, to file his 1995 return. The 105 additional days are the number of days in the 31/ 2 month filing period for 1995 returns that he has after the 180-day extension period ends on January 27, 1996. Under this provision, his 1995 return is due by May 12, 1996. He has until May 13 to file his return because May 12 falls on a Sunday. Note. If you know that you cannot file your return by the extended deadline, you can file Form 4868, Application for Automatic Extension of Time to File U.S. Individual Income Tax Return, by the extended deadline. Filing Form 4868 will give you an additional 4 months to file your return. It will not extend the time you have to pay any tax you owe. You must make an estimate of your tax for the year with the form. See the instructions for Form 4868 for more information. In the above example, if Maj. Willard files Form 4868 by May 13, 1996, he can extend the final date for filing his 1994 return to September 12, 1996. Likewise, if he files Form 4868 for 1995 by May 13, 1996, he has until September 12, 1996, to file his 1995 return. Example 4. You generally have 3 years from April 15, 1992, to file a claim for refund against your timely filed 1991 income tax return. If you wish to amend that return, your claim normally must be filed by April 15, 1995. However, if you served in the combat zone from November 1, 1994, through March 23, 1995, and were not injured, your deadline for filing that claim is extended 346 days (180 plus 166) after you leave the combat zone. This extends your deadline to March 4, 1996. The 166 additional days are the number of days in the 3-year period for filing the refund claim that were left when you entered the combat zone on November 1 (Nov. 1, 1994 – Apr. 15, 1995). the area designated as a combat zone. In the case of the Persian Gulf area, the injury must have occurred between August 2, 1990, and the date the President, by Executive Order, terminates the combat zone. Qualified hospitalization includes: 1) Any hospitalization outside the United States, and 2) Up to 5 years of hospitalization in the United States. Actions extended. The actions to which the deadline extension provision applies include: Page 22 1) Filing any return of income, estate, or gift tax (except employment and withholding taxes), 2) Paying any income, estate, or gift tax (except employment and withholding taxes), 3) Filing a petition with the Tax Court for redetermination of a deficiency, or for review of a Tax Court decision, 4) Filing a claim for credit or refund of any tax, 5) Bringing suit for any claim for credit or refund, 6) Purchasing a replacement residence to postpone paying tax on the gain on the sale of the old residence, 7) Making a qualified retirement contribution to an IRA, 8) Allowing a credit or refund of any tax by the IRS, 9) Assessment of any tax by the IRS, 10) Giving or making any notice or demand by the IRS for the payment of any tax, or for any liability for any tax, 11) Collection by the IRS of any tax due, and 12) Bringing suit by the United States for any tax due. If the IRS takes any actions covered by these provisions or sends you a notice of examination before learning that you are entitled to an extension of the deadline, you do not have to take any action. Simply return the notice with ‘‘Desert Storm’’ written across the top. No penalties or interest will be imposed for failure to file a return or pay taxes during the extension period. You may choose to take an action during the extension period even though the deadline for that action is extended. For example, you may want to file a return to receive any refund due. See Filing Returns, earlier. Spouses. Spouses of individuals who served in a combat zone are entitled to the same deadline extension with two exceptions. 1) The extension does not apply to a spouse for any tax year beginning more than 2 years after the date that combat activities end. 2) ‘‘initial ‘‘material impairment,’’ you must show that your income dropped as a result of going into military service. Request for deferment. If you have a current payment agreement, you must make a written request for deferment to the IRS office that you have the agreement with. If you have received a notice requesting payment, you must make your written request for deferment to the IRS office that issued the notice. In either of these situations, you their decision. Should you need further assistance, you may to be charged to 6% per year for obligations or liabilities incurred prior to your entry into active service. The reduced rate applies only to the period of your active duty. To substantiate your claim for this reduced interest rate, you must furnish a copy of your orders or reporting instructions that detail the call to active duty. Filing Returns for Combat Zone Participants You can choose to file your return before the end of your extension period. When you file, write ‘‘Desert Storm’’ at the top of your return and on the envelope in which you mail it. This will alert the IRS that you are entitled to the various forms of relief mentioned earlier. If you are acting on behalf of someone serving in the Persian Gulf area combat zone the Persian Gulf area combat zone to obtain that person’s signature on a joint return, power of attorney form, or other signed authorization to act on his or her behalf, the IRS will accept a written statement explaining that the husband or wife is serving in the combat zone. The statement must be signed by the spouse filing the tax return and attached to the return. Outside the combat zone. If you do not qualify for the deadline extension provision, your 1995 return is due by the normal due date, April 15, 1996 (June 17, 1996, if you are stationed outside the United States and Puerto Rico on April 15). Interest on any unpaid tax will be charged from April 15. There are other provisions that extend the time for filing your return. See the instructions for your tax return for more information. Page 23 Index Page 24 This action might not be possible to undo. Are you sure you want to continue? We've moved you to where you read on your other device. Get the full title to continue reading from where you left off, or restart the preview.
https://www.scribd.com/document/545309/US-Internal-Revenue-Service-p3-1995
CC-MAIN-2017-04
refinedweb
15,294
60.35