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
Hello! I have been working every night of the week on a new major version of my open-source JavaScript SAST JS-X-Ray. I've been looking forward to making significant changes to the code for several months now... Why ? Because I'm still learning every day and the project has grown quite large since 2.0.0. Also when I started the project I lacked a certain rigor in the way I documented the code (and also on some speculations). It became necessary to make changes in order to continue to evolve the project. So what's new ? sec-literal npm i sec-literal I started to work on a package to analyze ESTree Literals and JavaScript strings. This is a very important part that could be separated in its own package (which simplifies my documentation and testing). Some of the features of this package: - Detect Hexadecimal, Base64 and Unicode sequences. - Detect patterns (prefix, suffix) on groups of identifiers. - Detect suspicious string and return advanced metrics on it (with char diversity etc). It's a start... I plan to extend the features of the package in the coming months (but also to re-invest some time in documentation and testing). new project structure Still very far from the perfection I imagine but it's a good start. The code had become messy and it was almost impossible to reason properly. The new version is now much easier to maintain and evolve. I will surely continue to improve it for the next major release. More documentation, more tests I took advantage of the refacto to reinsert a whole set of documentation and unit tests. It also allowed me to fix a number of issues that had not been resolved in version 2.3. Obfuscation detection is hard I knew it! But I swear to you that it is much more complex than anyone can imagine. I had to rewind my steps several times. But if there were no challenges it wouldn't be fun. ESM Import evaluation Version 3 now throw an unsafe-import for import with javascript code evaluation. import 'data:text/javascript;base64,Y29uc29sZS5sb2coJ2hlbGxvIHdvcmxkJyk7Cg=='; For more info: Conclusion Nothing incredible for this new version. But the project continues to progress step by step and I hope to be able to add a whole bunch of new detections by the end of the year. Best Regards, Thomas Discussion (1) Good job Thomas 👏 👏 👏 !
https://practicaldev-herokuapp-com.global.ssl.fastly.net/fraxken/js-x-ray-3-0-0-3ddn
CC-MAIN-2021-49
refinedweb
404
65.52
@antv/g2 v4.1.16 Published the Grammar of Graphics in Javascript Downloads 329,332 Maintainers Readme A highly interactive data-driven visualization grammar for statistical charts. $ npm install @antv/g2 🔨 Getting Started Before drawing we need to prepare a DOM container for G2: <div id="c1"></div> import { Chart } from '@antv/g2'; const data = [ { genre: 'Sports', sold: 275 }, { genre: 'Strategy', sold: 115 }, { genre: 'Action', sold: 120 }, { genre: 'Shooter', sold: 350 }, { genre: 'Other', sold: 150 }, ]; // Step 1: Create a Chart instance. const chart = new Chart({ container: 'c1', // Specify chart container ID width: 600, // Specify chart width height: 300, // Specify chart height }); // Step 2: Load the data. chart.data(data); // Step 3: Declare the grammar of graphics, draw column chart. chart.interval().position('genre*sold'); // Step 4: Render chart. chart.render(); ⌨️ Development # Install dependencies $ npm install # Run test cases $ npm run test # Open electron to run test cases and listen to file changes $ npm run test-live # Run CI $ npm run ci # Run website $ npm start 🏷️ Releases - v3.5.x: - v4.0.x: You can also use G2Plot which is an interactive and responsive charting library based on G2. You can easily make superior statistical plots through a few lines of code. 🤝 How to Contribute Please let us know how can we help. Do check out issues for bug reports or suggestions first. To become a contributor, please follow our contributing guide. DingTalk Group: 30233731
https://www.pkgstats.com/pkg:@antv/g2
CC-MAIN-2021-21
refinedweb
234
61.87
Data::Dumper::EasyOO - wraps DD for easy use of various printing styles EzDD is an object wrapper around Data::Dumper (henceforth just DD), and uses an inner DD object to produce all its output. Its purpose is to make DD's OO capabilities easier to use, ie to make it easy to: 1. label your data meaningfully, not just as $VARx 2. make and reuse EzDD objects 3. customize print styles on any/all of them independently 4. provide essentially all of DD's functionality 5. do so with fewest keystrokes possible 1st, an equivalent to DD's Dumper, which prints exactly like Dumper does use Data::Dumper::EasyOO; print ezdump([1,3]); which prints: $VAR1 = [ 1, 3 ]; Here, we provide our own (meaningful) label, and use autoprinting, and thereby drop the 'print' from all ezdump calls. use Data::Dumper::EasyOO (autoprint => 1); my $gl = { Joe => 'beer', Betsy => 'wine' }); ezdump ( guest_list => $gl); which prints: $guest_list = { 'Joe' => 'beer', 'Betsy' => 'wine' }; And theres much more... is that you can choose your preferred printing style in the 'use' statement. EzDD replaces the usual 'import' semantics with the same (property => value) pairs as are available in new(). You can think of the use statement as a way to set new()'s default behavior once, and reuse those styles (or override and supplement them) on EzDD objects you create thereafter. All of DD's style-setting methods are available in EzDD as both properties to new(), and as object methods; its your choice. For maximum laziness support, ezdump() is exported into your namespace, and supports the synopsis example. $ezdump is also exported; it is the EzDD object that ezdump() uses to do its dumping, and allows you to tailor ezdump()s print-style. It also lets you use OO style if you prefer. Continuing from 2nd synopsis example... $ezdump->Set(sortkeys=>1); ezdump ( guest_list => $gl ); print "\n"; $ezdump->Indent(1); ezdump ( guest_list => $gl ); which prints: $guest_list = { 'Betsy' => 'wine', 'Joe' => 'beer' }; $guest_list = { 'Betsy' => 'wine', 'Joe' => 'beer' }; The print-styles are set 2 times; 1st as a property setting, 2nd done like a DD method. The styles accumulate and persist on the object. The following features are discussed in OO context, but are nearly all applicable to ezdump() via its associated $ezdump object-handle. EzDD 'knows' you prefer labelled => $data, and assumes that you've called it that way, except when you havent. Any arglist that looks like a list of pairs is treated as as such, by 2 rules: 1. arglist length is even 2. no candidate-labels are refs to other structures so this labels your data: $ezdd->(person => $person, place => $place); but this doesn't (assuming that $person is an object, not a string): $ezdd->($person, $place); If you find that EzDD sometimes misinterprets your array data, just explicitly label it, like so: $ezdd->(some_label => \@yourdata); DD::Simple does more magic labelling than EzDD (it grabs the name of the variable being dumped), but EzDD avoids source filtering, and gives you an unsuprising way to get what you want without fuss. EzDD recognizes that the only reason you'd use it is to dump your data, so it gives you a shorthand to do so. print $ezdd->dump($foo); # 'long' way print $ezdd->pp($foo); # shorter way print $ezdd->($foo); # look Ma, no function name It helps to think of an EzDD object as analogous to a printer; sometimes you want to change the paper-tray, or the landscape/portrait orientation, but mostly you just want to print. To save more keystrokes, you can set autoprint => 1, either at use-time (see synopsis), or subequently. Printing is then done for you when you call the object. $ezdd->Set(autoprint=>1); # unless already done $ezdd->($foo); # even shorter But this happens only when you want it to, not when you assign the results to something else (or return it into your own print statement) $b4 = $ezdd->($foo); # save rendering in var $foo->bar(); # alter printed obj # now dump before and after print "before: $b4, after: ", $ezdd->($foo); For laziness with greater impunity, ezdump() and friends will carp if you call them without printing (ie call them in void context). But if thats really what you want to do, set autoprint => 0 at use-time, and your calls will do nothing quietly. Then when you want to enable dumping, perhaps with a cmd-line option, you can do so once per object, and they are all enabled. With this, you can declutter your dumping calls. You can set an object's print-style by imitating the way you'd do it with object oriented DD. All of DDs style-changing methods are emulated this way, not just the 2 illustrated here. $ezdd->Indent(2); $ezdd->Terse(1); You can chain them too: $ezdd->Indent(2)->Terse(1); The emulation above is really dispatched to Set(); those 2 examples above can be restated: $ezdd->Set(indent => 2)->Set(terse => 1); or more compactly: $ezdd->Set(indent => 2, terse => 1); Multiple objects' print-styles can be altered independently of each other: $ez2->Set(%addstyle2); $ez3->Set(%addstyle3); For maximum laziness, mixed-case versions of both method calls and properties are also supported. Create a new printer, using default style: $ez3 = Data::Dumper::EasyOO->new(); Create a new printer, with some style overrides that are passed to Set(): $ez4 = Data::Dumper::EasyOO->new(%addstyle); Clone an existing printer: $ez5 = $ez4->new(); Clone an existing printer, with style overrides: $ez5 = $ez4->new(%addstyle2); # obvious way print $fh $ezdd->($bar); # auto-print way $ezdd->Set(autoprint => $fh); $ezdd->($bar); You can set autoprint style to any open filehandle, for example \*STDOUT, \*STDERR, or $fh. For convenience, 1, 2 are shorthand for STDOUT, STDERR. autoprint => 0 turns it off. TBC: autoprint => 3 prints to fileno(3) if it's been opened, or warns and prints to stdout if it hasnt. Data::Dumper::EasyOO is cumbersome to type more than once in a program, and is unnecessary too. Just provide an alias at use-time, and then use that alias thereafter. use Data::Dumper::EasyOO ( alias => 'EzDD' ); $ez6 = EzDD->new(); If calling $ez1 = EzDD->new is too much work, you can initialize it by passing it at use time. use Data::Dumper::EasyOO ( %style, init => \our $ez ); By default, $ez is initialized with DD's defaults, these can be overridden by %style. If you want to store the handle in my $ez, then declare the myvar prior to the use statement, otherwize the object assigned to it at BEGIN time is trashed at program INIT time. my $ez; use Data::Dumper::EasyOO ( init => \$ez ); You can even create multiple objects at use-time. EzDD treats the arguments as an order-dependent list, and initializes any specified objects with the settings seen thus far. To better clarify, consider this example: use Data::Dumper::EasyOO ( alias => EzDD, # %DDdefstyle, # since we use a DD object, we get its default style %styleA, init => \$ez1, # gets DDdef and styleA %styleB, init => \$ez2, # gets DDdef, styles A and B %styleC, init => \$ez3, # gets DDdef, styles A, B and C %styleD, ); This is equivalent: use Data::Dumper::EasyOO (alias => 'EzDD'); BEGIN { $ez1 = EzDD->new(%DDdefstyle, %styleA); $ez2 = EzDD->new(%DDdefstyle, %styleA, %styleB); $ez2 = EzDD->new(%DDdefstyle, %styleA, %styleB, %styleC ); } Each %style can supplement or override the previous ones. %styleD is not used for any of the initialized objects, but it is incorporated into the using package's default style, and is used in all new objects created at runtime. Each user package can set its own default style; you can use this, for example, to set a different sortkeys => \&pkg_filter for each. With this, YourReport::Summary and YourReport::Details can dump the info appropriate for your needs. If you decide during runtime that you dont like your use-time defaults, just call import again to change them. All newly built objects will inherit those new print-styles. This is a rather over-the-top usage. 1st, it sets an alias, with which you can shorten calls to new(). 2nd, it sets several of my favorite print styles. 3rd, it initializes several dumper objects, giving each of them slightly different print-styles. my $ezdd; # declare a handle for an object to be initialized use Data::Dumper::EasyOO ( alias => EzDD, # a temporary top-level-name alias # set some print-style defaults indent => 1, # change DD's default from 2 sortkeys => 1, # a personal favorite # autoconstruct a printer obj (calls EzDD->new) with the defaults init => \$ezdd, # var must be undef b4 use # set some more default print-styles terse => 1, # change DD's default of 0 autoprint => $fh, # prints to $fh when you $ezdd->(\%something); # autoconstruct a 2nd printer object, using current print-styles init => \our $ez2, # var must be undef b4 use alias => Ez2, # another top-level-name alias ); $ezdd->(p1 => $person); # print as '$p1 => ...' my $foo = EzDD->new(%style) # create a printer, via alias, w new style ->(there => $place); # and print with it too. $ez2-> (p2 => $person); # dump w $ez2, use its style $foo->(here => $where); # dump w $foo style (use 2 w/o interference) $foo->Set(%morestyle); # change style at runtime $foo->($_) foreach @things; # print many things These are both object methods, and are aliases which provide a familiar invocation for users of Data::Dump. # these are all the same $ezdump->(\%INC); $ezdump->pp(\%INC); $ezdump->dump(\%INC); This module pollutes the users namespace with 2 symbols: $ezdump and &ezdump. In the context of maximum easyness, this is construed to be a feature. The layering of defaults takes some getting used to. However, the complexity is not a bug, its a feature. Print-style defaults are stored in EzDD for each user package. This does not permit aliases to have separate defaults, which could be useful. This is fairly straightforward, and may be added in the future. Aliases could be treated like object 'init's, in that they could get defaults based upon the print-styles seen thus far in the use-time arguments. The difficulty with this idea is that it changes the declarative flavor of aliases. In the featureful example above, the EzDD alias appears before the various print-style settings, so they would not apply to it, but only to the 2nd alias, Ez2. If you 'use strict' and this module together, you may get weird errors; similar to the following. The last ones in particular are odd, since the code has NO variable named $class. Variable "$ezdump" is not imported at t/ezdump-strict.t line 18. at t/ezdump-strict.t line 18 (Did you mean &class instead?) at t/ezdump-strict.t line 18 Variable "$ezdump" is not imported at t/ezdump-strict.t line 18. at t/ezdump-strict.t line 18 (Did you mean &ezdump instead?) at t/ezdump-strict.t line 18 Global symbol "$class" requires explicit package name at t/ezdump-strict.t line 18. Global symbol "$ezdump" requires explicit package name at t/ezdump-strict.t line 18. I dont know the root cause of this, but the solution is simple; predeclare the $ezdump variable, as is done in t/ezdump-strict.t (the file proves that explicit importing of those default imports doesnt fix the oddity shown above). L<Data::Dumper> the mother of them all L<Data::Dumper::Simple> nice interface, basic feature set L<Data::Dumper::EasyOO> easyest of them all :-) L<Data::Dump> has cool feature to squeeze data L<Data::Dump::Streamer> highly accurate, evaluable output L<Data::TreeDumper> lots of output options Jim Cromie <jcromie@cpan.org> Copyright (c) 2003,2004,2005 Jim Cromie. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
http://search.cpan.org/dist/Data-Dumper-EasyOO/lib/Data/Dumper/EasyOO.pm
CC-MAIN-2017-09
refinedweb
1,956
67.69
file doc file - Java Beginners doc file i want to read .doc file ?....it is a part of my project plz help. if possible , can anyone give me the Jar File - Java Beginners Java Jar File What is a Java JAR file ..and how can i open a .jar file in Java? Just create a Jar file and Double click on it, it will automatically runs main method in that Jar : to create Project as JAR file arraival in java - Java Beginners file arraival in java A simple java program that runs continuously as a background process and prints out according to a given event based schedule(Arrival of a file in a specified directory) and is exited only through manual java - file delete - Java Beginners java - file delete I will try to delete file from particular folder... is: String dirname = null; File dir = new File("c:/writinnew...){ try { File delete = new File (incurrentFile); System.out.println java jar file - Java Beginners java jar file How to create jar Executable File.Give me simple steps... int buffer = 10240; protected void createJarArchive(File jarFile, File...(); System.out.println("Jar File is created successfully."); } catch (Exception ex Creating a temporary file :\ CreateTemporaryFile>java CreateTemporaryFile Temporary file file has been created... Java Temporary File - Temporary File Creation in Java... the existing file when you close the java program or your JVM. Code file upload : Thanks J2ME delete file - Java Beginners java program for writing xml file - Java Beginners java program for writing xml file Good morning i want to write values from my database(one table)into one xml file. Like i have 3 coloumns in my... xml file and storet that in particlar location. Please help me out Thanks download a file from browser - Java Beginners download a file from browser How to download a file from browser and save it in local path change jar file icon - Java Beginners change jar file icon How to create or change jar file icon Hi friend, The basic format of the command for creating a JAR file is: jar cf jar-file input-file(s) * The c option indicates that you want File download return value - Java Beginners File download return value How to get the return value of Open/Save/Cancel buttons in a File Download pop up using javascript How to format text file? - Java Beginners How to format text file? I want the answer for following Query ***(Java code) How to open,read and format text file(notepad) or MS-word.../example/java/io/java-read-file-line-by-line.shtml Thanks open a bufferedwriter file in append mode - Java Beginners open a bufferedwriter file in append mode hi.. i jus want knw how to opena bufferedwriter file in append mode.. Hi friend, FileWriter... simply overwrite the contents in the file by the specified string but if you put File copy through intranet - Java Beginners File copy through intranet Can i copy files from system A to System B connected through intranet?? Is this possible through java IO? If yes, please let me know searching a text string in file - Java Beginners searching a text string in file code to match a string in a file that is already mentioned in java code.if the string matches any part of a string that whole string is printed How to delete a character from a file in java - Java Beginners How to delete a character from a file in java I'm not gettting how to remove a character from a file in java....could any one help me out?? .../beginners/ Thanks I Reading text from image file - Java Beginners Reading text from image file How Read text from image file Program to read a dynamic file content - Java Beginners Program to read a dynamic file content Hi, In a single...", "020209.txt", "030209.txt","040209.txt". In a single file I'll get the datas... the database. Im using MySql Database and a standalone java program. I read adobe illustrator file - Java Beginners read adobe illustrator file Hi all, Could anybody tell me how we can read adobe illustrator(.AI) file in java. Please send me some examples. Thanks, Subodh Kumar Singh Shifting txt file to database - Java Beginners Shifting txt file to database Question Details: I want to shift data from txt file to Database. The data is written in the following text format... and put into database using Java/JSP. Database table is as below ID numeric File transfer to teh server - Java Beginners File transfer to teh server hi,, I've been trying to make... and then the program read all the files and then save the content of all in 1 file... or FileOutputStream ? this is my code : public class Main { static File initialise array by reading from file - Java Beginners would initialise an array by reading a text file, which contains a simple pattern. for example the file may look as shown below, with the star character...(String args[]) { try{ // Open the file that is the first how to store data in a text file - Java Beginners can save the data in a .txt file using swings....... for example, i want to store the arraylist data of swing program into a text file.......and also i want...() { public void actionPerformed(ActionEvent ae){ File file=new File File File How to find all files in our local computer using java Text File I/O - DVD.java - Java Beginners Text File I/O - DVD.java NEED HELP PLEASE. The application should use a text file with one value on each line of the file. Each movie would use... starts, read the data file and populate the array. When the file ends, use Read content for JPEG image File in Java - Java Beginners Read content for JPEG image File in Java How to Read content for JPEG image File in Java? or Extract text from JPEG image File in Java Character from text file - Java Beginners Character from text file Write a program that reads characters from a text file. Your program will count how many time each character appear in the text. Assume that the letters are case-sensitive. Example output FILE ;Java Read content of File import java.io.*; public class Appliance { public...FILE There is a file named Name.txt that contains information related to appliances.I want to read the contents of this file and I used the code How to Open Text or Word File on JButton Click in Java - Java Beginners How to Open Text or Word File on JButton Click in Java How to Open Text or Word File on JButton Click in Java where located mysql jar file - Java Beginners Inserting data in Excel File - Java Beginners code for recently created file from a folder in java - Java Beginners code for recently created file from a folder in java how to get the recently created file from a folder in java? Hi friend, Code...=""; try { File file = new File(dirname); if(file.isDirectory Program - Java Beginners Program Java link list I need program in Java to copy a file to another file Hi Friend,For more information Java - search/find a word in a text file - Java Beginners Java - search/find a word in a text file Hello, I would like... want to do nothing, if FAIL, I want to record in 1 master output file, the name of the file that has FAIL in it. Please help. Thank you. Manan  convert data from pdf to text file - Java Beginners convert data from pdf to text file how to read the data from pdf file and put it into text file(.txt File copy from one drive to another. - Java Beginners File copy from one drive to another. I want to copy a .mp3 file from one drive(let d: drive)to another drive(let e: drive) in my Windows XP. How can I do How to create a new text file that contains the file names of the copied files in a new directory? - Java Beginners How to create a new text file that contains the file names of the copied files... file that contains the file names of the copied files in a new directory... text file that has the file names of those files that I copied in a list how to add two object in a particular file - Java Beginners these two objects in a particular file using file handling in java....and also wants to retrieve the data of that file.............please help me out...(list1); BufferedWriter out = null; try { File file = new File Advertisements If you enjoyed this post then why not add us on Google+? Add us to your Circles
http://www.roseindia.net/tutorialhelp/comment/82300
CC-MAIN-2015-22
refinedweb
1,456
70.33
#include <hallo.h> * John Goerzen [Wed, Aug 02 2006, 04:12:50PM]: > Because everyone knows how to use cp and diff, and because I get diffs > sent to the BTS all the time. It works. And it has nothing to do with > VCS -- it's just Debian packages. Bingo. Therefore, your efforts to use the regular process as an argument supporting darcs' patch management are pointless. > > And if the user has more than one patch which needs to be maintained > > separately, is it still is still trivial FOR HIM? (or her) > > Who is the user? A system admin adding 3-5 extra patches to his local package installation? Eduard. -- <weasel> .oO( Graphischer installier fuer Debian: ein xterm und drinnen d-i ) <Ganneff> weasel: ATERM! <weasel> s/xterm/x-terminal-emulator/
https://lists.debian.org/debian-devel/2006/08/msg00172.html
CC-MAIN-2018-05
refinedweb
130
62.58
cin.get()to the end of the program, before the end of main, but it still closes after the last for loop?? I'm confused because the .exe file works fine on my laptop. system("pause");ever. Especially in this case if the OP is going to use this maybe in his office to help with claim related information. So since system() anything is proven to have major security issues along with other issues it would be a very bad thing to use. Most AV's will give warnings because of system() anything. #include <limits>. other then that the code should work, let me know if you run into any other problems.
http://www.cplusplus.com/forum/beginner/96117/
CC-MAIN-2017-22
refinedweb
112
73.07
Introduction You might be thinking: how is consuming WebServices in ABAP really related to BSP. Is it because the WebAS and the ICM (Internet Communication Manager) are at the core of both technologies? Or perhaps it is because you might describe Consuming WebServices in ABAP as BSP turned inside out? When it comes right down to it, I included this in BSP Weblog because for me using WebServices just goes hand-in-hand with the applications that I happen to be developing in BSP. But don’t feel that this technology is limited to BSP. In fact all the samples I am going to share today run within good old traditional ABAP. There is even one with – gasp – just plain List Output (talk about combining old technology with new!). Release 620 First off there is no easy, good way of consuming SOAP WebServices in 620. There is a client API realized as an ABAP Class Library. But if you read the SOAP Processor section on the service marketplace , you see that this method in 620 is basically incompatible with release 640. You have to work directly with the SOAP request at a fairly low level in the 620 API because proxy generation is not supported. All this and then you read the statement: applications based on this interface therefore will face a considerable migration workload. Automatic conversion will not be possible. Well that was enough to convince me to wait until 640 for full SOAP WebServices. I was faced with a problem. I have a requirement to build an application that sends SMS messages to cell phones in Poland. Our SMS provider was only giving me the option of interfacing via a SOAP WebService. I needed the working interface up in running by September 2004. But at this time, our 640 upgrade was more than 6 months away. I didn’t even have a copy of the install media yet! But as people in the area I live in are prone to say, there is more than one way to skin a cat (makes you wonder what we do for fun around here). In 620 I may not have a good SOAP WebService client, but I do have a HTTP Client. Meaning I can make HTTP requests and process the response from ABAP. So why not simplify the interface by removing the SOAP. We make a request and on the URL we specify certain parameters (SMS Number, Priority, Message, etc). The service provider processes the request and sends us back a confirmation number and status in the response object. Little did we know at the time that we were flirting in the SOAP vs. REST area of WebServices. Now I have never been the type of person to get involved in theoretical debates about the potential uses of technology. I’m more of Git-‘R-Done kind of guy. Does the solution meet the requirements, budget, and timeline? Can I support it after we go live. If yes – then I say go for it. If you are interested in the SOAP vs. REST debate you can find plenty of articles on the web (and a few right here in SDN). Configuration Before we could really get started with this solution, we needed to configure a few things in the WebAS of course. First we will be passing HTTP(s) out of our Corporate Network, across the public Internet, and finally reaching our Service Provider (hopefully!). That means that like most corporations, we needed to configure our proxy settings for passing through the firewall. You can find these settings in Transaction SICF under GOTO->HTTP Client Proxy. You can probably just copy the same settings that you find in your web browser to complete these settings. If not have a chat with your network administrator. We are going to be using HTTPS for our communication. Therefore we need to add our provider’s certificate to our Trust Manager. We can do this from transaction STRUST. Choose Environment->SSL Client Identities from the menu. This screen allows us to create a short SSL ID that we will attach our certificate to. We will also use this same ID later in our ABAP code to include this certificate in our HTTP Processing. We can return to the main screen in STRUST and upload their certificate. I had already navigated to the HTTPS URL that we would be using with my Internet Explorer browser. Therefore all I had to do was go into Certificates Listing in IE and Export the certificate. If you export as DER encoded binary X.509 (.CER) this matches up to the import option in SAP of File Format Binary. !! !! !! You then should see your certificate under your SSL ID with a green light. !! Coding We are ready to look at the coding now. We will break it down into little parts so that is can be easily digested. First I implemented this functionality as a function module so that it can be called via RFC from our 46C R/3 system. I take in the SMS number, the Message Class, the Message, and the Priority as importing parameters. I then pass back the unique SMS confirmation number, the status and the entire HTTP response as a string. *”—- ““Local interface: *” IMPORTING *” VALUE(SMS_NUMBER) TYPE AD_PAGNMBR *” VALUE(CLASS) TYPE CHAR1 DEFAULT 1 *” VALUE(MESSAGE) TYPE STRING *” VALUE(PRIORITY) TYPE CHAR1 DEFAULT 3 *” EXPORTING *” VALUE(SMS_ID) TYPE ZZES_SMS_ID *” VALUE(STATUS) TYPE ZZES_SMS_RESULT_STATUS *” VALUE(P_CONTENT) TYPE STRING *” EXCEPTIONS *” MESSAGE_TOO_LONG *” UNKNOWN_ERROR *”—- I wanted to make it easy to support different SMS providers or to make changes to the URL and SSL_ID; so ended up setting up everything in a configuration table. !! So we can then start of function module with a little bit of code to read the configuration settings from the config table. ****Lookup the setting for Webt data: page_srv type zes_sms_page_srv. select single * from zes_sms_page_srv into page_srv where serv = ‘WEBT’. Next up I want to perform some checks on the input data. First I will check to make sure the message isn’t too long. Next up I want to check for Polish Characters. Even though we are going through a Polish SMS provider, they asked us not to send any Polish National Characters. So we will use some SAP function modules to check the codepage of the string and then transliterate any national characters back to ASCII7. Finally we will replace any + in the SMS number and remove any spaces. ****Check the Lenght of the Message data: msg_len type i. msg_len = numofchar( message ). if msg_len > page_srv-max_chars. status = ’21’. raise message_too_long. endif.****Check Character set of the incomming message data: is_ok type scpuserec. call function ‘SCP_CHECK_CHARSET_OF_STRING’ exporting text = message langu = ‘E’ importing is_ok = is_ok exceptions internal_error = 1 fields_not_char = 2 overflow = 3 others = 4. if sy-subrc <> 0 or is_ok is initial.****Lookup the Codepage for Polish data: i_codepage type cpcodepage. call function ‘SCP_CODEPAGE_FOR_LANGUAGE’ exporting language = ‘L’ importing codepage = i_codepage exceptions no_codepage = 1 others = 2. call function ‘SCP_REPLACE_STRANGE_CHARS’ exporting intext = message in_cp = i_codepage importing outtext = message exceptions invalid_codepage = 1 codepage_mismatch = 2 internal_error = 3 cannot_convert = 4 fields_not_type_c = 5 others = 6. endif.****Check the recipient Number replace all occurrences of ‘+’ in sms_number with ‘ ‘. condense sms_number no-gaps. Next up is where things get really interesting. We will build our full Request URL by adding on all of the outbound parameters. We create the client object for this URL. data: client type ref to if_http_client, url type string.****Build the Sending URL concatenate page_srv-send_url `&Message=` message `&Class=` class `&Number=` sms_number `&Priority=` priority `&Project=` page_srv-project_name `&Sendingnumber=` page_srv-sending_number into url.****Create the HTTP client call method cl_http_client=>create_by_url exporting url = url ssl_id = page_srv-ssl_id importing client = client exceptions others = 1. Next up we set our request type to ‘GET’ and start the HTTP communications. ****Set the Request type to GET client->request->set_header_field( name = ‘~request_method’ value = ‘GET’ ). “#EC *****Make the call client->send( ). Now we are ready to receive the response back. We read it in character format. We then pull out the return parameters from this response block. ****Receive the Response Object call method client->receive exceptions http_communication_failure = 1 http_invalid_state = 2 http_processing_failed = 3 others = 4.****Get the response content in Character format p_content = client->response->get_cdata( ). data: result_string type string, id_string type string, junk type string.****Pull out the Result and the ID split p_content at `&` into result_string id_string. if result_string cs `Result`. split result_string at `=` into junk status. else. raise unknown_error. endif. In the end we have fairly simple approach to what could have been a complex problem. We leverage the ability of the WebAS to act as an HTTP client and create an end result that functions very much like a WebService. Release 640 If you really had your heart set on consuming SOAP WebServices from ABAP, you aren’t out of luck. WebAS 640 comes along and makes the process relatively painless by offering the ability to generate proxy classes. Since this technology is so new, I thought I might just build and walkthough a complete example here. I wanted to use a public webservice that was available for free for several reasons. First I wanted to demonstrate how flexible the technology was. Second I wanted anyone with a 640 system to be able to recreate the steps in this weblog on their own with the same webservice. I found a nice collection of webservices at the following web address: . I finally decided upon a simple service that returns book information when given an ISBN. It even gives us the current price of the book at several on-line retailers. The Service Description can be found here: . Now that we have our webservice picked out, we are ready to generate our ABAP Proxy. To get the process started, we turn to our old friend SE80. From the Enterprise Services Tab, we are going to select Client Proxy and then hit create. !! Next up we have to choose where our WSDL file is going to come from. We could connect directly to a UDDI server or XI repository and query for our object. Or we might have saved the WSDL definition to a file on our local machine. But in this case we are going to connect directly to the WSDL definition using the URL that we got from our on-line search. !! !! Now we are asked what Package (Development Class for those you upgrading from 46C or lower) we want to place the generated object in as well as what prefix we want to use. I’m just playing around so I am going to make the object Local Private by putting in my $TMP package. To follow SAP naming standards, as well as my company’s standards, I will get the object a prefix of ZES_ (In case you are wondering – the object starts with Z to follow SAP’s naming standard for customer development. The next letter E standard for Electronics – the division I work for. Finally the S stands for Basis – the application area that this development belongs to.) !! We have our generated Client Proxy. The following are some screen shots of what this should look like in SE80. You can see that not only do we have an ABAP class, but the process also generated structures and table types to represent all the importing and exporting data. !! !! There is only one last thing we need to do to our Client Proxy before we are ready to use it: we need to configure a Logical Port for it. We can do this in transaction LPCONFIG. We can configure more than one Logical Port and specify the one we want at runtime. However for this solution we will just configure one port and make it the default. !! Inside the definition of the Logical Port we can adjust settings for the Client Proxy such as the URL we going to call, the logging, State Management, etc. Since this is the default Logical Port, we will just save it with all the settings that were imported from the WSDL definition. !! We can then return to SE80 and perform a test on the WebService by hitting F8. We then get a dialog that allows us to set parameters for our test. !! We then choose which method we want to invoke. We are going to be using the GET_INFO method later in our example, so let’s test that. !! Hopefully you get a success message like the following: Once everything checks out OK in the test tool, we are ready to start programming against our Client Proxy. The following program example has one parameter for supplying the ISBN. We then take this parameter and use it to fill out the request object for our Client Proxy. After the call to the Client Proxy, all the returned data is contained in our response object. The response object has the format of the generated table types and structures as defined in the WSDL file. We can loop through this data and process as we see fit. For this case we are just going to output a simple ABAP list. PARAMETER: p_isbn(100) TYPE c OBLIGATORY. DATA: Reference variables for proxy and exception class lo_clientproxy TYPE REF TO zes_co_looky_book_service_soap, lo_sys_exception TYPE REF TO cx_ai_system_fault, Structures to set and get message content ls_request TYPE zes_get_info_soap_in, ls_response TYPE zes_get_info_soap_out. ****Set the input parameter ISBN into the Request of the SOAP Object ls_request-isbn = p_isbn. ****Create the Proxy and Clall it. CREATE OBJECT lo_clientproxy. TRY. CALL METHOD lo_clientproxy->get_info EXPORTING input = ls_request IMPORTING output = ls_response. CATCH cx_ai_system_fault INTO lo_sys_exception. Error handling ENDTRY. COMMIT WORK. ****Write Out the Basic Information WRITE: / ‘ISBN:’, ls_response-get_info_result-isbn. WRITE: / ‘Title: ‘, ls_response-get_info_result-title. WRITE: / ‘Author: ‘, ls_response-get_info_result-author. WRITE: / ‘Publish Date: ‘, ls_response-get_info_result-pubdate. WRITE: / ‘Publisher: ‘, ls_response-get_info_result-publisher. WRITE: / ‘Format: ‘, ls_response-get_info_result-format. ****Loop through the listing of Vendor Prices and output each one FIELD-SYMBOLS What I showed you here today is the tip of the iceberg for this technology. The possibilities for connecting applications through WebServices (even with different implementing technologies) are quite exciting. This is just one of the many new areas of NetWeaver that we all have to look forward to. My objective is to get an SAP system integrated via the ABAP stack and not the java stack. The application being connected to is generating complex WSDL files. Has anyone been able to solve the liimitations of the proxy generator? For instance, when the “extension” element is used or when recursion is defined. Do i need to use the SOAP framework to solve this problem? Any help would be greatly appreciated. Best regards Marcus If you can’t find such a solution, I might suggest that you open a problem with SAP. You might just find out that the ABAP Soap runtime doesn’t support such structures. On the other hand, this might make SAP aware that such features are required by their customers. Did you get any solution for this problem as I am exactly facing the same problem(I have some extension tags in my wsdls). I am glad to know if you get any kind of solution waither from SAP or anybody else. If you get any efficient and quicker solution for this problem please send me that to venkatmarni@gmail.com thanks in advance. Regards, Venkat Marni thanks for this great weblog! It really helped me to get started in this matter. Unfortunately I receive an error when testing the generated proxy (using the “test-functionallity” in SE80). I get a “SaupFaultCode:1” with the following error-text: Found 0 operation definitions using keys: Key name:’first-body-element-ns’ key value:’urn:EdilogUserManagementWebserviceWsd/EdilogUserManagementWebserviceVi/document’; Key name:’SoapRequestWrapper’ key value:’getDisplayName’; Do You have an idea whta might cause this error? Thanks in advance, Regards Jan Hempel the webservice is running on one of our SAP-J2EE, I have written it by myself. I have tested it with the testing-tool of the Netweaver-Developer-Studio (which I used to create this weservice), and it is working fine there. I followed Your suggestion with the tracing. Basically two things are conspicious: After sending the soap-message to the server I receive an internal server error: XRFC> INFO 09:22:52: SOAP HTTP Binding CL_SOAP_HTTP_TPBND_ROOT->HANDLE XRFC> _STATUS_CODE() Received return code 500 ( Internal Server Error ) The soap-message which is then received from the server says that there is a security-exception: com.sap.security.core.server.ws.service.WSSecurityException Starnge thing, because I did not set up any security-settings for the webservice when devolping it. It has no Authentication, no Authorization. Regards Jan Hempel This is probably due to the restricted fieldlength of ABAP-programnames. Regards Jan Hempel Thanks a lot for the weblogs! It’s really helpful. But I come to a situation that I need to create an abap client to consume some stateful web services, which I implemented by JAX-RPC. In java, JAX-RPC requires client to special stub property. How can I do that in abap? In general, how to create and consume stateful ws in abap? Thanks a lot! Song After you generate your proxy client, you should go to the preconfiguration tab. On this tab you can set your stub properties (such as authentication, transport guarantee, message id, etc). On of the options is for Session-Oriented Communication. You should just have to select this feature and activate the proxy. Thanks a lot for your reply. I did set the session property as Session-Oriented Communication. But it still works as stateless. I found another place need to set is in creating Logical Port. It seems I need selecting the State Management checkbox activates state management by means of http cookies. Dose it make sense to you? then there is a problem is that it only work with choosing HTTP destination in Call Parameters section. Then my question is: how can I change from url to HTTP destionation? I can’t create http destionation for my url of wsdl file, since it’s a query string. Thanks a lot! Song I’m also not suprised that you must setup an HTTP destination. Anything beyond a basic anonymous setup generally requires an HTTP destination. As to setting up the HTTP destination – have a look at the following weblog: Calling WebServices from ABAP via HTTPS In it, I just took the URL that had been stored in the Logical Port and broke it up into the separate fields of the HTTP Connection. Thanks for your reply. It’s very helpful. Following your instruction, I regenerated the client proxy with session feature checked and setup the Logical Port with state management and Http destination. But it still doesn’t work statefully. My abap code is trying to consume a email WS, which is stateful to keep a mail session alive as long as the user doesn’t close it. In my abap client side it seems still working stateless as: after “CALL METHOD mail_proxy->open_mail_session” to open a mail session, the “CALL METHOD mail_proxy->open_mail_store” throws an exception: “ICF Error when receiving the response: HTTP COMMUNICATION FAILURE”. Do you have any idea about it? Is it still the client proxy or logical port stateful setting problem? Thank you very much! Song Thanks a lot for the tutorial about webservices, I was able to create a client proxy based on the XI Repository but when executing the generated method I always get a popup for entering user and password. The popup has following info Resource XISOAPApps username ….. Is it possible the define a default user & password? Or determine the user & password at runtime? The sap system I use is a 2004s Thanks a lot, Vincent. Calling WebServices from ABAP via HTTPS Thanks a lot, Vincent. Is it possible to give this information in the client consumption program itself ? I came across this blog and wanted to use it in one of the scenarions in our project. I am trying to get stock price by consuming a web service but I get the error when I try to do it. HTTP error (return code 400, message “ICM_HTTP_CONNECTION_FAILED”) I tried the same books example to start with. Is there any setting which needs to be done before I can use this? Thanks, Kiran That is usually the most likely suspect. However you might check the HTTP logs (transaction SMICM) to see if they have more details. A 400 HTTP error according to the w3.org is a Bad Request: 10.4.1 400 Bad Request The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications. When I go to the SICF transaction and to client proxy config, I see two check boxes 1. Proxy Setting Active 2. No Proxy setting for Local Server None these are ticked, and below these two I see a table which says “No proxies for the following addresses” where I can enter entries which can be filtered from proxy settings… If I enter my webservice in those filter address, will it solve the problem? Or what exactly should I configure here? The other option I have is to download the WSDL file and upload it into WebAS. How can I download the WSDL? When I tried doing that it gave me error saying “text format not allowed”. Thanks, Kiran As far a downloading the WSDL file, that depends upon where you are getting the file from. Different sites will have different mechanisms. I ususally view the WSDL file in my browser (it is just XML) and the do a Save As to get the file local. However loading the WSDL file locally, isn’t going to help you get around your proxy problem. The WSDL is just the service definition, you still need to pass through the firewall when you make the Web Service call itself. Thanks Kiran Hi Thomas,Benjamin Hindelang This might get your proxy to generate, but then what happens at runtime. The proxy class encounters something different than what it expected – since the source webservice hasn’t changed. That is exactly the situation you have here – the proxy doesn’t match the web service it is calling and therefore produces an error. If the source Web Service is structured in such a way that you can’t generate a proxy for it, then you can’t expect to call it at runtime. You need to change the source webservice settings, not just the WSDL defition of the webservice. The webservice settings can’t be that wrong, because the the nwds webservice test tool copes with it and even a simple java client is without any problems able to call the service. But in both ways I’ve got a support for rpc encoded wsdls. Obviously, as mentioned in some sdn forums, r/3 does only support document/literal but not rpc/encoded wsdls. So if I can’t do anything at generation time, I have only two possibilities left: 1. not using soap with attachments but simple soap and having a large amount of bytes in my soap body. 2. making an rfc call to ejb which provides the webservice. Both ways are not really what I wanted to do, but if there’s no other way. Maybe you have another solution for my problem. Regards, Benjamin First of all, I’d like to thank you for all your very comprehensive blogs about this subject, they’ve helped me so much. I’ve followed this page step by step (the 6.40 part) in order to consume an external Web Service. The WS I’m using is a very simple one I found on xmethods, ‘Quote of the day’, which requires no input (minimizing the areas I might make a mistake in…) At first I had a connection problem (HTTP error 400, which many have had) which I’ve fixed by entering all the correct proxy info. Now, after I’ve created the client proxy, created the logical port for it, and activated both, I test them just as you suggest by hitting F8. This is where I’m stuck, I get an ERROR_WEBSERVICE_RUNTIME_INIT error message. I’ve tried looking up this error, and have found nothing on SDN, google, or CSS notes. I was wondering if you’ve ever encountered this problem and if you know what the reason for this error is? I’ve tried it with other webservices (to see if the error is maybe due to the WS itself?) and have gotten the same error, so I guess the error is coming from my side… I’d like to find out if the error is due to something I might have done wrong while creating the proxy object (I won’t bore you with the details of my step by step procedure unless you’re curious) or whether this error indicates to some wrong settings in my system, or maybe some missing building blocks? I have no clue … Thanks in advance, Micol Lazar I would suggest two things. First turn on trace for that logical port and try and run it again. The trace will hopefully give you a better description of what is going wrong or at least where it is going wrong. Also have you tried consuming a webservice from the J2EE stack or even from the same ABAP system? This would give you an even more controlled enviornment. You final option is to go ahead and open a support issue with SAP on the issue. They can connect to your system and see exactly what is going on. I’ve applied the process on WAS640 and I’ve got the same error message when testing the WS. “… ERROR_WEBSERVICE_RUNTIME_INIT …” Please help if you succeed in going through. Thanks. Philippe Hello Thomas, Thilo I found a workaround for that specific problem. When debugging the ABAP code I discovered a bug that causes this error. The framework cannot handle tags correctly. When using complexTypes, it works fine. I will open a CSN note for that issue. Best regards, Thilo Is there any cure for this issue? -I really need to make a WS client from wsdl that generated by JBoss… Thanx a lot. Your inquiry should be turned in as a formal support ticket however so that they can determine if this is a problem with the proxy generation on the ABAP side. My SAP version is 6.20 and i use your example to access an http web. Can you help me to describe the connection type ‘G’ in the SM59? Thanks for your help. Géraldine LAVENANT. Can you help me on this exception . Thanks . Thanks for your help : The subrc equal 0 now. Other question : I Get the response content in Character format but can i have an XML document in my version 6.20 Your going to get whatever format the response body was sent in. If it is actually XML in a character string then just use the iXML library to import the stream and then you can process it as XML. My version SAP is 6.20. Can i receive a pdf file to an external application HTML? I want to receive the pdf file and i want to save the pdf file in a change document (CV01N). Thanks a lot. I receive the xml document :<br/>—- <br/> <?xml version=”1.0″ encoding=”UTF-8″ ?> <br/>- <resultatCalculPrix><br/>- <codeRetour><br/> <code>0</code> <br/> <message>tout va bien</message> <br/> </codeRetour><br/> <prix>140.47</prix> <br/> <structureFormulePrix>JVBERi0xLjQKJeLjz9MKNSAwIG9iaiA8PC9GaWx0ZXIvRmxhdGVEZWNvZGUvVHlwZS9YT2JqZWN0L0xlbmd0aCA5NDEvQml0c1BlckNvbXBvbmVudCA0L0hlaWdodCA1OS9Db2xvclNwYWNlWy9JbmRleGVkL0RldmljZVJHQiAxNSj1ztb99PbbUm3GABfTLE3tqLXJBCPic4j76u3plabOFDbxucTlgZX43OHKACf///8pXS9TdWJ0eXBlL0ltYWdlL1dpZHRoIDk5Pj5zdHJlYW0KeJztlk1oE0EUgCOKgiIVqaCCRAgWUSSSiSlGWdD0RzwoUlqPBdeukuqCRESKUAQPsSo51HtbUqNGLHjxYJEgCooWEkUUlJjDyh5EHrOhIakxjO/NplqzJd1exbnsvpn99v3OmxFisfF5enq6sOiK4ItPxhjh5ZDVHUA2Lccoqgg8W05xGoEwBhbBtFFBNxzT1QVMIYAzrgnZgGCZQXCCddEH8Dig7GsFvCQjcmRAzgrFuipIA5Jj4AtLslWhXKBTpiFlwSPTLfPAXgd0dYKTCO4BMdGXRHzCl2ukcAAu6IrToEvfgs62BmxFMXxHPMhrRuCszOXQ41TqKSomzQGAXQWPfSxEZDRqPAcwd3qWJEcXeGbWLU1i/Gce6k3hu775NXYzhHnFuXQdRmaJsWGtU3bjbVo9Bc6JI2bBuMzBOtfwAiDoq3kF8wGxUXjDdaCIOaz47JKEDD7a9JQQAEz4ti6jUQNs2HqZBJJWJMHlyLKimwjgX4pYd2bjY40Equpt0H4hC2VUFtjxTcSPgJCFbFCMB4c4KTUWz7b7nPWfENRBGNMu78kWd10DJNiceYv/YFvlKv8zcl2lJatGWBbLWlog1bt4HI5OFvya25fNvmxIuxn/iXyCqV17ZwskZHG8FaZkaNf3JyhhS0vqTo/zrTUiVZWP77oNsLYA5qWb8wvNrIxFFcG7WV/nejR6ew73RHR0dSRYHDJL52DAuuHqeFA0JeVgZtwkp2q8M28XDz1avvGApcvRzfHI97heUbII3UTGfDQwGvJMosmzwviRidAlzz0zfDdUf7TntFUSXTgIbWUYSIFEj2Ij4gSWcvVnfl8Pkd/DrWIT8EEnfKD3DguiVg79qVcgYj7vb29Q/JHelSLaimMTRV/EKM2V1X9om3Qg0QlOSFKoXQ/EZpqAKPmwXUZK4pm195aklppKyr7Er6LRFnJVl4rA9IPU9NUuc5sRtvitOUmp7AHMvKp7geMZ8h8Sl8wxe4RFEQvvFb8Sch8pKr857jv1eFaDE1voZ1Jw8hEfsaCWRmQ5m65yVtQCyMFR7vxygucph1ili5wSv6UbwBPonE0X2jqK9aNUODEIvOWdFFIr9Vt24nxBrgwVeVMLPcCJyYJ4os4ekQ9MVRZWHx6jUN2qcwRAXWZa/Th6SeTaOsluo5Yu04lBE/LQbK4lkallaOTFJFagjPeewa9iCRk1ww7qEsDxySJmvp2L2rJDf5R7xXx3aGfQKZW5kc3RyZWFtCmVuZG9iago2IDAgb2JqIDw8L0ZpbHRlci9GbGF0ZURlY29kZS9MZW5ndGggMTkzNj4c3RyZWFtCnicnVrBcts4Er3rK3C0J2UKAAGCjE9xHKdmaz2jWUuprVpNpRiJsjlDSQktZT2fnG/YyzZASqSJR1ucgxOK/br79WMTbELiTLALwTjTiaZ/FvRt9HVdCQ10zwJDJsuR5wAuj6I48MZIeujMOoeGIfMB39RsHsn2T/oPMf6ZhC22ScssqYqSS2Kdaj8Y1ggrPpanQ2KfMntt/kuzQvM/aWnU//ILM8mIXigTJsdnc9/vNNp7dRBZAudqREwlD/7ZPN7t894Nttut8kxYgvCYROA/oj/WG1zqC4d/8MZZkjKRCvLuA71bcQDo2WiWPf/8t4Kr6KIYhsqQoSszEarZxoK9l8EujsaQkGG9SgWpj4uyOgpH4cH/keuQEgCGt4UGjvc3a7cL3Z7ujrLjK225XpfuMOvdOVwDK09sX7Zrn217m4mjCRn8zM5P/dDKalgrH/mX7KiOHHu82fsqXltchcXInpKe6FnG1snyyzR/atbppHP3xvhziiIOp19j1/BF3X9EaHmfCLvakF94JcTZ7YTxqwt6QfuKCPs7P6QR1vxsslpertMnOliUl7eTflR3teaMUxsoygVH5vxBbwmTOUQcnWKg00QW52ikBxMggudFjjpeKnOBD32iECe/qHUBIG1PjRXRSAhManxBYDbpXqVoN0OU4rhMd3tV5XDqPFKysgDJWslRLCRCZQHVNnQjgmi846uM0C6zoLooliOrjNAuiiWpatVDy1ngLScBdFCsRwtZ4C0UCxLSwmsIjrv6DoDpOssiC6K5eg6A6SLYlm6MsZ00XlH1xkgXWdBdFEsR9cZIF0Uy9J1yzWgi847us4A6ToLootiObrOAOmiWESX1pgqlBTP6MLzlm5lsHTbFku3ssSNoTtvhInpjhGf0jJPvxT0iM03u6xcZ8vcjnyPYOAS0csBFtvNrkx34EEcB5GgNUV1fWn88NGCx0EcIng9YYCHtCZaErnUz2k0HIhAGuTyiUbSfQnqD6MhZURKDS3DRHogJ3tNjWhmyAr98XrCfSwNqSdjBQ3XALze/pVtNtncev1neik5jy7D3y9bnSzTJ3NECGCQwuhAlEwqPI9PSe73KFuGu6ARA2pZlv4oZQ4gZyGAX9hNT2RQRrr2OgJ6nUo6gP7yh6IQ76XRyVvAj7VfQDCkE3m9I9Evp4GlB7JARYK2E1xz8pCW4q5yGviO9LOoeBZX2GeHeBciGT/a46NEcJeA0kVcXaoz734nrewoZBVoLqfpa1HehmbvR33wTbHdlq83KSCmeXThhKQwhr70PdZXuSbeytw0KMwjHaxL6r0CKII6ES9MovcLZF2Sdxfz2viuy7xi9oLBLACmvsQ6vL3t/CMPhpAvuuVEWSSJPEPfr6Hu3m+z8NcYb8NYmZFPtlrZieB7Vj7m2w2bsTGDAZzYfgAehLE0MsRy86iLv1ZNQAyLf/M3JTSwsnDTtLZIi0WyLdZeAWcVfDjzg/u/u63X2ehTzPHuiQluKsTfMGe0pa3zTTmzjNZmrIDfR52mZLrNptniYn4/BZom7sD4LYWhsECbWyYmbCtI97No7XK/g3cIen7QHIQhT4dVpL/1ah4MSREoMwhuZHjwDt8VpZnTnzvX8zgos34Z8OupDIB4/ZLgM/QneGlae1GHW1/u2rjb7vcL3Z0s4FhlNvRVUay6wxH11ByO7oCeO/oSu8AdfIZfKjzLfLfJHvgFtkQjvxArdnErnRzqYZ0s5bBOdvghnTwggWuIAXjXJ1086uSOKE0nP3dudXKnzFYnIxdAvNXJXYPXyWHSvebTdP9kO3nxkG7uwXRZd7GMBnWxD31i32Xk7rYdxvUxSJJBnWxiKNBXVzhB3TxkAS2GYbgbY94eNDFXVGOXdxxbrq4W2bTxdAFEG6GBpschP2JDdhX3Lk4pIjg0uODDZ5xHuSOwNMjlxccmRwyZHBJlemJ7kzwOTIxSVHBpe8a/AWDx52b7WfN3R70ti2L0Ssk7LxQO6Vd0SIhLv67SXlhAAf20JAS6nLCHA7YWtH2GOu3GHIbA9iIL5lQb8wU72i1bgdLvNwSZhpBQCR3YPBczoURo7Vy8eWR2REaFx4pWEM9ZPcUPtTJFe47vVC4DxYyiPoK99Evf59OdWtve8p/aeip/u5Og181xc08MEiMv1X34f7InxDDwYt3dcuIg7sV9tBezVSIZ2r7Gu79378VBxshjcWOi6affpezwb9mqdJAtmiRNxZlNAnW7USdKDokWYLsMWxZqN8/U9Z9db9myVa4NInzrCdDm6aA47qxVxSEKmbYm686uCX1erMmNXs1v24fqGvWVcjIUc20PNreK00trrTnaa6R3dFsdCgz7VIve3zXAa0l9oxPbO63ng0jsaZHEx9Pdh0AUnvTTibjz1f2Hpf1Rwde0ZNOHPCvLv9jHfV4U28UDfHPSMkhEX5Qiozl2zFWlpIjeav6W4z0LJY9se8iGMQ3s9ncz3vbLKl9mm12eFezdvz58eneUkpyb8o8XKw4DunFVtakgxgc0OwISEVjFVdV9/17JqvnD7vw5mEKZW5kc3RyZWFtCmVuZG9iago4IDAgb2JqPDwvVHlwZS9QYWdlL0NvbnRlbnRzIDYgOSAwIG9iaiA8PC9GaWx0ZXIvRmxhdGVEZWNvZGUvTGVuZ3RoIDk5MD4c3RyZWFtCniclZfLcts4EEX3/Ars4iwMofEgCGflxI/KVDKTB52aqkkWjkQ5TChpwtg1NZsv0iDFCTZQMPyxqZ0xI4FwTREgzYMTDBjDP4d7oofhYv60IaZoTjltWzQmABaH91XhfvURfcGuk0e/i/v/EXZXos04yUKxvivlj9VZhfaV5VR7iAJwWVo4uWckDbcpJbuGpg2lrubFPdZlScq2e6iq15dI91WWV5Lg4KZdfKsnwPW7LID9l1qbj1sh8o8Snfaok7GOMpnfKJNBjTKZyCiT6DuqUmSpBjlDRdgDFSEHKkIOVIQcqAjZUENclSDnKEi7IGKkAMVIQcqQg5UhOyplM5SDXKGirAHKkIOVIQcqAg5UBGyp5KQpRrkDBVhD1SEHKgIOVARcqAiZE8lqizVIGeoCHugIuRARciBipADFSEjlXImRzXKNBVl31BR8oaKkjdUlLyhSsnv/TnuT3aBR7ysmHbjVIviskFsIrV8Lo9XLWThs2e9Yu5931bbtaPq/1Nz2kcF/4laxa/1wt4mqpHAdIlb9pvzZdt44tGgwHl7K8W/ftCmfY3qZsleKqStlOl8s1QjWsX8/XfbOcNgmqEgPLDPqYv0SjS/o/XXfNXZ9IBuda6lAtN9WXZ/qV9IIcoX6ktsApDjQZUyxuXDYwCp8rpvF82v2z6BoisxnmaRSct0cMPhRg/BIJGXEeOhF9kArO9m0oEZyAQmM4EljXRgcfkBgcWmXGCZIXKBxTYfGGiVDkxVmcAgE1jSSAcWlx8QWGzKBZYZIhdYbAMoOe7XdGDSpAM7zoWVNNFhxeUHhBWbcmFlhsiFFdsAKl5qkw4L8dNh5bZi0kSHFZcfEFZsyoWVGSIXVmzLhaWcI8LKvOjTJjKsRPnjYSVMmbByQ2TCStjuh/Uz9fPUSH88EL/7uf7PZhWN2oL7DrsdtPXdCs2Cl43W07JEs6d9WPOa3jcm9KOHdWOvzkoTXghUZeDB/X08XbNIubgQ7W7F7XdhEWazuUM9K453lw8WGufgFDMe0YQ8QQyB/jWf4xq8vHrLzs8u2AkTMAE5wTe9ZZPrj6esQn7cXM1ubooPzPF8pq4elSN04zwbUbkXvFybXUmtsHTUDs9fLjYPv3LV9uuHTWqpDpmLrkLPtak6n2GPyP697ln9rW36/n92edd23Wr6LdXSlkZyB9Rduga72InQY5JQnhhxIojjVm5nS0xWVcNGxR1xby8Wi3n7axZ3rZNx04/nH863UaJ5h3drGw2cUtqYcFOJKTUM22BQ64T1yPT9/fczkfL8BYY0fQplbmRzdHJlYW0KZW5kb2JqCjEwIDAgb2JqPDwvVHlwZS9QYWdlL0NvbnRlbnRzIDkgNCAwIG9iajw8L1R5cGUvRm9udC9CYXNlRm9udC9IZWx2ZXRpY2EvU3VidHlwZS9UeXBlMS9FbmNvZGluZy9XaW5BbnNpRW5jb2RpbmcPgplbmRvYmoKMyAwIG9iajw8L1R5cGUvRm9udC9CYXNlRm9udC9IZWx2ZXRpY2EtQm9sZC9TdWJ0eXBlL1R5cGUxL0VuY29kaW5nL1dpbkFuc2lFbmNvZGluZz4CmVuZG9iagoxIDAgb2JqIDw8L01hdHJpeCBbMSAwIDAgMSAwIDBdL0ZpbHRlci9GbGF0ZURlY29kZS9UeXBlL1hPYmplY3QvRm9ybVR5cGUgMS9MZW5ndGggXT4L1N1YnR5cGUvRm9ybS9CQm94Wy0yMCAtMjAgMTAwIDEwMF0PnN0cmVhbQp4nAMAAAAAAQplbmRzdHJlYW0KZW5kb2JqCjIgMCBvYmogPDwvTWF0cml4IFsxIDAgMCAxIDAgMF0vRmlsdGVyL0ZsYXRlRGVjb2RlL1R5cGUvWE9iamVjdC9Gb3JtVHlwZSAxL0xlbmd0aCAzXS9Gb250PDwvRjIgNCAwIFIPj4L1N1YnR5cGUvRm9ybS9CQm94Wy0yMCAtMjAgMTAwIDEwMF0PnN0cmVhbQp4nHMK4dJ3M1IwNFAISeMyVDAAQggZksulYaQZksXlGsIFAIj4B0gKZW5kc3RyZWFtCmVuZG9iago3IDAgb2JqPDwvQ291bnQgMi9UeXBlL1BhZ2VzL0tpZHNbOCAwIFIgMTAgMCBSXT4CmVuZG9iagoxMSAwIG9iajw8L1R5cGUvQ2F0YWxvZy9QYWdlcyA3IDAgUj4CmVuZG9iagoxMiAwIG9iajw8L1N1YmplY3QoT2ZmcmUgQlVNIEVERiA6IDAxLzEyLzIwMDcgXChVU0QgLyBrZ1UvVUY2XCkpL0tleXdvcmRzKE9mZnJlIEJVTSBFREYgOiAwMS8xMi8yMDA3IFwoVVNEIC8ga2dVL1VGNlwpKS9DcmVhdGlvbkRhdGUoRDoyMDA3MDQyMzE2NTAwMyswMicwMCcpL1RpdGxlKE9mZnJlIEJVTSBFREYgOiAwMS8xMi8yMDA3IFwoVVNEIC8ga2dVL1VGNlwpKS9BdXRob3IoVGhpZXJyeSBHdWlsbG9jaG9uKS9Qcm9kdWNlcihpVGV4dCAxLjQuNiBcKGJ5IGxvd2FnaWUuY29tXCkpL0NyZWF0b3IoVGhpZXJyeSBHdWlsbG9jaG9uKS9Nb2REYXRlKEQ6MjAwNzA0MjMxNjUwMDMrMDInMDAnKT4CmVuZG9iagp4cmVmCjAgMTMKMDAwMDAwMDAwMCA2NTUzNSBmIAowMDAwMDA0ODI5IDAwMDAwIG4gCjAwMDAwMDUwNDEgMDAwMDAgbiAKMDAwMDAwNDczNyAwMDAwMCBuIAowMDAwMDA0NjUwIDAwMDAwIG4gCjAwMDAwMDAwMTUgMDAwMDAgbiAKMDAwMDAwMTE3MiAwMDAwMCBuIAowMDAwMDA1MzAzIDAwMDAwIG4gCjAwMDAwMDMxNzYgMDAwMDAgbiAKMDAwMDAwMzM4NCAwMDAwMCBuIAowMDAwMDA0NDQxIDAwMDAwIG4gCjAwMDAwMDUzNjAgMDAwMDAgbiAKMDAwMDAwNTQwNSAwMDAwMCBuIAp0cmFpbGVyCjw8L0lEIFs8MDZlMzViODNjNjVmNzZmOWRhN2Y4ODBkZGM4MDAxNzYPDU3NjNkNzc0MmUyZWJjYTdkMTZkMzQyOTM3ZjA3MzIxPl0vUm9vdCAxMSAwIFIvU2l6ZSAxMy9JbmZvIDEyIDAgUj4CnN0YXJ0eHJlZgo1NzUzCiUlRU9GCg==</structureFormulePrix> <br/> </resultatCalculPrix><br/><br/>—- <br/><br/>In the resultatCalculPrix>, i want to receive a path or file pdf.<br/>how can i receive the file pdf from an xml document? I’m not sure why you would want to receive a path and filename when it looks like you already have the full PDF in the XML? The binary content of the XML file is in the field structureFormulePrix. You just need to pull this out of the XML (I suggest using the iXML classes) and then you can process it as you see fit. As far as processing it into CV04N – like I said that is very application specific and very far off topic. I suggest you ask that question in the ABAP forum. As I remember the Document Management system has some BAPIs, but the coding is also dependent upon if you use the SAP Content and Cache server in conjunction with CV04N. Oh and in the future it really isn’t necessary to post the entire binary string of the XML into the comments. Most blog authors get their comments via Email – that created one heck of big email that my blackberry had problems dealing with. 🙂 Hi,Regards, Mathias CREATE OBJECT lo_clientproxy. If I wanted to supply the logical port name at runtime, I would just change this code to: CREATE OBJECT lo_clientproxy exporting LOGICAL_PORT_NAME = LPORT. LPORT would need to be a variable of type PRX_LOGICAL_PORT_NAME and contain the name of an existing logical port that had already been configured in LPCONFIG. Thanks for a great bolg. It really helped me to learn in how to consume a webservice. As of now I am facing an error when calling a method from the webservice. Following is the error ‘Index was outside the bounds of the array’. Can you please tell me why this error is coming and is it from SAP end. Thanks in advance for your help. Great tutorial. I was wondering if you know whether it is possible to use a DTD file as opposed to a WSDL file in your second example (Release 6.4). Do you have a similar solution that would consume a webservice using a DTD file? Thanks in advance. I have run into another error while trying to consume a WebService that was created in .NET. When I test the service, I get the following error message: SoapFaultCode:2 This is a little strange, since I previously created a different webservice in the same manner and did not run into any errors while consuming it. Do you have any ideas? Thanks in advance. Error during XML => ABAP conversion (Response Message; error ID: CX_ST_GROUP_MISSING_CASE; (/1SAI/TXS00000000000000000005 XML Bytepos.: 3013 XML Path: root(1)ns1:getEmployeeByPayrollCompanyResponse(1)ns1:result(1)ns_level1MgmtOrg:level1MgmtOrg(11) What is strange is that I seem to only get the error when certain data get returned but for other data I do not get this error, please tell me what this error means and if this is a error on the web services side or on my side in ABAP. Thanks for all your help Thanks for your reply, we have determined the problem, it seems the ABAP conversion routine can not process NULL values in the XML tags. So I asked the service provider to exclude sending fields that have NULL values and this worked. Hi Thomas Hi Thomas, Web Services: The Case of the Missing SOAP Action Header I doubt that overwriting the response payload with the requestion one would work. You would need to set the new URL directly. However if I remember correctly from trying to work with SalesForce.com in the past – there is a set_url method but either didn’t work or wasn’t public – I can’t remember. First of all thank you very much for your valuable time and quick response. You are correct I tried to set the url directly with “set_url” method in transporting binding (CL_WS_TRANSPORT_BINDING). This method doesn’t work. I have gone through your blog “The Case of the Missing SOAP Action Header” and tried getting the response payload(GET_SENT_RESPONSE_PAYLOAD) from WS protocol and set it to request payload (SET_REQUEST_PAYLOAD) of WS protocol. Do you think this should work? In this case, do you think the new url set in request payload will be used in further WS calls to salesforce? Could you please help me pointing any documentation/help on request/response protocol payloads. Thanks, Anil If you want to research it further I suggest you check out the online help: when I was using SalesForce.Com I used the enhancement framework to modify the set_url method so that it worked. I think from memory the correct codeing was commented out. The change was only a line or so. Once I had fixed this method it all worked fine. Cheers Graham Robbo Thanks a lot for the clear explanation. However, when testing the webservice, I don’t receive a success message but: ERROR_WEBSERVICE_RUNTIME_INIT What might be the problem? Hmm, still not working. This ne doesn’t seem as simple as the previous one. I see no references to ‘error_text’ anywhere else.: Then use Transaction ST11 to view the trace: SoapFaultCode:1 It seems like my first parameter is used as name of a method. I am also getting the same error ..How did you overcome error? .Please advise. Thanks Kris The Error that I mention here is SRT: Invalid settings in Web Service Registry detected ESRT_LPREG 043 Thanks kris There is raised an exception of type CX_SOAP_CORE: E_TEXT = SRT: Invalid settings in Web Service Registry detected E_ID = 1019 E_FAUL_LOCATION = 1 As a way to give back I wanted to post here a tracing tip i’ve discovered for WS client debugging purposes, which is an (easier?) alternative to activating tracing in LPCONFIG and then checking system logs: If you go inside method CL_PROXY_FRAMEWORK->WS_CALL_OUTBOUND( ) -which is called by the client proxies-, you’ll see there (among other coding) this method calls: ws_process_payload( ). <– This creates the XML request payload ws_process_call( ). <– This invokes the service ws_process_payload( ). <– This receives the XML response payload Now, if you put a breakpoint inside method ws_process_payload( ) you’ll see there’s a local variable L_SHOW, set that to ‘X’, and when you hit F7/F8, the XML payload gets shown on screen in a nice XML editor. I’m just beginning with web services and this discovery is helping me a lot while troubleshooting, hope it helps others as well. Regards This is a very useful weblog that I have tried to implement for a POC. I was using SAP ECC 5. The proxy generation form the WSDL file is just fine, but the soap request sent from the sap server is wrong… The WSDL defines an operation AAAA with input and output message types. In the soap request, it is the input message that is called and not th operation… This is the SOAP request that is generated : can anyone help ??? Nicolas I have still got the problem of the soap request that is wrong. Have you any idea of how I can find out why request is wrong. I have debugged the call and even when changing data manually before the actual SOAP call, the request is wrong… Thanks for any help you can provide. Nicolas. Thank you Thomas for the reply… The solution to our problem is a support package… We were in SP12 on ABAP Basis. I have tested on a SP14 system and the Soap message is OK… I hope this will help others… Regards, Nicolas i followed your blog and created abap proxy.then i used the method of the class generated in proxy for extraction program.But when i tested it in i am setting Exception(In tranx:SM21) saying:SOAP Runtime Protocol: SOAP Fault exception occurred in program CL_SOAP_RUNTIME_ROOT==========CP in include CL_SOAP_RU NTIME_ROOT=== ==========CM004 at position 80. Please suggest me wht kind of exception is this and is it related to XSD type. thanks Snehasish Das SOAP Exception just means that something went wrong. You need to provide the details listed along with the SOAP Exception before anyone will be able to help you. “Cannot figure out operation name. Bad SOAPAction or wsa:Action.” When i tested the created proxy ,it always hangs. Thanks Snehasish Das “Cannot figure out operation name. Bad SOAPAction or wsa:Action.” Thanks snehasish Hi Thomas,Kumar Have you checked via your PC/browser to see if the URL listed in the WSDL is actually reachable? Is the service outside your firewall? If so, you probably need proxy settings (just like on your client machine). Proxy settings can be maintained within transaction SICF. I am also facing a similar error.Can you please suggest me how you resolved the issue. Thanks, Chakram Govindarajan The ABAP client proxy was generated successfully. On Proxy-Test and selecting a method, an error message comes back. It turns out that the receiver cannot understand the SOAP header which is sent. We also tested with an external test application (soapUI), where the service can be called qithout any problem. It seems that the receiver has some problems with header tags like My question is if the ‘MustUnderstand=1’ can be removed. Is there a configuration? The second one is if the header is correct at all. If you look at the Action definition (n2) the action is a little strange, since it consists out of the namespace and the operation name ‘InitMapSession’. How should this action be interpreted? Can I configure the webservice runtime in a way that these header data are not sent? Thanks, Michael Do you know for sure that the mustUnderstand is the cause of the problem. mustUnderstand does appear to be a valid element: In SOA Manager did you use WDSL based or manual configuration of the logical port? my webservice contain total 6 methods. thanx for ur reply.. I checked the ST22.it contains no errors.. and another issue is if my proxy’s contain the errors(cx_root) When I call the methods in a function module they executed successfully.. Is there any problem in future??????? wait’s for ur reply.. lakshman A SOAP Runtime Core Exception occurred in method configure_features of class CL_SOAP_APPLICATION at position 32 with internal error 1019 and error text SRT: Invalid setting in Web Service Registry detected (fault location is 1). The feature it is working on is and the property is null. It needs to be either “Level” or “TlsType” or the error is produced. Can you tell me if this is a problem with perhaps the WSDL, or an SAP product error, or something else on the server side? Testing the proxy site, a simple validation app, with my web browser is successful. Thanks. I am no expert in proxies or when it comes to runtime environment of Services. Am using ECC 6.0 & CE 7.1 EP06 I have a Composite Application(CAF, using Java) which consumes BAPIs and Enterprise Service. For connecting the CAF(Java) layer to communicate with ECC I need to perform mapping between the destinations of the BAPI(RFC destination) and the Web Service destination. For authentication, in the case of RFC destination I have used the assertion ticket and is working fine. But for the Web Service Destination, when I try using the Logon Ticket I get the error ” Error while creating assertion ticket on demand. No logged in user found. “ and when using the Logon Ticket I get this error ” Properties not set: NS: Name: IncludeTimestamp “ Please help me in this issue. Any information is appreciated. Thanks Brian I just started to play with the ABAP service consumer proxy. I am using it to call a web service in a .Net server on my company’s intranet. I am facing the problem with the authentication. When testing in the SOAPUI tool I need to enter the username, password, and the domain. I could also enter the domain like domain\\username. It worked fine either way in SOAPUI. When I tried to call the service through an ABAP consumer proxy in an ABAP program it did prompt me for username and password but not the domain. I entered domain\\username and password but got the 401 unauthorized error. The .Net server and the SAP server running the ABAP proxy and program are all on the same domain. I have searched in SDN and google without much luck. Can you please provide some idea on how this can be resolved or where I can find more information? Thanks. Regards, Jiannan Hi Thomas,Chakram Govindarajan If this isn’t the case, then the service might actually be unreachable – hence an invalid URL or the authentication might be incorrect. Below is my thread Posted: Apr 8, 2009. Still without answer. I think I don’t need to create any Webservices – I’m not sure for this! Please help me to solve my problem exchanging xml file via https. We have in the company Netweaver, so there is the posibility to use xi. We don’t provide BSP Applications. I tried with an abap report: /community [original link is broken], which was failed! Which configurations must be done for a correct comunication via https. My Thread: I try to send/receive files via HTTPS. To send and receive files to/from the Server my script must include the following steps: 1. Open an HTTPS connection to Server using the URL that describes the action (send, retrieve, etc.). 2. Send the necessary HTTP headers. 3. Send any data needed for the action. 4. Read the answer from Server. 5. Close the connection. To open the connection I would like to use: HTTPS.Open(“”) Which Server (SAP Netweaver) configurations are necessary to get the connection? Regards You have to have something that you are connecting to on the sever – a service handler, a BSP application, a webservice. This isn’t a file server you are talking to. Also if this is a thread from the forum, then it would courteous to at least provide a link to that thread. Please tell me what is my mistake? I always become the http_communication_failure Exception calling client->receive method?Kind regards! Thats waht I get as from the ICM Monitor: [Thr 5540] *** ERROR => NiBufIConnect: non-buffered connect pending after 5000ms (hdl 9;) [nibuf.cpp 4611 [Thr 5540] *** WARNING => Connection request from (21/13936/0) to host:, service: 80 failed (NIECONN_REFUSED) RM-T21, U13936, 040 AGI, localhost:0, 14:53:46, M0, W1, SEU_, 4/2 {000321e0} [icxxconn.c 2321] — Go to transaction SICF. Execute to get the service node hiearchy. Then choose Client->Proxy Settings from the menu. Maintain the settings according to the demands of your network. Now I have a little success. I am able to receive a correct response from my BSP Applications. An Also the Test with http://***//sap/public/bc/sicf_login_run?sap-client=###‘ was successful. But I am still unable to get get the data from external server like I will ask to fire wall settings from the administrator and will turn to here again. Thank you. But I also don’t get the requested file. Perhaps you tell me about this error? “The requested URL could not be retrieved… Access Denied…” But the URL: is public and doesn’t need login. Thanks for such a wonderful blog. I am having problem in consuming a Internet webservice. I am getting the following error 404 connection failed. when i go to the message information it says to maintain the proxy settings. In SICF>Client>proxy setting Now I am really confused that which settings I have to make there. Like what host name and the etc, and where to get them all Kindly Suggest. Warm Regards Upendra Agrawal we try to do the same on new NetWeaver 7.0 ENH1, where are all stuff regarding SOA and WS upside-down. Right now we are stuck with a problem, how to set up a LogicalPort for Client proxy to connect to WS via HTTPS with authentication via client certificate. Simply there is NO field to mark “use X.509 certificate” for authentication. Do you have any experience with new SOAMANAGER in this matter ? Thank you in advance. Best regards Tomas This is a very helpful blog.I am trying to consume a web service in abap. Here is the piece of code which does the job: data: proxy type ref to ZPM_ESRICO_LOCATOR_HUB_SOAP, input type ZPM_ESRIMATCH_SOAP_IN, output type ZPM_ESRIMATCH_SOAP_OUT, exception type ref to CX_AI_SYSTEM_FAULT, data type string. data = ‘High Street Glasgow’. input-MATCHER = data. create object proxy. TRY. CALL METHOD proxy->match EXPORTING INPUT = input IMPORTING OUTPUT = output . CATCH CX_AI_SYSTEM_FAULT into exception. CATCH CX_AI_APPLICATION_FAULT . ENDTRY. When I execute it, I get a cx_ai_system_fault exception with error_text saying ‘Server was unable to process request. —> Object reference not set to an instance of an object’. Hi Thomas, After I created the client proxy I tested it and it worked but not perfectly. The web service I am consuming receives an XML file and returns a message with information about that XML file. The problem is that I am not getting that message back. I checked the data types created by the client proxy and some of them look like they were not created right. When I try to access to those objects I get the following error: No proxy exists for object comprobante (namespace)” ZCH_COMPROBANTE_TAB looks like a table use for sending the information about the XML file back to us. Please help me, I need any help you can give me. I wrote this blog in 2004. Much has changed about the web service tools since then. I would strongly recommend that you post your question to one of the appropriate SCN forums instead. Hi Thomas, I am consuming Microsoft .NET webservice in ABAP but after completing the proxy wizard it results in error ‘No Vendor specified‘ error. I used report RSSIDL_DESERIALIZE_DEMO to test WSDL correctness. The report showed the exception like ‘ Incorrect value:Namespace prefix q1 of Qname q1 Exception is undeclared‘.Bu the same WSDL works and gets consumed in SAP system with higher Releases.Please advise . Your help is highly appreciated. Thanks Prabaharan Hi thomas , i trying to create a service consumer usin se80 and i get this error.. “message part refers a type, not an element” SPRX 338 have you any idea about issue? please.. Thanks for you attention
https://blogs.sap.com/2004/11/17/bsp-a-developers-journal-part-xiv-consuming-webservices-with-abap/
CC-MAIN-2019-30
refinedweb
7,743
56.66
How to use Commands in Java ME Series 40 Symbian S60 3rd Edition FP2 This article explains the mapping rules between Commands and softkeys and Options menus for Nokia S60 and Series 40 devices. Overview Command(String shortLabel, String longLabel, int commandType, int priority) In Nokia devices Commands have mapping rules to softkeys and Options menus that are based on Nokia user interface guidelines. It is essential to use logically proper and correct types for Commands. If right command types for the Commands intent are used then the mapping should work as expected and commands should be presented automatically according to Nokia Series 40 and S60 user interface guidelines (e.g. according to S60 UI style). Commands have following types as specified in MIDP LCDUI API: - OK - ITEM - SCREEN - BACK - CANCEL - EXIT - STOP These commands can be grouped to positive (OK, ITEM, SCREEN, HELP) and negative (BACK, CANCEL, EXIT, STOP). Nokia user interface guidelines and style positions negative operations like backward navigation to right softkey. Positive operations like forward navigation is in left or middle softkeys. On left softkey there can also menu called Options. On S60 there can be also smaller menu called context sensitive menu on middle softkey. Command mapping rules The Command mapping to softkeys follow following rules: - Right softkey: There can be only one "negative" Command (STOP, CANCEL, BACK, EXIT in this priority order) mapped to Right softkey, and the Command mapped there is directly invoked by softkey press. - Left softkey: Mutiple commands can be mapped under Left softkey in which case there is "Options" label in Left softkey and selection of it will open a menu of commands. If there's however only a single "positive" Command (OK, ITEM, SCREEN or HELP) under left softkey it will be presented directly on Left softkey. (Note: Some LCDUI components have their own operations that will be also visible under left softkey thus forcing Options menu.) If there's more than one negative Command this will force Options menu on Left softkey and the commands will be presented in the order define below. - Middle softkey: In Series 40 only a single context sensitive Command (OK, ITEM) is mapped to Middle softkey. In S60 multiple context sensitive Commands (OK, ITEM) can be mapped to Middle Softkey. If there's only single Command it will be shown directly in softkey, otherwise commands are visible in context sensitive menu opened from middle softkey. Normally the same commands mapped to Middle softkey are also available in Left softkey (directly or via Options menu). Note: Some UI components override this rule and place component specific operation directly to Middle softkey. For example, POPUP ChoiceGroup has "Open" operation in Middle softkey. When Commands are presented in Options menu (or context options menu) the commands mapped to the menu are shown in following order based on the type: - STOP - OK - CANCEL - ITEM - SCREEN - BACK - EXIT. Command labels Command labels are used as follows: - If Command is direcly in softkey short Comand label is used. - If Command is presented in a menu (Options menu or context sensitive menu) long label is used if it fits to the space available, if not then short label is used. Command priority property Commands also have priority property. This is use in Nokia Command mapping only if there's multiple Commands with the same type. In this case the priority is used to choose which of the commands with same type is selected earlier in command mapping or placed before the other commands in menus. Commands in Canvas Commands in Canvas are mapped with the above rules. It should be noted that S60 in Canvas there is a change between 3rd ed fp 2 onward about Selection key and Commands. Prior to S60 3rd ed fp 2 Selection key in Canvas was treated as separate key that always delivered low-level key events and no commands were mapped to it. Pressing the selection key delivered -5 key code. From 3rd ed fp2 the S60 platform is more aligned with Series 40. In Canvas the Selection key will be always mapped a Command and it will not deliver the low-level key event. This change may impact Java applications that use normal mode Canvas as they no longer get -5 key code. It also impacts applications that use Commands in full-screen mode and also rely on Selection sending low-level key event (-5). However, applications that work properly with Series 40 will work OK. There is also a compatibility mode available to get existing applications work as they were (see next section). Most applications that use key events from softkeys are full screenCanvas applications and this change has no impact there. S60 3rd ed fp2 will also have a text label on portrait mode like Series 40. On full screen mode all the softkeys keys including the selection key will either deliver key events or will be mapped to commands. This depends on availability of CommandListener. Direct key events from softkeys There's also possibility to catch low-level key events from softkeys but this is only possible in full screen mode Canvas (or Nokia UI API FullCanvas class). In Canvas, if there is no Commands and no CommandListener then softkeys will deliver normal key events. The key codes in Nokia devices are following: Left/Top softkey: -6 Right/Bottom softkey: -7 Selection key/Middle softkey: -5 Note: make sure you don't have either Commands nor CommandListener if you want direct key events, as it depends on platform and platform version which, the non-existence of Commands or CommandListener used for checking whether to deliver key events or map to Commands. Differences between S60 3rd ed. fp 2 and previous S60 devices S60 3rd ed. fp 2 devices are introducing Labeled selection key to the portrait mode. This allows Java implementation to better align the Command mapping to Series 40 Java devices. Being more aligned with Series 40, however, introduces a potential backwards incompatibility to previous S60 devices. Since the existing user device space of previous Series 40 is larger than of S60 it was decided it is better to do this alignment as it was possible due to the introduction of labeled selection key in S60 platform. The difference mostly is about that in Canvas the Selection key will no longer send low-level key event (keyPressed/keyReleased/keyRepeated methods of Canvas and similar methods in CustomItem). Instead, Command gets mapped with above rules to the selection key and selection key behaves like Series 40 middle softkey. The additional benefit is that this allows Selection key to be labeled with Command's label as in native S60 3rd ed. fp 2 applications. In full-screen Canvas if application does not set a CommandListener and no Commands to the Canvas then low-level key events will be delivered in 3rd ed fp 2 like in previous S60 devices.There will also be a compatibility mode for S60 3rd ed fp 2 devices that allows developers to enable the legacy S60 Java Canvas Selection key behavior from 3rd ed fp 1 and earlier devices also on fp 2 devices. The compatibility mode is turned on by defining a JAD/manifest attribute: Nokia-MIDlet-S60-Selection-Key-Compatibility: true The best pattern in the applications that use normal mode Canvas is to use Commands with type ITEM. Then the applications also get them positioned to the selection key and have a proper label present in devices with labeled selection keys. For example, then these applications work well in both Series 40 and S60. For backwards compatibility to those devices without labeled selection key applications should still listen to the key event of selection key (-5 key code) and associate that key event with the same action as is activated from the selection command. In full screen Canvas applications should not use Commands at all but always have Command listener as null and rely on low-level key events from softkeys and selection key. That way the applications work in all devices. Another reason for this is that the usability of Commands in full screen canvas is not that good. Sample MIDlet for use of commands import javax.microedition.lcdui.*; import javax.microedition.midlet.*; public class TestMIDlet extends MIDlet implements CommandListener { Display disp; Form form = new Form("Test Command form"); static final Command exitCommand = new Command("Exit", Command.EXIT, 0); public TestMIDlet() { } public void startApp() throws MIDletStateChangeException { disp = Display.getDisplay(this); form.addCommand(exitCommand); form.setCommandListener(this); disp.setCurrent(form); } public void pauseApp() { } public void destroyApp(boolean unconditional) { notifyDestroyed(); } public void commandAction(Command cmd,Displayable disp) { String cmdLabel = cmd.getLabel(); if (cmdLabel.equals("Exit")) { destroyApp(true); } } }
http://developer.nokia.com/community/wiki/How_to_use_Commands_in_Java_ME
CC-MAIN-2014-35
refinedweb
1,444
50.67
Are you sure? This action might not be possible to undo. Are you sure you want to continue? 2. Getting Started 2.1 Downloading and Installing The first step to getting up and running with Grails is to install the distribution. To do so follow these steps: • Download a binary distribution of Grails and extract the resulting zip file to a location of your choice • Set the GRAILS_HOME environment variable to the location where you extracted the zip • On Unix/Linux based systems this is typically a matter of adding something like the following export GRAILS_HOME=/path/to/grails to your profile • On Windows this is typically a matter of setting an environment variable under My Computer/Advanced/Environment Variables • Now you need to add the bin directory to your PATH variable: • On Unix/Linux base system this can be done by doing a export PATH="$PATH: $GRAILS_HOME/bin" • On windows this is done by modifying the Path environment variable under My Computer/Advanced/Environment Variables If Grails is working correctly you should now be able to type grails Although the Grails development team have tried to keep breakages to a minimum there are a number of items to consider when upgrading a Grails 1.0.x or 1.1.x application to Grails 1.2. The major changes are described in detail below. Upgrading from Grails 1.1.x Plugin paths In Grails 1.1.x typically a pluginContextPath variable was used to establish paths to plugin resources. For example: 1 The Grails Framework - Reference Documentation <g:resource Tag and Body return values Tags no longer return java.lang.String instances but instead return a StreamCharBuffer instance. The StreamCharBuffer class implements all the same methods as String, however code like this may break: def foo = body() if(foo instanceof String) { // do something } In these cases you should use the java.lang.CharSequence interface, which both String and StreamCharBuffer implement: def foo = body() if(foo instanceof CharSequence) { // do something } New JSONBuilder There is a new version of JSONBuilder which is semantically different to earlier versions of Grails. However, if your application depends on the older semantics you can still use the now deprecated implementation by settings the following property to true in Config.groovy: grails.json.legacy.builder=true Validation on Flush Gra: static constraints = { author(validator: { a -> 2 The Grails Framework - Reference Documentation assert a != Book.findByTitle("My Book").author }) } The above code can lead to a StackOverflowError Gra Grails 1.1 now no longer supports JDK 1.4, if you wish to continue using Grails then it is recommended you stick to the Grails 1.0.x stream until you are able to upgrade your JDK. Configuration Changes 1) The setting grails.testing.reports.destDir has been renamed to grails.project.test.reports.dir for consistency. 2) The following settings have been moved from grails-app/conf/Config.groovy to grails-app/conf/BuildConfig.groovy: • • • • • grails.config.base.webXml grails.war.destFile grails.war.dependencies grails.war.copyToWebApp grails.war.resources 3) The grails.war.java5.dependencies option is no longer supported, since Java 5.0 is now the baseline (see above). 4) The use of jsessionid (now considered harmful) is disabled by default. If your application requires jsessionid you can re-enable its usage by adding the following to grailsapp/conf/Config.groovy: grails.views.enable.jsessionid=true 5) The syntax used to configure Log4j has changed. See the user guide section on Logging for more 3 The Grails Framework - Reference Documentation information." Script Changes 1) If you were previously using Grails 1.0.3 or below the following syntax is no longer support for importing scripts from GRAILS_HOME: Ant.property(environment:"env") grailsHome = Ant.antProject.properties."env.GRAILS_HOME" includeTargets << new File ( "${grailsHome}/scripts/Bootstrap.groovy" ) Instead you should use the new grailsScript method to import a named script: includeTargets << grailsScript( "Bootstrap.groovy" ) 2) Due to an upgrade to Gant all references to the variable Ant should be changed to ant. 3) The root directory of the project is no long on the classpath, the result is that loading a resource like this will no longer work: def stream = getClass().classLoader.getResourceAsStream("grails-app/conf/my-config.xml") Instead you should use the Java File APIs with the basedir property: new File("${basedir}/grails-app/conf/my-config.xml").withInputStream { stream -> // read the file } Command Line Changes The run-app-https and run-war-https commands no longer exist and have been replaced by an argument to run-app: grails run-app -https Data Mapping Changes 1) Enum types are now mapped using their String value rather than the ordinal value. You can revert to the old behavior by changing your mapping as follows: static mapping = { 4 The Grails Framework - Reference Documentation someEnum enumType:"ordinal" } 2) Bidirectional one-to-one associations are now mapped with a single column on the owning side and a foreign key reference. You shouldn't need to change anything, however you may want to drop the column on the inverse side as it contains duplicate data. REST Support Incoming XML requests are now no longer automatically parsed. To enable parsing of REST requests you can do so using the parseRequest argument inside a URL mapping: "/book"(controller:"book",parseRequest:true) Alternatively, you can use the new resource argument, which enables parsing by default: "/book"(resource:"book") 2.3 Creating an Application To create a Grails application you first need to familiarize yourself with the usage of the grails command which is used in the following manner: grails [command name] In this case the command you need to execute is create-app: grails create-app helloworld This will create a new directory inside the current one that contains the project. You should now navigate to this directory in terminal: cd helloworld 2.4 A Hello World Example To implement the typical "hello world!" example run the create-controller command: grails create-controller hello This will create a new controller (Refer to the section on Controllers for more information) in the grails-app/controllers directory called HelloController.groovy. Controllers are capable of dealing with web requests and to fulfil the "hello world!" use case our 5 The Grails Framework - Reference Documentation implementation needs to look like the following: class HelloController { def world = { render "Hello World!" } } Job done. Now start-up the container with another new command called run-app: grails run-app This will start-up a server on port 8080 and you should now be able to access your application with the URL: The result will look something like the following screenshot: This is the Grails intro page which is rendered by the web-app/index.gsp file. You will note it has a detected the presence of your controller and clicking on the link to our controller we can see the text "Hello World!" printed to the browser window. 2.5 Getting Set-up in an IDE IntelliJ IDEA Intell A We. 6 The Grails Framework - Reference Documentation TextMate Since: grails integrate-with --textmate Alternatively TextMate can easily open any project with its command line integration by issuing the following command from the root of your project: mate . 2.6 Convention over Configuration: • grails-app - top level directory for Groovy sources • conf - Configuration sources. • controllers - Web controllers - The C in MVC. • domain - The application domain. • i18n - Support for internationalization (i18n). • services - The service layer. • taglib - Tag libraries. • views - Groovy Server Pages. • scripts - Gant scripts. • src - Supporting sources • groovy - Other Groovy sources • java - Other Java sources • test - Unit and integration tests. 2.7 Running an Application Grails applications can be run with the built in Tomcat server using the run-app command which will load a server on port 8080 by default: grails run-app You can specify a different port by using the server.port argument: grails -Dserver.port=8090 run-app 7 The Grails Framework - Reference Documentation More information on the run-app command can be found in the reference guide. 2.8 Testing an Application The create-* commands in Grails automatically create integration tests for you within the test/integration directory. It is of course up to you to populate these tests with valid test logic, information on which can be found in the section on Testing. However, if you wish to execute tests you can run the test-app command as follows: grails test-app Grails also automatically generates an Ant build.xml which can also run the tests by delegating to Grails' test-app command: ant test This is useful when you need to build Grails applications as part of a continuous integration platform such as CruiseControl. 2.9 Deploying an Application Grails applications are deployed as Web Application Archives (WAR files), and Grails includes the war command for performing this task: grails war This will produce a WAR file in the root of your project which can then be deployed as per your containers instructions. NEVER deploy Grails using the run-app command as this command sets Grails up for auto-reloading at runtime which has a severe performance and scalability implication When deploying Grails you should always run your containers JVM with the -server option and with sufficient memory allocation. A good set of VM flags would be: -server -Xmx512M 2.10 Creating Artefacts Gra: 8 The Grails Framework - Reference Documentation grails create-domain-class book This will result in the creation of a domain class at grails-app/domain/Book.groovy such as: class Book { } There are many such create-* commands that can be explored in the command line reference guide. 2.10 Supported Java EE Containers Grails runs on any Servlet 2.4 and above container and is known to work on the following specific container products: • • • • • • • • • • • • • • • • Some containers have bugs however, which in most cases can be worked around. A list of known deployment issues can be found on the Grails wiki. 2.11 Generating an Application To 9
https://www.scribd.com/document/30794227/2-Getting-Started
CC-MAIN-2017-51
refinedweb
1,656
53.31
It's not the same without you Join the community to find out what other Atlassian users are discussing, debating and creating. Post function should update a custom field(labels field) say field ABC with value "a1b1c1" to all the newly created issues that have the custom field “XYZ” set to one of the following values: ("a1b1c1","a2b2c2","a3b3c3",.......) I read somewhere that this could be achieved using script runner post function but i am a novice in script writing. If someone could help me out here with the complete script, i would be extremely grateful to this forum as always. Regards, Ashley Ashley, If you already use script runner then: Go to Script Listeners -> Custom Listener Select the project, in the Events field select Issue Created and in the Inline Script textfield add the following script: import com.atlassian.jira.component.ComponentAccessor import com.atlassian.jira.issue.Issue import com.atlassian.jira.issue.label.LabelManager Issue issue = event.issue def customFieldManager = ComponentAccessor.getCustomFieldManager() def labelManager = ComponentAccessor.getComponent(LabelManager.class) def listOfPredefinedValues = ["Collateral Optimisation", "Financial Reporting", "Risk Platform and FRTB", "Trading Data Warehouse", "Market Data", "Technical Foundation", "Trading and Risk Domain"] def flag = false; def label = 'Trading&Risk-Domain' def cf = customFieldManager.getCustomFieldObjectByName("Project Name") def dropDownValue = cf?.getValue(issue) listOfPredefinedValues.each {value -> if (value.equals(dropDownValue?.toString())) { flag = true // If you want the label to have the same name (without spaces) with the drop down option, remove the comments // label = dropDownValue?.toString()?.replaceAll("\\s","") } } if (!flag) return def user = event.getUser() return labelManager.addLabel(user, issue.id, label, false) In this case a label with the same name as the option of the dropdown field (XYZ) is added to the label custom field (ABC). PS. The good with Atlassian answers is that there are cases that more than one options are proposed, if you don't use script runner then the choice is up to you . Many thanks for the swift reply and really appreciate that :) However i tried it in our instance but for some reason it didn't work. Let me provide you the exact details of the fields so that you could help me with the modified code. We have global Jira Labels field which we need to get populated with some value (continuous string as we know labels field does,'t allow spaces) once issue is created based on the drop down options we select for one of the custom fields here, Project Name (this is single select drop down field with few pre-configurd options. I will provide the options based on which we need the result upon issue creation:- "Collateral Optimisation", "Financial Reporting","Risk Platform and FRTB","Trading Data Warehouse","Market Data","Technical Foundation","Trading and Risk Domain" The value that needs to appear for Labels field upon issue creation is Trading&Risk-Domain If you could implement this in your script i would be extremely grateful If you think its not possible for system jira Labels field we are ready for a custom field of labels field as well, however other requirements would remain same. The drop down options for custom field Project Name are not continuous strings like Collateral Optimisation (2 words), so the script should be written to accomodate that. Looking forward to your response. Cheers, Ashley Hi Ashley I updated the script. If you want your label to be always Trading&Risk-Domain then use the script as it is. If you want your label to match with a valid (depending on the list of predefined values) dropdown option, then remove the comments. For example: Your Project Name dropdown has options ["Collateral Optimisation", "Financial Reporting", "Risk Platform and FRTB", "Trading Data Warehouse", "Market Data", "Technical Foundation", "Trading and Risk Domain", "Random Option 1"]. If the user selects "Random Option 1" then, NO label will be adde. If the user selects from dropdown the Technical Foundation option then a label will be added with the name TechnicalFoundation. PS. No need to create a custom field for the labels if you want to use the system's one (In the beginning I thought you had a custom field with labels). Please let me know if this works for you. Regards, Thanos And that worked like a charm :) Guys like you really add value to this forum and i really appreciate that. I had not expected such a swift and exact solution pertaining to my requirements to have come my way, but you made this possible, so big thanks to you. Will look forward to similar solutions in the future for other requirements as we are constantly trying to explore Jira in a highly customized way and script runner plugin really helps go a big deal in the journey. Cheers, Ashley Hi Ashley, Can I ask you what type is the custom field "XYZ" ? And does the label "a1b1c1" already exists or you have to create it ? Hi Ashley, You can do it using "Set a field as a function of other fields" post-function of JIRA Workflow Toolbox plugin. To do it use the following configuration in transition "Create Issue" (insert it after "Creates the issue originally" post-function): Captura de pantalla 2015-11-19 a las 16.06.45.png This configuration will add label a1b1c1 to field "ABC", keeping the current labels set in the field. If you want to replace any previous value with the new label, then remove prefix '+', i.e. use the following setting rule: (a1b1c1|a2b2c2|a3b3c3)a1b1c1 Thanks for the swift reply. XYZ is here a single select drop down field with pre-configured options like, a1b1c1,etc also a1b1c1 already exists as label. Hi Ashley, I updated the code to match with your requirements. If you decide to go with the script, please let me know if you need further.
https://community.atlassian.com/t5/Jira-questions/Post-function-in-Jira-should-update-a-custom-field-based-on/qaq-p/265586
CC-MAIN-2018-39
refinedweb
967
51.18
Coloc Feature While not technically a transport, use of the Coloc feature in CXF can dramatically speed up the interactions within the same JVM. The Coloc feature works by detecting when a client is calling a service that is registered on the same Bus instance and then bypasses most of the interceptor processing. The actual objects that the client sends are passed directly to the service without any serialization or other processing. Due to this, there are a bunch of restrictions: - The objects/parameters MUST be the exact same classes. The easiest way is by having the service and client implement the same interface. - They MUST be in the same classloader. This would be normal if on the same Bus. - Because it is pass by reference instead of pass by value, the semantics are different than a normal webservice call. Modifications to the objects would be reflected back to the caller. - Any extra processing at the soap or transport layers would be bypassed. Thus, things like security, WS-RM, JAX-WS handlers, etc... would not be part of the interation. If the above restrictions are acceptable, the Coloc feature is an easy way to boost performance for clients/services within the same Bus. Enabling coloc The easiest way to enable the coloc capabilities is to use the Coloc feature, either via the feature class of org.apache.cxf.binding.coloc.feature.ColocFeature or using the coloc namespace handler in spring. You can enable the feature at the bus level like: <cxf:bus> <cxf:features> <coloc:enableColoc/> </cxf:features> </cxf:bus> in which case all clients would check to see if the service is available locally and use them if possible. However, you can configure it on specific clients if you just want it done in the particular cases where the restrictions above are acceptable: <jaxws:client <jaxws:features> <coloc:enableColoc/> </jaxws:features> </jaxws:client>
https://cwiki.apache.org/confluence/display/CXF20DOC/Coloc+Feature
CC-MAIN-2019-30
refinedweb
314
53.92
Setting up Favourite Places and Current Location Buttons >] So guys in the last class redesigned you know our pickup and destination bars which is what we have here. So in this class we're going to be designing our main location button and favorite places. So to do that let's jump right into it. OK. So I'm just going to minimize this minimize this OK and also minimize this. All right. So here I'm going to art in you really to me out because this we need some attributes right. Layout height I want to use standard five DP. So for you guys we take no we are designing our current location button. All right. So we have under the layout with layout with real code to 25 DP as well. OK. So we need to make a clickable if that's the case. That means that we need to earn a 90 for a so let's call it my location you know be on display. So it is more like we needed to be centered and aligned to the right. So if that's the case you need to set a little gravity to be sent to and right. OK. We need to set the background so that we can be seen in the way. So this is really to layout. So no need to add so margin to the right should be sustained DP OK. So here we are. All right. So now we need some image. We need to put an image inside of it. You know our location image. So I've actually added the icon that I used to do resource for this class. So you guys could download it and add us as well. OK. So I have it on my desktop so I would just go ahead and add it to my map for the so it is the one I used enjoyed for NDP for exhales DP for says HDP and the last one. So now we are done. We now need to add an image and an image view. Now take up a Nikon Winter Wrap content me out tweet interrupt content swell let's add a tent or a tent will be sent to that sounds kind of OK. We need some bonding five DP. And of course this reference the image see which is excellent to meet. Map slash. I see my location block forty eight DP. So guys here we go. All right. So now that I've added that I still want to do is to add our right places button. OK so let's define button because this we need an I.D. Faisal right places button we outside a hundred DP file with call this my favor right. This is resounding over here. So less and little gravity now gravity should be center and button OK. So if that's the case we'll want to add some margin to the bottom one to talk to DP to lift it up a little bit. So we don't want the text to all be copied to Atlanta. Right. So we're just going to say test all caps and send that to force. OK. So we're going to send some budding so we we need to you know bringing the favorite icon that we have here right. So like I said before everything I actually need I've already added in resources but I have mine on my desktop. So I'm going to go into my resources. I'm going to look for the MDI and copy this. All right. I want to copy this and add it to him to my draw before that. OK just a very small one. OK so I'll paste it here and I'll grab a reference of it as our dollar bill left. So say draw more left and draw a bill slash I see. Action fave white OK. So you guys could see he's actually shooting here right. So let's continue. Let's add some part into our button. All right. So I want to add some bad left and we need some bad into tonight as well we need some bad into the riots as well. Said this to they say 12:00 DP C DP and we need some prodding to the bottom we've said this to the Saudis the NDP and to the top sell it to a deep yes. Well okay so we need to elevate this a little bit so let's add some elevation to DP and won some shadow so I can just say trans. Translation Z to A DP yesterday to add this lovely shadow here. So guys will add around edges to the button. You guys remember that. We did something similar when we are designing a log in a registration page. So we are just gonna do that same background and set it to drone war over random button d d And XM or found that we created earlier on. So you guys remember how we achieve this right. So this file that we are calling these drivable. This jawbone we create any earlier on when we are designing our log in a revision page. So this X M.O. is Y is actually giving this button. Iran edges it and as well the the the arson scholar they has the arena. So the next thing we need to do is to make a test called to be white. So we're going to say under his desk follow a code to I'd call a slash over white man. So we are done with that. So guys another thing I want to do is want to add some soft edges to our family out and our reality layout so to do that we need to create a shape. All right. And for me to do that we now need to add a new XM or file calling around and. OK. In that way it too will be able to implement a shape that will help us achieve the around edges so a new item maximal round edges squatting around edges so let's call it round edges and we've had this so how to do this is actually very simple and straightforward. Okay. So first of all we say shape and of course I'm gonna bring in our namespace Maxima namespace which would be an android is key. Maria's got Android dot com slash AP okay slash the rest slash Android OK. So you guys she and should I you spell this appropriately if not everything will work accordingly. And you're proud of me and you're wondering why is not working for you so instead of the shape we need to define a new solid okay and add weight to it we've wanted to be one DP and we define it Carlos. Wow. So we just have to add something you know that looks like ash. So I'm going to say Android color code too harsh see. Easy easy right. This is a shade of ash so the next thing I want to do is to define our corners so we say it corners inside a corner. We're going to have Android but done right re diamonds. Okay so you guys ensure that you sell. You spell your read is appropriate leaf notes you will be having issues. Okay. Anybody may not know why he's not working for you ADP and Android. The bottom GDP Android radio is GDP Android 3 Dios GDP OK. Correct yes. So guys that's all we need to do in this place. So let's save this. So now we head back into our design layout. So for the relatively out instead of having the background to be equal we're gonna sit around and edges to be the the background. OK. So we're going to say at drivable slosh around in ages. Okay you know you go Okay so you can see it has changed yeah. But I think we have days in mistake somewhere right. Okay so you guys could see it here right. But the background is not like. I think something is wrong with our round edges okay. This was supposed to be stroke okay. We're supposed to have solid thus as the color Android that corner where this is supposed to be white. All right. This should take care of that. So let's save huh. So now we are here. So the last thing we need to do is we need to apply these round edges to our frame layout as well. OK so let's open these up friendly out instead of having background to just be white or assign our round edges to be the background draw or slash round edges. Boom. So guys this is it. So to confirm everything that we've done so far we need to run it and ensure that everything checks out very well. OK. So let's run this OK. So it seems there is an arrow. Of course we know what caused that bottom left reduce a misspelling. So we're supposed to have putting okay. So now we're done with that. Let's join it again okay. There's another era. Okay so we got some arrow. So when you whenever you come across this kind of error what you do is to clean your project. Okay. Clean your project. So let's go ahead on clean as OK. So now we can our own app so once you actually cleaned your project naturally beauty into your app naturally it takes time to actually be longer than usual because it means to generate some binaries you know from your packages need to compile the whole project from ground all began. Right. So that's why it's taking a little bit of time on how we go bam. OK. So guys this is our beauty. All right. So we're successfully designed this and everything seems to be working just the way we want it. All right. So guys I hope you really enjoyed the class and thank you for being here. If you've come so far I encourage you to keep pushing hard. All right. We're going to get to the end of this together. All right. So see you in the next session. And of course in this class.
https://www.udemy.com/tutorial/xamarin-uber-clone-app/setting-up-favourite-places-and-current-location-buttons/
CC-MAIN-2021-10
refinedweb
1,772
91
Investors considering a purchase of Pfizer Inc (Symbol: PFE) stock, but cautious about paying the going market price of $40.60/share, might benefit from considering selling puts among the alternative strategies at their disposal. One interesting put contract in particular, is the January 2021 put at the $30 strike, which has a bid at the time of this writing of $1.29. Collecting that bid as the premium represents a 4.3% return against the $30 commitment, or a 2.5% annualized rate of return (at Stock Options Channel we call this the YieldBoost). Selling a put does not give an investor access to PFE Pfizer Inc sees its shares decline 26.2% and the contract is exercised (resulting in a cost basis of $28.71 per share before broker commissions, subtracting the $1.29 from $30), the only upside to the put seller is from collecting that premium for the 2.5% annualized rate of return. Below is a chart showing the trailing twelve month trading history for Pfizer.5% annualized rate of return represents good reward for the risks. We calculate the trailing twelve month volatility for Pfizer Inc (considering the last 251 trading day closing values as well as today's price of $40.60) to be 19%. For other put options contract ideas at the various different available expirations, visit the PFE Dow » The views and opinions expressed herein are the views and opinions of the author and do not necessarily reflect those of Nasdaq, Inc.
https://www.nasdaq.com/articles/commit-buy-pfizer-30-earn-4.3-using-options-2019-05-08
CC-MAIN-2021-25
refinedweb
251
64.81
We are about to switch to a new forum software. Until then we have removed the registration on this forum. This is for an art project. I'm trying to play 4 wav. files on an infinite loop at the volume 0. when I press a button, the volume should rise up to 100. each button is connected with a wav. file, so when I press button A, file A's volume would rise to 100. I hope this makes things clear enough? This is the ARDUINO code, I only have 2 wav files at the moment. int ledPin = 2; int ledPin3 = 3; int value = 0; void setup() { Serial.begin(9600); pinMode(ledPin, INPUT); pinMode(ledPin3, INPUT); } void loop() { if (digitalRead(ledPin) == HIGH) { Serial.println("1"); delay (50); } else { Serial.println("2"); delay (50); } if (digitalRead(ledPin3) == HIGH) { Serial.println("3"); delay (50); } else { Serial.println("4"); delay (50); } } This is the PROCESSING file, also with two files. import ddf.minim.*; import processing.serial.*; Serial port; float value = 0; float old = 0; Minim minim; AudioPlayer player; void setup() { size(50,50); minim = new Minim(this); player = minim.loadFile("harp.wav"); player.play(); player.shiftGain(-80,-80,100); player.rewind(); port = new Serial(this, "/dev/cu.usbmodem1421", 9600); port.bufferUntil('\n'); } void draw() { background(0); if ((value == 1) || (value == 2)) { if (value != old) { if (value == 1) { //volume up player.shiftGain(-80, 0, 100); } else if (value == 2) { //volume down player.shiftGain(0,-80,100); } } old = value; } } void serialEvent (Serial port) { value = float(port.readStringUntil('\n')); }` This is PROCESSING file version B, `import ddf.minim.*; import processing.serial.*; Serial port; float value = 0; Minim minim; Minim minim2; AudioPlayer player; AudioPlayer player2; void setup() { size(50,50); minim = new Minim(this); player = minim.loadFile("basses.wav"); player.play(); player.mute(); player.rewind(); minim2 = new Minim(this); player2 = minim2.loadFile("harp.wav"); player2.play(); player2.mute(); player2.rewind(); port = new Serial(this, "/dev/cu.usbmodem1421", 9600); port.bufferUntil('\n'); } void draw() { background(0); if (value == 2) { player.unmute(); delay(3000); } if (value == 1); { player.mute(); delay(3000); } if (value == 4) { player2.unmute(); delay(3000); } if (value == 3); { player2.mute(); delay(3000); } } void serialEvent (Serial port) { value = float(port.readStringUntil('\n')); } The problem is that a) files are not playing at the same time b) it's clicking when the button is pressed c) overall, it's not really responding to the button, just playing on and off by itself. Any ideas or an easier way to do this maybe? I really appreciate it. Answers Divide the program into parts, then find which part has problem. Check if the Serial part of the code works, then we can check about the minim part. okay, so the arduino part of the code works fine, i'm getting right signals in the monitor. the processing file version B works fine when it has only one track, when I add a track, it doesn't play the other track and also stops randomly. I have this code. It plays both sounds at the same time. It works only if you don'y interact with the p1 and p2 objects in draw(). However, if you uncomment players by blocks (case1&2 or case3&4) then only one sounds plays and the other one seems to get muted. If you enabled all four cases (1,2,3,4) then there is no sound at all. Weird.... Kf I tried too. Same wired result as @kfrajer. @kena1226 CHECK line 45 and 58! An if statement does not end with semi-colon. That will fix your problem. Kf Oops. Should have noticed earlier. i tried and it doesn't work even without the semi colon. I have the same problem with your code too @kfrajer Can you get both sounds to play individually? Next step, before you mute any of them, can you play them together? Kf Next step, set the mute/unmute commands. Make sure line 49 from my code is run as you need to reset the value of value as I show in my code. As an alternative, you can move your code from draw into your mouse event function. Remember that draw executes 60 fps! Kf @kfrajer in your code, I can get both sounds to play together and separately. I don't understand > As an alternative, you can move your code from draw into your mouse event function. Remember that draw executes 60 fps! This part, what does it mean? when i set the mute/unmute, it doesn't play anything or ummute anything. Now that you tell me that both songs play simultaneously, then the next step is to get the mute/unmute functions to work. Next code reflect suggested changes. I got the code working before. Note the code before is not complete. Kf
https://forum.processing.org/two/discussion/comment/80153/
CC-MAIN-2020-40
refinedweb
799
69.28
Name conflicts happen all the time in real life. For example, every school that I ever went to had at least two students in my class who shared the same first name. If someone came into the class and asked for student X, we would enthusiastically ask, "Which one are you talking about? There are two students named X." After that, the inquiring person would give us a last name, and we would introduce him to the right X. All this confusion and the process of determining the exact person we are talking about by looking for other information besides a first name could be avoided if everyone had a unique name. This is not a problem in a class of 30 students. However, it will become increasingly difficult to come up with a unique, meaningful and easy-to-remember name for every child in a school, town, city, country, or the whole world. Another issue in providing every child a unique name is that the process of determining if someone else has also named their child Macey, Maci or Macie could be very tiring. A very similar conflict can also arise in programming. When you are writing a program of just 30 lines with no external dependencies, it is very easy to give unique and meaningful names to all your variables. The problem arises when there are thousands of lines in a program and you have loaded some external modules as well. In this tutorial, you will learn about namespaces, their importance, and scope resolution in Python. What Are Namespaces? A namespace is basically a system to make sure that all the names in a program are unique and can be used without any conflict. You might already know that everything in Python—like strings, lists, functions, etc.—is an object. Another interesting fact is that Python implements namespaces as dictionaries. There is a name-to-object mapping, with the names as keys and the objects as values. Multiple namespaces can use the same name and map it to a different object. Here are a few examples of namespaces: - Local Namespace: This namespace includes local names inside a function. This namespace is created when a function is called, and it only lasts until the function returns. - Global Namespace: This namespace includes names from various imported modules that you are using in a project. It is created when the module is included in the project, and it lasts until the script ends. - Built-in Namespace: This namespace includes built-in functions and built-in exception names. In the Mathematical Modules in Python series on Envato Tuts+, I wrote about useful mathematical functions available in different modules. For example, the math and cmath modules have a lot of functions that are common to both of them, like log10(), acos(), cos(), exp(), etc. If you are using both of these modules in the same program, the only way to use these functions unambiguously is to prefix them with the name of the module, like math.log10() and cmath.log10(). What Is Scope? Namespaces help us uniquely identify all the names inside a program. However, this doesn't imply that we can use a variable name anywhere we want. A name also has a scope that defines the parts of the program where you could use that name without using any prefix. Just like namespaces, there are also multiple scopes in a program. Here is a list of some scopes that can exist during the execution of a program. - A local scope, which is the innermost scope that contains a list of local names available in the current function. - A scope of all the enclosing functions. The search for a name starts from the nearest enclosing scope and moves outwards. - A module level scope that contains all the global names from the current module. - The outermost scope that contains a list of all the built-in names. This scope is searched last to find the name that you referenced. In the coming sections of this tutorial, we will extensively use the built-in Python dir() function to return a list of names in the current local scope. This will help you understand the concept of namespaces and scope more clearly. Scope Resolution As I mentioned in the previous section, the search for a given name starts from the innermost function and then moves higher and higher until the program can map that name to an object. When no such name is found in any of the namespaces, the program raises a NameError exception. Before we begin, try typing dir() in IDLE or any other Python IDE. dir() # ['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__'] All these names listed by dir() are available in every Python program. For the sake of brevity, I will start referring to them as '__builtins__'...'__spec__' in the rest of the examples. Let's see the output of the dir() function after defining a variable and a function. a_num = 10 dir() # ['__builtins__' .... '__spec__', 'a_num'] def some_func(): b_num = 11 print(dir()) some_func() # ['b_num'] dir() # ['__builtins__' ... '__spec__', 'a_num', 'some_func'] The dir() function only outputs the list of names inside the current scope. That's why inside the scope of some_func(), there is only one name called b_num. Calling dir() after defining some_func() adds it to the list of names available in the global namespace. Now, let's see the list of names inside some nested functions. The code in this block continues from the previous block. def outer_func(): c_num = 12 def inner_func(): d_num = 13 print(dir(), ' - names in inner_func') e_num = 14 inner_func() print(dir(), ' - names in outer_func') outer_func() # ['d_num'] - names in inner_func # ['c_num', 'e_num', 'inner_func'] - names in outer_func The above code defines two variables and a function inside the scope of outer_func(). Inside inner_func(), the dir() function only prints the name d_num. This seems fair as d_num is the only variable defined in there. Unless explicitly specified by using global, reassigning a global name inside a local namespace creates a new local variable with the same name. This is evident from the following code. a_num = 10 b_num = 11 def outer_func(): global a_num a_num = 15 b_num = 16 def inner_func(): global a_num a_num = 20 b_num = 21 print('a_num inside inner_func :', a_num) print('b_num inside inner_func :', b_num) inner_func() print('a_num inside outer_func :', a_num) print('b_num inside outer_func :', b_num) outer_func() print('a_num outside all functions :', a_num) print('b_num outside all functions :', b_num) # a_num inside inner_func : 20 # b_num inside inner_func : 21 # a_num inside outer_func : 20 # b_num inside outer_func : 16 # a_num outside all functions : 20 # b_num outside all functions : 11 Inside both the outer_func() and inner_func(), a_num has been declared to be a global variable. We are just setting a different value for the same global variable. This is the reason that the value of a_num at all locations is 20. On the other hand, each function creates its own b_num variable with a local scope, and the print() function prints the value of this locally scoped variable. Properly Importing Modules It is very common to import external modules in your projects to speed up development. There are three different ways of importing modules. In this section, you will learn about all these methods, discussing their pros and cons in detail. from module import *: This method of importing a module imports all the names from the given module directly in your current namespace. You might be tempted to use this method because it allows you to use a function directly without adding the name of the module as a prefix. However, it is very error prone, and you also lose the ability to tell which module actually imported that function. Here is an example of using this method: dir() # ['__builtins__' ... '__spec__'] from math', 'trunc'] log10(125) # 2.0969100130080562 from cmath', 'phase', # 'pi', 'polar', 'pow', 'radians', 'rect', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', # 'trunc'] log10(125) # (2.0969100130080562+0j) If you are familiar with the math and cmath modules, you already know that there are a few common names that are defined in both these modules but apply to real and complex numbers respectively. Since we have imported the cmath module after the math module, it overwrites the function definitions of these common functions from the math module. This is why the first log10(125) returns a real number and the second log10(125) returns a complex number. There is no way for you to use the log10() function from the math module now. Even if you tried typing math.log10(125), you will get a NameError exception because math does not actually exist in the namespace. The bottom line is that you should not use this way of importing functions from different modules just to save a few keystrokes. from module import nameA, nameB: If you know that you are only going to use one or two names from a module, you can import them directly using this method. This way, you can write the code more concisely while still keeping the namespace pollution to a minimum. However, keep in mind that you still cannot use any other name from the module by using module.nameZ. Any function that has the same name in your program will also overwrite the definition of that function imported from the module. This will make the imported function unusable. Here is an example of using this method: dir() # ['__builtins__' ... '__spec__'] from math import log2, log10 dir() # ['__builtins__' ... '__spec__', 'log10', 'log2'] log10(125) # 2.0969100130080562 import module: This is the safest and recommended way of importing a module. The only downside is that you will have to prefix the name of the module to all the names that you are going to use in the program. However, you will be able to avoid namespace pollution and also define functions whose names match the name of functions from the module. dir() # ['__builtins__' ... '__spec__'] import math dir() # ['__builtins__' ... '__spec__', 'math'] math.log10(125) # 2.0969100130080562 Final Thoughts I hope this tutorial helped you understand namespaces and their importance. You should now be able to determine the scope of different names in a program and avoid potential pitfalls. Additionally, don’t hesitate to see what we have available for sale and for study in the marketplace, and don't hesitate to ask any questions and provide your valuable feedback using the feed below. The final section of the article discussed different ways of importing modules in Python and the pros and cons of each of them. If you have any questions related to this topic, please let me know in the comments. Envato Tuts+ tutorials are translated into other languages by our community members—you can be involved too!Translate this post
https://code.tutsplus.com/tutorials/what-are-python-namespaces-and-why-are-they-needed--cms-28598
CC-MAIN-2018-13
refinedweb
1,775
71.14
> -----Original Message----- > From: Alex Samad - Yieldbroker [mailto:Alex.Samad@yieldbroker.com] [snip] > > Hi Mladen > > Q) can I presume that this new version will not interfere with an old version > 1.2.32 ? as the mutex name used in this new one 1.2.34 wasn't used in 1.2.32 ? This has me thinking and think I have found another bug. :) Our setup is IIS 7.5 setup as a Reverse proxy. We run PRD, UAT through here. Trying to treat this an infrastructure box. We have 2 in a NLB setup For each environment I have a separate web server and directory setup so C:\ABC\ Prod\ Ajpconfig\ UAT\ Ajpconfig\ In each environment I have a ajpconfig directory where I put my dll and I keep all my config files for just that environment. The idea was that I could have different version of the tomcat connector thus test stuff out in UAT and then move on to PRD. BUT there is no way to set the name space used in the tomcat connector in relation to the Shared Memory or to semaphore. So Global\\JK_ISAPI_REDIRECT_MUTEX is used by all tomcat connectors (the ones in prod and the ones in UAT) And I would presume the Shared Memory would also be shared between the 2 ? Quote from the doco ! " The ISAPI redirector can read it's configuration from a properties file instead of the registry. This has the advantage that you can use multiple ISAPI redirectors with independent configurations on the same server. The redirector will check for the properties file during initialisation, and use it in preference to the registry if present." You can't do this with the IIS connector and with multiple processes (web gardens)! Could I make a bug/feature request to add something like Shm_namespace To the isapi_redirect.properties file and have this value post fixed to the shared memory name and the semaphore handle... Doesn't make sense if configured via the registry I have create a bugzilla for this basically outlining what I have here. The one thing I am not sure of is how much of a problem that is... The config files for uat and prd have different tomcat destinations, but the load balancer and worker names are the same !! The pathing is different though The previous bug which I think this version fixes is which I guess can be closed Thanks > > Alex > > -----Original Message----- > From: Alex Samad - Yieldbroker [mailto:Alex.Samad@yieldbroker.com] [snip] --------------------------------------------------------------------- To unsubscribe, e-mail: users-unsubscribe@tomcat.apache.org For additional commands, e-mail: users-help@tomcat.apache.org
http://mail-archives.apache.org/mod_mbox/tomcat-users/201203.mbox/%3CA3FB5D9FD28C50429DF7692DC31054E6048B72ED@DC1INTADCW8201.yieldbroker.com%3E
CC-MAIN-2016-18
refinedweb
435
64.2
Making Code Faster: The Interview Question Making Code Faster: The Interview Question The author offers a question to ask in coding interviews to illuminate several aspects about a particular candidate's thinking. Join the DZone community and get the full member experience.Join For Free Interview questions are always tough to design. an interview task, they are going to google, copy and paste, and: // code var summary = from line in File.ReadAllLines(args[0]) let record = new Record(line) group record by record.Id into g select new { Id = g.Key, Duration = TimeSpan.FromTicks(g.Sum(r => r.Duration.Ticks)) }; using (var output = File.CreateText("summary.txt")) { foreach (var entry in summary) { output.WriteLine($"{entry.Id:D10} {entry.Duration:c}"); } } // data class public class Record { public DateTime Start => DateTime.Parse(_line.Split(' ')[0]); public DateTime End => DateTime.Parse(_line.Split(' ')[1]); public long Id => long.Parse(_line.Split(' ')[2]); public TimeSpan Duration => End - Start; private readonly string _line; public Record(string line) { _line = line; } } You can find the full file here. The only additional stuff is that we measure just how much this cost us. This code processes the 276MB file in 30 seconds, using a peak working set of 850 MB and allocating a total of 7.6 GB of memory. I’m pretty sure that we can do better. That is the task we give to candidates. This has the nice advantage of being a pretty small and compact problem, but to improve upon it, you actually need to understand what is going on under the covers. Published at DZone with permission of Oren Eini , DZone MVB. See the original article here. Opinions expressed by DZone contributors are their own. {{ parent.title || parent.header.title}} {{ parent.tldr }} {{ parent.linkDescription }}{{ parent.urlSource.name }}
https://dzone.com/articles/making-code-faster-the-interview-question
CC-MAIN-2019-26
refinedweb
294
51.34
This action might not be possible to undo. Are you sure you want to continue? 7 Penguin Group (USA) Inc., Appellant, v. American Buddha, Respondent. Richard Dannay, for appellant. Submitted by Charles H. Carreon, for respondent. Michael H. Page, for Public Citizen, amicus curiae. International Trademark Association; American Association of Publishers et al., amici curiae. GRA 1 The Ralph Nader Library is not affiliated with Ralph - 2 - Nader. - 3 archives. No. 7 nondomic - 3 - - 4 - No. 7).2 Because the Internet plays a significant role in this case, we narrow and reformulate - 2 - 5 principal place of business of the copyright holder? In answer to this reformulated question and under the No. 7 circumstances of this case, we conclude it is the location of the copyright holder. CPLR 302 (a) (3) (ii) or international commerce." Consequently, a plaintiff relying on this statute must show that (1) the defendant - 5 - - 6 - No. instate injury within the meaning of the statute. raise compelling arguments. Our analysis begins with Fantis Foods, where we found personal jurisdiction to be lacking in the absence of a "direct injury" within New York. In that case, Standard, a New York Both parties - 6 - - 7" (id. at 326). No. 7 instate - 7 - - 8 - No. 7 - 8 - - 9 - No. 7.3 Unlike American Eutectic, 3 Of course, we take no position on the merits of Penguin's - 9 - claims. - 10 - No. 7 it may make sense in traditional commercial tort cases to equate a plaintiff's injury with the place where its business is lost or threatened, it is illogical to extend that concept to online copyright infringement cases where the place of uploading is inconsequential and it is difficult, if not impossible, to correlate lost sales to a particular geographic area. In short, the out-of-state location of the infringing conduct carries less weight in the jurisdictional inquiry in circumstances alleging digital piracy and is therefore not dispositive. The second critical factor that tips the balance in favor of identifying New York as the situs of injury derives from the unique bundle of rights granted to copyright owners. - 10 - - 11 § 106). Hence, a copyright holder possesses an overarching No. 7 "right to exclude others from using his property" (eBay Inc. v MercExchange, L.L.C., 547 US 388, 392 [2006] [internal quotation marks and citation omitted]). Based on the multifaceted nature of these rights, a New York copyright holder whose copyright is infringed suffers something more than the indirect financial loss we deemed inadequate in Fantis Foods. For instance, one of the harms arising from copyright infringement is the loss or diminishment of the incentive to publish or write - 11 - - 12 - No. 7 fatal to a finding that the alleged injury occurred in New York.4, it is undisputed that American Buddha's Web sites are accessible by any New Yorker with an Internet connection and, as discussed, an injury allegedly inflicted by digital piracy is felt throughout the United States, which necessarily includes New York. In sum, the role of the Internet in cases alleging the uploading of copyrighted books distinguishes them from traditional commercial tort cases where courts have generally linked the injury to the place where sales or customers are lost. The location of the infringement in online cases is of little - 4 - 13 - No. 7 import inasmuch as the primary aim of the infringer is to make the works available to anyone with access to an Internet connection, including computer users in New York.).5) We do not find it necessary to address whether a New York copyright holder sustains an in-state injury pursuant to CPLR 302 copyright infringement case did not exist because the injury occurred where the alleged out-of-state infringement took place]). - 13 - 5 - 14 - No. 7 . Accordingly, as reformulated, the certified question should be answered in accordance with this opinion. * * * * * * * * * * * * * * * * * -
https://www.scribd.com/document/51495413/Penguin-Group-v-American-Buddha
CC-MAIN-2017-13
refinedweb
643
55.95
Serverless solution for uploading files on s3 using lambda function as api for getting pre-signed urls with write access to upload files directly on s3. Of various ways of uploading images or any files on s3, here we are focussed on providing front-end a way to directly upload file on s3. This approach saves back-end server processing, network bandwidth and provides easy yet secure way to directly upload files on s3. Summary of what we are doing - Front-end makes a request to get pre-signed urls which can be used to upload file on s3. - A lambda function is connected with api gateway, thus get’s invoked when front-end makes a request to get pre-signed urls. - Lambda function connects with s3 to get pre-signed urls and pass these urls to the front-end in response. - Front-end after receiving the pre-signed urls makes a PUT request to this url along with the file to upload. Alright let’s see the code of lambda function that gets the pre-signed urls and pass it on to front-end. It is written in typescript. import AWS from 'aws-sdk' import { APIGatewayEvent, Context, Callback } from 'aws-lambda' // Setting AWS authentication const myAWSConfig = new AWS.Config() myAWSConfig.update({ accessKeyId: process.env.AWS_ACCESS_KEY_ID, secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY, region: process.env.AWS_REGION, }) // Create a S3 service object const s3Client = new AWS.S3(myAWSConfig) export const handler = (event: APIGatewayEvent, context: Context, callback: Callback) => { const params = { Bucket: 'bucket-name', // Name of your S3 bucket Key: 'some-file-name or unique id', // Filename Expires: 300, // Time to expire in seconds } try { // Generating a preSignedUrl for a putObject const data = await s3Client.getSignedUrlPromise('putObject', params) // 'putObject' for writing and 'getObject' for reading const response = { statusCode: 200, body: JSON.stringify(data), } return response } catch (e) { return { statusCode: 500, } } } That’s all! Now the front-end can make a PUT request on the received url along with file that needs to be uploaded and that will be uploaded on the s3 bucket. Let me know your feedback/suggestions in the comments. - Ayush 🙂
https://heyayush.com/using-lambda-function-as-rest-api-to-upload-files-on-s3/
CC-MAIN-2021-21
refinedweb
348
54.83
Feature Comparisons ADLS Gen 2 is where all future development of Azure Big Data storage is taking place, in the cloud server as well as the client connector. In contrast, ADLS Gen 1 must be considered a maintenance only data store, which is not being rolled out across more Azure regions. Differences between ADLS Gen 1 and ADLS Gen 2 ADLS Gen 2 should be considered as a reimplementation of the ADLS Gen 1 features, but integrated with the original Azure Storage. Features of ADLS Gen 2 - Supports the Hadoop FileSystem API, with directories, file and directory permissions, and other key features. - Reads and writes data stores in the original Azure Storage (which has previously used the wasb:// URL) - No integration with ADLS Gen1. The adls:// connector must be used there. - Available in all Azure regions. - If an ADLS Gen 2 account is created "without hierarchical namespaces" then the wasb:// connector can read/write data stored in ADLS Gen 2. - Capable of storing many Petabytes of data.
https://docs.cloudera.com/cdp-private-cloud-base/7.1.7/cloud-data-access/topics/cr-cda-feature-comparisons.html
CC-MAIN-2021-39
refinedweb
167
61.26
Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video. Instantiation6:28 with Jeremy McLain Instantiation is the process of creating an object from a class. Click on the Downloads tab to download all the code written in each video of this course. C# Namespaces from C# Basics Course Common C# Naming Conventions - 0:00 One place we can easily see object oriented programming in action - 0:04 is in video games. - 0:05 This is because many video games portray simulations of things - 0:08 that might exist in the real world. - 0:10 Take a tower defense game for example. - 0:13 There are lots of tower defense games out there. - 0:16 They all have a few things in common though. - 0:18 The player places towers on a map, invaders move down a path and - 0:22 the towers shoot at them as they pass by. - 0:25 The player wins if the towers destroy the invaders before they - 0:29 can reach the end of the path. - 0:31 In order to write this game, one of the first things we need to do is - 0:35 decide what types of objects the game should contain. - 0:38 In other words, we need to determine what classes we need to code up. - 0:42 For this, it's often a good idea to pay attention to the nouns that are used to - 0:47 describe the program. - 0:48 Let's take a look at the description of the game. - 0:51 The player places towers on a map, invaders move down a path, and - 0:56 the towers shoot at them as they pass by. - 0:59 The player wins if the towers destroy the invaders before they - 1:03 can reach the end of the path. - 1:05 Let's see here. - 1:06 We have the nouns, player, tower, - 1:11 map, invader and path. - 1:14 We can model each of these types of objects in code. - 1:18 Let's open work spaces and do it. - 1:20 To open work spaces, just click on the work spaces button on your screen. - 1:24 Let's start by creating a class for our tower. - 1:28 The first thing we need to do is create a file. - 1:30 We'll call it tower.cs. - 1:33 The code for this game will go in the treehouse defense namespace. - 1:37 If you're unsure about why I'm using a namespace here, - 1:41 I suggest checking out the teachers notes for a video about namespaces in C#. - 1:46 Now, we can declare a class called tower. - 1:51 Now, we have a tower class. - 1:53 Right now it's just an empty class though. - 1:56 Other than the name, there's nothing about this class that describes what a tower is, - 2:00 or how it should behave. - 2:02 We still need to add code to the class to do this. - 2:05 It's important to remember that the tower class is not a tower itself. - 2:08 It's just a template for creating tower objects. - 2:11 To create an actual tower object, - 2:14 we need to use this class to create an object of type tower just like we use - 2:18 the heart cookie cutter to create a heart-shaped cookie. - 2:22 Let's see how to do that now. - 2:24 You can see here, that I've already created a file called game.cs. - 2:30 It contains the definition of the game class. - 2:33 It also contain our main method. - 2:36 Remember the main method is a specially named method that will be run first when - 2:40 our program starts. - 2:42 This is where we'll create our first tower object. - 2:45 We can do this by first saying what type of an object it is. - 2:49 So, Tower then give the object a name. - 2:53 We'll use tower with the lowercase t and - 2:57 then equals new Tower followed by open and closing parentheses. - 3:03 Remember, we end all statements in C# with a semicolon. - 3:07 This creates a new variable called tower with a lowercase t that - 3:12 is of type Tower with an uppercase T and assigns it a newly created Tower object. - 3:19 In C# the convention is to name classes starting with a capital letter. - 3:25 This is handy when creating objects because then we - 3:28 can just name them the same as their types except the first letter is in lowercase. - 3:33 We could have named this anything. - 3:35 We could have named it Bob except that that wouldn't make a lot of sense. - 3:39 But we wanna give our variables meaningful names. - 3:41 For now, tower with a lower case t will do. - 3:46 Let’s review what we just did. - 3:48 We just used the tower cookie cutter to stamp out a new tower cookie, - 3:53 and that's how you create an object. - 3:56 Now you'll hear me and others use the terms object and instance interchangeably. - 4:01 By creating a tower object, we've just created an instance of the tower class. - 4:07 We could also call this a tower instance. - 4:11 In fact, the term for creating an object from a class is called instantiation. - 4:17 We just instantiated an object from the tower class. - 4:22 Sometimes you might think that all of this - 4:25 redundant terminology is just there to confuse you and maybe it is. - 4:29 But even so, - 4:31 it's good to be able to recognize these terms when you hear or read them. - 4:35 Just remember that an object is an instance of a class and - 4:39 you can use the terms object and instance interchangeably. - 4:43 Let's go ahead and create the rest of our classes. - 4:46 We'll need to have one for Invader. - 4:48 We'll create a new file called Invader.cs. - 4:52 To save on typing, I'll just copy the code from Tower.cs. - 4:59 Paste it here and then change the name of the class to Invader. - 5:07 Let's make another one for map in map.cs - 5:21 We'll also make one for path. - 5:34 As you can see, we've created classes for - 5:36 all of the nouns in our description except for player. - 5:39 For now, let's hold off on creating a class for the player. - 5:44 We now have five files in our project, one for each of the classes we've created. - 5:49 You don't have to create a separate file for each class. - 5:53 You also don't need to name them the same as the class. - 5:56 This is just the convention that most people use. - 5:59 You'll notice that a lot of the way that we name things and - 6:02 organize things in a C# project are based on convention. - 6:06 Conventions are not hard and set rules. - 6:09 They're just things that developers have come to a general consensus to do in - 6:14 order to make the code easier to read and to use. - 6:17 Using conventions helps make the code look more professionally done. - 6:21 What we've just done is create a scaffold for a game project. - 6:25 Now we just need to fill out the class definitions.
https://teamtreehouse.com/library/instantiation
CC-MAIN-2019-43
refinedweb
1,312
82.24
time() Determine the current calendar time Synopsis: #include <time.h> time_t time( time_t * tloc ); Since: BlackBerry 10.0.0 Arguments: - tloc - NULL, or a pointer to a time_t object where the function can store the current calendar time. Library: libc Use the -l c option to qcc to link against this library. This library is usually included automatically. Description: (GMT)). You typically use the date command to set the computer's internal clock using Coordinated Universal Time (UTC). Use the TZ environment variable or _CS_TIMEZONE configuration string to establish the local time zone. Returns: The current calendar time, in seconds, since 00:00:00 January 1, 1970 Coordinated Universal Time (UTC). If tloc isn't NULL, the current calendar time is also stored in the object pointed to by tloc. Examples: Classification: Last modified: 2014-06-24 Got questions about leaving a comment? Get answers from our Disqus FAQ.comments powered by Disqus
https://developer.blackberry.com/native/reference/core/com.qnx.doc.neutrino.lib_ref/topic/t/time.html
CC-MAIN-2020-10
refinedweb
153
50.94
Updating a webview Hi, I'm fairly new to Pythonista development and was struggling to get the contents of a webview to change when I click a button in my script. The script has a UI, on which I've dropped a button and a webview. I've wired the button event to 'ButtonClick' (below), and I know this gets called as I've tested it with a console alert. I've tried alternatives such as referring to the original webview instance and also via the sender superview. What I'm seeing is that the webview gets updated initially, but never seems to show the effect of the new contents in the button click ('my second heading'). What am I doing wrong? Thanks! Tom === import ui import tempfile import os import console def ButtonClick(sender): v1 = sender.superview #w=v1['webview1'] #console.alert(str(w)) w.load_html('<!DOCTYPE html><html><body><h1>My Second Heading</h1></html>') #w.present() v = ui.load_view('Test') w=v['webview1'] w.load_html('<!DOCTYPE html><html><body><h1>My First Heading</h1></html>') v.present('fullscreen') Your code works exactly as expected for me. "My First Heading" is displayed initially in the WebView. After a button press, "My Second Heading" is displayed in the WebView. @ccc Thanks ccc. A bit embarrassing but I'd left in the console alert on my script and that seems to prevent the webview from updating even after you acknowledge the alert. Without it, it works for me too.
https://forum.omz-software.com/topic/3007/updating-a-webview
CC-MAIN-2017-47
refinedweb
249
59.5
@jsh6789: I've added it to optdepends for now, since not every Mnemosyne installation needs to support starting a sync server. Search Criteria Package Details: mnemosyne 2.4.1-4 Dependencies (10) - python-cherrypy - python-matplotlib (python-matplotlib-git) - python-pillow - python-pyqt5 (python-pyqt5-hotfix) - python-webob - qt5-webengine - python-setuptools (make) - python-cheroot (optional) – support for starting a sync server - texlive-core (texlive-dummy) (optional) – support for mathematical formulae in cards -) – support for non-latin labels on statistic plots Required by (0) Sources (1) Latest Comments smls commented on 2017-04-28 09:50 jsh6789 commented on 2017-04-04 00:05 In order to start the sync server, the package python-cheroot must be installed; please add it as a dependency. Relevant error message: Traceback (innermost last): File "/usr/lib/python3.6/site-packages/mnemosyne/pyqt_ui/configuration_dlg.py", line 54, in accept self.tab_widget.widget(index).apply() File "/usr/lib/python3.6/site-packages/mnemosyne/pyqt_ui/configuration_wdgt_servers.py", line 84, in apply self.component_manager.current("sync_server").activate() File "/usr/lib/python3.6/site-packages/mnemosyne/pyqt_ui/qt_sync_server.py", line 193, in activate component_manager=self.component_manager) File "/usr/lib/python3.6/site-packages/mnemosyne/pyqt_ui/qt_sync_server.py", line 65, in __init__ super().__init__(ui=self, **kwds) File "/usr/lib/python3.6/site-packages/mnemosyne/libmnemosyne/sync_server.py", line 31, in __init__ port=config["sync_server_port"], **kwds) File "/usr/lib/python3.6/site-packages/mnemosyne/libmnemosyne/component.py", line 48, in __init__ super().__init__(**kwds) File "/usr/lib/python3.6/site-packages/openSM2sync/server.py", line 98, in __init__ from cheroot import wsgi ModuleNotFoundError: No module named 'cheroot' Thanks in advance, JSH bonob commented on 2017-01-11 15:16 Support for Fcitx input method requires fcitx-qt5 when upgrading to Mnemosyne 2.4. Not sure if that deserves an optional dependency here, or maybe a note on the wiki page? In any case, if someone runs into the same problem as me, my comment may be of help. smls commented on 2016-12-21 00:47 @bialou: Added. bialou commented on 2016-12-20 23:32 @smls So we probably should put that python-pillow package as a dependency. .... or any other package that has pillow and/or(?) image in it. P.S. I run i3wm, if it matters. bialou commented on 2016-12-20 23:26 @Ichimonji10 "pip3 install --user image" installed 3 packages: django-1.10.4 image-1.5.5 pillow-3.4.2; I uninstalled them manually and tried python-pillow package instead. Everything still works good now and I don't have that error on "Browse Cards" button you have. So, it must be something else going on. The only thing I did before installing python-pillow is to uninstall django, image, and pillow with "pip uninstall ..." Ichimonji10 commented on 2016-12-20 22:57 @smls, thanks for the fix! Mnemosyne no longer suffers from the error I outlined. I now suffer from the same error described by @bialou: PIL (python imaging library) is not installed. The suggested solution is to install image with pip. I *think* a more generic solution is to install the python-pillow package with pacman. It works well enough to let mnemosyne start. Edit: I'm now suffering from a new issue. It's probably an issue with mnemosyne itself. @smls, can you take a look, and let the maintainers know about it if appropriate? This error log pops up when I press the "Browse cards" button. bialou commented on 2016-12-20 06:16 @hongleong: Installing it manually "pip3 install --user image" takes care of that problem. Hopefully, this can be fixed correctly later. Thank you, for help. hongleong commented on 2016-12-20 03:28 @bialou: pip3 install --user image bialou commented on 2016-12-20 03:03 mnemosyne 2.4-2 fails to start. /usr/bin/python ==> Python 3.5.2 --------------------------------------------------- ~]$ mnemosyne QIODevice::write (QProcess): device not open An unexpected error has occurred. Please forward the following info to the developers: Traceback (innermost last): File "/usr/bin/mnemosyne", line 229, in <module> debug_file=options.debug_file) File "/usr/lib/python3.5/site-packages/mnemosyne/libmnemosyne/__init__.py", line 234, in initialise self.main_widget().activate() File "/usr/lib/python3.5/site-packages/mnemosyne/pyqt_ui/main_wdgt.py", line 52, in activate self.start_review() File "/usr/lib/python3.5/site-packages/mnemosyne/libmnemosyne/component.py", line 121, in start_review self.review_controller().reset() File "/usr/lib/python3.5/site-packages/mnemosyne/libmnemosyne/review_controllers/SM2_controller.py", line 62, in reset self.show_new_question() File "/usr/lib/python3.5/site-packages/mnemosyne/libmnemosyne/review_controllers/SM2_controller.py", line 123, in show_new_question self.update_dialog() File "/usr/lib/python3.5/site-packages/mnemosyne/libmnemosyne/review_controllers/SM2_controller.py", line 200, in update_dialog self.update_qa_area(redraw_all) File "/usr/lib/python3.5/site-packages/mnemosyne/libmnemosyne/review_controllers/SM2_controller.py", line 237, in update_qa_area w.clear_answer() File "/usr/lib/python3.5/site-packages/mnemosyne/pyqt_ui/review_wdgt.py", line 248, in clear_answer self.update_stretch_factors() File "/usr/lib/python3.5/site-packages/mnemosyne/pyqt_ui/review_wdgt.py", line 145, in update_stretch_factors self.estimate_height(self.question_text) File "/usr/lib/python3.5/site-packages/mnemosyne/pyqt_ui/review_wdgt.py", line 114, in estimate_height from PIL import Image ImportError: No module named 'PIL' ------------------------------------- smls commented on 2016-12-16 12:21 @Ichimonji10 It turns out `qt5-webengine` needed to be explicitly specified as a dependency. The package has been updated. (I thought `python-pyqt5` pulls in all the Qt stuff, but apparently Qt is more modular now than it was during Qt4 times.) smls commented on 2016-12-16 11:57 @Ichimonji10 It starts fine for me. Maybe I forgot to explicitly specify a dependency or something? Please ensure that your Arch Linux is fully upgraded, and that /usr/bin/python points to python3. Meanwhile, I'll try to investigate the issue on my end. Ichimonji10 commented on 2016-12-15 18:40 The current version of mnemosyne fails to start. Downgrading to version 2.3.6 (git checksum a35a25f) allows mnemosyne to start. See: smls commented on 2016-05-19 02:55 @marmistrz Sorry about that. Fixed now. marmistrz commented on 2016-05-18 13:06 The md5sum check fails as of 2016-05-18. smls commented on 2014-10-20 16:59 It looks like russo79's patch was committed upstream, so after the next Mnemosyne release it will no longer need to be bundled with the PKGBUILD... :) shuu commented on 2014-10-12 02:51 It looks like python2-distribute should be changed to python2-setuptools in the extra repo. Python2-distribute is not in the AUR anymore. shuu commented on 2014-10-08 23:03 python2-distribute doesn't appear to be in the AUR anymore. russo79 commented on 2014-09-03 19:51 Here [1] (in the mnemosyne directory)! russo79 commented on 2014-09-03 19:51 Here [1]! joelsc commented on 2014-09-03 17:45 Note that you can get the basic functionality (without plotting) by commenting line 9 from the file /usr/lib/python2.7/site-packages/mnemosyne/pyqt_ui/statistics_wdgts_plotting.py: - from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas + #from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas vagyok commented on 2014-08-30 18:54 Thanks for your quick and helpful response. I can confirm that downgrading to python2-matplotlib 1.3.1-4 fixed the issue for me. As far as I can see, though, the current version of python2-matplotlib in [community] has been 1.4.0-1 since 2014-08-28. smls commented on 2014-08-30 14:15 For now, you can make it work by downgrading python2-matplotlib to version 1.3.x (which is still the current version in [community] -- only version 1.4.0 from [community-testing] is causing the issue). As for the python2-pyqt -> python2-pyqt4 rename, I've updated the PKGBUILD now to reflect this. Still investigating the issue with matplotlib 1.4 though. smls commented on 2014-08-30 13:06 @vagyok: Thanks for reporting; I see the same errors. For what it's worth, python2-pyqt4 is the correct dependency as Mnemosyne is a Qt4 program; the fact that the matplotlib dependency tries to load Qt5 is strange. I'll investigate. vagyok commented on 2014-08-30 12:09 python2-pyqt , which is currently a dependency of this package, no longer seems to exist - it is apparently either python2-pyqt4 (which replaced python2-pyqt ) or python2-pyqt5 in [extra] now. Trying it with python2-pyqt4 (and its pyqt4-common dependency) gave me the following error: File "/usr/lib/python2.7/site-packages/matplotlib/backends/qt_compat.py", line 91, in <module> from PyQt5 import QtCore, QtGui, QtWidgets ImportError: No module named PyQt5 (in full: ) Trying it with both python2-pyqt4 (and its pyqt4-common dependency) and python2-pyqt5 (and its pyqt5-common dependency) installed before rebuilding the package gave me the following error: File "/usr/lib/python2.7/site-packages/matplotlib/backends/qt_compat.py", line 91, in <module> from PyQt5 import QtCore, QtGui, QtWidgets RuntimeError: the PyQt5.QtCore and PyQt4.QtCore modules both wrap the QObject class (in full: ) Trying to remove python2-pyqt4 (and/or pyqt4-common) so as to use only python2-pyqt5 and pyqt5-common failed because this package depends on python2-matplotlib in [community], which requires python2-pyqt4 explicitly, which, in turn, requires pyqt4-common. Any suggestions? smls commented on 2013-08-24 11:39 Glad it worked out :) gojun077 commented on 2013-08-24 05:05... gojun077 commented on 2013-08-24 05:00... smls commented on 2013-08-23 11:36 @gojun077 If the problem persists, try manually following the individual steps that Mnemosyne performs, to see where exactly the problem lies: 1) Create a file called tmp.tex with the following content: \documentclass[12pt]{article} \pagestyle{empty} \begin{document} $\sqrt{x^3}$ \end{document} 2) Execute the command... latex tmp.tex ...which will try to create a file called tmp.dvi in the same folder. Be sure to also check the console output for errors. 3) Execute the command... dvipng -D 200 -T tight tmp.dvi ...which will try to create a file called tmp1.png in the same folder. smls commented on 2013-08-23 11:29 @gojun077 That's strange, there should not be any need for special permissions or groups - for me it just works. Mnemosyne creates its LaTeX related temporary tex/dvi/png files in this folder (insert the name of your Mnemosyne database in place of "___TMP___", if you have given it an explicit name.): ~/.local/share/mnemosyne/___TMP___.db_media/_latex Make sure that there are no permission problems with this folder, and if there are old files there that may cause problems, remove them. gojun077 commented on 2013-08-23 06:01 Thanks for your help in the dvipng / LaTeX thread on the main Arch Linux forums () -- Now dvipng LaTeX rendering works in mnemosyne if I run it as root. When I run mnemosyne as regular user and try to create a card with LaTeX, however, the CLI output says "tmp.dvi: No such file or directory" and Mnemosyne complains, "Problem with latex. Are latex and dvipng installed?" This seems to be a file permission issue, but ls -l shows dvipng as r-x for regular users. Does my regular user need to be member of some group (i.e. tex) to be able to run LaTeX as non-root? After the texlive update I accidentally overwrote my /etc/group file when merging .pacnew files but have mostly recovered my original settings. I'm not sure if this is the right place to post this issue, as mnemosyne AUR package works just fine -- I seem to be having problems with texlive which is just an optional dependency for mnemosyne... Note: LaTeX editors like Gummi, which render to PDF, are working just fine for me (I can run it as local user). smls commented on 2013-03-29 18:56 @gojun077 Thanks, I've bumped the version number of the mnemosyne-bzr package. For the mnemosyne package, I prefer to stick to stable releases only. gojun077 commented on 2013-03-29 17:21 According to main developer Peter Bienstman 2.2.1 RC1 released yesterday: smls commented on 2013-01-08 03:01 done prettyvanilla commented on 2013-01-08 02:00 2.2a was released (), and even though the changelog only concerns windows, the tarball on sourceforge has also been renamed accordingly, so the PKGBUILD needs updating. Anonymous comment on 2012-08-03 06:05 Working reliably now with version 2.0.1, thank you. smls commented on 2012-08-02 20:41 Version 2.0.1 was just released - package updated accordingly. smls commented on 2012-08-01 22:36 No crashes here. Anyways, according to the upstream mailinglist, a new version (2.0.1) which supposedly fixes certain crashes will be released soon. A release candidate is already available, you can install it using the following PKGBUILD: - can you try that one and see if it solves your issue? Anonymous comment on 2012-08-01 16:40 Is anyone else experiencing random crashes with 2.0? I am crashing the program using the same database on two different Arch systems. The developer has acknowledged a problem but it does not seem to be prevalent on Linux. It's been a couple of weeks now and I'm thinking about going back to the old program. smls commented on 2012-07-15 14:11 I've updated the package to the current stable version 2.0 now. In case of problems or suggestions, please leave a comment. smls commented on 2012-07-15 14:08 @dsr: Thanks... Anonymous comment on 2012-07-14 20:45 Sorry I had forgotten I was the maintainer. I am disowning it now so you can adopt it. :) smls commented on 2012-06-16 08:08 @Maintainer: See my "mnemosyne-bzr" package for build instructions for the 2.x version, and a useful post-install message for users who upgrade from 1.x ... I think it makes sense to let "mnemosyne-bzr" continue to point the head of the main development branch, and let this package ("mnemosyne") install the newest stable version of that branch, i.e. currently 2.0... In case anybody wants to keep using Mnemosyne 1.2 (why would they?), a legacy "mnemosyne1" package could be created. What do you think? (PS: If you don't want to maintain this package anymore, I'd be happy to take it over.) smls commented on 2012-06-16 08:03 Version 2.0 is finally out! (Announcement at) smls commented on 2012-02-11 17:41 FYI, I just created the AUR package mnemosyne-bzr, which installs the latest development snapshot of Mnemosyne 2 (which finally uses Qt4 instead of Qt3, and provides several cool new features) from the official bazaar repository. The current state is already past version 2.0-beta10, and is already stable enough for normal usage. Anonymous comment on 2010-10-24 20:28 All right, just did. bostonvaulter commented on 2010-10-21 23:06 Thanks dsr, I've adopted and updated the package. Although I don't use mnemosyne anymore (I use Anki), maybe you'd like to adopt the package instead? Anonymous comment on 2010-10-21 17:36 Now that python was changed to python2 and python3 was changed to python, the line in the PKGBUILD that reads ``python setup.py install --root=${pkgdir}" should be changed to ``python2 setup.py install --root=${pkgdir}"
https://aur.archlinux.org/packages/mnemosyne/?comments=all
CC-MAIN-2017-22
refinedweb
2,583
59.19
Well… this has been one of the longer blog series I have done, but there is so much meat here! Maybe someone will write a book or two? Anyway, in this post, I wanted to spend a little time looking at the project structure we have been working with and see if there is a way to improve it a bit with more clear separation of concerns. For those of you just joining it, this is yet more updates… The core project structure we have been using so far is a single solution with two projects in it: MyApp – The Silverlight App MyApp.Web – the web application The MyApp.Web project actually has two very distinct concerns.. the first is handing the AppLogic for the entire app, the 2nd is the web and services interfaces (specifically the default.aspx down level rendering, sitemap.aspx and SuperEmployeeService.svc). Two concerns in the same project bother me at some level as I tend to like a cleaner separation for maintenance and better cross team work. Luckily, new in the July update to RIA Services is a new RIA Services Class Library project. We will look at refactoring the MyApp.Web project to pull out the appLogic concerns into a separate project. Right click on the solution and select “Add New Project….” This creates a pair of class library projects.. one for the client and one for the server. First you will need to add a reference from the MyApp.Web project to the SuperEmployeeRIAServicesLibrary.Web.. We are going to want to access the DomainService defined in this library from several places in the WebApp. Now, simply add an Entity Framework model and SuperEmployeeDomainService to the SuperEmployeeRIAServicesLibrary.Web project exactly as we way back in step 2. Once you have the SuperEmployeeDomainService class created, you can copy over the implementations we did thus far… remember to grab the cool metadata validation attributes as well. Then you can delete the Domain services classes from the MyApp.Web project. This gives you a very clean set of concerns.. Notice that SuperEmployeesRIAServicesLibrary.Web contains the datamodel and Domain classes and the MyApp.Web project has the asp.net pages and the service. All that access the DomainModel from the class library project. Notice if you are using the “Business Application Template” as I am in this walk through, you will notice a Services folder that includes some DomainServices for dealing with user management. In some ways, I think of this as an application wide concern, so it might make sense to leave these in the web project, but if you’d like to move them, no problem. Just add the following steps: 1. Move the entire directly to the SuperEmployeeRIAServicesLibrary.Web project. It is likely a bit cleaner to update the namespaces in these types, if you do so, you will need to update the namespaces on the client as well. 2. Break the “RIA Services Link” from the Silverlight client to the MyApp.Web project in the MyApp properties page. 3. Add a project reference from MyApp to SuperEmployeesRIAServicesLibrary 4. Add a simple RIAContext class to your application public sealed partial class RiaContext : System.Windows.Ria.RiaContextBase{partial void OnCreated();public RiaContext(){this.OnCreated();}public new static RiaContext Current{get{return ((RiaContext)(System.Windows.Ria.RiaContextBase.Current));}}public new User User{get{return ((User)(base.User));}}} 5. Explicitly wire up the AuthDomainContext in App.xaml.cs with lines 5 and 6. 1: private void Application_Startup(object sender, StartupEventArgs e)2: {3: this.Resources.Add(“RiaContext”, RiaContext.Current);4:5: var auth = RiaContext.Current.Authentication as FormsAuthentication;6: auth.DomainContext = new AuthenticationContext();7:8: this.RootVisual = new MainPage();9: } Again, the above steps are optional – only if you want to factor out the DomainService completely from your web application. Now we just need to update some namespace references across the silverlight client and the web because our DomainService class is in a new namespace. And presto! The apps works great, but now the project is better factored for long term maintenance. Notice that every aspect of the app keeps working…. The Silverlight client.. The ASP.NET view (for SEO).. The Service… And of course the WinForms client for that service.. So Brad, let my clarify this: a) Your new RIAServiceLibrary.Web is referencing the old MyApp.Web? b) And your SL Client is Referencing the new RIAServiceLibrary (client dll)? c) And what happens after you break the link “RIA Services Link” from the Silverlight client to the MyApp.Web project? Do you leave it broken? d) I think it would be great if the "Business Template" would do this automatically! Brad, this whole series have been very helpful, but this was something I needed now 🙂 The RIA docs is very brief on this sunject. Thanks! ..Ben This is a great post for Silver light application. I am looking forward for your upcoming posts. Good Work Singh Brad, I have encountered the following errors: 1. When using EF DAL, if I add an association I get a compile error that the association cannot be found when generating the client side code. 2. When using LTS with a DomainService I get compile errors that all the entities are defined multiple times when generating client side code. Also, an example of using the DomainContext.Load method with callback methode would be usefull. Thanks for this great series. Brad, never mind on my (a) question. So, basically the SL Client (MyApp) reference the new RIA Service client and the SL web section (MyApp.Web) references the new RIA Service Web. But I’m still puzzled about the Link breakage. Could you also explain the addition of RIAContext class. Thanks! ..Ben Part 13? Where’s the first part? Chris — wow, the series has gotten long if you can’t even see the first one 😉 Try this: OK, so I’ve followed this through and done exactly as you’ve said, but as soon as I load the application my datagrid is empty and the Activity doesn’t even show. Any ideas as to why this might happen? Great, I suppose this will make integrating with Prism much easier! Hopefully I can save someone else some pain 🙂 If you are following along with this series, the above will work just fine. HOWEVER if you never built this app with a combined library, but rather created it from scratch with a split RIA services library then remember this… YOU MUST COPY THE CONNECTION STRING from the Services library projects App.Config to the .Web projects Web.Config. I feel like such a newb 🙂 Ken Soulhuntre – thanks for the tip! This is a very important point… sorry I did not make that clear in the flow. Hi. "YOU MUST COPY THE CONNECTION STRING from the Services library projects App.Config to the .Web projects Web.Config" . – it’s there a way to provide this connectionString dynamically. The main idea is: – I want to dynamically deploy service (RIAServiceLibrary.Web modules) into my running application. The only problems is this connection string – I don’t want to manual add them in web.config file. Thanks! Radu
https://blogs.msdn.microsoft.com/brada/2009/07/28/business-apps-example-for-silverlight-3-rtm-and-net-ria-services-july-update-part-13-the-new-class-library-project/
CC-MAIN-2017-13
refinedweb
1,190
67.65
On June 26, 2013, in a 5-4 decision, the U.S. Supreme Court overturned the federal Defense of Marriage Act (“DOMA”) provision that. Washington State has recognized same sex marriage since 2012. However, significant estate planning opportunities for same-sex couples in our state. Additional Frequently Asked Questions Can my digital assets be a part of my estate plan? With so many people keeping their records electronically, participating in social media and storing photos on their computers, digital assets should be considered in many estate plans. As with your other assets, your Personal Representative or Successor Trustee will have control of many of the digital assets when you pass away. However, there may be various concerns. First, the person needs. Certain providers may also have their own process to transition or remove accounts. Finally, providing clear instructions is important. There may be other considerations as well so be sure to discuss this with your professional advisor..25 million per person. However, in the State of Washington, the estate tax exemption is only $2 million. I have heard references to “spousal portability” of the estate tax exemption. What is this? Is it a good idea to rely on this for estate planning? Spousal portability, which became a permanent part of the federal estate tax law earlier this year, is helpful for couples who do not have wills, or whose wills leave everything to the surviving spouse outright. With spousal portability, it is now possible for a second-to-die spouse to claim the first deceased spouse’s unused federal estate tax exclusion, thus allowing for the maximum use of both spouses’ federal estate tax exclusions. However, there are limitations to its use and a federal estate tax return must be filed to claim portability. Significantly, spousal portability is not available for Washington state estate taxes. Particularly for couples with a net worth over $2 million, you should consult your advisors to ensure that you have achieved appropriate planning for portability. What Action Did Congress Take That Impacts Estate and Gift Tax Planning? On January 1, 2013, Congress passed the “American Taxpayer Relief Act of 2012,” which is being described as a compromise deal to avert the fiscal cliff. This new law approves the first “permanent” set of estate, gift and generation-skipping transfer tax provisions in 12 years. The new Act continues many of the estate tax provisions that were in effect in 2012. Most significantly, the federal estate tax exemption remains at $5 million, indexed for inflation from 2011, which means that, for 2013, the federal estate tax exemption is $5.25 million. Similarly, the federal gift tax exemption remains at the same high level ($5.25 million), as does the federal generation-skipping transfer tax exemption. All three of these exemptions are indexed for inflation and therefore we can expect to see the exemptions increase in future years to reflect cost of living increases. In addition, the portability of the federal exemption between spouses is retained under the new law. However, the new Act does change the estate and gift tax rates. If an estate exceeds the federal exemption amount, it will be taxed at a top rate of 40%, which has been increased from the previous 35%. The same 40% rate applies to taxable gifts (i.e., lifetime gifts in excess of the available gift tax exemption).. My spouse died in 2011 or 2012. Even though a federal estate tax return is not required to be filed, should the estate file one anyway? In order to elect portability, a federal estate tax return (Form 706) must be timely filed. Portability allows a decedent’s unused federal exemption to be transferred to the surviving spouse’s exemption, allowing the surviving spouse to use his or her own exemption, plus the unused amount, when he or she later dies. Based upon the changes in the estate tax laws at the end of this year, portability may be an effective estate planning tool for a surviving spouse. Please note that the Form 706 must be timely filed, though recent regulations have provided for an automatic extension when the decedent passed away in the first six months of 2011. If you’ve lost your spouse recently, be sure to talk to your professional advisor about the portability election. .
https://www.lexology.com/library/detail.aspx?g=8aa10c28-80d0-482a-a94e-24105928526f
CC-MAIN-2018-13
refinedweb
717
54.52
No More Page Refreshes: use jQuery! Here's an open apology to users of web sites I helped build: “Sorry I made you suffer through unnecessary page refreshes.” That's the first thing that popped into my head after learning about jQuery earlier this year. jQuery is a powerful yet unobtrusive JavaScript library with a lousy name. It's concise, very readable syntax has me exciting about writing JavaScript again. It's unobtrusiveness makes it easy to add rich behavior—such as background form submissions—to web applications with very little modification of existing code. Being unobtrusive is particularly important when you are working with a large code base, or where extensive refactoring just isn't going to get funding. My boss is not going to give me 4 weeks to go back and add some visual goodness to an existing site. But I might get 4 hours, and that's where jQuery can help. As a simple example, imagine an automobile search function that returns results based on a vehicle Model. Enter text into the field, click submit, and the results are displayed. The JSP might look like: After the user enters a name and clicks submit, the entire screen turns white while the page refreshes and then the results are displayed. This is not a good user experience. Now, let's use jQuery to improve that experience by refreshing only the part of the page that actually needs to change. The modifications made to the existing page are: - Split the search form and search results into 2 separate JSPs so the results can be displayed separately, without having to re-render the search form. - Add a placeholder <div> on the search form JSP to hold the search results. - Add a line of jQuery that submits the search form in the background using AJAX, placing the results in the placeholder <div>. The resulting code looks like this: When the user enters a name and clicks submit, only the search results <div> will refresh. The user experience is improved, and we didn't have to write a lot of JavaScript. Let's look at the jQuery script fragment in a little more in depth: The code reads: Line 2 -- “When the page gets loaded...” Line 3 -- “Select a form with an id= 'searchForm', and make it AJAX-enabled (submit in the background)” Line 4 -- “Use POST as opposed to GET” Line 5 -- “Puts the results in a DIV with an id of 'searchResults'” Lines of jQuery code start with “$()” and always select an element such as “document” or “#searchForm” to operate on. jQuery acts like a decorator and allows you add all kinds of interesting behavior to elements such as AJAX-enabling forms, visual effects, drag-and-drop, and more. The example shows a lot of functionality baked into a couple of lines of code, and demonstrates why I like jQuery: the decorator approach makes it ideal for enhancing existing web apps. Rather than rewriting existing HTML, you can apply jQuery to decorate it and add new behavior. Returning data instead of HTML using Spring MVC and XStream/Jettison In the first example, jQuery was used on the client, but nothing significant was changed on the server. We still kept the basic flow, which involved the user clicking on something in the browser, a server request being created, and HTML being returned. But what if the server can return data in the form of JSON or XML instead of HTML? Returning data rather than renderable HTML allows the client to potentially cache the result, which reduces the number of server requests. Data is potentially more terse than HTML—this also reduces the size of the result when it needs to be returned. Look at the following example: In the standard flow, three user interactions with browser result in three server requests. Now let's look at an optimized flow where the server returns data instead of HTML: In the optimized flow, three user interactions only generated one server request. There are many potential data formats that can be returned by the server. Which one to select depends on the situation. Some options and reasons for selecting them: Let's look at a code example where the server returns JSON data to the browser. Let's replace the original car model search page with a page that includes both a make and model drop-down. When the user selects make, the models for that make are populated. When the user selects a model, a table listing the available model years is populated. Starting on the server side, we will see how we can use Spring MVC along with XStream and Jettison to serve up JSON data. First we'll build a Spring MVC controller: Line 1 – The @Controller annotation tells Spring MVC to use this class as, you guessed it, a controller Line 4 – The @RequestMapping annotation maps the request URL to the handler method Line 6 – A ModelAndView object is created with a view name of “carselector” which will get mapped to carselector.jsp Line 7 – A list of Makes is added to the ModelAndView using the key “makeList”. This object will be available in the JSP using the expression: ${makeList} Line 11 – Again, the @RequestMapping annotation maps the request URL to the handler method Line 12 – The @RequestParam annotation maps a request parameter to a method argument Line 13 – This ModelAndView is created using a simple JSON-rendering View class that I wrote called JsonView. Spring MVC makes is quite easy to write custom views, and JsonView is where XStream gets hooked in. Line 14 – A list of Models is added to the ModelAndView using a key that is expected by JsonView. In summary, the controller responds to two URLs, “carselector.html” and “models.html”. It renders an HTML page as the response to the “carselector.html” URL, via a standard JSP view. Let's take a look at the JsonView class, which renders the JSON result for the “models.html” request: Line 4 – XStream is instantiated using the JettisonMappedXmlDriver to output JSON instead of XML Line 6 – Spring MVC View classes must implement a render() method Line 9 – Get the data out the model that was created by the controller Line 11 – Actually generate the JSON (despite the fact that the method is named toXML) It really is that easy. The XStream library also includes a set of annotations that you can place on your domain or transfer objects to provide hints on how to render the JSON, but in general the library works with minimal configuration. Now the server is generating JSON, but how does the client use it? For that answer, we'll look at jQuery again. Remember, there are 2 events that we need to handle: selecting a value from the “make” dropdown populates the “model” dropdown. Selecting a value from the model dropdown populates the model year table. Here's the jQuery ready function that sets up the event handlers: The “select[name^=make]” expression looks a lot like a CSS selector, and that's because jQuery selectors are a super set of CSS selectors (kind of like if CSS and Regex had a baby together). These expressions are very powerful, and can be used to select single or multiple items at a time. In this case, the expression reads, “Select a <select> element whose name attribute is 'make' and bind the loadModels function to the change event". Every time a user selects a value from the dropdown, the change event is generated by the browser, and the loadModels function will get invoked. Now let's take a look at one of the event handlers: Line 2 - The getJSON method will perform a AJAX request and expect JSON returned by the server. It requires 3 parameters: the request URL, any request parameters, and a callback function to invoke once the server responds. Line 4 - The callback function is a closure. Closures in JavaScript are similar to anonymous inner classes in Java, and they are very useful to use as callbacks. Notice that this function expects the JSON returned from the server to be passed in as a parameter. Line 6 - At this point we need to know a little bit about the structure of the JSON we're working with. In this simple example, the model data is structured as the following: The code at line 6 reads, "For each model..." Line 7 & 8 - Construct an element from each model Line 10 - Select the <select> element where name=model, and replace the option list with the options that were just constructed. With the bare minimum of JavaScript, we were able to: - register an event handler, - get JSON data asynchronously - update the options in a dropdown based on that JSON. That's powerful stuff, and one of the reasons I really like jQuery. Now what about caching? It is a trivial case to add an "if" statement prior to the getJSON call to see if the result already exists in cache. There is a nice little jQuery plugin called jCache that you can use. Conclusion jQuery + Spring MVC + XStream/Jettison provides a really nice stack to rapidly develop web applications that cleanly separate data and presentation, provide the user with a better experience, and potentially improve performance along the way. Are there other high-quailty frameworks that can help you do this? Sure, but I like the combination of jQuery, Spring MVC and XStream/Jettison, and I feel each are "best-of-breed" in their particular niches. YOu can download the full example code HERE. About the Author Since his first Java assignment, printing reports with Java 1.02, Joel Confino has been hooked on Java technology. He has been working on distributed systems, various web architectures, and JEE design and programming for the past 10 years. Confino has consulted at many large financial services and pharmaceutical companies, and helped them use Java to expand their business and reach their customers with sophisticated web-based systems. He is currently a Java architect at Chariot Solutions.. Community comments How does this compare to the Ajax support that is in Spring MVC? by Jacek Furmankiewicz, Re: How does this compare to the Ajax support that is in Spring MVC? by Solomon Duskis, Re: How does this compare to the Ajax support that is in Spring MVC? by Joel Confino, Authentication by Gabriel Silva, Re: Authentication by Joel Confino, Example Code Posted by Joel Confino, Comparison to other JSon/Data Server side technologies by Solomon Duskis, Re: Comparison to other JSon/Data Server side technologies by Ayan Barua, Questions by Ilan M, Download lInk by Carlos Tevez, How does this compare to the Ajax support that is in Spring MVC? by Jacek Furmankiewicz, Your message is awaiting moderation. Thank you for participating in the discussion. I was just reading that Spring MVC 2.0 added a whole Javascript support module (based on Dojo). How would you describe your jQuery option compared to that default functionality? Re: How does this compare to the Ajax support that is in Spring MVC? by Solomon Duskis, Your message is awaiting moderation. Thank you for participating in the discussion. The Spring MVC JS support that you're talking about is based off of Spring 2.5+. I built something similar to Joel's framework. I've also looked into the Spring-JS stuff that's in the Spring Web Flow package. Basically, Spring-JS is an integration between Spring MVC and Tiles that only renders a partial HTML fragment rather than the whole page. The JS/Dojo portion calls the original controller and tells it which parts to render, and then how to place that HTML fragment back into the current page. Spring-JS is not in the Spring core package, and has to be downloaded as part of the Spring Web Flow package. Joel's approach uses JSon rather than HTML fragments. It also uses JQuery's built in DOM manipulation. It's more network friendly, but you may end up with more cross-browser issues, since you're doing a lot of DOM manipulation. JQuery handles a lot of issues, but not everything. JQuery seems to be a favorite of UI developers who are more comfortable in JS. Dojo seems to be a favorite of the Java/back-end guys. Authentication by Gabriel Silva, Your message is awaiting moderation. Thank you for participating in the discussion. Hello, What if user looses his/her session and then tries to use the system. How would you handle such situation? Is there any built-in solution in JQuery to handle that? Thank you for the article. Re: How does this compare to the Ajax support that is in Spring MVC? by Joel Confino, Your message is awaiting moderation. Thank you for participating in the discussion. Thanks Solomon for the good summary of Spring JS. I am new to Spring JS myself (2.0 was just released in April), but I agree with your assessment. So how do jQuery and Spring JS compare? I think they overlap. jQuery is more flexible and general purpose, but Spring JS looks promising and provides some features that jQuery doesn't (more on that below). Spring JS is geared towards the server returning HTML snippets. That architecture has advantages and disadvanges like any other. One really nice advantage is that Spring JS will degrade nicely if the browser doesn't support JavaScript. jQuery can also be used to return HTML snippets, but obviously can only function in browsers that run JavaScript. While Spring JS currently uses Dojo as the underlying JavaScript framework, the documentation states that jQuery *may* be supported in the future -- guess we'll see. I personally like the server returning data instead of HTML, and to do that you'll need a framework like jQuery or Flex or GWT on the front end. A major advantage of that architecture is that the UI and server are completely decoupled. The XML/JSON document becomes the contract between them, and often the server implements a REST-based API. This allows them to be developed on different schedules independently. So UI folks can immediately develop the UI using a static XML file for data and don't have to wait for the server to be developed. Likewise the server can be developed and tested without needing the UI. Re: Authentication by Joel Confino, Your message is awaiting moderation. Thank you for participating in the discussion. Just to expand your question a little bit, I'll rephrase it as, "What happens when you make an AJAX call and you are not authenticated with the server?" In my experience there is no built-in standard solution in jQuery to handle authentication. However the custom solution is not too difficult. After making an AJAX call, you check the server response in a callback function. If the response from the server is "Hey you're not authenticated" you show the user a login dialog or something, and send the username/password to the server in another AJAX call. It is actually quite common to need to do some custom stuff before and after AJAX calls (like checking the response for something after a call or checking a local cache before making a request), and jQuery is extensible and makes it easy to make your own custom functions and have them be available in the jQuery "$." namespace. So instead of calling jQuery's $.getJSON function you call your custom $.getJSONCustom function which does additional work and delegates to jQuery's $.getJSON for the actual AJAX call. Example Code Posted by Joel Confino, Your message is awaiting moderation. Thank you for participating in the discussion. I posted the full example code at:-... Comparison to other JSon/Data Server side technologies by Solomon Duskis, Your message is awaiting moderation. Thank you for participating in the discussion. There was some discussion about Browser-side technologies (Dojo vs. JQuery). I'd also like to throw in some other technologies that can return server-side JSon/XML and integrate with Spring MVC: 1. The next version of Spring 3.0 MVC will have more support to do this, including more "RESTful URLs." The current model is limited to "/models.html?modelId=1010." Spring MVC 3.0 will allow you to map "/models/1010.json" to your controller. All of this is still in progresss, but it has to be out before Spring One - just take a look at all of the Web and REST sessions in the schedule 2. JAX-RS - It's a JEE standard API for "Web Services." It has a similar annotation-driven model. Jersey, the reference implementation of JAX-RS, integrates with Spring. It has the concepts of JSonView, XmlView, YourOwnView, already built in 3. DWR - Direct Web Remoting. It's a framework that's been around for quite a while. It has a server-side component and it's own JavaScript framework. It has some pretty advanced performance and security features Re: Comparison to other JSon/Data Server side technologies by Ayan Barua, Your message is awaiting moderation. Thank you for participating in the discussion. Might be bit of a stupid question here, but will this work with Hibernate 3+? I am looking at a jquery/jsonview/spring/hibernate/mysql stack hence the question. We tried to use JSONView from another project and apparently there were some conflicts. What is your take on this architecture? I would much appreciate if you throw some light on this. Thanks Ayan Questions by Ilan M, Your message is awaiting moderation. Thank you for participating in the discussion. 1. I understand that the demo carsearchresults.html is ajax with out JSON. Correct? 2. I tried to the same as the carsearchresults.html example in my code. The action took place, it returned to the url with carsearch.html page but showning only the context of carsearchresults.html. Do you have an idea what I have to do? The only different in my code is that I am using a formcontroller. Download lInk by Carlos Tevez, Your message is awaiting moderation. Thank you for participating in the discussion. hello, could you please update the download link? it doesn't work anymore. I'm really interested in the example code. Thanks reseba
https://www.infoq.com/articles/First-Cup-Web-2.0-Joel-Confino
CC-MAIN-2021-31
refinedweb
3,052
63.8
Hello, I've encountered a strange bug that appears to be either in gcc's gomp implementation or in how python loads extension modules linked against gomp. Here's the error: Using gcc (multiple versions) on linux, I compile an empty c extension module and pass -lgomp as a linker arg. If I import it, running a simple script in matplotlib causes a segfault. Not passing -lgomp or not loading the empty module makes the code works fine. More specifically, if I compile: #include "Python.h" static struct PyMethodDef methods[] = { {0, 0, 0, 0} }; PyMODINIT_FUNC initempty(void) { Py_InitModule4("empty", methods, 0, 0, PYTHON_API_VERSION); } using ``ext_modules = [Extension("empty", ["empty.c"], extra_link_args = ["-lgomp"])]``, then import empty import matplotlib.pylab as plt plt.figure() plt.plot([0,1], [0,1], '-b') plt.show() causes the program to segfault (removing ``import empty`` makes it fine). Looking at a traceback: #0 0x00f78bc7 in __cxa_allocate_exception () from /usr/lib/libstdc++.so.6 #1 0x008f51f2 in py_to_agg_transformation_matrix (obj=0x8223f58, errors=false) at src/agg_py_transforms.cpp:20 #2 0x008fdd73 in _path_module::update_path_extents (this=0x8e45f90, args=...) at src/path.cpp:378 #3 0x009048bd in Py::ExtensionModule<_path_module>::invoke_method_varargs (this=<value optimized out>, method_def=0x8e9ae30, args=...) at ./CXX/Python2/ExtensionModule.hxx:184 #4 0x008f0d96 in method_varargs_call_handler (_self_and_name_tuple=0x8e6eeac, _args=0x94e683c) at CXX/Python2/cxx_extensions.cxx:1714 #5 0x080dc0d0 in PyEval_EvalFrameEx () #6 0x080dddf2 in PyEval_EvalCodeEx () While occurring in some of matplotlib's extension code (and I haven't found another library that crashes it), the fact that the deciding factor is whether I link against gomp indicates the it's probably upstream somewhere. I encountered this error a year ago and asked about it on the matplotlib mailing list, but found a quick workaround then, and with deadline pressure I forgot about it. However, it's come up again, and then I was asked to bump it to python-dev, which is why I'm posting it here. I can reproduce it on the following systems. In all cases, matplotlib is compiled from source on the development branch (r8969) and uses QT4Agg as the backend, as is numpy, scipy, etc. If needed, I can track down more versions. gcc (Ubuntu/Linaro 4.4.4-14ubuntu5) 4.4.4, 64bit, Python 2.6.6, ubuntu 10.10 gcc (Ubuntu 4.4.3-4ubuntu5) 4.4.3, 64bit, Python 2.6.5, ubuntu 10.04 gcc (Ubuntu 4.4.1-4ubuntu9) 4.4.1, 32bit, Python 2.6.4, ubuntu 9.10 gcc 4.5.2 (source build), Python 2.6.5, ubuntu 10.04. On this build, the given source example does not produce the result, and I haven't been able to tweak it so it does. However, linking to a much larger extension library that uses many different parts of openmp causes exactly the same crash. If I recompile that library without openmp support, then everything works fine; with openmp support it corrupts something and matplotlib crashes in exactly the same way. gcc 4.3.2, Python 2.6.2, ubuntu 9.04 (I don't have access to this system any more, since it got upgraded, but it had the same problem a year ago). I'd be happy to provide any more information if needed. I attached example code that reproduces it. Let me know if I should file a bug report (and where to file it -- which is why I haven't yet). Thanks, --Hoyt python-gomp-bug.tar.gz (672 Bytes) ··· ++++++++++++++++++++++++++++++++++++++++++++++++ + Hoyt Koepke + University of Washington Department of Statistics + + hoytak@...149... ++++++++++++++++++++++++++++++++++++++++++
https://discourse.matplotlib.org/t/bug-in-linking-to-gomp-with-python-causes-crash-in-matplotlib/15062
CC-MAIN-2019-51
refinedweb
584
60.21
Beans Binding Via The Road Less Travelled By (Part 1) By Geertjan-Oracle on Feb 11, 2008 At the end of this blog entry, you'll have a JFrame that contains a JTable. The JTable is filled with data from a database. Whenever you select a row in the JTable, the JTextFields below the JTable are filled with the data from the currently selected row: And no code was typed to make all of this functionality possible. However, in the explanation that follows, we will ONLY use the code editor. Nothing will be generated. And, again, I could have used a Swing Application Framework template to generate all of the above (plus a lot more, such as CRUD functionality). However, let's only look at beans binding. We'll also assume that you are NOT using the Matisse GUI Builder, either because you don't like NetBeans IDE or you don't like having your code generated or because you actually want to learn what all the code does or some other reason. So everything will be hand coded. Let's get started. - First, we create the JFrame that will contain all the other Swing components: public class DemoJFrame extends JFrame { public DemoJFrame() { setTitle("Demo Frame"); setSize(400,400); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); } public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new DemoJFrame().setVisible(true); } }); } } Run the JFrame and you see a nice pristine space where all the action will take place. - Next, you need to manually set up your database connection, which is not much fun, especially when you consider that all this can automatically be done for you. However, to set up the database, you need the following JARs on your classpath (again, these would be put there for you if you were to use the IDE's tools instead of doing it manually): beansbinding-1.2.1.jar, toplink-essentials.jar, toplink-essentials-agent.jar and derbyclient.jar. Next, you need an entity class called Customer.java, to represent the data in your database, which you can download here. Finally, for this step, you need to have a database started up and you need an XML file named "persistence.xml", in your application's META-INF folder. The content of the XML file should be as follows, assuming you're using the 'sample' database that comes with NetBeans IDE (so, you'd need to tweak it, as well as the Customer.java class, for your own purposes): <?xml version="1.0" encoding="UTF-8"?> <persistence version="1.0" xmlns="" xmlns: <persistence-unit <provider>oracle.toplink.essentials.PersistenceProvider</provider> <class>demoframe.Customer</class> <properties> "/> </properties> </persistence-unit> </persistence> - Now, having dealt with the formalities, let's create a JTable and bind its columns to columns in our database. Let's start by declaring some fields and variables: private java.util.List customerList; private javax.persistence.Query customerQuery; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable jTable1; private javax.persistence.EntityManager samplePUEntityManager; private org.jdesktop.beansbinding.BindingGroup bindingGroup; Then, here is the actual code, which all belongs in the constructor, below the three lines we added previously. Note the pattern by which things happen: we create a binding group, we add other binding groups to it, within which we add bindings. The bindings use expression language to link to database column names, they also specify table column names and the type of the data. //Create new binding group: bindingGroup = new BindingGroup(); //Persistence manager for our database: samplePUEntityManager = javax.persistence.Persistence.createEntityManagerFactory("samplePU").createEntityManager(); //Query that we call on the persistence manager: customerQuery = samplePUEntityManager.createQuery("SELECT c FROM Customer c"); //List that results from our query: customerList = customerQuery.getResultList(); //JScrollPane that will contain our table: jScrollPane1 = new javax.swing.JScrollPane(); //JTable that will contain our data: jTable1 = new javax.swing.JTable(); //Create the JTable binding: JTableBinding jTableBinding = SwingBindings.createJTableBinding( AutoBinding.UpdateStrategy.READ_WRITE, customerList, jTable1); //Add the first column binding to our table binding: ColumnBinding columnBinding = jTableBinding.addColumnBinding(ELProperty.create("${name}")); columnBinding.setColumnName("Name"); columnBinding.setColumnClass(String.class); //Add the second binding to our table binding: columnBinding = jTableBinding.addColumnBinding(ELProperty.create("${city}")); columnBinding.setColumnName("City"); columnBinding.setColumnClass(String.class); //Add the final binding to our table binding: columnBinding = jTableBinding.addColumnBinding(ELProperty.create("${zip}")); columnBinding.setColumnName("Zip"); columnBinding.setColumnClass(String.class); //Add our table binding to the binding group: bindingGroup.addBinding(jTableBinding); //Bind the table binding: jTableBinding.bind(); //Set the JTable in the JScrollPane's view port view: jScrollPane1.setViewportView(jTable1); //Add the JScrollPane in the North: getContentPane().add(jScrollPane1, java.awt.BorderLayout.NORTH); //Bind the whole group: bindingGroup.bind(); //Pack: pack(); If you run the above, assuming you've actually gone through the pain of setting up the database manually, you'll see the columns in the database bound to the columns in the table. Now experiment a bit! For example, change the expression ${city} to ${email} which, if you look in your Customer.java class, maps to the "email" column in the table. Then run the application again and the City column is filled with e-mail data. - Now we'll add our JTextFields. These we will bind to the columns in the table so that, whenever a row is selected, the fields will be filled with the data from the selected row. First, declare the new Swing components that we will work with: private javax.swing.JTextField jTextField1; private javax.swing.JTextField jTextField2; private javax.swing.JTextField jTextField3; private javax.swing.JPanel jPanel1; Next, below the line that adds the JScrollPane to the South, add all the following code, simply for adding a JPanel with our three JTextFields: jTextField1 = new javax.swing.JTextField(); jTextField2 = new javax.swing.JTextField(); jTextField3 = new javax.swing.JTextField(); jPanel1 = new javax.swing.JPanel(); jTextField1.setText(""); jTextField1.setColumns(10); jPanel1.add(jTextField1); jTextField2.setText(""); jTextField2.setColumns(10); jPanel1.add(jTextField2); jTextField3.setText(""); jTextField3.setColumns(10); jPanel1.add(jTextField3); getContentPane().add(jPanel1, java.awt.BorderLayout.SOUTH); - And, finally, we add the bindings. These will bind our JTextFields to columns in the table. The additions to the code I have marked in bold below: jTextField1.setText(""); jTextField3.setEditable(false); jTextField1.setColumns(10); Binding binding1 = Bindings.createAutoBinding( AutoBinding.UpdateStrategy.READ_WRITE, jTable1, ELProperty.create("${selectedElement.name}"), jTextField1, BeanProperty.create("text")); bindingGroup.addBinding(binding1); jPanel1.add(jTextField1); jTextField2.setText(""); jTextField3.setEditable(false); jTextField2.setColumns(10); Binding binding2 = Bindings.createAutoBinding( AutoBinding.UpdateStrategy.READ_WRITE, jTable1, ELProperty.create("${selectedElement.city}"), jTextField2, BeanProperty.create("text")); bindingGroup.addBinding(binding2); jPanel1.add(jTextField2); jTextField3.setText(""); jTextField3.setEditable(false); jTextField3.setColumns(10); Binding binding3 = Bindings.createAutoBinding( AutoBinding.UpdateStrategy.READ_WRITE, jTable1, ELProperty.create("${selectedElement.zip}"), jTextField3, BeanProperty.create("text")); bindingGroup.addBinding(binding3); jPanel1.add(jTextField3); For what it's worth, here's a full list of my import statements: import javax.swing.JFrame; import org.jdesktop.beansbinding.AutoBinding; import org.jdesktop.beansbinding.BeanProperty; import org.jdesktop.beansbinding.Binding; import org.jdesktop.beansbinding.BindingGroup; import org.jdesktop.beansbinding.Bindings; import org.jdesktop.beansbinding.ELProperty; import org.jdesktop.swingbinding.JTableBinding; import org.jdesktop.swingbinding.JTableBinding.ColumnBinding; import org.jdesktop.swingbinding.SwingBindings; I know I haven't explained everything in detail. I'll do that another time (once I know what those details are). On top of that, though, I think the code is relatively easy to read. You should be able to figure out what is happening, in most cases. And remember: every single piece of code that you see above, every line, every JAR, everything, is generated for you in the IDE. You do not need to go through any of this at all. Unless, of course, you want to really understand beans binding! Here is another request. What is the best way of approaching a Netbeans RCP application which reads data off a JMS Bus, TCP/IP connection, etc., and populates a JTable (or whatever netbeans uses)? I would like to try building a small stock trading application using Netbeans, which requires LOTS of streaming data, binding, etc. Do I introduce the streaming data sources as some sort of services or plug-ins? Posted by falcon on February 11, 2008 at 12:04 PM PST # That question has nothing to do with this blog entry and I don't know the answer. Please write to dev@openide.netbeans.org and someone there will probably have implemented something similar. Posted by Geertjan on February 11, 2008 at 03:15 PM PST # jTableBinding.bind(); ... bindingGroup.bind(); Is this really needed? Why I must order 2 bindings if the tableBinding was asigned to the groupBinding? Posted by peregrino on February 17, 2008 at 05:15 PM PST # How do you make the column bindings using Netbeans IDE only? If I look at the properties, bindings of a table I can only bind things like elements or selectedElement(s)? The columns tab also doesn't appear to contain anything to do with bindings? Could the same technique be used with the swinglabs JXTable implementation? Posted by Richard Osbaldeston on February 18, 2008 at 07:40 PM PST # Oh think I've found the limits myself. I was being blocked by a "can't import data to the default package" message. So you can only bind columns to a database table? I'm using RMI (raw objects/pojos) guess the existing Netbeans editor can't help here? Posted by Richard Osbaldeston on February 18, 2008 at 07:48 PM PST # 2Richard, from what I have understood at SwingX forums, yes, you should be able to bind to JXTable too. Also, I would be interested in replies to Richard Osbaldeston's questions regarding binding POJOs in NB. I managed to do that "manually" but not in NB binding editor. Related to POJOs is my question - did anyone got working create and delete from underlying table model, i.e. DefaultTableModel or class extending that. If so, how? The binding does not seem to listen on table model events... Posted by Dale Cooper on February 19, 2008 at 09:23 AM PST # I wrote something for NetBeans Zone today that attempts to answer some of the questions here. If it doesn't feel free to leave questions at the end of that article:- Posted by Geertjan on February 19, 2008 at 04:39 PM PST # Hi! Thanks for your tutorial! I did the same within a Netbeans RCP App, but when i write text into one of my TextFields, the corresponding Table Column doesn't get updated. When i do the same outside Netbeans RCP Platform everything works perfect.... Whats wrong within Netbeans RCP? Best Regards, christian Posted by Christian on April 09, 2008 at 07:50 PM PDT # Has you tried this to work with EclipseLink JPA, resource local, i.e. the javax.persistence_1.0.0.jar? Can you suggest a site that shows how to migrate toplink-essentials 1.0 to eclipselink? By the way, this is a really informative example ... Some of us are using Java SE with JPA, and not just for testing. Posted by Mike Rainville on August 12, 2008 at 08:48 AM PDT # this might have been useful if the 3 examples had been for string int and boolean instead of all being for string Posted by tom ballard on March 29, 2010 at 07:32 AM PDT # Thanks very much for your tutorial. Are there any NetBeans 6.9 Java DB tutorials which show add/update/delete functionality to a jTable that was not generated by master/detail -it is a single table with some data. -Thanks Lana Posted by Lana on August 10, 2010 at 06:09 AM PDT # Posted by veronel on October 02, 2010 at 04:08 PM PDT # Posted by guest on July 25, 2011 at 02:45 PM PDT # Hi, I would like to know how can i change the data in the JTable when I make a new query and have a new customerList (after an insert in the Customers table for example)? Thanks a lot, Posted by guest on October 25, 2011 at 11:57 PM PDT # Posted by Lesanjo on January 22, 2012 at 06:34 AM PST #
https://blogs.oracle.com/geertjan/entry/beans_binding_via_the_road
CC-MAIN-2016-36
refinedweb
2,007
50.02
restricts the input proxies to one or more data types More... #include <vtkSMDataTypeDomain.h> restricts the input proxies to one or more data types vtkSMDataTypeDomain restricts the input proxies to one or more data types. These data types are specified in the XML with the <DataType> element. VTK class names are used. It is possible to specify a superclass (i.e. vtkDataSet) for a more general domain. Works with vtkSMSourceProxy only. Valid XML elements are: * <DataType value=""> where value is the classname for the data type for example: vtkDataSet, vtkImageData,... Definition at line 41 of file vtkSMDataTypeDomain.h. Reimplemented from vtkSMSessionObject. Returns true if the value of the propery is in the domain. The propery has to be a vtkSMProxyProperty which points to a vtkSMSourceProxy. If all data types of the input's parts are in the domain, it returns. It returns 0 otherwise. Implements vtkSMDomain. Returns true if all parts of the source proxy are in the domain. Returns the number of acceptable data types. Returns a data type. Set the appropriate ivars from the xml element. Should be overwritten by subclass if adding ivars. Reimplemented from vtkSMDomain. Definition at line 72 of file vtkSMDataTypeDomain.h. Definition at line 74 of file vtkSMDataTypeDomain.h.
http://www.paraview.org/ParaView3/Doc/Nightly/html/classvtkSMDataTypeDomain.html
crawl-003
refinedweb
205
62.34
Only 70 votes so far for covariant return types in C# (and all .Net languages)!! 🙁 I thought that there was a lot more interest than that. Here's a chance for you to really show what you're interested in seeing. If you haven't voted yet, and you do care about this, do it asap: If you go to this page you can submit your vote: out of curiousity, how many votes are required to make this a reality? Jim: The more the merrier 🙂 I never missed them, so why should I vote for them? Maybe I’m missing whats so helpful about them? Sam Maybe it might help if you were asking for votes for CoVariant Return Types in the whole of .NET, so that afte the dust settles this is not again a feature that is C#-only. The E&C for C#, no Refactoring for VB.NET failure was more then enough. Jens, could you explain what you mean? The vote is for covariant return types in C# and .net. Sam, a useful example is: //represents an arbitrary node in an abstract syntax tree class AstNode { ….public virtual AstNode Parent { get { … } } } class NamespaceNode : AstNode { ….//Since i know that the parent of a namespace node is always a namespace node ….//i can declare it here. It’s totally fine since it follows the contract of the ….//supertype which states that you have to return an AstNode (and a ….//NamespaceNode is an AstNode ….public override NamespaceNode Parent { get { … } } } //but i can’t do that, i’m forced to do: class NamespaceNode : AstNode { ….public override ***AstNode*** Parent { get { … } } } Having covariant return types is useful for two reasons. First, when i’m implementing NamespaceNode.Parent, having the return type checked by the compiler is incredibly useful. It means that i can’t make a mistake where i accidently return a node that isn’t a NamespaceNode. Also, i have to document the property to state this so that anyone reading this will know. if in the future i ever need to change what .Parent returns there is no way to make sure that all the callers will still work correctly. Second, when someone is consuming these apis they now need to introduce casts all over the place. For example: NamespaceNode n = … NamespaceNode nParent = (NamespaceNode)n.Parent; this is error prone and cluttered. There is no need for that cast and it’s possible that it could cause a runtime exception. This can all be avoided with covariant return types. It allows for better defined APIs and easier consumption by users. It’s very much Win/Win. I’m sorry, I didn’t read it good enough. It indeed says ‘C# / all.NET languages’. I guess I’m still pissed about the refactoring decision and I’m venting that in the wrong place … Anyway, I did vote for it, and I do hope that if it gets included in the next .NET (whenever that will be) it’s not a C# only feature ‘because VB.NET developers are not really interested in this’. Jens: NP I can understand your frustration though. but you should *not* think that C# gets more attention than VB because it’s absolutely not the case. Rather each team tries to figure out hte best they can do with the time they have. So C# did things like refactoring, and VB did things like "My". I wouldn’t mind talking about this a little more with you though cuz i really want you to know how we decide on all of this stuff. Cyrus, It’s not that I think that C# gets more attention than VB.NET, it’s that sometimes I feel that the kind of attention VB.NET gets really affirmes the feeling that C# is the ‘business development’ language and VB.NET is the language that non-ITers use (business analysts, accountants, consultants, …). I guess my profile is much more the profile of a C# developer, except that I can’t stand curly braces, the cryptic way of writing code in C-derived languages, and case sensitivity. Some say that people like me should get over it and switch to C#, but that would take the joy out of developing, it would be an imense frustration to have to fight with the aforementioned reasons why I don’t like C# on a dialy basis. So I find myself a bit left out in the cold. The things C# gains are more geared towards professional developers (refactoring), the things VB.NET gains are more geared towards the others (My). Businesswise, this might be the correct decision for MS, one can only spend a dollar once, and throwing more developers at the problem is rarely the solution, but from my point of view the grass really *is* greener on the other side … If on the other hand things like Refactoring, E&C, CoVariant ReturnTypes are solved in the framework (or in Visual Studio, but then in common code), the grass is suddenly equally green on both sides and everyone is happy. Jens I voted. Peripherially, are you also going to push for overloads that only differ in return type? I don’t see it on your list of requests for the next version of C# (though this would probably be something baked into the CLS). Sadly, I don’t have a ready example of where I’d’ve like to use it, but I do recall wanting the feature several times over the past couple years. Anybody who still has spare votes – can cast them once more at about the same suggestion at This suggestion is "Under Review" since 2004-07-22 😉 RonO: How would you modify the overload lookup rules to account for return types? Jens: Thanks for the thoughtful feedback. I’ve sent your feedback to the VB team which is very understanding of these issues. If you’re interested with communication with someone from that team, send me your email address (through the contact link on the left) and i’ll get you connected with them. I think they woudl like to talk in depth about how you feel and what they can do to rectofy the situation. Note: If it makes you feel better C# *still* doesn’t have background compile, and there are many C# users who think the grass is greener on the VB side because of that! 🙂 Voted. BTW, I’ve noticed that the request has Postponed/Closed status. Does it really mean that we have no chance to get covariant return types in Whibey or am I missing something? Dmitry: The chance of covariant return types being in whidbey is practically Nill. However, when planning the features for the next release this info will go a long way. Dmitry: The chance of covariant return types being in whidbey is practically Nill. However, when planning the features for the next release this info will go a long way. Cyrus: Re overload lookup rules, as I see it (admittedly I very well could be missing a lot of details in the overall picture), this is only a problem when there could be ambiguity in determining the return type. An arbitrary example (thanks to C-Sharp Corner for the base of the code): class CombineUtil { static double Combine(object a,object b) { return (double)a+(double)b; } static string Combine(object a,object b) { return Convert.ToString(a)+ " " + Convert.ToString(b); } public static void Main() { Console.WriteLine("Concat double: {0}", Combine(1.2,1.8)); Console.WriteLine("Concat string: {0}", Combine("1.2","1.8")); Console.Read(); } I’d raise a compile error to require the code to explictly cast to a valid return type (or one that can be unabiguously determined). The same checks are currently performed for method params (or at least the same types of checks), so I expect it could be adapted (if not used directly) to make the same determinations. Of course, I realize this is my own pie-in-the-sky dreaming on this issue. 🙂
https://blogs.msdn.microsoft.com/cyrusn/2005/03/21/tsk-tsk/
CC-MAIN-2019-18
refinedweb
1,341
71.95
In the playbooks that we have considered so far, we have used tasks, links to the inventory and modules. In this post, we will add another important feature of Ansible to our toolbox – variables. Declaring variables Using variables in Ansible is slightly more complex than you might expect at the first glance, mainly due to the fact that variables can be defined at many different points, and the precedence rules are a bit complicated, making errors likely. Ignoring some of the details, here are the essential options that you have to define variables and assign values: - You can assign variables in a playbook on the level of a play, which are then valid for all tasks and all hosts within that play - Similarly, variables can be defined on the level of an individual task in a playbook - You can define variables on the level of hosts or groups of hosts in the inventory file - There is a module called set_fact that allows you to define variables and assign values which are then scoped per host and for the remainder of the playbook execution - Variables can be defined on the command line when executing a playbook - Variables can be bound to a module so that the return values of that module are assigned to that variable within the scope of the respective host - Variable definitions can be moved into separate files and be referenced from within the playbook - Finally, Ansible will provide some variables and facts Let us go through these various options using the following playbook as an example. --- - hosts: all become: yes # We can define a variable on the level of a play, it is # then valid for all hosts to which the play applies vars: myVar1: "Hello" vars_files: - vars.yaml tasks: # We can also set a variable using the set_fact module # This will be valid for the respective host until completion # of the playbook - name: Set variable set_fact: myVar2: "World" myVar5: "{{ ansible_facts['machine_id'] }}" # We can register variables with tasks, so that the output of the # task will be captured in the variable - name: Register variables command: "date" register: myVar3 - name: Print variables # We can also set variables on the task level vars: myVar4: 123 debug: var: myVar1, myVar2, myVar3['stdout'], myVar4, myVar5, myVar6, myVar7 At the top of this playbook, we see an additional attribute vars on the level of the play. This attribute itself is a list and contains key-value pairs that define variables which are valid across all tasks in the playbook. In our example, this is the variable myVar1. The same syntax is used for the variable myVar4 on the task level. This variable is then only valid for that specific task. Directly below the declaration of myVar1, we instruct Ansible to pick up variable definitions from an external file. This file is again in YAML syntax and can define arbitrary key-value pairs. In our example, this file could be as simple as --- myVar7: abcd Separating variable definitions from the rest of the playbook is very useful if you deal with several environments. You could then move all environment-specific variables into separate files so that you can use the same playbook for all environments. You could even turn the name of the file holding the variables into a variable that is then set using a command line switch (see below), which allows you to use different sets of variables for each execution without having to change the playbook. The variable myVar3 is registered with the module command, meaning that it will capture the output of this module. Note that this output will usually be a complex data structure, i.e. a dictionary. One of the keys in this dictionary, which depends on the module, is typically stdout and captures the output of the command. For myVar2, we use the module set_fact to define it and assign a value to it. Note that this value will only be valid per host, as myVar5 demonstrates (here we use a fact and Jinja2 syntax – we will discuss this further below). In the last task of the playbook, we print out the value of all variables using the debug module. If you look at this statement, you will see that we print out a variable – myVar6 – which is not defined anywhere in the playbook. This variable is in fact defined in the inventory. Recall that the inventory for our test setup with Vagrant introduced in the last post looked as follows. [servers] 192.168.33.10 192.168.33.11 To define the variable myVar6, change this file as follows. [servers] 192.168.33.10 myVar6=10 192.168.33.11 myVar6=11 Note that behind each host, we have added the variable name along with its value which is specific per host. If you now run this playbook with a command like export ANSIBLE_HOST_KEY_CHECKING=False ansible-playbook \ -u vagrant \ --private-key ~/vagrant/vagrant_key \ -i ~/vagrant/hosts.ini \ definingVariables.yaml then the last task will produce an output that contains a list of all variables along with their values. You will see that myVar6 has the value defined in the inventory, that myVar5 is in fact different for each host and that all other variables have the values defined in the playbook. As mentioned before, it is also possible to define variables using an argument to the ansible-playbook executable. If, for instance, you use the following command to run the playbook export ANSIBLE_HOST_KEY_CHECKING=False ansible-playbook \ -u vagrant \ --private-key ~/vagrant/vagrant_key \ -i ~/vagrant/hosts.ini \ -e myVar4=789 \ definingVariables.yaml then the output will change and the variable myVar4 has the value 789. This is an example of the precedence rule mentioned above – an assignment specified on the command line overwrites all other definitions. Using facts and special variables So far we have been using variables that we instantiate and to which we assign values. In addition to these custom variables, Ansible will create and populate a few variables for us. First, for every machine in the inventory to which Ansible connects, it will create a complex data structure called ansible_facts which represents data that Ansible collects on the machine. To see an example, run the command (assuming again that you use the setup from my last post) export ANSIBLE_HOST_KEY_CHECKING=False ansible \ -u vagrant \ -i ~/vagrant/hosts.ini \ --private-key ~/vagrant/vagrant_key \ -m setup all This will print a JSON representation of the facts that Ansible has gathered. We see that facts include information on the machine like the number of cores and hyperthreads per core, the available memory, the IP addresses, the devices, the machine ID (which we have used in our example above), environment variables and so forth. In addition, we find some information on the user that Ansible is using to connect, the used Python interpreter and the operating system installed. It is also possible to add custom facts by placing a file with key-value pairs in a special directory on the host. Confusingly, this is called local facts, even though these facts are not defined on the control machine on which Ansible is running but on the host that is provisioned. Specifically, a file in /etc/ansible/facts.d ending with .fact can contain key-value pairs that are interpreted as facts and added to the dictionary ansible_local. Suppose, for instance, that on one of your hosts, you have created a file called /etc/ansible/facts.d/myfacts.fact with the following content [test] testvar=1 If you then run the above command again to gather all facts, then, for that specific host, the output will contain a variable "ansible_local": { "myfacts": { "test": { "testvar": "1" } } So we see that ansible_local is a dictionary, with the keys being the names of the files in which the facts are stored (without the extension). The value for each of the files is again a dictionary, where the key is the section in the facts file (the one in brackets) and the value is a dictionary with one entry for each of the variables defined in this section (you might want to consult the Wikipedia page on the INI file format). In addition to facts, Ansible will populate some special variables like the inventory_hostname, or the groups that appear in the inventory file. Using variables – Jinja2 templates In the example above, we have used variables in the debug statement to print their value. This, of course, is not a typical usage. In general, you will want to expand a variable to use it at some other point in your playbook. To this end, Ansible uses Jinja2 templates. Jinja2 is a very powerful templating language and Python library, and we will only be able to touch on some of its features in this post. Essentially, Jinja2 accepts a template and a set of Python variables and then renders the template, substituting special expressions according to the values of the variables. Jinja2 differentiates between expressions which are evaluated and replaced by the values of the variables they refer to, and tags which control the flow of the template processing, so that you can realize things like loops and if-then statements. Let us start with a very simple and basic example. In the above playbook, we have hard-coded the name of our variable file vars.yaml. As mentioned above, it is sometimes useful to use different variable files, depending on the environment. To see how this can be done, change the start of our playbook as follows. --- - hosts: all become: yes # We can define a variable on the level of a play, it is # then valid for all hosts to which the play applies vars: myVar1: "Hello" vars_files: - "{{ myfile }}" When you now run the playbook again, the execution will fail and Ansible will complain about an undefined variable. To fix this, we need to define the variable myfile somewhere, say on the command line. export ANSIBLE_HOST_KEY_CHECKING=False ansible-playbook \ -u vagrant \ --private-key ~/vagrant/vagrant_key \ -i ~/vagrant/hosts.ini \ -e myVar4=789 \ -e myfile=vars.yaml \ definingVariables.yaml What happens is that before executing the playbook, Ansible will run the playbook through the Jinja2 templating engine. The expression {{myfile}} is the most basic example of a Jinja2 expression and evaluates to the value of the variable myfile. So the entire expression gets replaced by vars.yaml and Ansible will read the variables defined there. Simple variable substitution is probably the most commonly used feature of Jinja2. But Jinja2 can do much more. As an example, let us modify our playbook so that we use a certain value for myVar7 in DEV and a different value in PROD. The beginning of our playbook now looks as follows (everything else is unchanged): --- - hosts: all become: yes # We can define a variable on the level of a play, it is # then valid for all hosts to which the play applies vars: myVar1: "Hello" myVar7: "{% if myEnv == 'DEV' %} A {% else %} B {% endif %}" Let us run this again. On the command line, we set the variable myEnv to DEV. export ANSIBLE_HOST_KEY_CHECKING=False ansible-playbook \ -u vagrant \ --private-key ~/vagrant/vagrant_key \ -i ~/vagrant/hosts.ini \ -e myVar4=789 \ -e myEnv=DEV \ definingVariables.yaml In the output, you will see that the value of the variable is ” A “, as expected. If you use a different value for myEnv, you get ” B “. The characters “{%” instruct Jinja2 to treat everything that follows (until “%}”) as tag. Tags are comparable to statements in a programming language. Here, we use the if-then-else tag which evaluates to a value depending on a condition. Jinja2 comes with many tags, and I advise you to browse the documentation of all available control structures. In addition to control structures, Jinja2 also uses filters that can be applied to variables and can be chained. To see this in action, we turn to an example which demonstrates a second common use of Jinja2 templates with Ansible apart from using them in playbooks – the template module. This module is very similar to the copy module, but it takes a Jinja2 template on the control machine and does not only copy it to the remote machine, but also evaluates it. Suppose, for instance, you wanted to dynamically create a web page on the remote machine that reflects some of the machines’s characteristics, as captured by the Ansible facts. Then, you could use a template that refers to facts to produce some HTML output. I have created a playbook that demonstrates how this works – this playbook will install NGINX in a Docker container and dynamically create a webpage containing machine details. If you run this playbook with our Vagrant based setup and point your browser to, you will see a screen similar to the one below, displaying things like the number of CPU cores in the virtual machine or the network interfaces attached to it. I will not go through this in detail, but I advise you to try out the playbook and take a look at the Jinja2 template that it uses. I have added a few comments which, along with the Jinja2 documentation, should give you a good idea how the evaluation works. To close this post, let us see how we can test Jinja2 templates. Of course, you could simply run Ansible, but this is a bit slow and creates an overhead that you might want to avoid. As Jinja2 is a Python library, there is a much easier approach – you can simply create a small Python script that imports your template, runs the Jinja2 engine and prints the result. First, of course, you need to install the Jinja2 Python module. pip3 install jinja2 Here is an example of how this might work. We import the template index.html.j2 that we also use for our dynamic webpage displayed above, define some test data, run the engine and print the result. import jinja2 # # Create a Jinja2 environment, using the file system loader # to be able to load templates from the local file system # env = jinja2.Environment( loader=jinja2.FileSystemLoader('.') ) # # Load our template # template = env.get_template('index.html.j2') # # Prepare the input variables, as Ansible would do it (use ansible -m setup to see # how this structure looks like, you can even copy the JSON output) # groups = {'all': ['127.0.0.1', '192.168.33.44']} ansible_facts={ "all_ipv4_addresses": [ "10.0.2.15", "192.168.33.10" ], "env": { "HOME": "/home/vagrant", }, "interfaces": [ "enp0s8" ], "enp0s8": { "ipv4": { "address": "192.168.33.11", "broadcast": "192.168.33.255", "netmask": "255.255.255.0", "network": "192.168.33.0" }, "macaddress": "08:00:27:77:1a:9c", "type": "ether" }, } # # Render the template and print the output # print(template.render(groups=groups, ansible_facts=ansible_facts)) An additional feature that Ansible offers on top of the standard Jinja2 templating language and that is sometimes useful are lookups. Lookups allow you to query data from external sources on the control machine (where they are evaluated), like environment variables, the content of a file, and many more. For example, the expression "{{ lookup('env', 'HOME') }}" in a playbook or a template will evaluate to the value of the environment variable HOME on the control machine. Lookups are enabled by plugins (the name of the plugin is the first argument to the lookup statement), and Ansible comes with a large number of pre-installed lookup plugins. We have now discussed Ansible variables in some depth. You might want to read through the corresponding section of the Ansible documentation which contains some more details and links to additional information. In the next post, we will turn our attention back from playbooks to inventories and how to structure and manage them.
https://leftasexercise.com/2019/11/25/q-automating-provisioning-with-ansible-variables-and-facts/
CC-MAIN-2021-04
refinedweb
2,605
58.01
ion-menu ion-menu to the app's content element. There can be any number of menus attached to the content. These can be controlled from the templates, or programmatically using the MenuController. Usage <ion-menu [content]="mycontent"> <ion-content> <ion-list> <p>some menu content, could be list items</p> </ion-list> </ion-content> </ion-menu> <ion-nav #mycontent [root]="rootPage"></ion-nav> To add a menu to an app, the <ion-menu> element should be added as a sibling to the ion-nav it will belongs to. A local variable should be added to the ion-nav and passed to the ion-menus content property. This tells the menu what it is bound to and what element to watch for gestures. In the below example, content is using property binding because mycontent is a reference to the <ion-nav> element, and not a string. Opening/Closing Menus There are several ways to open or close a menu. The menu can be toggled open or closed from the template using the MenuToggle directive. It can also be closed from the template using the MenuClose directive. To display a menu programmatically, inject the MenuController provider and call any of the MenuController methods. Menu Types The menu supports several display types: overlay, reveal and push. By default, it will use the correct type based on the mode, but this can be changed. The default type for both Material Design and Windows mode is overlay, and reveal is the default type for iOS mode. The menu type can be changed in the app's config via the menuType property, or passed in the type property on the <ion-menu> element. See usage below for examples of changing the menu type. Navigation Bar Behavior If a MenuToggle button is added to the Navbar of a page, the button will only appear when the page it's in is currently a root page. The root page is the initial page loaded in the app, or a page that has been set as the root using the setRoot method on the NavController. For example, say the application has two pages, Page1 and Page2, and both have a MenuToggle button in their navigation bars. Assume the initial page loaded into the app is Page1, making it the root page. Page1 will display the MenuToggle button, but once Page2 is pushed onto the navigation stack, the MenuToggle will not be displayed. Persistent Menus Persistent menus display the MenuToggle button in the Navbar on all pages in the navigation stack. To make a menu persistent set persistent to true on the <ion-menu> element. Note that this will only affect the MenuToggle button in the Navbar attached to the Menu with persistent set to true, any other MenuToggle buttons will not be affected. Menu Side By default, menus slide in from the left, but this can be overridden by passing right to the side property: <ion-menu...</ion-menu> Menu Type The menu type can be changed by passing the value to type on the <ion-menu>: <ion-menu...</ion-menu> It can also be set in the app's config. The below will set the menu type to push for all modes, and then set the type to overlay for the ios mode. // in NgModules imports: [ IonicModule.forRoot(MyApp,{ menuType: 'push', platforms: { ios: { menuType: 'overlay', } } }) ], Displaying the Menu To toggle a menu from the template, add a button with the menuToggle directive anywhere in the page's template: <button ion-button menuToggle>Toggle Menu</button> To close a menu, add the menuClose button. It can be added anywhere in the content, or even the menu itself. Below it is added to the menu's content: <ion-menu [content]="mycontent"> <ion-content> <ion-list> <ion-item menuClose detail-none>Close Menu</ion-item> </ion-list> </ion-content> </ion-menu> See the MenuToggle and MenuClose docs for more information on these directives. The menu can also be controlled from the Page by using the MenuController. Inject the MenuController provider into the page and then call any of its methods. In the below example, the openMenu method will open the menu when it is called. import { Component } from '@angular/core'; import { MenuController } from 'ionic-angular'; @Component({...}) export class MyPage { constructor(public menuCtrl: MenuController) {} openMenu() { this.menuCtrl.open(); } } See the MenuController API docs for all of the methods and usage information. Input Properties Output Events Sass Variables Related Menu Component Docs, MenuController API Docs, Nav API Docs, NavController API Docs
https://ionicframework.com/docs/2.3.0/api/components/menu/Menu/
CC-MAIN-2018-51
refinedweb
749
61.97
Overview Atlassian SourceTree is a free Git and Mercurial client for Windows. Atlassian SourceTree is a free Git and Mercurial client for Mac. scriptoresque – a ClojureScript scriptoresque? scriptoresque is now a plugin for Gradle, which adds ClojureScript support. It allows compilation with automatic namespace recognition. The plugin is based on the Java plugin and hooks into the standard configurations and archives. Usage Create a build.gradle script in the root directory of your project. Note that gradle derives the project name from the name of this directory! buildscript { repositories { maven { url '' } } dependencies { classpath 'clojuresque:scriptoresque:1.0.0' } } apply plugin: 'clojurescript' Meta plugin This is a meta plugin applying the various parts of the clojuresque and scriptores
https://bitbucket.org/clojuresque/scriptoresque/overview
CC-MAIN-2017-09
refinedweb
117
52.66
Performing joins across two sequences with the LINQ Join operator With the Join operator in LINQ you can perform joins similar to using the JOIN keyword in SQL: the result will be a join on two sequences based on some common key. We’ll use the following data structures: public class Singer { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } } public class Concert { public int SingerId { get; set; } public int ConcertCount { get; set; } public int Year { get; set; } }} }; } I think most LINQ operators are quite straightforward to use. Join is probably one of the more complex ones with its Func delegates. The signature of the operator looks as follows: IEnumerable<TResult> result = IEnumerable<TOuter>.Join<TOuter, TInner, TKey, TResult>(IEnumerable<TInner> inner, Func<TOuter, TKey> outerKeySelector, Func<TInner, TKey> innerKeySelector, Func<TOuter, TInner, TResult> resultSelector); Let’s see an example of how the singer and concert objects can be joined using the singer ids: var singerConcerts = singers.Join(concerts, s => s.Id, c => c.SingerId, (s, c) => new { Id = s.Id, SingerName = string.Concat(s.FirstName, " ", s.LastName), ConcertCount = c.ConcertCount, Year = c.Year }); foreach (var res in singerConcerts) { Console.WriteLine(string.Concat(res.Id, ": ", res.SingerName, ", ", res.Year, ", ", res.ConcertCount)); } - ‘singers’ is the outer sequence of the two sequences - ‘concerts’ will be the inner sequence - s – s.Id: the outer key selector, in this case the singer’s ID - c – c.SingerId: the inner key selector, in this case the SingerId secondary key of a Concert object - The last element is the result selector where we declare what type of object we want returned from the operation The Join operator has an overload which accepts an EqualityComparer of TKey. In our case it’s not necessary as the TKey will be the singer ID, i.e. an integer, and .NET can easily compare those. However, if the comparison key is an object, then you can implement the IEqualityComparer interface. Here’s an example how to do that. You can view all LINQ-related posts on this blog here. Pingback: Creating a grouped join on two sequences using the LINQ GroupJoin operator – sadiqrashid
https://dotnetcodr.com/2014/05/20/performing-joins-across-two-sequences-with-the-linq-join-operator/
CC-MAIN-2021-49
refinedweb
360
56.55
CodePlexProject Hosting for Open Source Software I want to be able to set a tool tip on each edge, where the contents of the tool tip is defined by a non-element property of the edge's target vertex. I started by defining something like this: <Style TargetType="{x:Type graphsharp:EdgeControl}"> <Setter Property="ToolTip"> <Setter.Value> <StackPanel> <ListView ItemsSource="..."> ... </ListView> </StackPanel> </Setter.Value> </Setter> ... </Style> This works if the tool tip contains something simple, like a string. However, I couldn't figure out how to set up a data context/binding to populate the list view from the target vertex's properties. I eventually gave up and duplicated the template code for the EdgeControl, so I now have something like this: <Style TargetType="{x:Type graphsharp:EdgeControl}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type graphsharp:EdgeControl}"> <Path ...> ... <Path.ToolTip> <StackPanel> <ListView ItemsSource="{Binding Path=Target.Vertex.MyProperty, RelativeSource={RelativeSource TemplatedParent}}"> ... </ListView> </StackPanel> </Path.ToolTip> </Path> </ControlTemplate> </Setter.Value> </Setter> </Style> This displays the required tool tip. However, apart from the obvious downside of duplicating the template code, it also seems to cache the result. So when the property of the destination vertex that provides the data for the tool tip is altered the tooltip still shows the old result. But if I set a tool tip on the custom target vertex itself that's connected to the same property it shows the new result. Anyone have any idea as to why the value is not changing? Of course ideally it would make more sense to store the data driving the tool tip in the edge, rather than the target vertex, as there may be multiple edges to the target, each one needing it's own data. But although I could build my graph using a custom edge class, derived from IEdge, it's unclear to me what XAML I need to write to tie this into Graph#. For custom vertices I just define a data template for the class, but edges are more complex, with their paths etc. Has anyone managed to use Graph# with custom edge classes, and if so what does the XAML look like? Thanks, Kevin I'll answer the final part of the question myself... Suppose you define your own vertex class, MyVertex, and the corresponding edge class, MyEdge:Edge<MyVertex>. You then define a custom graph class MyGraph:BidirectionalGraph<MyVertex, MyEdge> When you try to use these classes you find that no graph appears. The bit I was missing was that you also need to define class MyGraphLayout : GraphSharp.Controls.GraphLayout<MyVertex, MyEdge, MyGraph> and update the XAML so that it uses the MyGraphLayout element, instead of GraphLayout, to instantiate the graph view. The library desperately needs some documentation, or at the very least an FAQ, to avoid such frustrations :-( Kevin, the answer to your first question (how to get the ToolTip change to appear when using just the style setters) is the following: 1) the edge control template should be modified to use ToolTip from a template binding on the path. In other words, it should have a Path.ToolTip property set to a {TemplateBinding ToolTip}. This is an oversight in the implementation of the control template, so it makes sense that the control template needs to change - this is not something that each user should have to change - it should be changed in the 'stock' templates. 2) your style will then be able to set ToolTip on the EdgeControl and have it passed down by virtue of (1) to the Path. This means for your own customization (adding tooltip values) you can do so in the "regular" style template without having to replace the control templates. 3) if your binding is not updating after changes to your property, it's likely you aren't implementing INotifyPropertyChanged properly, and you aren't using a DependencyObject/DepedencyProperty for your source object/property. You should raise PropertyChanged when changing the value of your property on your Edge class, when the property is changed by whatever is making the change. This will notify the binding to refresh the tooltip. I don't know if refreshes occur during the tooltip showing, so if you need that, you may need some "magic". Thanks for the reply Kelly. I think I understand the first part of your suggestion; I modified my copied version of the EdgeControl template to set the tool tip to {TemplateBinding ToolTip} instead of my custom tooltip, and hopefully I'll be able to strip out this copy when Graph# gets updated. But I'm not sure what to write for the second part of your suggestion. If I define <Style TargetType="{x:Type graphsharp:EdgeControl}"> <Setter Property="ToolTip"> <Setter.Value> ... </Setter.Value> </Setter> </Style> Kevin, the only way this should be giving a duplicate resource exception (if I understand correctly) is if you have two of these styles in the same resource dictionary. Are you using a merged dictionary, or a dictionary that you copied from the sample project? If so, you should probably just modify that style to add the setter as appropriate in there. If you want to keep those as "stock" styles that you customize, you need to add your customizations at a lower (deeper child) level in the logical tree. For instance, in Window.Resources (but don't merge the resource dictionary if you're doing so). You definitely won't be able to put both styles in the same resource dictionary (whether merged or inline). Thanks Kelly, now you mention it I remember reading about this stuff. I'll go back and look at my WPF book. Thanks for your help. Nearly there... Rather than modifying and rebuilding Graph# I moved the modified version of the edge control template to the application xaml file and kept the tooltip style setter in the main window xaml file. This fixed the duplicate resource exception, as you had predicted. So now if the tool tip is a simple string I can just define something like this: <Style TargetType="{x:Type graphsharp:EdgeControl}"> <Setter Property="ToolTip"> <Setter.Value>...</Setter.Value> </Setter> </Style> That works fine. However, if I want a slightly more ambitious tooltip, e.g. a list in a stack panel populated by a collection property in my edge class, I can't just write something like this: <Style TargetType="{x:Type graphsharp:EdgeControl}"> <Setter Property="ToolTip"> <Setter.Value> <StackPanel> <ListView ItemsSource="{Binding Path=Edge.MyList}"> ... </ListView> </StackPanel> </Setter.Value> </Setter> </Style> as you get a Xaml parse exception. I can get around this by putting the stack panel in a resource, and then referencing it in the setter, as in <StackPanel x: ... </StackPanel> <Style TargetType="{x:Type graphsharp:EdgeControl}"> <Setter Property="ToolTip" Value="{StaticResource EdgeToolTip}"/> </Style> However, I can't figure out how to set the ItemsSource attribute to pick up the edge property list. As with most problems in WPF, there's probably a one line bit of magic I'm missing somewhere. Suggestions would be appreciated. Kevin, what's the XamlParseException that you get when trying the Setter.Value with StackPanel in it. I see no reason why that shouldn't work. BTW, I just checked in a change that allows you to use bindings that refer to the Edge or Vertex properties using simple binding syntax. Currently, the binding stuff would refer to the Graph object, not the Vertex or Edge objects, since DataContext was not being set on the VertexControl and EdgeControl. The latest source (revision 31550 or later) should contain this fix, and allow you to use "normal" binding syntax. With my fix, you would just bind to {Binding MyList}, not {Binding Edge.MyList}. If you wanted to go through the "Edge" property, you need to use the templated source (i.e. {Binding Edge.MyList, RelativeSource={RelativeSource TemplatedParent}} instead of the simple Binding, since the simple binding looks in the DataContext for it's source). The error you get is "Cannot add content of type 'System.Windows.Controls.StackPanel' to an object of type 'System.Object'". It sounds like it's a known problem, with the use of a resource the suggested fix. It's just getting the binding set up correctly that's causing the problem. I'll try using the revision you suggested to see if I can get further. Kevin, check out revision 31556, specifically the Graph#.Sample/MainWindow.xaml file (line 316) and the resource that I've added to the graph layout tag. You should be able to see how to do a binding from this example (using the inline resource, like you found is necessary for ToolTip's (I never knew that was necessary)). In order to get yours to work, you should be able to just replace my TextBlock with your ListView and have it work. If that doesn't work, you might try a simpler ItemsControl type, so that interactivity is not involved. I remember reading that there are some weird things about interactive controls being in tooltips. I also pushed the ToolTip support code into the Poc GraphVertex and GraphEdge templates. I didn't push them into the stock templates, but if you're using them and you'd like me to, I can. I just figured nobody is using the stock ones, so I didn't bother unless someone asks for it. Actually, I went ahead and pushed the changes down to the core templates. That way if you're using the templates in GraphSharp.Controls.dll, you will get the ToolTip support (i.e. you just need a style to set ToolTip on the Vertex / Edge, and it will be pulled down to the appropriate place in the logical tree). Kelly Excellent. Your 31556 build, together with ItemsSource set to "(Binding Path=MyListProperty}", worked fine. Thanks for all your help Kelly. Kevin On a related note, suppose I wanted to use a data trigger to alter a property of an edge, e.g. it's stroke thickness. I started by defining the following: <Style TargetType="{x:Type graphsharp:EdgeControl}"> <Setter Property="ToolTip" Value="{StaticResource EdgeToolTipContent}"/> <Setter Property="ContextMenu" Value="{StaticResource EdgeContextMenu}"/> <Style.Triggers> <DataTrigger Binding="{Binding Path=Active}" Value="True"> <Setter Property="???StrokeThickness???" Value="4"></Setter> </DataTrigger> </Style.Triggers> </Style> However, it's not clear to me how to refer to the StrokeThickness property of the path making up the edge in the setter element. I've tried various specifying various things for the property, e.g. Path.StrokeThickness, and none of them seem to alter the thickness. You can probably use the TargetName property of Setter, and use the TargetName of your "path" element, but the better approach would be for us to add a DP on EdgeControl to allow you to 'pass on' these values just like what we did with ToolTip. I'll work on that over lunch. Hmm... I don't know what's going on, but no matter what I change the stroke thickness in the path to, it doesn't seem to matter - it always looks the same. I even changed it from 2 to 5 and then to 0.5 and couldn't see any difference. If you can figure out how to get the strokethickness to do whatever you want (by mucking with the path directly) then let me know and I'll figure out how you can get the value set via a binding or style. I'm not going to check in what I've done so far, since it seems silly to add a DP and the plumbing in the xaml if the Path is just going to ignore it anyway. If I copy the edge control template into my zoom control resources, as I did for the tool tip, then I can set the stroke thickness to different values and get the expected outcome. Furthermore, if I add a trigger to the control template, for example <ControlTemplate.Triggers> <DataTrigger Binding="{Binding Path=Active}" Value="True"> <Setter Property="StrokeThickness" Value="5" TargetName="edgePath"></Setter> </DataTrigger> </ControlTemplate.Triggers> then the line thickness varies, as expected. But ideally you'd want to be able to write something like the trigger without having to also duplicate the EdgeControl control template code. ok... I have no idea why I couldn't see any changes in the size, but I've checked in the changes I made. See if when you set the StrokeThickness on the style whether it does what you'd expect. It didn't seem to do anything when I tried it, but maybe I was not using it correctly, or looking in the wrong place. And do you do when the tooltip is a property of the custom Edge that you want to bind, and the datacontext do not include him? Here is the custom Edge public class PocEdge : Edge<PocVertex> { public string ID { get; private set; } public PocEdge(string id, PocVertex source, PocVertex target) : base(source, target) { ID = id; } } Here is the Xaml <Style TargetType="{x:Type graphsharp:EdgeControl}"> <Style.Resources> <ToolTip x: <StackPanel> <TextBlock FontWeight="Bold" Text="Edge.ID"/> <TextBlock Text="{Binding ID}"/> </StackPanel> </ToolTip> </Style.Resources> <Setter Property="ToolTip" Value="{StaticResource ToolTipContent}"/> </Style> The error I get at runtime: System.Windows.Data Error: 40 : BindingExpression path error: 'ID' property not found on 'object' ''MainWindowViewModel' (HashCode=27666100)'. BindingExpression:Path=ID; DataItem='MainWindowViewModel' (HashCode=27666100); target element is 'TextBlock' (Name=''); target property is 'Text' (type 'String') Thanks I'm going to guess that you're using the Jun 2009 build (v1.0) and not building from the latest sources. I made several changes but a new build has not been posted with my changes. I'd recommend you grab the sources and build sources and see if that fixes your problems. Thanks a lot problem solved with the last version build from source of graphsharp and the control. <TextBlock FontWeight="Bold" Text="Edge.ID"/> There is no error is running the code except there is no binding to the Edge.ID Each Tooltip has exactly the same word "Edge.ID" Any suggestion, kind of learning WPF now. That’s because you didn’t put any binding for Text. Bindings look like “{Binding Edge.ID}”, you just supplied text (“Edge.ID”). This is a tough project to start learning WPF with, I’d recommend you try to learn how binding works a bit before you dive into trying to use it on this project. From: OnSharp <notifications@codeplex.com> [mailto:OnSharp <notifications@codeplex.com>] Sent: Thursday, February 10, 2011 6:15 AM To: kelly.leahy@milliman.com Subject: Re: Tool tips on edges [graphsharp:70832] From: OnSharp <TextBlock FontWeight="Bold" Text="Edge.ID"/> Hi there, I've been reading through this thread with great interest. I am unfortunately still trying to puzzle out the correct style template to set the edge thickness. Any change you could write it out in full, i think i am missing things between posts. Even just to set the stroke thickness to a constant value would get me going many thanks David Hi. I have been impressed with the functionlaity of GraphSharp. I have been working on what information is available on this. I also am new to the C# environment. I have read through the thread, since I am looking for a functionlaity to display a tooltip on a Vertex. The tooltip needs to take the string value from the Vertex and do a database call to obtain other information. Hence each tooltip will be unique. I would apprecita if the code that was dicussed in this thread could be available. This helps to understand how each componenet work together. Kind regards. 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.
https://graphsharp.codeplex.com/discussions/70832
CC-MAIN-2017-13
refinedweb
2,640
63.9
Question 1 : What will be the output of the program? class MyThread extends Thread { MyThread() { System.out.print(" MyThread"); } public void run() { System.out.print(" bar"); } public void run(String s) { System.out.println(" baz"); } } public class TestThreads { public static void main (String [] args) { Thread t = new MyThread() { public void run() { System.out.println(" foo"); } }; t.start(); } } Option B is correct because in the first line of main we're constructing an instance of an anonymous inner class extending from MyThread. So the MyThread constructor runs and prints "MyThread". The next statement in main invokes start() on the new thread instance, which causes the overridden run() method (the run() method defined in the anonymous inner class) to be invoked, which prints "foo" Question 2 : What will be the output of the program? class MyThread extends Thread { public static void main(String [] args) { MyThread t = new MyThread(); t.start(); System.out.print("one. "); t.start(); System.out.print("two. "); } public void run() { System.out.print("Thread "); } } When the start() method is attempted a second time on a single Thread object, the method will throw an IllegalThreadStateException (you will not need to know this exception name for the exam). Even if the thread has finished running, it is still illegal to call start() again. Question 3 : What will be the output of the program? class MyThread extends Thread { MyThread() {} MyThread(Runnable r) {super(r); } public void run() { System.out.print("Inside Thread "); } } class MyRunnable implements Runnable { public void run() { System.out.print(" Inside Runnable"); } } class Test { public static void main(String[] args) { new MyThread().start(); new MyThread(new MyRunnable()).start(); } } If a Runnable object is passed to the Thread constructor, then the run method of the Thread class will invoke the run method of the Runnable object. In this case, however, the run method in the Thread class is overridden by the run method in MyThread class. Therefore the run() method in MyRunnable is never invoked. Both times, the run() method in MyThread is invoked instead. Question 4 : What will be the output of the program? class s1 implements Runnable { int x = 0, y = 0; int addX() {x++; return x;} int addY() {y++; return y;} public void run() { for(int i = 0; i < 10; i++) System.out.println(addX() + " " + addY()); } public static void main(String args[]) { s1 run1 = new s1(); s1 run2 = new s1(); Thread t1 = new Thread(run1); Thread t2 = new Thread(run2); t1.start(); t2.start(); } } Both threads are operating on different sets of instance variables. If you modify the code of the run() method to print the thread name it will help to clarify the output: public void run() { for(int i = 0; i < 10; i++) System.out.println( Thread.currentThread().getName() + ": " + addX() + " " + addY() ); } Question 5 : What will be the output of the program? public class Q126 implements Runnable { private int x; private int y; public static void main(String [] args) { Q126 that = new Q126(); (new Thread(that)).start( ); /* Line 8 */ (new Thread(that)).start( ); /* Line 9 */ } public synchronized void run( ) /* Line 11 */ { for (;;) /* Line 13 */ { x++; y++; System.out.println("x = " + x + "y = " + y); } } } The synchronized code is the key to answering this question. Because x and y are both incremented inside the synchronized method they are always incremented together. Also keep in mind that the two threads share the same reference to the Q126 object. Also note that because of the infinite loop at line 13, only one thread ever gets to execute.
http://www.indiaparinam.com/java-question-answer-java-threads/finding-the-output
CC-MAIN-2019-22
refinedweb
576
73.27
Attempted relative import in non-package - Webmaster4o I get this error when I call import gittle(after installing both gittle and dulwich), which, from what I understand, should only exist if running the script directly, not if I call import. What's up win this? Does pythonista not change __name__, or am I confused? How can I fix this? Are you running this in the interactive interpreter, or is there other code that runs before the import? Also where did you install gittle, and does it have a __init__.pyfile in the package folder? - Webmaster4o I installed it from GitHub, just running the import statement. I fixed the problem by renaming some files and removing some relative imports.
https://forum.omz-software.com/topic/2381/attempted-relative-import-in-non-package
CC-MAIN-2020-40
refinedweb
118
67.04
it easy to make Post your Comment Swap two any numbers (from Keyboard) Swap two any numbers (from Keyboard)  ... will learn how to swap or exchange the number to each other. First of all we have... in command line. Use a temporary variable z of type integer that will help us to swap adding two numbers with out using any operator adding two numbers with out using any operator how to add two numbers with out using any operator import java.math.*; class AddNumbers { public static void main(String[] args) { BigInteger num1=new Adding two numbers Adding two numbers Accepting value ffrom the keyboard and adding two numbers Applet for add two numbers () { String num1; String num2; // read first number from the keyboard...); add(text2); label3 = new Label("Sum of Two Numbers...Applet for add two numbers what is the java applet code for add two adding of two numbers in designing of frame adding of two numbers in designing of frame hello sir, now i'm create two textfield for mark1&mark2 from db.how to add these two numbers...=st.executeQuery("select * from student where id=1"); int mar1=0,mar2=0 Swap two any numbers Swap Any Two Numbers  ... to swap or exchange the number to each other. First of all we have to create.... Use a temporary variable z of type integer that will help us to swap Numbers Java NotesNumbers Two kinds of numbers. There are basically two kinds of numbers in Java and most other programming languages: binary integers (most commonly using the type int) and binary floating-point numbers (most commonly using Comparing Two Numbers Comparing Two Numbers  ... of comparing two numbers and finding out the greater one. First of all, name a class "Comparing" and take two numbers in this class. Here we have taken a=24 Swapping of two numbers in java values from the command prompt. The swapping of two numbers is based on simple...Swapping of two numbers in java In this example we are going to describe swapping of two numbers in java without using the third number in java. We Write a program to list all even numbers between two numbers Write a program to list all even numbers between two numbers Java Even Numbers - Even... all the even numbers between two numbers. For this first create a class named Addition of two numbers Addition of two numbers addition of two numbers Rational Numbers rational numbers. A rational number can be represented as the ratio of two integer... form. That is, any common factor of a and b should be removed. For example... static method that returns the largest common factor of the two positive Keyboard Input Java NotesKeyboard Input There are two approaches to getting keyboard input from the user. GUI (Graphical User Interface). Displaying a graphical text... simple keyboard input, eg, something like C++'s cin. Java 5 (introduced Listing all even numbers between two numbers Listing all even numbers between two numbers Hi, How to write code to list all the even numbers between two given numbers? Thanks Hi... the numbers. Check the tutorial Write a program to list all even numbers between two without using third variable Swapping of two numbers without using third variable In this tutorial we.... This is simple program to swap two value using arithmetic operation Swapping of two... to swap two variables without using the third variables. First we declare one Prime Numbers - IDE Questions Prime Numbers Create a program that calculates the prime numbers from any inputted start and end range of values (e.g. 5 and 28) and print the prime numbers in rows of 10. Hint: Use a counter to count how many values are printed Mysql Multiply ; Mysql Multiply is used to define the product of any two or more numbers... two or more numbers in a specified table. select(a*b) : The Query return you the product of two numbers a and b. Query: The given below query is used Mysql Multiply ; Mysql Multiply is used to define the product of any two or more numbers... of any two or more numbers in a specified table. select(a*b) : The Query return you the product of two numbers a and b. Query: The given below query Midpoint of two number important to find the number that is exactly between two numbers. In this example we are finding a midpoint of two numbers by using the while loop.  ...Midpoint of two number   Two Element Dividing Number Dividing Two Numbers in Java  ... will learn how to divide any two number. In java program use the class package.... If you are newbie in java programming then you can understand very easy way from Swap two numbers without using third variable Swap two numbers without using third variable In this section we are going to swap two variables without using the third variable. For this, we have used... from the command prompt. Instead of using temporary variable, we have done some Keyboard Java Notes: Keyboard Not normally used. You don't normally need to capture the low-level keyboard events because components (eg, JTextField) handle them... whenever any key is pressed or released. Regular character keys also produce Swapping of two numbers program to calculate swap of two numbers. Swapping is used where you want... ability. In this program we will see how we can swap two numbers. We can do... swap the numbers. To swap two numbers first we have to declare a class Swapping java programingchellycyl fee February 21, 2012 at 1:11 PM it easy to make Post your Comment
http://www.roseindia.net/discussion/20790-Swap-two-any-numbers-(from-Keyboard).html
CC-MAIN-2014-15
refinedweb
936
63.8
tor,,, :. -.,windows 10.1 Update Download Free for PC is now available for laptop and computer users. Windows 10.1 update free in in low size as you think about it. You can update your Windows 10 into windows 10.1 without newly installing in your laptop.etc.) residing in a potentially unsecured environment. It is mainly porta per vpn used to secure data links between safeguarded servers and end-points (such as mobile devices,) a VPN (or Virtual Private Network)) is an encryption protocol for Internet data transmissions. Laptops, Porta per vpn the main downside is that a good VPN connection costs money. It's also faster than the alternatives. The advantage of VPN is that it guarantees that every program on your computer/device that talks to the Internet does so via an porta per vpn encrypted tunnel.1- Configuring a new VPN L2TP/IPSec connection with the Windows 7 native porta per vpn client. 3- Disconnect from the VPN. 4- If you experience problems with your VPN connection. 1- Configuring a new VPN L2TP/IPSec connection with the Windows 7 native client. 2- Connect to the VPN.vPN. OpenVPN porta per vpn VPN Windows., import and export functions are available both through the GUI or through direct command line options. ). Secured import and export functions To allow IT Managers to deploy porta per vpn VPN Configurations securely,c o m : now serving over 10,000 files ( 2,200 active html pages)) adb creative suite easy uk vpn 3 compare lyberty. L y b e porta per vpn r t y. The PE routers are always owned by the service provider. Provider (P) routers. These routers are commonly referred to as transit routers and are located in the service providers core network. Routing information is passed from the Customer Edge router to the Provider Edge router. Once installed, log in with your username and password, and select US as your country. The visit Netflix, and you will be automatically routed to the Netflix US library. How To Setup Netflix With PureVPN On Your Laptop And Desktop PCs? Install the app on. Porta per vpn in USA and United Kingdom! vPN Virtual porta per vpn Private Network. VPN., vPN.,Betternet is with you on every platform iOS. 1-st Question is what address you porta per vpn get as VPN client? Your computer is on the same LAN 24) with your QNAP. ( if my interpretation is correct - )). where the original IP packet is decrypted and forwarded to its intended destination. De-encapsulation happens at the end vpn master for mac download porta per vpn of the tunnel, and confidentiality. Integrity, its design meets most security goals: authentication, encapsulating an IP packet inside an IPsec packet. IPsec uses encryption,um jede populäre Website, rufen Sie das kuvia Web-Proxy-Proxy-Zugriffsbeschränkungen umgehen. Sowie porta per vpn Online-Reisezielen wie Orkut, kuvia ist eine benutzerfreundliche Proxy, die Sie zugreifen müssen, der Ihnen helfen, diese Proxy-Website verwendet werden, mySpace, proxyblock kostenlos umgehen wird. VPN . Zero VPN is a Productivity Game for android download last version of Zero VPN Apk (Unlocked) for android from revdl with direct link. All new designed free VPN, one touch to build a secured network, unblock website or app like Facebook, Twitter, Pandora,, Skype, watch restricted videos, play blocked games, encrypt all network traffic, protect hotspot data, hide real ip for keep anonymous. you will sometimes need to setup a porta per vpn specific proxy for them to use, when using applications from the command line,feel like your downloads are sluggish? To ensure your data stays safe, speed isnt the only thing you need in a VPN. ExpressVPN deploys strong 256-bit AES encryption along with a zero-logging policy that covers traffic, run porta per vpn the test and find out for sure!numerous personal information could be captured by the 3rd party, web login credentials, people mostly don't realize that when simply open your web browser to surf the internet, the secure and private data includes email password, home physical address, porta per vpn credit card number, the provider also offers different kinds of tunneling protocols like OpenVPN, l2TP/IPsec and others. The service does not log the subscribers information and follows no logging policy. 4. Moreover, nordVPN offers dedicated streaming servers porta per vpn to support P2P activities of the users.paths, there is no guarantee that every web server will provide any of these; servers may omit some, the porta per vpn entries in this array are created by the web server. Description _SERVER is an array containing information such as headers, and script locations.how to porta per vpn create a vpn for my home network! topics: What is SSL VPN NetExtender? Using SSL VPN Bookmarks SSL VPN NetExtender Overview porta per vpn This section provides an introduction to the SonicOS SSL VPN NetExtender feature. NetExtender Concepts What is SSL VPN NetExtender? Benefits.you have to pay 299! Most importantly, vip72 tends to be speed vpn pro apk so expensive. VIP72 plans ranging from 50 to 200. If you want a yearly subscription, we are not exactly sure as to why. Web proxy authentifizierung hp 6700! that should do the trick. Now tap the little blue arrow next to Onavo and switch off the Connect porta per vpn On Demand. The easiest way to turn the automatic VPN off would be to go to your settings general VPN.further documentation is available here. Click Go. DOI System Proxy Server Documentation, w3.org/TR/xhtml1/DTD/xhtml1-transitional. Dtd" Resolve a DOI Name doi: Type or paste a DOI name into the text box. DOI. ORG, send porta per vpn questions or comments to. "http www. Your browser will take you to a Web page (URL)) associated with that DOI name. DOI, once install, hMA PRO VPN Crack is installed. Go to crack folder and open KEY. Thats it. Have fun. Use any HMA PRO VPN Serial Key to register. Txt file. Run the software.the more options youll have for a solid connection. UK so you can get a coveted. BBC approved porta per vpn IP address. BBC outside of the UK wherever you travel. Server network The bigger a VPNs server network, you also need plenty of servers within the.,,,.,,. in fact, a quick test using a UK-based server had HD video up and running on both porta per vpn All4 and Netflix within seconds. The same was true for our mobile test. We downloaded the app,actual contacts on the left on this page VIP72 works for you within 11 years! Which registered till that date will be able to use old prices 01.2010 All our customers having paid socks account, great days for big discounts. Registered after porta per vpn '05 november 2014 00:00'. Special promo plans already available Socks Client has been updated Update is high priority and affect GEO database We offer new prices for all accounts, customers, but Nick Kroll. (A coincidence that should remain between Amy porta per vpn Poehler and her therapist.)) American Vandal Metacritic score: Season 1: 75 ; Season 2: 76 Stream on. Netflix. Also I'll save you some time: Maurice the Hormone Monster is voiced not by Will Arnett,betternet Betternet, betternet ; porta per vpn VPN-; ; ;..select a porta per vpn plan that best suits your needs and requirements. Click on the Buy Proxy tab. Click on the Buy Now option and follow instructions for completing payment. malware and spyware. Download FREE AVG antivirus software. Easy-to-use virus scanner. Get protection against download vpn china untuk android viruses,
http://malopolskadays.eu/speed/porta-per-vpn.html
CC-MAIN-2019-09
refinedweb
1,273
66.13
Pure-Python non-blocking IO functions Project description Non-blocking python IO functions These are pure-python functions which perform non-blocking I/O in python. nonblock_read nonblock_read provides the ability to read anything available on a buffer, like a file or a pipe or a socket, in a non-blocking fashion. Methods like readline will block until a newline is printed, etc. You can provide a limit (or default None is anything available) and up to that many bytes, if available, will be returned. When the stream is closed on the other side, and you have already read all the data (i.e. you’ve already been returned all data and it’s impossible that more will ever be there in the future), “None” is returned. def nonblock_read(stream, limit=None, forceMode=None): ‘’‘ nonblock_read - Read any data available on the given stream (file, socket, etc) without blocking and regardless of newlines. @param stream - A stream (like a file object or a socket) @param limit <None/int> - Max number of bytes to read. If None or 0, will read as much data is available. @param forceMode <None/mode string> - Default None. Will be autodetected if None. If you want to explicitly force a mode, provide ‘b’ for binary (bytes) or ‘t’ for text (Str). This determines the return type. @return <str or bytes depending on stream’s mode> - Any data available on the stream, or “None” if the stream was closed on the other side and all data has already been read. ‘’‘ Keep in mind that you can only read data that has been flushed from the other side, otherwise it does not exist on the buffer. If you need to do nonblocking reads on sys.stdin coming from a terminal, you will need to use “tty.setraw(sys.stdin)” to put it in raw mode. See examples/simpleGame.py for an example. Example usage: from nonblock import nonblock_read pipe = subprocess.Popen([‘someProgram’], stdout=subprocess.PIPE) … while True: data = nonblock_read(pipe.stdout) if data is None: # All data has been processed and subprocess closed stream pipe.wait() break elif data: # Some data has been read, process it processData(data) else: # No data is on buffer, but subprocess has not closed stream idleTask() # All data has been processed, focus on the idle task idleTask() An example simple game that uses nonblock_read to drive input whilst always refreshing the map and moving a monster around can be found at: Background Reading - bgread Sometimes you may want to collect data from one or more streams in the background, and check/process the data later. python-nonblock provides this functionality through a method, “bgread”. You provide a stream object and options, and it outputs an object which will automatically be populated in the background by a thread, as data becomes available on the stream. ‘’‘ bgread - Start a thread which will read from the given stream in a non-blocking fashion, and automatically populate data in the returned object. @param stream <object> - A stream on which to read. Socket, file, etc. @param blockSizeLimit <None/int> - Number of bytes. Default 65535.If None, the stream will be read from until there is no more available data (not closed, but you’ve read all that’s been flushed to straem). This is okay for smaller datasets, but this number effectively controls the amount of CPU time spent in I/O on this stream VS everything else in your application. The default of 65535 bytes is a fair amount of data. @param pollTime <float> - Default .03 (30ms) After all available data has been read from the stream, wait this many seconds before checking again for more data.A low number here means a high priority, i.e. more cycles will be devoted to checking and collecting the background data. Since this is a non-blocking read, this value is the “block”, which will return execution context to the remainder of the application. The default of 100ms should be fine in most cases. If it’s really idle data collection, you may want to try a value of 1 second. @param closeStream <bool> - Default True. If True, the “close” method on the stream object will be called when the other side has closed and all data has been read. NOTES – blockSizeLimit / pollTime is your effective max-throughput. Real throughput will be lower than this number, as the actual throughput is be defined by: T = (blockSizeLimit / pollTime) - DeviceReadTime(blockSizeLimit) Using the defaults of .03 and 65535 means you’ll read up to 2 MB per second. Keep in mind that the more time spent in I/O means less time spent doing other tasks. @return - The return of this function is a BackgroundReadData object. This object contains an attribute “blocks” which is a list of the non-zero-length blocks that were read from the stream. The object also contains a calculated property, “data”, which is a string/bytes (depending on stream mode) of all the data currently read. The property “isFinished” will be set to True when the stream has been closed. The property “error” will be set to any exception that occurs during reading which will terminate the thread. @see BackgroundReadData for more info. ‘’‘ So for example: inputData = bgread(sys.stdin) processThings() # Do some stuff that takes some time typedData = inputData.data # Get all the input that occured during ‘processThings’. Background Writing - bgwrite python-nonblock provides a clean way to write to streams in a non-blocking, configurable, and interactive-supporting way. The core of this functionality comes from the bgwrite function: def bgwrite(fileObj, data, closeWhenFinished=False, chainAfter=None, ioPrio=4): ‘’‘ bgwrite - Start a background writing process @param fileObj <stream> - A stream backed by an fd @param data <str/bytes/list> - The data to write. If a list is given, each successive element will be written to the fileObj and flushed. If a string/bytes is provided, it will be chunked according to the #BackgroundIOPriority chosen. If you would like a different chunking than the chosen ioPrio provides, use #bgwrite_chunk function instead.Chunking makes the data available quicker on the other side, reduces iowait on this side, and thus increases interactivity (at penalty of throughput). @param closeWhenFinished <bool> - If True, the given fileObj will be closed after all the data has been written. Default False. @param chainAfter <None/BackgroundWriteProcess> - If a BackgroundWriteProcess object is provided (the return of bgwrite* functions), this data will be held for writing until the data associated with the provided object has completed writing. Use this to queue several background writes, but retain order within the resulting stream. @return - BackgroundWriteProcess - An object representing the state of this operation. @see BackgroundWriteProcess ‘’‘ You can create a queue of data to be written to the given stream by using the “chainAfter” param, providing the return of a previous “bgwrite” or “bgwrite_chunk” function. This will wait for the previous bgwrite to complete before starting the next. bgwrite will write data in blocks and perform heuristics in order to provide interactivity to other running threads and calculations, based on either a predefined BackgroundIOPriority, or you can provide a custom BackgroundIOPriority (see “Full Documentation” below for the parameters) Examples An example of a script using several bgwrites in addition to performing CPU-bound calculations can be found at: Full Documentation Can be found . Project details Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/python-nonblock/3.0.0/
CC-MAIN-2018-30
refinedweb
1,237
62.68
go to bug id or search bugs for Description: ------------ PHP 5.2.4 (FCGI), APC from CVS loading module apc.so in php.ini cause each php process has own cache (as far as i can see by reloading apc.php). Is it possible on to share one cache between all processes ? APC conf: ./configure --enable-apc-spinlocks php.ini: extension=apc.so apc.enabled=1 apc.shm_segments=1 apc.shm_size=1024 apc.num_files_hint=10000 I found similar 'bug' reported with WIN32, but maybe it is possible on linux or freebsd ? Add a Patch Add a Pull Request Changing to feature request as this behaviour is the intended one as of now. Maybe in future version of APC, memcached daemon can be used as storage because of its independence. If you need memcached, use it directly. APC is faster than memcached for local retrieval. I don't intend to slow it down by using any other backend which needs serialization. Yes, but memcache can't cache opcode itself. I need to cache opcode, and share it between FCGI PHP processes. The point is that memcached is way too slow to make it worthwhile to do this. There's a way to get around this missing feature (at least with Apache/mod_fcgid): Force the fcgi-module to start only one process per Virtual-Server and let the php-cgi binary spawn enough children. Put this into the fcgid.conf: DefaultMaxClassProcessCount 1 DefaultMinClassProcessCount 1 And this into your wrapper script: PHP_FCGI_CHILDREN=32 export PHP_FCGI_CHILDREN PHP_FCGI_MAX_REQUESTS=10000 export PHP_FCGI_MAX_REQUESTS This way you get one APC-Cache/Virtual-Server. To Bruno: That wont scale, fast-cgi is supposed to start up more processes to cope with the load when required. And if your php process dies, then your going to get up to 32 Error 500's in a big batch, especially if a fast-cgi timeouts waiting for input back for the cgi process. I get this happening with 2 children to a limited degree. I believe this is basically a duplicate of bug #11666. Could you do something like let us set a path to a socket, for IPC between the php5-fcgi+apc processes. So for php processes running as the same user, on the same document root, could share the cache. Look at the apc_mmap() function in apc_mmap.c and get rid of the unlink() call in the type of mmap you would like to do. That way multiple processes should be able to mmap the same memory segment. That doesn't work for me. I already have 2-5 differents cache files. I have commented all unlink in that file but the problem continues. Is there any way to work with APC with only 1 cache file? With fastcgi the problem is critical for me. Well, read the code. You obviously also want to use a fixed filename and not do the mkstemp() or mktemp() on the filemask. You want to just use the filename that is passed in for every process. I think suExec + fastcgi/fcgid PHP is becoming widely adopted. A workaround to not waste all the cache on each respawn would be seriously appreciated. Is this problem fixed or workaround exist (without using PHP_FCGI_CHILDREN) ? Rasmus, i looked at apc_mmap(). I try to remove "unlink" and "mkstemp" in apc_mmap.c in last section (regular files) to make one cache for all system. Now it looks like that: else { struct passwd *userinfo; char file_mask2[250]; //fd = mkstemp(file_mask); userinfo=getpwuid( geteuid()); sprintf(file_mask2,"%s-%s",file_mask,userinfo->pw_name); fd = open(file_mask2, O_CREAT|O_RDWR, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH); if(fd == -1) { apc_eprint("apc_mmap: mkstemp on %s failed:", file_mask); return (void *)-1; } if (ftruncate(fd, size) < 0) { close(fd); //unlink(file_mask); apc_eprint("apc_mmap: ftruncate failed:"); } shmaddr = (void *)mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_NOSYNC, fd, 0); close(fd); //unlink(file_mask); } } if((long)shmaddr == -1) { apc_eprint("apc_mmap: mmap failed:"); } return shmaddr; } It is also add current user name to "file_mask". Files "file_mask.username" are created, but there is too much segmentation faults. So it not work. I try to switch to shm (--disable-mmap), and change apc_shm.c, adding one fixed key id and set permission flags to grant r/w access to all processes, also remove apc_shm_destroy call to make shared memory segment persistent between all fastcgi processes. int apc_shm_create(const char* pathname, int proj, size_t size) { int shmid; /* shared memory id */ int oflag; /* permissions on shm */ key_t key; /* shm key returned by ftok */ key = IPC_PRIVATE; #ifndef PHP_WIN32 /* no ftok yet for win32 */ if (pathname != NULL) { if ((key = ftok(pathname, proj+1)) < 0) { apc_eprint("apc_shm_create: ftok failed:"); } } #endif // oflag = IPC_CREAT | SHM_R | SHM_A; //old flag oflag = IPC_CREAT | 0666; key=11; //fixed key for test if ((shmid = shmget(key, size, oflag)) < 0) { apc_eprint("apc_shm_create: shmget(%d, %d, %d) failed: %s. It is possible that the chosen SHM segment size is higher than the operation system allows. Linux has usually a default limit of 32MB per segment.", key, size, oflag, strerror(errno)); } return shmid; } void* apc_shm_attach(int shmid) { void* shmaddr; /* the shared memory address */ if ((long)(shmaddr = shmat(shmid, 0, 0)) == -1) { apc_eprint("apc_shm_attach: shmat failed:"); } /* * We set the shmid for removal immediately after attaching to it. The * segment won't disappear until all processes have detached from it. */ // apc_shm_destroy(shmid); // REMOVED THIS return shmaddr; } But there is segmentation fault too. error_log: "Premature end of script headers: script.php". strace on php-cgi shown last call to "futex(". It will be very nice, if apc will have 2 options: 1. One fixed size cache for entry server, shared between all users and fcgi processes. Ideal for dedicated server, where hosted only trusted or own projects, and when different user/sites need to share the same data. 2. One cache for each user, shared between each fcgi processes under same user. Ideal for not trusted hosting. p.s. apc from cvs head, php 5.2.6. the issue isn't sharing data, but sharing locks PHP-fpm is grate solution for that. Gopal, you asked to test Lockhammer in production systems on your blog -- lockhammer.html Can you explain what output is expected, and what output is not expected ? e.g i have: [root@km30609 3.1.12]# ./lockhammer_pthread > (3120) waiting > (3121) waiting > (3121) in lock > (3122) waiting > (3123) waiting > (3124) waiting > (3125) waiting > (3126) waiting > (3127) waiting > (3128) waiting > (3129) waiting > (3130) waiting > (3131) waiting > (3132) waiting > (3133) waiting > (3134) waiting > (3135) waiting > (3136) waiting > (3137) waiting > (3138) waiting > (3139) waiting > (3122) in lock < (3121) off lock > (3121) waiting > (3123) in lock < (3122) off lock > (3122) waiting > (3124) in lock < (3123) off lock > (3123) waiting < (3124) off lock > (3120) in lock > (3124) waiting < (3120) off lock > (3125) in lock > (3120) waiting > (3126) in lock < (3125) off lock > (3125) waiting > (3127) in lock < (3126) off lock > (3126) waiting > (3128) in lock < (3127) off lock > (3127) waiting May be cache sharing already work at apc 3.1.12 ? Are there any plans to add this feature to apc in near future? I think most people are switching to fastcgi/fcgid or already switched and _all_ will have or have this problem! This feature request is now over 2 years old and there is still no visible progress. For users with the popular apache webserver php-fpm is no solution and all the other workarounds like using memcache are crap. The other two popular caches (eaccelerator and xcache) do not have this feature. If APC fixes this problem, a lot of people will switch to APC. What is the problem of this feature request? Is it just lack of time? Are there not enough developers? Or is the problem hard to fix? Is there anyone who is still trying to fix this? Maybe we should start a website where people can vote for the problem and donate 5$ until someone is willing to fix this! Best regards, Frieder Hmm... maybe I should put up my threadless/thinkgeek wishlist up ;) Anyway, jokes aside. The reason I haven't fixed it so far is that fixing it so that it works for fcgi and with multiple processes makes it slower for the apache mode of operation. And there's a high likelihood that I'll break some of the already working apc functionality in the process. The locking sub-system + memory management subsystem is what needs to be fixed here. So that pointer 0xf00 in process #1 becomes 0xbaa in process #2, so that all references are held properly. Right now, apache2 prefork mode ensures that both processes share the same address space, which makes this rewrite-on-the-fly unnecessary. But I'm planning some other apache2 fixes which might make this less expensive that it looks right now. Real life keeps interfering though :) Why it is so hard make simple unix shared cache for first time, like php-shm functions does ? Why you ask for Lockhammer YEAR ago and silent after that ? Why you name you as 'official php cache' while you can't fix this simple issue with official mod_fcgid over the years? Why there is NO documentation AT ALL on all new 3.x stuff like "Lazy loading", "preload_path", "file_md5" ? Gopal already explained why it is way more complicated to do this across non-forked processes. Add to his list is the fact that there will be no owner-death protection for the cache, so you end up leaving huge chunks of garbage shared memory segments around if things don't exit gracefully. Patches are welcome. Never posted to developer forums before, but learning that the problem of sharing user cache between all processes when using fast-cgi (in my case with Lighttpd) comes as feature and is still unsolved makes me really desperate. I wanted to use APC caching quite extensively on the new version of the site I'm working on when I realized that there is *that* problem. I couldn't find any alternative solution when I tried googling for it. Just more and more bug reports and vague related postings. That leads me to the question. Is there *any* memory caching system around, working with fast-cgi (under Lighttpd) that actually supports sharing of cached variables across processes? I'm interested in some solution for apache2-mpm-worker and mod_fcgid. Any roadmap for this feature? I know this is a tricky problem, but it's also an important one. Has there been any progress in the last 2.5+ years on this? Maybe this is bring approached (by us, the 'bug submitters') in the wrong manner. As it stands now there is basically a choice if you want to use the FastCGI/FCGID- modules- 1) Use a low limit for memory to keep the over all memory down, since each process gets it's own. Downside is more cache misses. 2) The opposite- use a high limit- will ensure less misses but at a large memory cost. So far the focus (at least on this ticket) is trying to share memory, like with mod_php, but that's got it's own downfalls. What if we instead tried to reduce the cost of a miss instead, to make lowering the memory less of a negative? One possible way to do this would be by having a central, file-based cache behind the memory one. If APC can't find it in memory it could check this backend before recompiling- if it's present we can just load it into memory from there. If there is no opcode cache then APC can do it's normal thing, only then save a copy of the opcode to file. The benefit here is that lower shm limits on each process doesn't have nearly as much of a negative affect- rather than having to load and recompile a file, it just has to load a file. There would be extra overhead in the event of both a memory and file miss (an extra stat call), but I think it would be worth it for cgi and should be disabled for mod_php. I'm not on the mailing list and haven't seen the source code (yet, lol) so there could be flaws to this I'm not aware of it, but I think it's a reasonable solution to the bigger issue, if not the underlying problem itself. It works fine if you use spawnfcgi or php-fpm. Any process manager that launches a parent process and spawns child processes from that will work fine. I have an experimental patch for mmaped shared memory which appears to work but needs more testing: Thanks Rasmus. This settles my unease. :) Is there any sort of development happening to solve this rather huge issue? We've switched all our servers to using FastCGI & as you can imagine it's not pretty to see each process making up it's own cache. Would be wonderful if there is even some sort of workaround. thangarajj at gmail dot com, did you read the comments? It works fine if you use php-fpm in PHP 5.3. Rasmus, Yes, I did see that, but since we're using cpanel & cpanel has still not even estimated support for php-fpm on a future version, we are unable to use it. I should have mentioned this in my original comment, sorry. Plus I've read somewhere that fastcgi is supposed to be able to manage processes/children better than php-fpm. I'm not sure how accurate this is though. What do you recommend in my situation? A better web host? FPM is the way forward and it is superior to other process managers in every way. You asked if we worked on it. We did. FPM is that work. But really any process manager that launches a single master process and then spawns children from that will work fine with APC. And any process manager that doesn't do it that way is inherently broken. Rasmus: What's the matter with mod_fcgid so ? Isn't that what it actually does ? Just to have a small question at the side ... You've mentioned that php-fpm should work ... My Question: If I configure two fpm ... on different sockets ... The first fpm should be responsible for and the second one for ... I assume that if has 4 workers all worker will have the same cache because they're controlled by the same manager. Will both manager have the same shared APC-cache or will there be a separate cache for each one? In my opinion it would be nice if they'd have separate one. This is untested and just a question how it is designed to be. @simonsimcity: sadly (or luckily for some people here), the way php-fpm works makes all the processes share the same cache, since apc is loaded into the main process that is forked to spawn children. This is a problem for me, since I am looking into offering shared hosting through php-fpm, and this behaviour causes insecurities (and doesn't allow a single user to have TOTAL_MEMORY/NUMBER_OF_USERS memory available, so racing happens). I am working to fix the insecurities, but the racing would still happen unless the module would be heavily rewritten. I am looking into it, but anyway it is likely the new code would not be disclosed (but the way to do it will). Since the thread is somewhat old, please let me know if you already have a solution about that! :) Sorry for posting the small question here (was too off-topic). I now wrote the question to the PHP Mailinglist:
https://bugs.php.net/bug.php?id=57825
CC-MAIN-2017-17
refinedweb
2,602
72.46
10-06-2010 08:13 AM I use the BB JDE 5.0 to build my app with the library. I simply add the .jar file to the project and reproduce the code segment of the provided sample. The app compile without error but I have two problems. 1- I noticed the fact that signature Tool Give me a not registered status with two lines of registration, related to signer name RIM. 2- In simulator the app never show up after loading it (with simulator load from the menu). Solved! Go to Solution. 10-06-2010 08:24 AM CBissonnette wrote: 2- In simulator the app never show up after loading it (with simulator load from the menu). You need to "install" the sdk cod on the simulator first - this can be done by installing the jad via the Browser OTA (that's what I did)... I uploaded the jad+cod on my webserver an requested that jad from the simulator browser... 10-06-2010 08:40 AM I don't have a webserver installed, can this be done in an other way? In the documentation, it is written to copy the .cod file into the folder simulator. This is what I did 10-06-2010 08:47 AM you can alternativly use the DesktopManager and connect the Sim via USA and load the ALX into the DesktopManager [for some reasons I had difficulties to do that last night at home - but I have to admit that was after a 13h workday] 10-06-2010 11:06 AM That's a good idea but did not work. I'll recreate my project from scratch, clean my simulators and redo everything step by step. There must be something missing? Any idea about my other question? Do you know why I can't sign the project? 10-06-2010 03:43 PM 10-06-2010 04:24 PM The library shouldn't need to be signed since the library cod's already are. Can you explain precisely how you added the library into the project? 10-06-2010 05:24 PM Hi, I first use the "How To - Compile a jar into a BlackBerry Library". It gives me a second project and I made my main project dependent of this one. It compile ok but I don't know if it is the desired way to go. I also just add the .jar file from the sdk to my main project and once again it compile without problem. Is it good? 10-06-2010 05:30 PM While this is normally correct the ad service has unique requirements so there is a different procedure. You need to add the jar to the build path so that the workspace can reference the library but not compile it. When you load the application, you must load the cod as well. There is a detailed explanation in the pdf documentation. Take a look, try it out and let me know if you have any trouble. Joe 10-08-2010 10:36 AM Probably I overlooked it, but I didn't find any explanations how to use BBAS with BB JDE (in the docs only Eclipse). Actually it is easy: - Copy the net_rim_bbapi_adv_appXXXXX.jar in the folder where your workspace is defined (where the <workspace_name>.jdw resides) - Open the workspace in BB JDE - Select the <workspace_name>.jdw, right mouse click - Properties - There is a list "Imported Jar files", click the Add button, select net_rim_bbapi_adv_appXXXXX.jar - Click OK and you are done To test if everything is ok, just write a single line in any class of your project import net.rim.blackberry.api.advertising.appXXXXX.Banner If there are no compilation errors you are ready to go
http://supportforums.blackberry.com/t5/BlackBerry-Advertising-Service/Linking-the-jar-with-BB-JDE/m-p/608364
CC-MAIN-2013-48
refinedweb
621
73.58
Difference between revisions of "Talk:Dm-crypt" Revision as of 07:23, 20 January 2014 Contents Cleanup and Clarification) Splitting sections into separate pages Does anyone else feel that 11,305 words is too long for a single article? I'd like to propose splitting this article across multiple pages. If MediaWiki's Subpages feature is enabled, this might be a good time to use it. The article contains many sections that are not greatly related to one another. For example, does one really need to know how to (section 6) encrypt a loopback filesystem or (section 3.2) use a keyfile in order to (section 3.3) encrypt a swap partition? It's common to encrypt a swap partition without using a keyfile or an encrypted loopback filesystem, so why are they discussed in the same article? I acknowledge that all the sections are related to LUKS, but many of them are not dependent on each other. Having many vaguely related topics makes the article difficult to follow and maintain. I propose Subpages because subpages can show their relationship to LUKS (and other sections, just as an example: /LUKS/Configuration/Keyfiles). In the absence of Subpages, placing a general overview of LUKS in the main article -- and links to pages on more specific topics -- would also be an improvement. Separating sections into (sub)pages would also keep talk pages attuned to a specific subject. I have some suggestions for improvement of individual sections as well, but I think separating sections would be a good first step. EscapedNull (talk) 14:26, 29 September 2013 (UTC) - Hi, the article is among the longest, splitting it into subpages could help not feeling overwhelmed by it, however a lot of care should be taken in doing it, that's why I think you've been very wise to start a discussion first. We've had a number of users working hard on it, in particular I'd like to point you to a recent discussion I had with User:Indigo, #Encrypting_a_LVM_setup_.28ex_section_8.29, on which we agreed on keeping Dm-crypt_with_LUKS#Encrypting_a_LVM_setup here instead of merging it to Encrypted LVM: moving it to a subpage would somehow conflict with that decision, so I'll try to invite Indigo to discuss here with us on what to do now. - Finally, just to answer your doubts, this wiki doesn't have the subpage feature enabled on the Main namespace, nonetheless subpages (i.e. article names with slashes) are already commonly used to keep series of related articles together, so that would indeed be the way to split this article. - -- Kynikos (talk) 02:54, 30 September 2013 (UTC) - After reading the discussion, I see what you mean. However, I don't think splitting up the article would interfere too much with the decision to keep a brief overview of LUKS and LVM in addition to the Encrypted LVM page. The setup I had in mind was roughly giving each top-level section its own page (but don't quote me on that). The overview and the Encrypted LVM page seem to overlap, and I don't see much benefit to maintaining both, although Kynokos and Indigo might not agree and that's fine. Personally I find the Encrypted LVM page easier to follow and I think it gives the reader a better understanding of the subject, which is why my own edits on the subject have gone there rather than this page. Case and point, I'd propose replacing the overview with Encrypted LVM (as a pseudo-subpage, or just a link), but maintaining the overview is also okay, and perhaps it would just get its own article or pseudo-subpage. The main point I was trying to make is that I think LUKS/dm-crypt is too broad a topic for a single article. And as you said, I'd also be interested in hearing what Indigo has to say about this. EscapedNull (talk) 17:24, 30 September 2013 (UTC) - Hi, thanks for sharing your ideas here. Getting rid of not required content would be a preferable way, if you ask me. Particularly by (a) streamlining to LUKS and vacuuming for clarity. Then (b) splitting content by moving out sections to new pages can help and be a way forward. Yet I don't see a reason why (a) cannot be done while possibilites for (b) are figured out. If you look at the sections you quote in your first post, you will notice 2/3 have short introductory paras and would work as a subpage or even separate pages. Quite a number of edits were made to that respect and continuing with it should make it easier to re-structure the article, if that is the outcome of the discussion. If not, it is still more readable this way. - I don't grasp what you have in mind with replacing the "overview" (?) with Encrypted_LVM. I would rather merge LUKS#LVM:_Logical_Volume_Manager (the "overview"?) to there and link it from here. If you are instead referring to LUKS#Encrypting_a_LVM_setup (and hence the talk quoted by Kynikos above) as the "overview", it would be a great contribution to merge it into Encrypted_LVM. I am sure Kynikos will agree - he proposed to do that originally. In case you would like to approach the merge, please go forward with it. I'll make sure LUKS#Encrypting_a_system_partition regains the cross-linked content. - Back to your original topic: - For (a) maybe you want to re-consider to join in for editing in the suggestions you have in mind first. - For (b) another point that should be addressed along is how the new pages (plain dm-crypt and encrypted LVM) could benefit at the same time. If you ask me now, separating common content would be a preferable approach to using a subpage structure (e.g. like the multipage BG). Perhaps you can detail options you see for (b). How would you re-structure the top sections on this page? Which sections would you fork out from LUKS, ideally with perspective to the other encryption pages? --Indigo (talk) 05:03, 1 October 2013 (UTC) - By "overview" I was talking about section 7 "Encrypting an LVM setup." I didn't even notice that LVM was discussed twice (a testament to disorganization of the page as it is now). I see what you mean about the disadvantages of subpages. I mentioned subpages because, for example, an LVM can be encrypted using almost any block level encryption, and one could argue that setups using different underlying technologies should be separate pages (e.g. LUKS/Encrypted_LVM, Plain_dm-crypt/Encrypted_LVM, and cryptoloop/Encrypted_LVM) as the information is likely to be different (but this could lead to duplicated information, too). It was only an idea, and perhaps something like Category:Disk_Encryption would be more appropriate. After all, subpages are disabled for a reason. - I thought it would be a good idea to split the article first and edit second because it would be easier to focus on a single topic, and because it could save us from editing information twice in case it conflicts with the new structure. But if you think it would be best to edit first and restructure later, I'm fine with that I guess. Kynikos, do you have a preference? EscapedNull (talk) 13:44, 1 October 2013 (UTC) - My suggestion was that editing section content can be done in a way so that forking one out does not require major double edits. Meanwhile we gained another section LUKS#Encrypting_the_home_partition. With that it becomes easier to get rid of LUKS#Encrypting_a_LVM_setup here by finalizing Encrypted_LVM and double checking nothing is lost. Apart from that, anyone has a suggestion which section may be a first worthwhile candidate for a separate page? --Indigo (talk) 21:54, 1 November 2013 (UTC) - I'm sorry for losing sight of this discussion... I think managing to finalize the merge to Encrypted LVM would be a great way of starting to split this article. Then maybe Dm-crypt with LUKS#Specialties and I'd say also Dm-crypt with LUKS#Backup the cryptheader could be moved to a Dm-crypt with LUKS/Specialties article. Then... well, without those sections around it will be a little easier to understand the next steps I hope. -- Kynikos (talk) 04:36, 2 November 2013 (UTC) - Hm, since you mention subpages again: the reason I am unsure about them, as described above, is that I find them confusing to browse. The example I keep having in mind is the multipage BG guide. Reading that I have to scroll down to the page end in order to see links to subsequent subpages (e.g. Beginners'_Guide/Post-installation). If the master page had a TOC including sections of the subpages, that would be more transparent. But the TOC always starts with 1 per page and makes no reference back or forth. A reader not knowing the content will only find the subpages by coincidence, if at all. - Now, while writing the reply, I had the idea to leave in the section heading, but move the content to a subpage. This way the main LUKS article keeps at least a reference in the TOC and links out content not necessary for all readers. I just created two subpages to see and show how it works out: - 1. Dm-crypt_with_LUKS#Backup_the_cryptheader now leading to Dm-crypt_with_LUKS/Backup_the_cryptheader - 2. Dm-crypt_with_LUKS#Encrypting_a_loopback_filesystem now leading to Dm-crypt_with_LUKS/Encrypting_a_loopback_filesystem - (Feel free to revert the edits I did to test it out for 1 and 2. I thought it's important to see in context). - I would not want to do that with a section like Dm-crypt_with_LUKS#Specialties because that contains only short subsections (hence the main TOC would loose the references to them). But another candidate is surely Dm-crypt_with_LUKS#Using_Cryptsetup_with_a_Keyfile and of course the remaining LVM bits (until Encrypted LVM is complete). - Thoughts? --Indigo (talk) 20:26, 10 November 2013 (UTC) - Honestly I wasn't thinking of creating many subpages with just little content in each, my "idea" (not very clear yet) was to end up having just a bunch of big subpages (e.g. Dm-crypt with LUKS/Initial Setup, Dm-crypt with LUKS/Configuring LUKS, Dm-crypt with LUKS/Specialties...) and use Dm-crypt with LUKS as just a very short overview page, using a format similar to General Recommendations, with a section for each subpage that links there and briefly introduces its content, preferably with inline links to its various sections. - Quoting your last post, "A reader not knowing the content will only find the subpages by coincidence, if at all", I think this system would avoid that problem, both because of the little introductions with links, and because the shortness of the article would make the reader curious to open all the subpages to see what they talk about, none of them being seen as a subpage more important than the others. - I hope I've been able to express the idea clearly enough ^^' -- Kynikos (talk) 10:36, 11 November 2013 (UTC) - You develop it further and I see what you mean, yes. Yet the General Recommendations serve a totally different purpose. That article gives a guide across a wide variety of system setup topics. The LUKS page focusses on one kernel toolset and the various specialities for it (which is why I prefer a complete TOC as a reader totally). Nonetheless, I like your idea and (quickly - not attempting to change content but to show the case) tried to mod the test case 2 above accordingly: [1]. Now that results in us keeping the TOC of the main page complete but still forks the section out: Dm-crypt_with_LUKS#Encrypting_a_loopback_filesystem. Is this more something you would anticipate? - --Indigo (talk) 19:29, 11 November 2013 (UTC) - I will try to put my ideas together in User:Kynikos/Dm-crypt with LUKS first. -- Kynikos (talk) 08:51, 13 November 2013 (UTC) - Ok, a very rough draft is ready in: - How do you like it? If you agree with the general idea, I will apply it to the real article, but then would you be willing to help me finishing the job? Especially I'd like to still take some generic content off User:Kynikos/Dm-crypt with LUKS/Examples, filling Dm-crypt with LUKS#System configuration. -- Kynikos (talk) 11:04, 13 November 2013 (UTC) - Ah, of course we should also take care of updating all the reciprocal links among the sub-articles (all those containing a #Fragment). -- Kynikos (talk) 11:07, 13 November 2013 (UTC) - Kynikos, thank you for your time to set it out so clearly! - I still prefer the single page format myself really, but the point is more how other readers not familiar with the topic can cope with it in KISS style. (unfortunately just few raised opinions). All in all I agree now that this can be a good way forward to re-structure the article. I guess I could just not picture it earlier. Anyhow, it will be a pleasure to help you with it. I have left comments and questions in User_talk:Kynikos/Dm-crypt_with_LUKS. - --Indigo (talk) 22:27, 17 November 2013 (UTC) - Just to make it as clear as possible, User:Kynikos/Dm-crypt with LUKS has "moved" to Dm-crypt with LUKS/draftand User talk:Kynikos/Dm-crypt with LUKS has moved to Talk:Dm-crypt with LUKS/draft. -- Kynikos (talk) 14:00, 18 November 2013 (UTC) - The new links are Dm-crypt and Talk:Dm-crypt. -- Kynikos (talk) 04:18, 1 December 2013 (UTC) - So what have we decided, exactly? I see there's now a Dm-crypt page with subpages. Is that where sections from this page are going to be moved? What about the merge from section 7 to Encrypted LVM that User:Kynikos mentioned? Is that still happening, or are we going to make a Dm-crypt/Encrypted LVM subpage instead and merge Encrypted LVM into it? I'm willing to help, but I'm not sure as to what I should be doing. - Have a look at Talk:Dm-crypt#New_idea for your questions and the new plan, and then the Dm-crypt subpages. There's plenty of stuff to do to implement it to plan. If you are unsure how to help, look for the 'accuracy' and 'expansion' tags for example. Would be great, if you want to join in. --Indigo (talk) 19:35, 6 December 2013 (UTC) - I'd only like to add that Encrypted LVM is already merged into the new dm-crypt/Encrypting an Entire System, it's only a matter of properly moving duplicated content to the other subpages of dm-crypt. Of course any help is really welcome, as there's still a lot to do! -- Kynikos (talk) 02:50, 7 December 2013 (UTC) New idea The philosophy behind the current old structure was to try to generalize the various steps for encrypting an entire system or a device and managing it, however we've noticed it's kind of hard. A new idea for reducing duplication of content while maintaining, if not improving, readability, would be to rename the "/Examples" subpage to "/Common Scenarios" and move it to first place in Dm-crypt with LUKS/draft, so it's used use the dm-crypt#Common scenarios section as the starting point by the readers. It should contain the most common uses for encryption, which IMO are: - dm-crypt/Encrypting a Non-Root File System - partition - loopback - dm-crypt/Encrypting an Entire System - plain dm-crypt (merge Plain dm-crypt without LUKS, done) - dm-crypt + LUKS (no LVM) - LVM on LUKS (merge Encrypted LVM, done) - LUKS on LVM (merge Encrypted LVM, done) - (I think it would be really cool if we could also include an example with software RAID) Each of those scenarios should be mostly a stripped sequence of commands with short descriptions that should link to generic sections in the other subpages of Dm-crypt with LUKS dm-crypt, pointing out all the particular suggested adaptations that apply to that particular scenario. The idea is quite clear in my mind, I hope I've managed to explain it well enough, I'll try to put it into practice and see if it raises major problems. -- Kynikos (talk) 03:08, 23 November 2013 (UTC) EDIT: since Plain dm-crypt without LUKS would be merged here, the main article should be just renamed to dm-crypt. -- Kynikos (talk) 03:09, 23 November 2013 (UTC) EDIT: updated for current structure. -- Kynikos (talk) 04:31, 8 December 2013 (UTC) Scenario structure - Plenty of stuff to do, yet: Taking for granted we want an additional example with RAID sometime, it might be worth considering to split dm-crypt/Encrypting an Entire System into a subpage for (e.g.) dm-crypt/Encrypting a single disk system and dm-crypt/Encrypting a system across multiple disks scenarios. The latter covering "LUKS on LVM" and said RAID. Main reason: page length. If you agree, let's better do it now. --Indigo (talk) 12:11, 8 December 2013 (UTC) - Not a bad idea at all! However IMHO the proposed titles are a bit misleading: I would go for dm-crypt/Encrypting a System on Physical Devices and dm-crypt/Encrypting a System on Virtual Devices, in fact you can use multiple physical disks in every case if you want. -- Kynikos (talk) 03:48, 9 December 2013 (UTC) - EDIT: Note that the history of dm-crypt/Encrypting an Entire System should be preserved by moving it to one of the two titles, and then (or before) splitting the other page. -- Kynikos (talk) 03:49, 9 December 2013 (UTC) - +1 to your edit, I learned that from watching. The one letdown of this whole fun exercise is that the wiki engine does not seem to support basic content splits and joins preserving history. Anyhow, we might as well just keep it in mind and consider splitting it later (when there is something about RAID). Funnily, I find the use of "physical" (all blockdevices are on one) and "virtual" (suggests a qcow device) as differentiator not totally clear too. Let's meditate over it again until someone has another snappy idea. --Indigo (talk) 23:16, 9 December 2013 (UTC) Scenario intros I want to bring up another contexual point: You put in 'expansion' tags at the beginning of each section of the scenario page to "Compare to the other scenarios with advantages/disadvantages.". If I understand those tags correctly, you have Dm-crypt/Encrypting_an_Entire_System#Plain_dm-crypt in mind as an example. Yes, we want a common structured intro for each scenario, but I'd like it better to be just shortly descriptive regarding the scenario content. For example a para introducing the setup, followed by an ascii chart of the disk layout used (as per Dm-crypt/Encrypting_an_Entire_System#Preparing_the_logical_volumes example), followed by another sentence or two max. Remember the core of your scenario idea was to cut verbose in the scenario down as much as possible. A small comparison of the section scenarios may be suitable as the first subpage intro itself, anything more better be linked (pros/cons of disk layouts in Dm-crypt/Drive_Preparation#Partitioning, scenario specific pros/cons of encryption modes in Dm-crypt/Device_Encryption#Encryption_options_with_dm-crypt, general ones should be in: Disk_encryption#Comparison_table anyway, ..). --Indigo (talk) 23:16, 9 December 2013 (UTC) - I added intros on Dm-crypt/Encrypting_an_Entire_System and Dm-crypt/Encrypting_a_non-root_file_system. Is that similar to what you were going for? I really want to emphasize the importance of keeping these introductions concise. It's easy to write about use case after use case, but let's not forget why we refactored Dm-crypt with LUKS in the first place. Even Dm-crypt/Encrypting_an_Entire_System has gotten rather long and disorganized already, but that's a discussion for its own talk page. Dm-crypt has a nice layout so far, and it is definitely more readable than Dm-crypt with LUKS. --User:EscapedNull - @Indigo: I approve 100% what you said: a single, small comparison section is what we need! - @EscapedNull (please remember to sign your edits in talk pages, use ~~~~): I think you're referring to this edit on the dm-crypt page; honestly those intros, despite being very clear and well written, are indeed too long for that page, as you note yourself: the intended size of those intros was like the ones in Dm-crypt#Swap device encryption or Dm-crypt#Specialties, they should just sum up very briefly what's contained in each subpage. I wouldn't like to just throw your work away, I'd rather move it to a more suitable place in some of the existing subpages, what do you reckon? - Dm-crypt/Encrypting_an_Entire_System is still (not "already") "long and disorganized", if you read the discussions above you'll see that it's the result of merging some pre-existing articles, and our goal is indeed slimming it down by moving duplicated content to the other subpages. - -- Kynikos (talk) 15:13, 10 December 2013 (UTC) - Maybe they are a little too long for an introduction, but in comparison to what we were dealing with before, I'd say they're pretty succinct. I wrote them with the goal of educating the reader about the different scenarios enough to make a decision, but no more than that. If you'd like to strip them down further, however, I'm completely okay with that. - Re: Dm-crypt/Encrypting_an_Entire_System: You're right. Still long and disorganized is more accurate. I think there are some improvements still to be made (i.e. splitting sections into subpages even further), but I wasn't trying to criticize anyone's decisions about the merge. - About the scenario comparison: that's more or less what I was trying to accomplish with the introductions. Are you just suggesting that we follow the "advantages and disadvantages" bulleted lists format for all scenarios on Dm-crypt, or did you have different semantics in mind? Additionally, User:Indigo mentions adding a paragraph introducing the setup, and an ascii chart of the disk layout. I'd be strongly opposed to including any how-to or step-by-step information on the main Dm-crypt page. That's what the subpages are there for. The main page should serve to inform the reader about what options are available and what strengths and weaknesses each one has, not about the execution of those options. Besides that, I do feel that comparing and contrasting scenarios is highly beneficial, I'm just uncertain as to whether the introductions I wrote are what you had intended. - (Yes, I have been forgetting to sign my edits. That really should be automatic.) EscapedNull (talk) 20:39, 10 December 2013 (UTC) - Uh now I see where the confusion comes from: Indigo and I were discussing about Dm-crypt/Encrypting_an_Entire_System, but instead you understood we were talking about dm-crypt#Common scenarios, and that's why you've put the intros there :) Note the difference between "subpage", "section" and "subsection": subpages have a "/" in the article title, while sections and subsections are indicated by the link fragment ("#"). - >>EscapedNull: "The main page should serve to inform the reader about what options are available and what strengths and weaknesses each one has" - We have to be even stricter than that on the main page (dm-crypt): it should only "serve to inform the reader about what options are available"; the "what strengths and weaknesses each one has" part should be described in the subpage. - >>Indigo: "A small comparison of the section scenarios may be suitable as the first subpage intro itself" - He means that a unified comparison section should be put at the top of Dm-crypt/Encrypting_an_Entire_System instead of having comparisons at the start of each section of Dm-crypt/Encrypting_an_Entire_System, and that's what I agreed with. - -- Kynikos (talk) 05:48, 11 December 2013 (UTC) - Oops. We were talking about different things I guess. Since you moved the intros to the subpages, I see that does make a lot more sense now. I understand the difference between subpages and sections/subsections, but I guess I didn't read the discussion closely enough. - In addition, when User:Indigo said "comparison" I thought he or she meant Encrypting an Entire System versus Encrypting a Non-root Partition. You're saying the suggestion was to compare LUKS on LVM versus LVM on LUKS versus Plain dm-crypt without LUKS? EscapedNull (talk) 15:25, 11 December 2013 (UTC) - Yes, that was the suggestion he had. Just a small comparison comparing the scenarios (read: examples to employ dm-crypt for specific (not generic) setups) on that page, as Kynikos writes. Great you joined in. Let me add to your above discussion: In September we worked a bit on Disk_encryption to finalise it as the entry point comparing methods. References you wrote in [2] to ecryptfs et al are discussed there. If you feel you can add to it - cool, but generic encryption comparison and references leading away from the dm-crypt subpages are meant to belong there. --Indigo (talk) 21:13, 11 December 2013 (UTC) - +1 for merging those intros to Disk Encryption, e.g. Disk_Encryption#Data_encryption_vs_system_encryption deals with the same subject. -- Kynikos (talk) 08:48, 12 December 2013 (UTC)
https://wiki.archlinux.org/index.php?title=Talk:Dm-crypt&diff=293686&oldid=277159
CC-MAIN-2017-13
refinedweb
4,228
58.62
import "go.chromium.org/luci/server/caching/cachingtest" Package cachingtest contains helpers for testing code that uses caching package. WithGlobalCache installs given BlobCaches as "global" in the context. 'caches' is a map from a namespace to BlobCache instance. If some other namespace is requested, the corresponding caching.GlobalCache call will panic. type BlobCache struct { LRU *lru.Cache // underlying LRU cache, create it with lru.New(capacity). Err error // if non-nil, will be returned by Get and Set } BlobCache implements caching.BlobCache on top of lru.Cache for testing. Useful for mocking caching.GlobalCache in tests. See also WithGlobalCache below. Get returns a cached item or ErrCacheMiss if it's not in the cache. Set unconditionally overwrites an item in the cache. Package cachingtest imports 5 packages (graph). Updated 2019-10-14. Refresh now. Tools for package owners.
https://godoc.org/go.chromium.org/luci/server/caching/cachingtest
CC-MAIN-2019-43
refinedweb
138
55.81
A crucial benefit of using the logging module is the ability to format log messages. This allows us to include helpful information with each logged message, including: - timestamps - the module name - the line number - and much more. If no custom formatting is specified, Python uses the default formatting for all log messages: %(levelname)s:%(name)s:%(message)s %(levelname)sis a string that represents the log level name %(name)srepresents the string of the name of the logger %(message)sis the logged message string. A colon separates each of these strings. Let’s examine the default formatting on a logged message. import logging import sys logger = logging.getLogger(__name__) stream_handler = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) logger.warning("This is a warning!") produces the following log message output: WARNING:script:This is a warning! Imagine that we want to include a timestamp and line number in our log. We can create a custom formatter object using the logging module’s Formatter class, which accepts the formatted string as the first input value. We can do the following to add in our timestamp and line number formatting: formatter = logging.Formatter("[%(asctime)s] %(levelname)s:%(name)s:%(lineno)d:%(message)s") To set this formatter object to our logger, we use the setFormatter(fmt) method where the fmt parameter is the Formatter object. Our revised code will resemble this: import logging logger = logging.getLogger(__name__) stream_handler = logging.StreamHandler(sys.stdout) formatter = logging.Formatter("[%(asctime)s] %(levelname)s:%(name)s:%(lineno)d:%(message)s") stream_handler.setFormatter(formatter) logger.addHandler(stream_handler) logger.warning("This is a warning!") which will now produce the following log message output: [2021-11-04 02:58:51,847] WARNING:script:This is a warning! The setFormatter method will work on several different types of handler classes, including StreamHandler as seen above and FileHandler. This means that we can set other formatting options for various handlers. For example, if we choose to log to both console and a file, we can have different formatting for the log messages for each one by applying two separate Formatter objects to each handler. This can be useful if we need to, for example, log DEBUG messages to console with more information in each log message than what we need in our written log file. You can find more information about formatting options can in the Python documentation here. Instructions In script.py, we have preloaded a FileHandler object called file_handler. Format the object to match the following: [%(asctime)s] {%(levelname)s} %(name)s: #%(lineno)d - %(message)s To do this, create a Formatter object called formatter1. Then set the format of file_handler to the formatter1 object. Run the program by typing python3 script.py in the terminal and clicking Enter. Click Check Work once the program is complete. In script.py, we have preloaded a StreamHandler object called stream_handler. Format the object to match the following: [%(asctime)s] {%(levelname)s} - %(message)s To do this, create a Formatter object called formatter2. Then set the format of stream_handler to the formatter2 object. Run the program by typing python3 script.py in the terminal and clicking Enter. Click Check Work once the program is complete. Uncomment the following last three lines of script.py: #result = division() #if result == None: # logger.warning("The result value is None!") Run the program by typing python3 script.py in the terminal and clicking Enter. View and verify that the formatted.log file has differently formatted log messages than the console log messages. Once you have done this, click Check Work to move onto the next exercise.
https://www.codecademy.com/courses/seds-software-engineering-in-python-i/lessons/python-logging/exercises/formatting-the-logs
CC-MAIN-2022-40
refinedweb
598
51.24
Hi, i have a problem with scan. I was going to create a namepspace backup, so i used command: “asbackup --node-list xxxxxxx:3000 --namespace ppchelp --directory /backups/aerospike” After scan started, i pushed “Cntrl-z” cause i thought that scan have already run. But when some minutes later i decided to stop scan using command “asinfo -v ‘scan-abort-all:’” and start new dump process, i have seen this: The top line it is the first dump process i’ve run. I used commands "asinfo -v ‘jobs:module=scan;cmd=kill-job;trid=’ " and “asinfo -v ‘scan-abort:id=’”, but it is still have status ACTIVE. For example, i run the second dump process and successfully stopped it. Now when i try to start dump process it gets status “active(ok)”, but in fact process speed = 0. I also tried to change new scan process priority to 5, but nothing have changed. How can i remove scan and start dump? Thanks!
https://discuss.aerospike.com/t/scan-doenst-stop/3782
CC-MAIN-2018-30
refinedweb
162
69.82
django-shawty 0.0.3 Shawty URL shortener server integration for Django.django\_shawty ============= This is an implementation in Django for Shawty webserver integration. This is a very simple Django app that adds a single new model that can work with the Shawty Webserver called ShawtyURL. This model contains classmethods that allow you to communicate with Shawty and store/retrieve short URLs. ## PREREQS django\_shawty requires the following packages to be installed: [South] [Requests] ## INSTALLING You can install django\_shawty simply by running a "pip install django-shawty" and adding 'shawty' to your INSTALLED\_APPS. Then you can run the south migrations to initialize the models in your database. ## CONFIG django\_shawty has a set of configurations that you can use to define how to interact with the Shawty webserver. SHAWTY\_REQUEST\_URL (string)- The URL of the Shawty server in the form of SHAWTY\_USE\_DB (bool) - Determine whether or not django\_shawty should store the shoretened URLs in the DB SHAWTY\_USE\_CACHING (bool) - Determine whether or not django\_shawty should store/retreive short urls from a cache backend SHAWTY\_CACHE\_EXPIRE (int) - The time (in seconds) after which the cache for the URL should expire ## Example To get a new short URL for a set of links, simply invoke the ShawtyURL classmethod "get\_short\_urls" passing a python list of links. For example: from shawty.models import ShawtyURL links = [link1, link2, link3] shortenedlinks = ShawtyURL.get\_short\_urls(links) print shortened\_links > {link1:shortlink1, link2:shortlink2, link3:shortlink3} - Downloads (All Versions): - 0 downloads in the last day - 37 downloads in the last week - 239 downloads in the last month - Author: John Nadratowski - Categories - Package Index Owner: John.Nadratowski - DOAP record: django-shawty-0.0.3.xml
https://pypi.python.org/pypi/django-shawty/0.0.3
CC-MAIN-2015-35
refinedweb
288
50.36
Types. Void type functions do not return any values. Function with no arguments and no return value: void function_name(); Think of this as a self-contained block of reusable code that does not need any data from the outside or have to return any data back to its caller. Functions that print values are good candidates for this type of function. Sometimes you have a list of data you want to print to the console and you keep copy and pasting it or retyping it over and over again in different places. This practice is error prone and unprofessional. Consider the following example. void main() { int x = 10; int y = 5; printf("value of x: %d", x); printf("value of y: %d", y); printf("n"); x += y; printf("value of x: %d", x); printf("value of y: %d", y); y++; printf("value of x: %d", x); printf("value of y: %d", y); } The quality of this program would greatly be improved by moving the print statements into a function. printxy1.c: Now instead of retyping the same three lines over and over, you simply make a call to the function to perform the exact same task in a more readable and maintainable manner. Here is the output. Function with arguments and no return value: void function_name(int var); Did you notice in the last example that we had to move the x and y variables to the global scope in order to use this function type. This should be avoided whenever possible. Global variables are considered bad practice, but in reality there are times (especially in embedded systems development) where you just have to give in. In our case we can fix it by using a function that takes arguments and does not have to return a value to its caller. Let us change our function declaration from the last example to this: void printxy(int val1, int val2); This function declaration has a parameter list which is just a comma-separated list of variables that will be used within the function that the caller can assign values when the function is called. Here is a good place to introduce the idea of function signatures. A signature is just a function declaration or prototype, but it is called as such because no two functions may have the same signature or the compiler will not be able to resolve the call to a function. The signature is made up of the data type, function name, and the parameter list. Let us fix our program so that it does not need to rely on global variables. Changes are in bold. printxy2.c: #include <stdio.h></stdio.h> //Function for printing variable's values. 2 arguments, no return value. void printxy(int x, int y); void main() { int x, y; x = 10; y = 5; printxy(x, y); x += y; printxy(x, y); y++; printxy(x, y); } void printxy(int x, int y) { printf("value of x: %d, ", x); printf("value of y: %d", y); printf("n"); } All we did was change the signature of our printxy function so it now takes two arguments and prints those values. Main is the caller, and passes the new function the values it currently has for x and y when it makes the call. Now we do not need to use global variables to access x and y, we can just pass local variables as arguments. Here is the output. Functions with no arguments and a return value: <data type></data> function_name(); A function of this form takes no arguments, but does return a value of some variable local to the function back to its caller. The data type refers to what kind of data is returned by the function on exiting. Sometimes global flags are used in a program to indicate the current state of something, this is very common in embedded systems applications or system level programming. That is one thing you might use this type of function for. Instead of inventing some useless function, let us use the standard C function from the stdio.h library as an example. This is the prototype for the getchar function: int getchar(); This function returns a character input from standard input as an integer. Although you would most likely set a char variable with this function. char character = getchar(); That would set character to the value returned by getchar once it finished executing. Function with arguments and a return value: <data type></data> function_name(<data type></data> arg1, <data type></data> arg2, ...); This type allows you to use a variable from an external source within the scope of the function, and you can return data back to the caller. Main is actually a function of this type, we just have not been passing it arguments or using it is return values for anything. It is not necessary to use or catch a function’s return value but you can if you want to. Usually main takes the following form: int main(int argc, char *argv[]); For now, ignore the odd looking second parameter, its explanation is reserved for the pointers topic. This form of main is very useful because it allows your program to receive command-line arguments and return data. Unix, DOS, and Linux programmers know about this if they ever use terminal commands or write bash scripts that rely on the output of a command. Let us modify our printxy example to show the name of the program before it runs and a message telling when it is finished. Ignore the fact that the argv argument is a pointer to an array of chars for now and focus on the fact that we are able to use the values passed through these function arguments. Below is the latest source code for our printxy example. Changes are in bold. printxy3.c: #include <stdio.h></stdio.h> #include <stdlib.h></stdlib.h> //Function for printing variable's values. 2 arguments, no return value. void printxy(int x, int y); int main(int argc, char *argv[]) { int x, y; x = 10; y = 5; printf("%s is runningn", argv[0]); printxy(x, y); x += y; printxy(x, y); y++; printxy(x, y); printf("%s is finishedn", argv[0]); return 0; } void printxy(int x, int y) { printf("value of x: %d, ", x); printf("value of y: %d", y); printf("n"); } The function main takes two arguments, argc and argv, we use the value in argv to print the name of the program and a message about the state of the program. Main returns 0 to indicate that it completed successfully. You may be wondering where the program name was passed to main from. It is passed automatically by the command line as the first element in the argv array. In case you were wondering, argc is the number of arguments passed by the command-line when the program is launched from the terminal. Here is what the output of printxy3 should look like.
http://www.exforsys.com/tutorials/c-language/c-functions-part-2.html
CC-MAIN-2019-13
refinedweb
1,164
68.3
Sending ctrl+C break signal in the terminal? - altoidnerd Is it possible to send Ctrl + C ( SIGINT ) to break in the shell? That is something I use quite often, in any python shell. There are many use cases. Tapping the stop ( [x]) button effectively does the same. - altoidnerd To break execution during runtime, it behaves the same. But there are other cases (due to the syntax of python-language its not unique to pythonista and is shared by ALL shells). When in the shell, you enter functions and control sequences line by line - so you commit lines before execution. If you make an error, you need to break from that commitment to an indent-level to get your shell back (during this time, the button isn't available to do this, but that would be a good fix). example: this happens to me fairly often def do_something(x): ..if x not in [elm for elm in os.listdir('.').startswith('.')]: ....> # oh shoot. I meant to use os.environ not listdir ........> it thinks im still going. now I need to escape ....> just mashing buttons now ....>(*opovdv ......>;powef;l. ...> To be fair pythonista handles this better than ipython or cpython. cpython's shell is awful, and ipythons is great but has this syndrome really bad when it comes to functions... you'd have to use it to understand ... If you're not in a triple-quoted string, typing ;;is guaranteed to produce a syntax error, which breaks you out of the current "chunk". But yes, it would be great if you could use the [X]button to do that. (I think in Pythonista 1.4 that was possible and the feature was somehow lost in 1.5.)
https://forum.omz-software.com/topic/2661/sending-ctrl-c-break-signal-in-the-terminal
CC-MAIN-2021-39
refinedweb
284
84.98
There is a question of how to parse HTML pages on Python or rather here is a link to the page: // 3dtoday.ru/3D-Models?page=1 . It is necessary to poore this piece of code: & lt; div class = "threedmodels_models_list__elem__title" & gt; & lt; a href = " title = "" & gt; Coffee makers horn filter holder. & lt; / a & gt; & lt; / div & gt; I do not understand how to spar tag text & lt; A & GT; ? Answer 1 You needed to use Requests and BS4 import requests From BS4 Import Beautifulsoup R = Requests.get (' Soup = Beautifulsoup (R.Text, 'HTML.PARSER') Element = Soup.find_all ('Div', class _ = 'threedmodels_models_list__elem__str') Elem_Soup = Beautifulsoup (STR (Element [1]), 'HTML.PARSER') title = elem_soup.find_all ('A') [2] .text Print (Title) output: Coffee maker horn filter holder. Reply to the comment to get headlines 18 elements, you need to add a cycle for index in range (18): elem_soup = Beautifulsoup (Element [Index]), 'HTML.PARSER') title = elem_soup.find_all ('A') [2] .text Print (Title) Answer 2 Popular Library for XML and HTML Parsing. Discern about a similar question.
https://computicket.co.za/html-how-to-pass-html-tags-on-python/
CC-MAIN-2022-21
refinedweb
169
60.92
General Purpose Histogram. More... #include <vbl/vbl_ref_count.h> #include <vbl/vbl_smart_ptr.h> #include <vul/vul_timestamp.h> Go to the source code of this file. General Purpose Histogram. This histogram is mainly a port from the old histogram class in TargetJr which resided in GeneralUtility/Basics. In this initial version, not all the functionality is ported but it is intended to be useful. It is placed in vsrl right now because it is not determined yet where it should permanently live. Modifications 2003/04/14 Initial Version 2003/06/02 MPP Moved to vifa, since it's the only user for now... Definition in file vifa_histogram.h. Definition at line 120 of file vifa_histogram.h.
http://public.kitware.com/vxl/doc/release/contrib/gel/vifa/html/vifa__histogram_8h.html
crawl-003
refinedweb
114
53.78
The first time I saw the abbreviation BDD I thought it was a miss-print of TDD (Test Driven Development), but it’s not. It stands for Behaviour Driven Development and it is a technique derived from TDD. The difference between the two is a bit nuanced and best felt when you start using some BDD tools. One such tool is PHPSpec. It will help you write better code and have fun in the process. Sounds good? Let’s give it a try! There is a dog Dogs are fun so let's build a Dog game: In PHPSpec you start by creating the specification first. It will describe the Dog class we are going to build: PHPSpec generates the specification file for us: <?php namespace spec\App; use App\Dog; use PhpSpec\ObjectBehavior; use Prophecy\Argument; class DogSpec extends ObjectBehavior { function it_is_initializable() { $this->shouldHaveType(Dog::class); } } It doesn't say (describe) much at the moment - just that the class Dog should be initializable. Let's run PHPSPec to see what happens. Whoa, that's a lot of pink! What's up with that? Well, this is how PHPSPec indicates that the code is broken (doesn't even run), which is different than it running but returning wrong results. It is also asking us to fix it by creating the missing Dog class for us. So we comply and we get this: <?php namespace App; class Dog { } After creating the Dog class, it runs again and now we have our first spec passing giving us that green light all devs love so much. Dogs make sounds As all dog owners will tell you, dogs bark, so let's add this behavior to our doggo: We describe the desired behaviour in the spec class: <?php # spec/App class DogSpec extends ObjectBehavior { // ... function it_should_make_a_sound() { $this->makeSound()->shouldBe('Vuf Vuf'); } } I know. This looks a bit wired. We are calling the makeSound method but there is no such method in our spec class. And there won't be. The $this keyword in a spec class doesn't refer to the spec class itself, but to the class the spec is describing. In this case, DogSpec described the Dog class, so PHPSpec will try to call the makeSound method on the Dog class. (There is always one spec class per class). Another wired thing is the shouldBe method chained to the makeSound method. This is what is called a matcher in PHPSpec and it's equivalent to PHPUnit's assertions (and there's a bunch of them). In this case, it will take the output of the makeSound method and check if it matches Vuf Vuf. Now that we've straightened that out, we can run PHPSpec again: Since we don't have the makeSound() method on our Dog class yet, there's that purple color again and there's PHPSpec again being nice and helpful offering to create the method for us. After creating the method it runs again and now we finally have some red color meaning the code works but not as expected. Time to write some code and get us back to green! <?php # src/App class Dog { public function makeSound(): string { return 'Vuf Vuf'; } } Stubs Our object often time collaborate with other objects by asking them questions (and doing something with the answer). If we go back to our pet game, dogs are usually very happy to great people: To describe this in our specification we'll need a stub: <?php # spec/App class DogSpec extends ObjectBehavior { // ... function it_can_greet_a_person(Person $person) { $person->name()->willReturn('Mike'); $this->greet($person)->shouldBe('Hello Mike, Vuf Vuf'); } } Looking at this, you may be wondering where is some createTestDouble() method call? In PHPSpec you just inject classes/objects you need and PHPSpec will create test doubles out of them (using prophecy framework) so you can immediately configure them. Here, we are stating the person's class name() method will return Mike when called. By now you can assume when we run PHPSpec it will offer to create the actual Person class for us, right? But wait. It says "Would you like me to generate an interface". Why not a class? Hm, now that I think about it, dogs also like to greet other dogs not just humans, so maybe there is an abstraction here that we missed. Let's introduce an interface called Named and make our Dog class is dependent on an interface instead of a concrete class. <?php # spec/App class DogSpec extends ObjectBehavior { // ... function it_can_greet_a_person(Named $named) { $named->name()->willReturn('Mike'); $this->greet($named)->shouldBe('Hello Mike, Vuf Vuf'); } } Now our Dog can greet any class that implements the Named interface. This design will make it easy to expand the list of earthlings our doggos can greet - just implement the Named interface. Thnx PHPSpec! We can let PHPSpec make that interface and the greet method for us now And now we can implement our greet method to get us back to green again: <?php # src/App class Dog { public function makeSound() { return 'Vuf Vuf'; } public function greet(Named $named) { return 'Hello ' . $named->name() . 'Vuf Vuf'; } } Mocks and Spies Let's say for business reason, every time a Dog greets someone we want to our application to log that information. In this case, our object is going to issue commands to other objects, so we need a mock or spy. First, we are going to state that Dog will be constructed with a Logger: <?php # spec/App class DogSpec extends ObjectBehavior { function let(Logger $logger) { $this->beConstructedWith($logger); } } Now we can describe the interaction with a Logger: <?php # spec/App class DogSpec extends ObjectBehavior { /// ... function it_logs_the_greeting(Named $named, Logger $logger) { $named->name()->willReturn('Marry'); $logger->log('Hello Marry, Vuf Vuf')->shouldBeCalled(); $this->greet($named); } } We are setting an expectation that the log method will be called with Hello Mike, Vuf Vuf once we execute our code. This is a mock. If we wish to use a spy we would describe it as: <?php # spec/App class DogSpec extends ObjectBehavior { /// ... function it_logs_the_greeting(Named $named, Logger $logger) { $named->name()->willReturn('Mike'); $this->greet($named); $logger->log('Hello Mike, Vuf Vuf')->shouldHaveBeCalled(); } } As always, PHPSpec will help us by creating some methods or us: Then it's up to us to add some code to satisfy the spec: <?php # src/App class Dog { // ... public function greet(Named $named) { $greeting = 'Hello ' . $named->name() . ', Vuf Vuf'; $this->logger->log($greeting); return $greeting; } } As you see, in PHPSpec we describe our object behaviors using a very descriptive syntax. There is always one spec per object/class which is why PHPSpec can only be used for testing at the unit layer/level. If you want to have some higher-level test you'll need to use some other tool. Maybe another BDD tool as Behat (don't get me started on how cool Behat is)? Another thing you probably don't want to do is introduce PHPSpec in a legacy codebase (with bad design). It will be painful and authors of PHPSpec never intended it to be used that way. But if you are starting a greenfield project, why not give PHPSpec a try. Hope you'll find is as fun as I do. Posted on Jun 14 by: konrad_126 Software Developer mostly working in PHP Discussion
https://dev.to/konrad_126/fun-driven-development-with-phpspec-28gf
CC-MAIN-2020-29
refinedweb
1,218
63.19
Patent application title: Content delivery network service provider (CDNSP)-managed content delivery network (CDN) for network service provider (NSP) Inventors: Timothy N. Weller (Boston, MA, US) Charles E. Leiserson (Cambridge, MA, US) Assignees: AKAMAI TECHNOLOGIES, INC. IPC8 Class: USPC Class: 705 30 Class name: Data processing: financial, business practice, management, or cost/price determination automated electrical financial or business practice or management arrangement accounting Publication date: 2012-05-24 Patent application number: 20120130871 Abstract:. Claims: 1. Apparatus associated with a content delivery network (CDN), the CDN deployed, operated and managed by a content delivery network service provider (CDNSP), comprising: a set of processors; and computer memory associated with each processor and holding computer program instructions that when executed by the processor comprise a content server, the content servers executing on the processors together comprising a private content delivery network associated with a network service provider (NSP) entity distinct from the CDNSP, where the private content delivery network enables the NSP entity to provide content delivery to content providers associated with the NSP entity; the content servers in the private content delivery network providing the content providers associated with the entity on-net content delivery over the private content delivery network; and one or more machines associated with the private content delivery network for managing content server data collection for the private content delivery network, for managing billing for the private content delivery network, and for providing a network operations center (NOC) for the private content delivery network. Description: [0001] This application is a continuation of Ser. No. 12/951,091, filed Nov. 22, 2010, now U.S. Pat. No. 8,108,507, which application was a continuation of Ser. No. 12/122,764, filed May 19, 2008, now U.S. Pat. No. 7,840,667, which application was a continuation of Ser. No. 11/636,849, filed Dec. 11, 2006, now U.S. Pat. No. 7,376,727, which application was a division of Ser. No. 10/114,080, filed Apr. 2, 2002, now U.S. Pat. No. 7,149,797, which application was based on Ser. No. 60/280,953, filed Apr. 2, 2001. BACKGROUND OF THE INVENTION [0002] 1. Technical Field [0003] The present invention relates generally to delivery of digital content over a distributed network. [0004] 2. Description of the Related Art [0005] It is well-known to deliver digital content (e.g., HTTP content, streaming media and applications) using an Internet content delivery network (ICDN). addition, the CDN infrastructure typically includes network monitoring systems to continuously monitor the state and health of servers and the networks they are in, a network operations command center (NOCC) that monitors the state of the network on a 24×7×365 basis, a customer-facing extranet portal through which CDN customers obtain real-time and historical usage information and access to content management provisioning tools and the like, administrative and billing systems, and other CDN infrastructure and support. Some CDN service providers provide ancillary infrastructure and services such as high performance, highly-available, persistent storage, tiered distribution through cache hierarchies, edge content assembly, content targeting, and the like. [0007] that provides web content, media streaming and application delivery is available from Akamai Technologies, Inc. of Cambridge, Mass. [0008] Implementation, operation and management of a global distributed network--such as an Internet CDN--is a complex, costly and difficult endeavor. A large CDN may have thousands of servers operating in hundreds of disparate networks in numerous countries worldwide. Typically, the CDN service provider (a CDNSP) does not own physical support infrastructure (i.e., networks, buildings, and the like) on which the CDN servers run, nor does the CDNSP necessarily have the capability of administrating those servers that are often deployed throughout the world. Rather, the service provider must deploy and then remotely administer these services and applications as what is, in effect, a virtual network overlaid on the existing (often third party owned and controlled) physical networks and data centers. [0009] Many network service providers desire to provide content delivery services, however, the cost of designing, installing, managing and operating a full end-to-end CDN is prohibitive. BRIEF SUMMARY OF THE INVENTION [0010] According to the present invention,. [0011] The CDNSP provides its NCDN customer with content delivery service for the NCDN's participating content providers in a so-called "on-net" manner, meaning that the content that is actually available to be delivered over the CDN is transported on the NSP's own network. When the NSP's private CDN is over-loaded, however, according to the invention the CDN service provider allows the NCDN to overflow onto the global CDN so that end users can still obtain the desired content in an efficient manner. When traffic is overflowed to and delivered over the global CDN, it is said to be "off-net." Thus, according to the present invention, one or more private CDNs share infrastructure of a larger CDN, which manages the private CDNs and makes its potentially global network available to handle off-net overflow traffic. [0012] In a conventional content delivery network implementation, the CDN service provider may already have its content servers located "on-net," i.e., in the NSP's network, which simplifies the provisioning of the private CDN.13] In a representative embodiment, a content delivery network service provider shares its infrastructure to enable network service providers to offer CDN services to participating content providers. One or more private CDNs are deployed, operated, and managed by the CDNSP on behalf of one or more respective network partners. The CDN service provider is paid to deploy, operate and manage the private CDN on behalf of the NSP. In addition, preferably the CDN service is paid by the network to deliver the network's off-net traffic to peers or to a bandwidth pool. [0014]15] FIG. 1 is a diagram of a known content delivery network in which the present invention may be implemented; [0016] FIG. 2 is a simplified block diagram of a CDN server; [0017] FIG. 3 is simplified diagram of a streaming media overlay network; [0018] FIG. 4 is a block diagram of the basic CDN infrastructure services that are made available to the NSP according to the present invention; [0019] FIG. 5 is a simplified illustration of how a CDNSP provides a managed CDN on behalf of a network service provider (NSP) according to the present invention; and [0020] FIG. 6 illustrates how NCDNs are implemented using naming schemes that differ from the CDN; and [0021] FIG. 7 illustrates a representative mapping mechanism to enable NCDNs to overflow onto the global CDN. DETAILED DESCRIPTION OF THE PREFERRED EMBODIMENT [0022] As seen in FIG. 1, a known23] In one service offering, available commercially from Akamai Technologies, Inc. of Cambridge, Mass., content is tagged for delivery from the CDN using a content migration refers to a set of control options and parameters for the object (e.g., coherence information, origin server identity information, load balancing information, customer code, other control codes, etc.), and such information may be provided to the CDN content servers in various ways.24] FIG. 2 illustrates a typical machine configuration for a CDN content edge server. For HTTP content,. In operation,. [0025] As described above, the Internet CDN may also provide live and on-demand streaming media. In one approach, the CDN incorporates a fan-out technique that allows the data comprising a given stream to be sent on multiple redundant paths when required to enable a given edge server to construct a clean copy of the stream when some of the paths are down or lossy. FIG. 3 illustrates the use of a so-called "reflector" transport network that implements such a process. This network is described in U.S. Pat. No. 6,751,673, titled "Streaming media subscription mechanism for a content delivery network." [0026] As seen in FIG. 3, a broadcast stream 300 is sent to a CDN entry point 302. An entry point, for example, comprises two servers (for redundancy), and each server can handle many streams from multiple content providers. Once the entry point receives the stream, it rebroadcasts copies of the stream to set reflectors 304a 306d, of a set of regions 306a-n. A subscribing region 306d is a CDN region that contains one or more streaming edge nodes 308a 309, e.g., a local area network (LAN). Typically, an edge node, e.g., node 308d, comprises a streaming server 312 and it may include a cache 310. 314 to facilitate the subscription mechanism as described in the above-identified application. [0027] Although not shown in detail, a typical content delivery network includes other infrastructure (servers, control facilities, applications, and the like) in addition to the HTTP and streaming delivery networks described above. Such infrastructure provides for an integrated suite of services and functions as set forth in the CDN "building block" diagram illustrated in FIG. 4. These services and function are representative, of course, and a given CDN need not include all of them or be implemented according to the configurations described above and illustrated in FIGS. 1-3. For purposes of the present invention, it is assumed that a content delivery network operates a distributed infrastructure on behalf of its participating content provider customers, typically leveraging the networks of various third party network service providers. Thus, for example, it is assumed that the CDN operates servers in various large (e.g., backbone) networks such as those owned and operated by such companies as: UUNet, AT&T, Qwest Communications, Cable & Wireless, Sprint, British Telecom, Deutsche Telecom, NTT, and the like. It is also assumed that a given NSP desires to offer content delivery to its own participating content providers (which, typically, will not be the same content providers that use the services of the global CDN). [0028] According to the present invention, and as illustrated in FIG. 5, the global CDN 500 shares its infrastructure with one or more NSPs 502a-n to enable each NSP to provide its participating content providers with a so-called "private CDN" 504. As illustrated, a given private CDN (or network content delivery network ("NCDN") preferably uses the CDN servers provisioned in the network 506. Participating content providers 508a-n migrate their content to the NCDN using tools, techniques or instructions provided or facilitated by the CDNSP, and the CDNSP deploys, operates and manages the NCDN on behalf of the NSP partner. Participating content providers 508 have their content made available from the private CDN (instead of from their origin servers), thus providing an enhanced end user experience and flash crowd protection for participating content provider web sites. Generalizing, the Content Delivery Network for Network Service Providers (NCDN) is a CDNSP-managed service that offers network service providers (NSPs) a turnkey content delivery network (CDN). The CDNSP preferably provides the hardware and software services required to build, deploy and manage a CDN for the NCDN customer. The NCDN customer is provided with their own fully branded CDN that has similar core functional capabilities for HTTP object and streaming delivery as does the CDNSP CDN. In particular, the CDNSP preferably provides to the NCDN customer (i.e., the NSP) the functional CDN capabilities illustrated, for example, in FIG. 4. These functional components are offered as an integrated solution for the NCDN customer to bring its own content delivery services to market. [0029] As illustrated in FIG. 6, the CDNSP typically operates its set of content servers under a global CDN namespace 600, e.g., cdnsp.net. When an end user browser makes a name query against that domain, the CDN request routing mechanism returns the IP address of a CDN edge server that is not overloaded and that is likely to host the desired content. A representative technique is described in U.S. Pat. No. 6,108,703, which is incorporated herein by reference. Network Service Providers (NSPs) in which they have their own separate namespaces 602 and 604 (e.g., ncdn1.net and ncdn2.net instead of cdnsp.net) and, optionally, their own branding. Preferably, the NSP leases its equipment from the CDNSP, and the NSP provides Tier 1 customer support to its own customers. Although not a requirement, the NSP preferably does not have root access to its CDN machines, but contracts for the CDNSP to provide CDNSP-owned software and to operate their NCDN. The NSP may have a virtual Network Operations Control Center (NOCC) that gives it the ability to monitor their NCDN, but preferably all actual operating decisions are made by the CDNSP. [0030] The NCDN has many advantages. It enables the NSP to provide its content provider customers with flash-crowd protection, it enables the NSP to diminish traffic within its network, and it provides good performance. An NSP may offer content delivery to its content provider customers at a lower cost than a CDNSP's premium service, as well as other benefits, because many of the NSP's customers may already be hosting their web sites with the NSP. As illustrated in FIG. 6, the NSP may rely on the CDNSP to handle overflow using the CDNSP's global network whenever the NSP's own smaller network cannot handle the load. Preferably, the CDNSP network does not overflow into the NSP's NCDN, and one NCDN will not be allowed to overflow into another NCDN. The CDNSP preferably invoices the NSP on a periodic basis, e.g., a monthly service charge, for operating the NCDN, and that fee may be based on the size of deployment, traffic served, or some other metric. In addition, CDNSP may charge the NSP for overflowing into the CDNSP network according to a fee structure, e.g., a structure that encourages the NSP to deploy more servers rather than to use CDNSP bandwidth. [0031] As noted above, preferably the NCDN uses shared CDN infrastructure. Thus, auxiliary NCDN services, such as data aggregation, collection, log delivery, content management, customer portal services, and the like, use the CDNSP tools, machines, systems and processes. Some or all of the customer-facing services, however, may be labeled with the NSP's branding, rather than with the CDNSP's. Billing data for the NSP customers is provided by the CDNSP to the NSP in any convenient format, although preferably via an XML-formatted file transfer mechanism. To account for charges due to NCDN overflow to the CDNSP, the CDNSP billing database may include appropriate fields to identify the NSP's customer for the hit and whether the NSP or the CDNSP served the content. In one embodiment, the hostname portion of an embedded object URL (e.g., ncdn1.net, ncdn2.net, cdnsp.net, or the like) is logged by CDN content server to enable these fields to be populated by billing software. In addition, log-based alerts may warn when an NCDN customer has erred in migrating its content to the CDN, which might cause an NSP customer to use the CDNSP network improperly or one NSP's customer to use a different NSP's NCDN network. [0032] By sharing the CDN infrastructure, the NCDN preferably uses the streaming network and, thus, the NSP also provides live and video-on-demand (VOD) streaming, perhaps in multiple formats such Real, Windows Media, and QuickTime. The NSP's preferably have at least several (e.g., three) entry points within their network for redundancy. Live streaming events preferably are managed (and charged for) by the CDNSP subject to CDNSP approval. Preferably, overflow is handled by the CDNSP network via a reflector subscription mechanism, such as the mechanism described in U.S. Pat. No. 6,751,673. In an illustrated embodiment, a limit is placed on the number of CDNSP servers on which the NCDN can overflow so that no load underestimation by the NSP can adversely impact the CDNSP's network. To handle VOD storage needs, the NSP may use its own storage network or, alternatively, the CDNSP's storage solution. An illustrated storage solution implemented within a content delivery network infrastructure may be the technique described in U.S. Pat. No. 7,340,505, titled "Content storage and replication in a managed Internet content storage environment." [0033] As noted above, other CDN infrastructure support is provided to the NSP. Thus, for example, delivery over SSL may be provided using a generic SSL solution based on wildcard certificates and the Key Management Infrastructure. Service Level Agreement (SLA) monitoring for NCDN content delivery service may be implemented using, for example, redundant monitoring agents (a pair of servers in nearby datacenters) download test images from both the NSP's customer and the NSP's NCDN network. The minimum time for corresponding downloads from the two servers may then be used to determine whether the SLA conditions have been met. The CDNSP preferably monitors both the SLA from the CDNSP to the NSP, as well as from the NSP to its customers. The NSP-customer SLA may be modeled after the existing CDNSP-customer SLA. In one embodiment, the CDNSP-NSP SLA offers a given uptime guarantee, perhaps rebating any fees for the duration of any delivery outage. An NSP's virtual NOCC preferably provides simplified information on the status of each of the NCDN servers. It may have status windows to show machines that need to be fixed, overflow status, and the like. Detailed information preferably is displayed in the CNDSP NOCC. Preferably, the virtual NOCC does not have control of the NCDN software. The NSP's customers preferably access the CDNSP's customer portal (preferably a secure extranet application) for real-time reporting and historical data. Secure connections to the portal are made, for example, via an NCDN-branded domain, either by setting up separate portal machines or allocating additional IP addresses on existing portal machines. [0034] Several different techniques may be used to "map" requests for NCDN content to the NCDN. In a first approach, referred to as overlay NCDN, the NSP does not have dedicated regions or machines. In this example, the NSP's content providers are just identifiable with separate mapping rules so that requests are simply mapped to a set of machines that serve the content and other non-NCDN content. [0035] A second embodiment is sometimes referred to as an independent NCDN without overflow. In this embodiment, the NSP has a set of dedicated machines organized into regions, with each region being a set of CDN content servers sharing a back-end switch. These regions preferably are only used to deliver content of a specific service for private CDN requests. This type of solution may be over-provisioned to handle NCDN traffic spikes, and any overflow control mechanism in the CDN is modified to prevent overflow between the CDN and the NCDN. [0036] In a preferred embodiment, however, an independent NCDN has overflow capability. In this embodiment illustrated in FIG. 7, the NSP also has a separate set of one or more regions 700a-n, each of which include content servers 704 dedicated to the NCDN. This embodiment, however, also uses an overflow controller 706. In a representative implementation, the overflow controller 706 is a mechanism for overriding the assignment of clients to regions generated by a CDN mapping process 708. In particular, it is assumed that the CDN mapping process has the capability of assigning clients (typically, an end user's local name server) to CDN regions, each of which comprise a set of one or more content servers. The overflow controller 706 modifies these assignments under certain conditions. Thus, for example, when a region is receiving more than a given % of the load that it is deemed to be capable of serving (e.g., 75%), the overflow controller begins to spill traffic to other regions. Preferably, the overflow controller accomplishes this by instructing an individual low-level nameserver that is directing traffic into the region to begin directing traffic to another region. The low-level nameserver then joins a load-balancing group for the new region. If necessary, the overflow controller directs more than one low-level nameserver to direct traffic to another region, and different low-level nameservers may point to different regions. The overflow controller may comprise a group of machines, located on different backbones, each running the overflow controller process. These machines elect a leader, called the lead overflow controller, who is responsible for determining if any low-level nameservers should be redirected. The lead overflow controller determines which low-level nameservers should be redirected, and to where, e.g., by performing a minimum-cost flow calculation. The nodes in the graph are CDN regions. [0037] Thus, in a preferred embodiment, separate maprules are used to cause overflow within an NCDN to favor the NCDN servers over CDNSP servers. A maprule is a set of rules for a type of content defining which CDNSP region (a subset of CDNSP servers that typically share a common backbone, such as a LAN, in a datacenter) may serve it. A maprule defines which regions should be used for a certain service and defines overflow preferences. In a simpler embodiment as noted above, an NCDN simply serves the NSP's customers out of the CDNSP network. As NCDN regions are added within the NSP's network, they are added to the CDNSP network as ordinary CDNSP regions. NCDN regions would then be prioritized over CDNSP regions using a maprule, but overflow from an NCDN region preferably is not prioritized to within the NCDN's other regions. In the preferred embodiment, as noted above, the NCDN is partitioned from the CDNSP network, and overflow is prioritized to within the NCDN. [0038] The following describes additional details for an illustrative implementation. Mapping and Load Balancing [0039] It is required to determine proper maps for each NCDN and to use these maps to make load-balancing decisions. Because the ability of the NCDN to overflow into the CDNSP network when needed is an advantage of the NCDN product/service, an audit trail is preferably provided to justify any overflow into the CDNSP's network. In one embodiment, the NCDN uses a simple maprule that preferentially serves customers from the NCDN regions but which does not prioritize the NCDN regions during overflow. The CDNSP preferably includes a mapping mechanism that monitors the Internet and maps based on dynamic conditions. The mapping mechanism may use monitoring agents, such as servers that perform network traffic tests including traceroutes, pings, file downloads, and the like, to measure dynamic network conditions. Such data may then be used to assess which CDNSP regions are best, in terms of Quality of Service (QoS) performance, to serve content for each (NsIP, MapRule), where NsIP is the IP address of a requesting client's name server and the MapRule is a set of rules for a type of content defining which region may serve it. These maprules preferably encode the fact that content should be preferentially served from the NCDN regions. Preferably, the mapping mechanism is able to generate candidate regions (best data centers for delivering content) in the NCDN for each client name server (or group of name servers) so that a given scoring routine (based on some Q-o-S criteria) can provide sufficiently many scores within the NCDN for each group of client name servers, and so that, in turn, a region assignment can be made to map end users of NCDN content to an appropriate region. The particular algorithms and techniques for performing the actual region assignment are not part of the present invention. As the CDNSP deploys more NCDNs, it should ensure that the set of candidate regions for a specific client name server over all maprules does not grow too large, because otherwise too much network traffic testing may occur and/or become unwieldy. Content Migration and Content Servers [0040] Content providers served by an NCDN may utilize one or more content migration tools or other techniques to migrate content provider (CP) content to the NCDN. Preferably, each content provider is assigned a distinct CP-code from all other CP-codes using the same NCDN, another NCDN, or the CDNSP. A table may be used to provide the mapping from CP-code to legal domains on the content provider's origin server. Distribution of the legal domains to the CDNSP content servers may be provided by a metadata transmission system. [0041] A CDNSP's content servers preferably are used for the NCDN. A conventional content server is a Pentium-based caching application with a large amount of RAM and disk storage. [0042] For collecting data from CDNSP content server regarding the content served, preferably the CDNSP uses a log delivery service that logs host headers. Distributed Data Collection [0043] The CDNSP's billing of the NCDN may include a preference to prescribe a large bursting rate in the case of an overflow condition, whereby the NCDN (due to network traffic congestion) is permitted to serve content from the CDNSP network. The overflow degree is the difference between the traffic served by the NCDN's content servers and the total traffic served by the CDNSP's network for the particular NCDN's CP codes. Direct measurement of the overflow degree is highly desirable from an auditing perspective (both in reviewing billing and accidental misapplication of the content migration process by the NCDN's customer). Direct measurement may be accomplished by including an additional field in a log database application to collect host header names, which allows the CDNSP to use existing SQL queries to collate this data. Unique IDs may be assigned during the provisioning process of each NCDN. The new fields in the log database may be used, for example, to indicate what NCDN was named in the rebranded portion of the URL and to show out of what network the content was served. Logging and Billing [0044] A log database changes can be generated as follows: parse additional fields in logs, map modified URL hostname into NCDN code, map content server IP to NCDN code, and automate delivery into a distributed data collection (DDC) function. In addition to logging this data for the host header name, logging may raise alerts when an overflow condition exists. [0045] For the NCDN's billing of their customers, a reseller approach may be utilized. For example, the CDNSP delivers to the NCDN on a monthly basis an XML file containing summarized traffic information for each of their CP-codes. The NCDN is then responsible for filtering this data and generating branded invoices for their customers. Streaming [0046] A reflector network as described in U.S. Pat. No. 6,751,673 may be provided for each NCDN. This network preferably comprises 3 distribution trees (to provide fault tolerance and redundancy), with at least 3 entry points. To support the requirement for the NCDN to be able to overflow onto the CDNSP network, the NCDN reflector network may be rate limited and will be mapped to overflow into no more than a small percentage of the CDNSP network. This restriction minimizes the impact on the CDNSP reflector network that would occur if the NCDN took on more load than both networks could handle. Storage [0047] Preferably, the NCDN uses the NSP's existing storage solution. NSP's preferably obtain storage in several ways, e.g.: NSPs that host web sites can provide storage "behind" the customer web site, and NSPs can provide storage servers "in front" of the customer web site to which the customer uploads content. For storage "behind" the web site, the customer web server accesses the storage directly. For storage "in front" of website, the CDNSP may require the NSP to use a CDNSP global load balancing mechanism service such as described in U.S. Ser. No. 10/113,183, identified above. This mechanism provides an IP-based access control for the NCDN storage customers. During provisioning of the NCDN, an appropriate CDNSP DNS entry for the NSP's storage servers is provided. Once this has been done, the NCDN can CNAME its customer names on their nameserver to the CDNSP DNS entry. Preferably, the NCDN is responsible for managing issues with their customer's uploads into the storage sites. This solution provides a level of anonymity to the storage servers and branding of the storage servers with the NSP's domain and customer names without any software modifications. Performance Assurance and Agents [0048] A basic approach to Service Level Agreements (SLAs) will be the use of two types of SLA's: Type 1--the SLA between the NSP and its customers (e.g., one for web content delivery, one for streaming media content delivery); Type 2--The SLA between the CDNSP and the NSP (e.g., one for web content delivery, one for streaming media content delivery). [0049] Preferably, the CDNSP monitors the NCDN, alerts the NSP of any problems, and assists the NSP in developing a monitoring and alert policy with its customers. NOCC Monitoring Applications [0050] The monitoring of the NCDN by the CDNSP NOCC may provide region-level monitoring and region overflow monitoring. For region-level monitoring, the NOCC operating data is monitored, aggregated and used to update relevant NOCC GUI displays. The NOCC may assign the same or different priorities on NCDN and CDNSP alerts. There may also be a general prioritization of the form "CDNSP network is more important than any CDN" (or vice versa). There may be various types of alerts for NCDN operation including, e.g.: NCDN has only N % machines serving; NCDN is overflowing N % of traffic to CDNSP; NCDN not visible to NOCC (which will happen if there is a peering problem with the network), or the like. Of course, the above examples are merely representative. An indication whether the NCDN is overflowing into a CDNSP region may be provided. NSP Virtual NOCC Applications [0051] Preferably, the CDNSP limits the amount (and type) of data viewable by the NSP, although this is not a requirement. The data presented to the NSP's virtual NOCC may be the following: an "indicator" showing whether a particular server on the NCDN network is operational or non-operational and, by region, traffic served in megabits per second and hits per second. The definition of operational machines preferably includes suspended machines, and the only machines considered non-operational are those with hardware or connectivity problems. Reporting [0052] The CDNSP's realtime and historical data modules may be used. Preferably, logs are aggregated by the NCDN CP-codes and delivered to the NSP. The NSP is then responsible for filtering this data and providing it to the NCDN customers (i.e., participating content providers). [0053] Thus, according to the present invention, a content delivery network shares its infrastructure by building and managing private content delivery (sub)-networks (an NCDN) for one or more network service providers (or other third parties). Although part of a shared infrastructure, each NCDN preferably comprises at least one private CDN region that is separate from the CDN regions that comprise the potentially global CDN. These private regions can share the same data centers and racks as some of the CDN regions but preferably have separate backend networks and may be tracked in the CDN system separately. This separation makes it possible to prevent off-net overflow from CDN regions, if desired. It might also be possible for off-net traffic to overflow into private CDN regions if the CDNSP chooses. [0054] Sharing CDN infrastructure provides additional advantages to the CDN service provider.55] The following is a more concrete example of a representative bandwidth pooling exchange as contemplated by the present invention. In this example, the CDNSP offers the following options to its NSP customers that have bought an NCDN. As noted above, an NCDN is a private CDN based on the CDN infrastructure (in whole or in part) to otherwise sharing a common interface with the CDN of the CDNSP. If the NSP wishes to deliver some content from "off-net" servers, i.e., using servers on the global CDN of the CDNSP, the NSP pays the CDNSP given agreed-upon consideration. The rate paid, for example, may be based on the rate for another NSP where the particular servers in question are located. The CDNSP then aggregates groups of NSPs (aggregating across all or some networks where the CDNSP's servers are located) and offers "tranches" of NSP pricing. Thus, for example: [0056] 1. $350/Mbps for UUNET bandwidth [0057] 2. $300/Mbps for any NSP in which CDNSP servers are co-located [0058] 3. $400/Mbps for domestic Tier 1 NSPs [0059] 4. $500/Mbps for cable company NSPs [0060] 5. $700/Mbps for European telco NSPs [0061] 6. etc. [0062] Of course, the above amounts and classifications are merely representative, as the CDNSP can designate any number of classifications and pricing variables as it desires. [0063] To facilitate a bandwidth exchange, the CDNSP can offer a particular NSP NCDN customer reduced "off-net" bandwidth prices in exchange for cheaper bandwidth on the network of that NSP (which would then be resold to other NSP NCDN customers of the CDNSP). If the NSP customer offered to others enough "on-net" bandwidth, the NSP could, in theory, buy its "off-net" cost down to zero (or even be paid). Thus, a true CDN bandwidth exchange would be provided, with buyers and sellers of bandwidth, and the CDNSP getting a "spread" between buy and sell rates. The bid-ask prices for bandwidth on each participating NSP preferably are posted by the CDNSP over an online system, e.g., through web-based access through the CDNSP extranet portal. [0064] The present invention may be implemented in any content delivery network. As noted above, preferably, the CDN includes mapping and load balancing software that uses dynamic monitoring of the system status (load, connectivity, etc.) and Internet conditions to direct end users (primarily via DNS) to an optimal region and then an optimal server in that region. In general, any request can be sent to any region, and the edge servers dynamically fetch content, run applications, and serve end-user requests. Additionally, the CDN may run several overlay networks to provide efficient and scalable communications between customers' web sites and the large CDN edge network. Some of these overlay networks are dynamically constructed of the edge regions themselves, while others may use specialized non-edge regions (e.g., the streaming fan-out network). A variety of side channels (e.g., the metadata transmission system) may also exist to efficiently deliver configuration and other data to the edge servers as well as to collect system state data for real-time monitoring and other functions. This CDN infrastructure is shared by a number of network service provider (NSP) partners, who each operate a private CDN for their participating content provider customers. Patent applications by Charles E. Leiserson, Cambridge, MA US Patent applications by AKAMAI TECHNOLOGIES, INC. Patent applications in class Accounting Patent applications in all subclasses Accounting User Contributions: Comment about this patent or add new information about this topic:
http://www.faqs.org/patents/app/20120130871
CC-MAIN-2014-41
refinedweb
5,841
50.77
[Table of Contents] [Next Topic] There are many times when composing queries that you have to do aggregation. There are a number of built-in aggregators: · Count · LongCount · Sum · Min · Max · Average · Aggregate Aggregators are extension methods that operate on IEnumerable<T>, and return some type T (or U) that is not a collection. Another way to say it: aggregation is the process of taking a collection and making a singleton. Using the Sum aggregate extension method can be as simple as: int[] ia = { type. It has a couple of different forms. If you want to use it to aggregate a collection of some type T into a single T, you can use it like this: Console.WriteLine(ia.Aggregate((a, i) => a += i)); This does the same thing as Sum. There is another overload of the Aggregate extension method that allows you to specify a seed for the aggregation - in other words, to provide an initial value for aggregation. The following code shows setting the seed to zero: Console.WriteLine(ia.Aggregate(0, (a, i) => a += i)); This will produce the same results as the previous example. To use the Aggregate operator to concatenate strings, you could do this: string[] ia = { "aaa", "bbb", "ccc" }; The observant will notice that this use of Aggregate creates a new short-lived string object on the heap for every item in the collection. You can use Aggregate in combination with the StringBuilder class, as follows: Console.WriteLine( ia.Aggregate( new StringBuilder(), (sb, i) => sb.Append(i), sb => sb.ToString() ) ); This example uses an overload of the Aggregate extension method that allows you to set the seed (where it news up the StringBuilder, and to specify another lambda expression that projects the results of the aggregation). In this case, the projection is to convert the StringBuilder to a string. This eliminates the creation of so many strings on the heap, but it adds syntactic complexity. It also isn't pure, as the side effect of the changing StringBuilder would be observable in the lambda expression, but I don't care. This is a side effect that I can live with. But the best method to concatenate strings is to write an extension method, StringConcatenate, as follows: public static string StringConcatenate( this IEnumerable<string> source) { return source.Aggregate( (s, i) => s.Append(i), s => s.ToString()); } Its use: Console.WriteLine(ia.StringConcatenate()); Finally, it is useful to have another overload of StringConcatenate. This one that takes a delegate that does the projection from T to string: public static string StringConcatenate<T>( this IEnumerable<T> source, Func<T, string> projectionFunc) (s, i) => s.Append(projectionFunc(i)), Here is a small program that contains both extension methods, and code to exercise them. The code is attached to this page: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Xml; using System.Xml.Linq; public static class LocalExtensions public static string StringConcatenate( this IEnumerable<string> source) { return source.Aggregate( new StringBuilder(), (s, i) => s.Append(i), s => s.ToString()); } public static string StringConcatenate<T>( this IEnumerable<T> source, Func<T, string> projectionFunc) (s, i) => s.Append(projectionFunc(i)), class Program static void Main(string[] args) string[] stringList = new[] { "aaa", "bbb", "ccc" }; XElement xmlDoc = XElement.Parse( @"<Root> <Value>111</Value> <Value>222</Value> <Value>333</Value> </Root>"); string s1 = stringList.StringConcatenate(); string s2 = xmlDoc.Elements().StringConcatenate(el => (string)el); Console.WriteLine(s1); Console.WriteLine(s2); PingBack from This topic took some work to understand, mostly because it uses C# syntax and methods I've never used. It would help to explain Func<T, TResult>, and the 3 different forms of Aggregate that are used. An explanation of the Aggregate methods would have helped a lot since unlike Sum, the use of their arguments and their operation are not apparent from reading the code. For example, it was not obvious where seed is created or initialized in: Console.WriteLine(ia.Aggregate((seed, i) => seed += i)); and would have be easier to understand if Console.WriteLine(ia.Aggregate(0, (seed, i) => seed += i)); were introduced first with the explanation that 0 is the initial value for the aggregate, is can be any identifier and represents the current value of the aggregate, and that when the initial value is the default initial value for the aggregate type, the expression can be shortened to the first form. [Table of Contents] [Next Topic] Our next goal is to retrieve the text of the paragraphs in the document. You are absolutely right, Marv. I've modified the topic accordingly. -Eric If you would like to receive an email when updates are made to this post, please register here RSS Trademarks | Privacy Statement
http://blogs.msdn.com/ericwhite/pages/Aggregation.aspx
crawl-002
refinedweb
785
57.16
I'm trying to implement simple res-net like below and it works with CPU. class ResNet(nn.module): def __init__(self): super(Net, self).__init__() self.conv_1 = nn.Conv2d(3, 64, 4, stride=2) self.bn_1 = nn.BatchNorm2d(64) self.res_1 = self.__res_block(64, [32,32,128], True) ... def forward(self, x): x = self.conv_1(x) x = F.relu(self.bn_1(x)) x = F.max_pool2d(x, 2, 2) x = self.res_1(x) ... def __res_block(self, in_channels, nb_filters, right=False): def __res_base(_in_channels, out_channels, kernel_size=1, padding=0): def g(x): x = nn.Conv2d(in_channels=_in_channels, out_channels=out_channels, kernel_size=kernel_size, padding=padding)(x) x = nn.BatchNorm2d(num_features=out_channels)(x) return x return g def f(x): y = F.relu(__res_base(in_channels, nb_filters[0])(x)) y = F.relu(__res_base(nb_filters[0], nb_filters[1], kernel_size=3, padding=1)(y)) y = F.relu(__res_base(nb_filters[1], nb_filters[2])(y)) if right is True: x = __res_base(in_channels, nb_filters[2])(x) return F.relu(x+y) return f but it doesn't work with GPU and throws TypeError, TypeError: _cudnn_convolution_full_forward received an invalid combination of arguments - got (torch.cuda.FloatTensor, torch.FloatTensor, torch.FloatTensor, torch.cuda.FloatTensor, tuple, tuple, int, bool), but expected (torch.cuda.RealTensor input, torch.cuda.RealTensor weight, torch.cuda.RealTensor bias, torch.cuda.RealTensor output, std::vector<int> pad, std::vector<int> stride, int groups, bool benchmark) I think this is because the parameters in __res_block doesn't pass to GPU but how can I pass them to GPU? Thank you. __res_block Hi, From the error message it looks like you give him torch.FloatTensor as input.If your model is on GPU, you should give him torch.cuda.FloatTensor (EDIT: sorry wrong name for cuda tensors).You can convert your inputs to cuda by doing: input = input.cuda() before forwarding it through the network. torch.FloatTensor torch.cuda.FloatTensor input = input.cuda() I uploaded the code here. The code except the module above is same as my other examples and they work with GPUs. So I think the cause is in the __res_block. And, does torch.CudaFloatTensor equal to torch.cuda.RealTensor? torch.CudaFloatTensor torch.cuda.RealTensor In your __res_block you create new objects that are not composed by torch.CudaFloatTensors torch.CudaFloatTensors Did you try just in def g(x):return x.cuda() instead of return x def g(x) return x.cuda() return x Ho I see, I think you want both your __res_block and __res_base functions to return an instance of Modules.Otherwise their parameters won't be recognized as being part of the main network.You want both of them to be classes that subclass the nn.Module class.In each, you want in the init to initialize the operations and store them in self as done here then a forward pass that just use them as done here. __res_base Module nn.Module self There's no such thing as torch.CudaFloatTensor, only torch.cuda.FloatTensor. Also, as @albanD said, you can't return a closure from the __res_block and expect the modules inside it to be recognized as part of the model. Just create a new nn.Module subclass. You can see how ResNets are implemented in torchvision. @alexis-jacq thank you for your advice, but that didn't work because the input to g(x) is already torch.cuda.**Tensor and the problem is the weights etc are not torch.cuda.**Tensor. g(x) torch.cuda.**Tensor @albanD @apaszkethank you two, ok I'll create blocks as nn.Module subclasses like the tochvision implement. @apaszkeIs torch.cuda.RealTensor in the TypeError message equivalent to torch.cuda.FloatTensor? I couldn't find RealTensor in the doc. RealTensor @moskomule torch.cuda.RealTensor refers to any torch.cuda.*Tensor, and in this context, is probably a torch.cuda.FloatTensor torch.cuda.*Tensor thank you all, I updated the code and it works well. So briefly, the instances of subclasses of nn.Module are able to be backproped. No, nn.Module subclasses only add support for some convenience methods like .parameters(), .cuda() and some others. It's possible to implement neural networks in autograd without modules, and some people actually prefer this style. But this means that you'll need some additional helpers and custom data structures for handling parameters. .parameters() .cuda()
https://discuss.pytorch.org/t/how-to-make-custom-method-in-nn-module-work-with-gpus/406
CC-MAIN-2017-26
refinedweb
714
53.78
2.2.2.6 Birthday The Birthday element specifies the birth date of the contact. It is defined as an element in the Contacts namespace and is used in ActiveSync command requests and responses as specified in section 2.2.2. The value of this element is a datetime data type in Coordinated Universal Time (UTC) format, as specified in [MS-ASDTYPE] section 2.3. The time portion of the datetime value SHOULD be ignored, so that synchronizing between different time zones does not change the date. This element can be ghosted. For details about the use of ghosted properties, see [MS-ASCMD] section 2.2.3.179..
https://msdn.microsoft.com/en-us/library/ee203040(v=exchg.80).aspx
CC-MAIN-2017-22
refinedweb
108
55.03
I want to combine weapon aiming idle with humanoidwalk. So in the script when i click on the mouse right button it will aim and then when i press W it will start walking. Now with the animator controller and script i have i can make right click on the mouse button and it will aiming but won't walk or i can just press W and it will walk with aiming. But i want to first right click and aiming and then press W and walk. The screen shot is on my main layer the base layer: The Aiming state is with weapon idle animation. And two transitions using parameter name Aiming type bool one transition set to true the other to false. With this i can make right click button on mouse and aiming but not walking. The second screenshot show the blend tree i did when making double click on Movement it's getting to the blend tree: Using this blend tree with the script when i press on W it will walk and aiming the same time. Now i tried to create a new layer with a avatar mask to make that when i click mouse right button it will first aim and then when pressing W it will walk. But it's not working. In this layer i have only weapon aiming idle state with the weapon idle animation. What should i do here else ? And what should i add/change in the script ? Script: using System.Collections; using System.Collections.Generic; using UnityEngine; public class Soldier : MonoBehaviour { private Animator anim; (Input.GetMouseButtonDown(1)) { anim.SetBool("Aiming", !anim.GetBool("Aiming")); } } private void FootStep() { } } The main goal: To be able to click on mouse right button for aiming and then pressing W and walking. This is the toroso the avatar mask i 435 People are following this question. I'm still not get it how to mix/blend soldier character weapon aiming animation with walking animation ? 1 Answer Opening one door in a scene causes all others to open 1 Answer A better way to trigger animations. 0 Answers What is the proper way to wait for an Animator Controller to update? 1 Answer How to check if Animator is playing 3 Answers
https://answers.unity.com/questions/1402739/how-do-i-use-the-animator-avatar-mask-to-combine-t.html?sort=oldest
CC-MAIN-2020-50
refinedweb
377
71.65
Introduction to Java Lecture Notes. Ryan Dougherty - Colleen Reeves - 2 years ago - Views: Transcription 1 1 Introduction to Java Lecture Notes Ryan Dougherty 2 Table of Contents 1 Versions Introduction Computers Data Types Decisions Loops Introduction to Classes Methods Static Method Overloading Arrays Searching Sorting Versions Here are the versions of the book over time. 1.0 Initial release 3 3 Introduction Welcome to these lecture notes for CSE110! This guide will help you on your journey in learning the basics of programming in Java, including methodologies for problem solving using computers. Programming is becoming more of an important tool in the last few decades. Understanding of these technological shifts, therefore, is imperative. The topics are split up according to the Table of Contents above, and their corresponding page numbers. At the end of each chapter are written and programming exercises. The written exercises are for testing your knowledge of the material, and the programming ones are to see if you can write programs using the material from that chapter. If there are any questions/errors/comments that you want to send regarding the material, send an to: 4 4 Computers 3.1 Motivation This chapter concerns basic knowledge of computers. In order to write programs for computers, we need to have a basic understanding of how computers work. Once we have this understanding, we can write programs that make use of the computer s hardware and software. A computer is a general-purpose device that can be programmed to carry out a set of arithmetic or logical operations automatically. Since a sequence of operations can be readily changed, the computer can solve more than one kind of problem. In recent years, computers have become much faster due to advancements in hardware speed and software breakthroughs. However, there is only a limit to how fast these advancements can take us. Therefore, we need to write programs that use the hardware efficiently. 3.2 Introduction to Java/Programming Languages Java is an object-oriented programming language invented by Sun Microsystems in 1995, and Sun was acquired by Oracle in One large benefit of Java is that it is run in a virtualmachine, which means that it can be run on almost all major platforms: Windows, Mac OS X, Linux, Solaris, etc. A programming language is a formal constructed language designed to communicate instructions to a machine; particularly, a computer. Basically, it allows a person to code a sequence of instructions that makes the computer do what he/she wants. A computer program, or just a program, is a sequence of instructions, written to perform a specified task on a computer. A computer requires programs to function, typically executing the program s instructions in a central processor. 3.3 Java Program Structure All Java programs follow the same basic structure. A typical Java file (with a.java extension) is composed of 1 or more classes, which have 1 or more methods, which have 1 or more statements. We will give more rigor to what these terms mean later. Java classes are (typically) provided in packages, which contain one 1 or more classes. 3.4 First Java Program A typical first program for a programmer in any programming language is called a Hello, World program, which prints that phrase to the screen/console. The reason that this is the first program for many programmers is that they can demonstrate that they know the basic structure of a Java program. To print to the screen, a program (that must be saved in a text file that is called HelloWorld.java) to do this is: public class HelloWorld { public static void main ( String [] args ) { 5 System. out. println (" Hello, World "); You must type this program in a raw text editor, not in a rich text editor such as Microsoft Word. The reason for this is that Microsoft Word adds special characters, which are not recognized when you compile and run your program (see below). For many beginners, this program may be a little daunting and confusing. But as we can see, this program follows the basic structure of a Java program: it has 1 class, named HelloWorld; it has one method, named main, and it has one statement, which prints to the screen. For each of the terms, the precise meaning of them will be covered in later chapters. However, the basic structure of: public class YourProgram { public static void main ( String [] args ) { // Insert statements here will be enough for most beginning Java programs. As a programmer, you will put the statements between the opening and closing brace of the main method. Note: the main method is the starting point of execution for every Java application/program. Note: the text Insert statements here is in green. This is a comment, in which you can add any text. There are 3 types of Java comments: Line comments - start with //, and last for the rest of the line. Multiline comments - start with /* and end with */, and last until the */ is reached. JavaDoc comments - these have the same form as multiline comments, but have a purpose in providing documentation for Java code. They are typically put right before a method declaration Running/Compiling Java Programs Now that we understand how to create Java programs, we want to run them on our computers. In order to run a Java file, we need to do 2 steps: compile it, and then run it. A compiler (for most programming languages) is software that translates the user-created code into object (or machine ) code. Obviously, user-created code is readable by the user, since the user created it. However, object code is not readable, since it is code that the computer can read, and then execute. There are a few ways of compiling a Java file: If you have an Integrated Development Environment (IDE), such as Eclipse, Netbeans, etc. on your machine (they are available on the web for free), running your program is done by clicking the green arrow ( Run ) button in the toolbar. This operation will compile and run the program. If you are not using an IDE, and have a Terminal/Command Prompt, etc. application in which you supply commands, you enter these commands to compile and then run a Java program: javac YourProgramName.java 6 6 java YourProgramName (Note: no.java extension on this command) If you do not have a Terminal/Command Prompt application, consult sources online on how to use the JDK (which means Java Development Kit). 3.6 Compilation Errors However, if you mistyped during creating your program, you encounter what is called a compilation error, which shows an appropriate error message. Common errors include: Incorrect class name - the name of the class must exactly match the name of the file that it is saved in. Invalid class name - there are rules for what a class name can be. For example, it cannot be a Java keyword (i.e. public, class; all of the words that highlight in blue). No semicolon after statements - all statements must end in a semicolon. Not putting quote marks around what is put inside the System.out.println statement. This is called a string of characters. If no quote marks are put, then the Java compiler cannot recognize what Hello, World means. However, it does know what Hello, World means. 3.7 Notes There are 2 kinds of print statements in Java: System.out.print - prints out exactly what is given in the parentheses. System.out.println - same as print but adds a newline after the text given in the parentheses. The next time something is printed, it will start on the next line. There are numerous special characters that appear in between quote marks (called escape characters ): \n - a newline character. Suppose we have this line of code: System. out. print (" Testing newline \ ntest2 "); The output for this code would be: Testing newline Test2 Notice that the character \n was not printed because it has a special purpose: providing a new line. Therefore, one can see that the following lines of code do the same thing: System.out.println("Text"); System.out.print("Text\n"); \t - a tab character. The text that follows \t will appear in the same manner as a tab key is used in any other text document. \" - to print a double quote. 3.8 Written Exercises 1. What does a compiler do? 2. Consider the following Java Program: 7 public class VendingMachine { public static void main ( String [] args ) { System. out. println (" Please insert 25c"); By what name would you save this program on your hard disk? 3. Is Java a functional language, procedural language, object-oriented language, or logic language? 4. What is a plain text file? 5. How is a text file different than a.doc file? 6. What is a source program? 7. What is Java bytecode? 8. What is the program that translates Java bytecode instructions into machine-language instructions? 9. Is Java case-sensitive? Programming Exercises 1. Write a program to print the following to the screen using a number of print statements: 8 8 Data Types 4.1 Motivation Now that we know how to compile and run programs, and print to the screen, we will bump up the complexity of our programs a little. In this chapter, we will be exploring data types, and how to do basic calculations. 4.2 Types There are 8 primitive (fundamental) data types in Java (we will explain constraints that they have later): byte - an integer with a small range. short - same as byte, but a larger range. int - same as short, but even larger range. long - same as int, but even still larger range. float - a real value, that has some precision. double - same as float but with more precision. boolean - a type that takes one of two possible values: true, or false. char - a Unicode character. Think of a or b as chars - any single character is a char. Now, we give the range for each of the primitive data types (all inclusive on both ends). These are all of the values that they can hold: byte: -128 to short: to int: 2 31 to long: 2 63 to float: to double: to boolean: true or false. char: 0 to Now that we know the 8 fundamental data types, we want to know how to use them. To do that, we have to declare a variable with a type. 9 9 4.3 Variable Declaration Like classes in the previous chapter, declaring variables follow the same basic structure, which is: < T ype > < V ariablename >= < V alue >; For example, if we want a int variable called val to have a value of 2, we would write the line of code as: int val = 2; // assign val to a value of 2 Also, we can declare several variables of the same type in the same line using a comma between the names: int val = 2, otherval = 3; Notes: In a list of declarations, there is no need to declare the type twice (in fact, there will be a compiler error if this is done) The convention in Java names is to follow camel casing: the first word is lowercase, and the subsequent words in the same variable are capitalized (see example above). Now, there are only certain names that our Java variables can have. The rules are: The name cannot be a keyword (any of the words in this document that are colored blue, such as int, public, etc.). The first character must be a letter (either upper or lowercase), the underscore symbol, or a dollar sign ( $ ). However, a variable name cannot start with a number. Any character other than the first may be letters, underscores, the dollar sign, or also numbers. Here are some variable declarations using all primitive types: byte b = 1; short s = 2; int i = 300; long l = 1000 L; // note the L float f = 0.56 f; // note the f double d = ; // no suffix boolean b = true ; char c = a ; // chars are surrounded in single quotes After we have initialized a variable, we can also modify it without having to declare it again. Here is an example: int i = 300; i = 301; // modifies i s value to be 301 // int i = 301; // this causes a compiler error //( declare once ) 10 Primitive Operators Now that we know how to declare and modify values, we need to learn how to do various operations on them, such as addition, subtraction, multiplication, and division. An example showing all of them is the following (with comments): /* Addition */ // int works the same as byte and short int i1 = 0, i2 = 3; int i3 = i1 + i2; // adds i1 s value (0) and i2 s (3) // doubles and floats work the same way : double d1 = 2.5, d2 = 3. 0; float d3 = d1 + d2; float f1 = 2.5 f, f2 = 3.0 f; float f3 = f1 + f2; // Can add across types, but is promoted to " most precise " // If we add double + int, the result is a double int i4 = 4; double d4 = 5. 3; double d5 = d4 + i4; // But we can also " cast " ( with parentheses ) to the type we want if it is less " precise " - this truncates the fractional part : int casted = ( int )( d4 + i4); // error without ( int ) // cannot do operations on booleans ( compiler error ) // boolean b1 = true + false ; /* Subtraction */ // Works with primitive types the same way as addition int i5 = 0, i6 = 3; int i7 = i5 - i6; // i6 has value -3 /* Multiplication */ // Multiplication is the same as addition in the same type // However, we promote to " most precise " value if multiple types int i8 = 5; double d6 = 5. 3; double d7 = d6* i8; // promote i8 to a double valued 5.0 /* Division */ // Division is easy to understand except for when the numerator and denominator are both int / short / byte. int i9 = 10, i10 = 3; // What is i9 / i10? We expect , but we get 3 instead. Java does " integer division ", where the numerator and denominator are both ints, which is truncating all the fractional parts. int i11 = i9 / i10 ; // i11 has value 3. 11 // However, if we " cast " one of the values to a double, then we do not have this problem double d8 = ( double ) i9 / i10 ; // cast i9 to a double of value // d8 now has value Another operation is called the mod operator (or remainder ): int i1 = 10, i2 = 3; int i3 = i1 % i2; // i3 has value 1, since 10 remainder 3 = 1. We can also shorten times when we are modifying the same value with another. For example: int i = 5; i += 3; // equivalent to: i = i + 3; i -= 3; // equivalent to: i = i - 3; i *= 3; // equivalent to: i = i * 3; i /= 3; // equivalent to: i = i / 3; For int variables, there are 2 operations that are done very often, so they were put into the language: increment and decrement: int i = 2; i ++; // equivalent to: i += 1; i - -; // equivalent to: i -= 1; Boolean So how do we compare values? There are various operators (parentheses added for clarity - they are not needed): int i1 = 5, i2 = 6; boolean larger = ( i1 > i2); // false, since 5 < 6 boolean largerorequal = ( i1 >= i2); // also false boolean smaller = ( i1 < i2); // true boolean smallerorequal = ( i1 <= i2); // true boolean notequal = ( i1!= i2); // true boolean equal = ( i1 == i2); // false // Note that == means compare value, = means assign There are also operators to work with booleans: and, or, and not. /* And = && */ boolean t = true, f = false ; boolean andtruetrue = t && t; // true boolean andtruefalse = t && f; // false boolean andfalsetrue = f && t; // false boolean andfalsefalse = f && f; // false /* Or = */ boolean ortruetrue = t t; // true boolean ortruefalse = t f; // true boolean orfalsetrue = f t; // true boolean orfalsefalse = f f; // false /* Not =! */ 12 12 boolean nottrue =!t; // false boolean notfalse =!f; // true // We can use multiple operators at once : boolean myst =!( true && ( true false )); // false What if we do not want our variable values to change? There is a way, with the final keyword: final int NUM = 100; // convention : all capital letters for final variables // NUM ++; // compilation error 4.6 String Now that we fully understand how primitive data types work, we can move on to using classes provided by the Java API (Application Programmer Interface). One such class is provided in the Java package java.lang, called String. This package is so often that Java automatically imports it for you, so the programmer does not have to do extra work. A String is a set of characters in between double quotes. Any character can be inside a string, except for a double quote. Examples are: String str1 = " I love "; String str2 = " Java "; String str3 = str1 + str2 ; // is now " I lovejava " // str3 is called the " concatenation " of str1 and str2 int i1 = 3; str3 = str1 + i1; // has value " I love3 " However, there is another way to declare a String variable, and that is done using the Java keyword new: String str1 = new String (" I love "); // same as above String is the only Java class that can declare (also called instantiate ) a variable without the new keyword. All other Java classes must be instantiated with this keyword. Now we need to see what we can do with these String variables. As we covered in the last chapter, every Java class has one or more methods. The syntax for calling a method is: variable.methodname(optionalparameters) Note: we cannot call methods on primitive data types (see later chapters on classes and methods). Examples of various methods in Java for the String class are: String str1 = " I love Java "; /* String. touppercase () and tolowercase */ String upper = str1. touppercase (); // " I LOVE JAVA " String lower = str1. tolowercase (); // " i love java " /* String. replace ( char c, char d)*/ // Replaces all instances of c with d String repl = str1. replace ( a, p ); // "I love Jpvp " 13 // We can even chain method calls String myst = str1. replace ( a, p ). touppercase (); // "I LOVE JPVP " /* String. length () - int which is # of characters */ int len = str1. length (); // 11, since there are 11 characters /* String. charat ( int n) - gets the nth character */ // Strings are 0- indexed, so the first character is at index 0 // Error at runtime if input >= length () char firstchar = str1. charat (0) ; // has value I char secondchar = str1. charat (1) ; // has value char lastchar = str1. charat ( str. length () -1); // a /* String. substring ( int n, int m)*/ // gives a String that consists of index n through m, not inclusive on m String substr1 = str1. substring (0, 3); // " I lo" String substr2 = str1. substring (2, 6); // " love " /* String. equals ( String other )*/ // gives true ( boolean ) if the first String is exactly the same as the other boolean equal1 = substr1. equals ( substr2 ); // false boolean equal2 = " Equal ". equals (" Equal "); // true // We can also check for equality ignoring the case boolean equal3 = " Equal ". equalsignorecase (" equal "); // true /* String. indexof ( char c)*/ // Returns index ( int ) of the first instance of c; otherwise, -1 int found1 = str1. indexof ( o ); // 4 int found2 = str1. indexof ( f ); // -1 /* String. compareto ( String other )*/ // Returns int showing lexicographic ordering of strings according to ASCII table ( negative if first < second, 0 if equal, positive if first > second ) int c1 = "A". compareto ("B"); // negative int c2 = "A". compareto ("b"); // more negative, lowercase has higher ASCII value int c3 = "A". compareto ("A"); // 0 int c4 = "B". compareto ("A"); // positive Scanner Now that we know how to create and modify modify String variables, it is important to know how to get input from the user so that we can make our programs usable. For that, we use the Scanner class in the java.util package. 14 14 However, since this class is not in the package java.lang, we must import it from the Java library, by putting an import statement at the beginning of our file: import java. util. Scanner ; // import the Scanner class from the java. util package // Equivalent : import java. util.*; // import everything from this package public class SomeClass { //... So how do we use this class? We must initialize it with the new keyword: Scanner s = new Scanner ( System. in); // System. in means from the keyboard This code creates an variable (often called object in this case, since it is a class) in which we can call various methods on it to get input from the user. There are various ways of getting input from the user: Scanner s = new Scanner ( System. in); int x = s. nextint (); // the first integer entered by the user ( after pushing the enter / return key ) will be put into x // If an integer is not entered, then a run - time error will occur. double y = s. nextdouble (); // if a user enters a double String str1 = s. next (); // this is the next " word " ( does not include spaces ) String str2 = s. nextline (); // this is the entire line of characters before pressing the enter / return key 4.8 Math There is another class, called Math (in the java.lang package) that provides some useful functionalities: /* Square root */ double num1 = ; double d1 = Math. sqrt ( num1 ); /* PI - constant */ double pi = Math. PI; /* Math.{ min, max - minimum or maximum of 2 ints */ int num1 = 5, num2 = 3; int max = Math. max (num1, num2 ); // 5 // also can be: Math. max (num2, num1 ); int min = Math. min (num1, num2 ); // 3 /* Pow - take first double to power of second */ double d2 = 3.5, d3 = 4. 3; double d4 = Math. pow (d2, d3); // = 3.5^4.3 15 Written Exercises 1. Give the output of the following program: public class Example { public static void main ( String [] args ) { int y = 2, z = 1; z = y * 2; System. out. print (y + z); 2. What will be the output of the following program? public class Example { public static void main ( String [] args ) { String s = new String (" Arizona state university "); char ch1 = s. tolowercase (). touppercase (). charat (0) ; char ch2 = s. touppercase (). charat (8) ; char ch3 = s. touppercase (). charat (s. length () - 1); System. out. println ("ch 1 is: " + ch1 ); System. out. println ("ch 2 is: " + ch2 ); System. out. println ("ch 3 is: " + ch3 ); 3. What will be the output of the following program? public class Example { public static void main ( String [] args ) { int num1 = 4, num2 = 5; System. out. println ("4"+"5"); System. out. println ( num1 + num2 ); System. out. println (" num1 "+" num2 "); System. out. println (4+5) ; 4. Which of the following correctly invokes the method length() of the String variable str and stores the result in val of type int? int val = str. length (); int val = length. str (); int val = length ().str ; int val = length ( str ); 5. Evaluate each of the following expressions. String s = " Programming is Fun "; String t = " Workshop is cool "; System. out. println (s. charat (0) +t. substring (3, 4)); System. out. println (t. substring (7) ); 16 16 6. Evaluate each of the following expressions, assuming j is an int with value 11, k is an int with value 3, and s is a String with value Ford Rivers. j / k j % k s. substring (1, 5) s. length () s. charat (3) 7. True or False? The type String is a primitive data type. 8. True or False? The type char is a primitive data type. 9. Write the output of the following program: public class Question { public static void main ( String [] args ) { String str = " hello "; System. out. println (" abcdef ". substring (1, 3)); System. out. println (" pizza ". length ()); System. out. println ( str. replace ( h, m )); System. out. println (" hamburger ". substring (0, 3)); System. out. println ( str. charat (1) ); System. out. println ( str. equals (" hello ")); System. out. println (" pizza ". touppercase ()); System. out. println ( Math. pow (2, 4)); double num4 = Math. sqrt (16.0) ; System. out. println ( num4 ); 10. Write the output of the following program: public class Question { public static void main ( String [] args ) { String s1 = " Clinton, Hillary "; String s2 = new String (" Obama, Barack "); System. out. println (s1. charat (2) ); System. out. println (s1. charat (s1. length () -1)); System. out. println (s2. touppercase ()); System. out. println (s2. substring ( s2. indexof (",")+2, s2. length ()); 11. What value is contained in the int variable length after the following statements are executed? length = 2; length *= 9; length -= 6; 12. What is the result of 2/4 when evaluated in Java? Why? 17 Programming Exercises 1. Write a Java program that asks the user for the radius of a circle and finds the area of the circle. 2. Write a Java program that prompts the user to enter 2 integers. Print the smaller of the 2 integers. 18 18 Decisions Note: all code snippets from here on are assumed to be in a main method (they will not compile if not). 5.1 Motivation We now know basic data types and how to use them. Now, we will see how to execute conditional code based on values. We will cover if, if-else, and switch statements. 5.2 If Statements Suppose we were given a task of printing True only when a value entered by the user was larger than another value. Currently, we do not know of a way to do this. Therefore, we have if statements. They have the form: if(condition){... where... means other lines of code, and condition is evaluated to a boolean value. The rule for if statements is: if the condition evaluates to true, then the code between the braces is executed; if false, then it is not executed. If we have one line of code that will be executed in the if statement, then the braces are optional: int x = 8; if (x > 7) System. out. print (" This one line "); However, the second line after the if statement in the following example will not execute as if it were in the if statement, even though it is indented: int x = 8; if (x > 7) System. out. print (" This one line "); System. out. println (" What about this line?"); The above code is functionally equivalent to: int x = 8; if (x > 7) { System. out. print (" This one line "); System. out. println (" What about this line?"); // always prints To fix this, we add braces: int x = 8; if (x > 7) { System. out. print (" This one line "); System. out. println (" What about this line?"); 19 and therefore, both lines will print if the condition evaluates to true (which it does in this case). Now suppose we want to execute some code when the condition is true, and some other code when the condition is false (and only when it is false). Therefore, we need an if-elsestatement, which is of the form: if(condition){...else{... If the condition is false, then the code in the else section will automatically execute, and the code in the if section will not. If the condition is true, then the else section will not execute, and the if section will. Suppose we have been given a task of printing true if the user s input is greater than or equal to 8, and false otherwise. Our code then will look like: Scanner s = new Scanner ( System. in); int input = s. nextint (); if ( input >= 8) { System. out. print (" true "); else { System. out. print (" false "); We can even chain multiple if-else statements together (and even nested ones!): Scanner s = new Scanner ( System. in); int input = s. nextint (); if ( input >= 8) { if ( input == 8) { System. out. print (" Equal to 8"); else { System. out. print (" Larger than 8"); else if ( input >= 4) { if ( input == 4) { System. out. print (" Equal to 4"); else { System. out. print (" Larger than 4, < 8"); else { System. out. print (" Less than 4"); Switch Statements An alternative to if-else statements are switch statements, because if-else statements can be very complex and lengthy. A switch statement structure consists of 1 or more case statements (with an optional default case). The programmer supplies a switch statement with a value: switch ( value ) { //... 20 20 where value is a primitive type or a String (Note: String is only allowed in later versions of Java). For each of the case statements, value is compared to the value supplied in the case statement (see form below). Only if they are equal will the code after the case statement be executed. Each case statement is of the form: case value: /* statements */. At the end of the code section for a case statement, an optional break; statement is allowed. However, not putting this statement at the end of the code section for the case statement will immediately execute the next case statement, regardless of the value. An optional default: case statement at the end of the switch block is allowed, which is executed if the input value is not equal to any other case statement s value. For example, if we were to print 1 if the input value is equal to 1, and 2 if equal to 2, and ignore any other inputs, our code might look like: Scanner s = new Scanner ( System. in); int input = s. nextint (); switch ( input ) { case 1: System. out. print ("1"); break ; case 2: System. out. print ("2"); break ; Now, if we remove the break statements: Scanner s = new Scanner ( System. in); int input = s. nextint (); switch ( input ) { case 1: System. out. print ("1"); case 2: System. out. print ("2"); this code will output 12 if the input is 1, and 2 if the input is 2, which is not the behavior we might want. This is because we removed the break statements, and so the code flows through until it hits a break statement. What a break statement does is exit the switch statement altogether. On the other hand, if we want to add the requirement of printing other if we have any other value than 1 or 2, then we use a default statement: Scanner s = new Scanner ( System. in); int input = s. nextint (); switch ( input ) { case 1: System. out. print ("1"); break ; case 2: System. out. print ("2"); break ; 21 default : System. out. print (" other "); break ; We can see that this code can be constructed in an if-else statement fashion. However, sometimes switch and case statements are easier to understand and read. 5.4 Written Exercises 1. What is the output of the following code? int depth = 30; if ( depth >= 29) { System. out. print (" Bigger than 8!"); System. out. print (" Don t swim!"); System. out. println ("Yes, you can swim."); 2. What is the output of the following code? int mystery1 = 12; int mystery2 = 42; System. out. print (" You have : "); if ( mystery1 >= 8) System. out. print ("1 "); if ( mystery2 <= 50 && mystery1 <= 12) System. out. print ("2 "); System. out. println ("3."); 3. If k holds a value of the type int, then the value of the expression: k <= 10 k > 10 a) must be true b) must be false c) could be either true or false d) is a value of type int 4. For the following code, fill in the missing condition to check if str1 and str2 are the same. String str1 = " Java is fun "; String str2 = " Java is fun "; if ( /* */ ) System. out. println (" String1 and String2 are the same "); else System. out. println (" String1 and String2 are different "); 5. Evaluate the following expressions, assuming that x = -2 and y = 3. x <= y (x < 0) (y < 0) (x <= y) && (x < 0) ((x + y) > 0) &&!(y > 0) 21 22 22 6. Write the output of the following code: int grade = 45; if ( grade >= 70) System. out. println (" passing "); if ( grade < 70) System. out. println (" dubious "); if ( grade < 60) System. out. println (" failing "); 7. Write the output of the following code: String option = "A"; if ( option. equals ("A")) System. out. println (" addrecord "); if ( option. compareto ("A") == 0) System. out. println (" deleterecord "); 8. Write the output of the following code: double x = -1.5; if (x < -1.0) System. out. println (" true "); else System. out. println (" false "); System. out. println (" after if... else "); 9. Write the output of the following code: int j = 8; double x = -1.5; if (x >= j) System. out. println ("x is high "); else System. out. println ("x is low "); 10. Write the output of the following code: double x = -1.5; if (x <= 0.0) { if (x < 0.0) System. out. println (" neg "); else System. out. println (" zero "); else System. out. println (" pos "); 5.5 Programming Exercises 1. Write a program that asks for 3 integers and prints the median value of the 3 integers, using only if statements. 23 2. Write code that ensures that an int variable called number is an odd integer. 23 24 24 Loops 6.1 Motivation With the last chapter, we now know how to execute conditional code. This chapter will greatly increase our powers in what we can do with programming, by being able to execute code many times without having to re-write (or copy and paste) code over and over. 6.2 Introduction to Loops Loops are a way of executing some code an arbitrary number of times. What determines the number of times a loop executes is based largely on a condition, just like if and switch statements were. There are 3 kinds of loops in Java: while loops do-while loops for loops 6.3 While loops while loops are the simplest to understand kind of loop. The structure of one is: while(condition){... The semantics are: the loop will continue as long as the condition evaluates to true. The main reason while loops are used is that we may not know the number of times looping occurs. If we do, we usually use a for loop (see below). However, both while and for loops can be converted back and forth. For example, let s say we are given a task of displaying a positive integer that the user enters, and continue doing so until the user enters 0. Setting up is easy: Scanner s = new Scanner ( System. in); while (/* something */) { // somehow take user input and display it Let s initialize an int variable, initialized to the first input a user gives: Scanner s = new Scanner ( System. in); System. out. println (" Enter an integer :"); int input = s. nextint (); while (/* something */) { // somehow take user input and display it Now, we need to create the condition for the while loop. We stop after the user enters 0, so let s make that condition (and display it): 25 Scanner s = new Scanner ( System. in); System. out. println (" Enter an integer :"); int input = s. nextint (); while ( input!= 0) { System. out. println ( input ); // anything else go here? This code seems good, but unfortunately we can encounter what is called an infinite loop, which does not stop looping. If we enter a non-zero integer, then we print that output. Then since there is nothing else to do in the loop body, we check the condition again, which evaluates to true, prints out, loops back, prints out, etc. We need to get the user input again at the end of the loop: Scanner s = new Scanner ( System. in); System. out. println (" Enter an integer :"); int input = s. nextint (); while ( input!= 0) { System. out. println ( input ); System. out. println (" Enter another integer :"); input = s. nextint (); // avoid infinite loop Now our solution code for the example is correct Do-While loops do-while loops are the same as while loops, but guarantee that the loop body will be executed at least once. Remember our earlier while loop example: if we initially entered 0, then the loop s condition evaluates to false, and does not execute the body. Therefore, it loops 0 times. The structure of a do-while loop is: do{...while(condition); Note: the semicolon after the last parentheses of the while s condition is necessary. For example, if we modify our example from above to be a do-while loop, we guarantee that the user must enter at least one integer: Scanner s = new Scanner ( System. in); System. out. println (" Enter an integer :"); int input = s. nextint (); do { System. out. println ( input ); System. out. println (" Enter another integer :"); input = s. nextint (); // avoid infinite loop while ( input!= 0); 6.5 For loops for loops are used when we know precisely how many times the loop will execute. However, they are equivalent in functionality to while loops (i.e. one can construct a for loop from a while loop, and vice versa). All for loops have the same structure: 26 26 f or(initialization; condition; modif ication){... Initialization - creating a variable, usually called the loop control variable. Condition - checking a condition, usually related to the loop control variable, against some value. The loop will continue to iterate (and do the modification step) as long as the condition is true. Modification - modify, usually the loop control variable, at each iteration of the loop. For example, let s say we are given the problem of summing all of the integers from 1 to n, where n is an integer 1. An example solving this problem is the following: Scanner s = new Scanner ( System. in); int n = s. nextint (); int sum = 0; // put some kind of for loop here System. out. println ( sum ); Now we need to reason how to construct our for loop. Let s initialize a loop control variable, called i, to be 1. Then, for each iteration of the loop, add i to sum, and at each iteration, add 1 to i. An unraveling of the loop s logic will be this: sum = 0. 1st iteration of loop: i = 1, add to sum, sum = 1, add 1 to i (i = 2). 2nd iteration of loop: i = 2, add to sum, sum = 3, add 1 to i (i = 3). 3rd iteration of loop: i = 3, add to sum, sum = 6, add 1 to i (i = 4). and so on. By this logic, we want the loop to stop at n, inclusive. So, we need to have a condition of i <= n. And on each loop, we execute i++. Therefore, our final code will be: Scanner s = new Scanner ( System. in); int n = s. nextint (); int sum = 0; for ( int i =1; i <=n; i ++) { sum += i; // add to sum System. out. println ( sum ); 6.6 Loop Example In many programming interviews, there are questions designed to test one s knowledge of loops. One of them is called FizzBuzz. The idea is this: print Fizz if the number is divisible by 3, Buzz if the number is divisible by 5, FizzBuzz if the number is divisible by 3 and 5 (i.e., 15), and nothing otherwise. Now, we want the user to input an integer n, and from 1 to n, we want to print the appropriate value. We start with a setup of our program: public class FizzBuzz { public static void main ( String [] args ) { // something goes here... 27 Now we need to add appropriate code to get an integer n from the user: import java. util. Scanner ; public class FizzBuzz { public static void main ( String [] args ) { Scanner s = new Scanner ( System. in); int n = s. nextint (); // get the integer Since we know the number of loop iterations (i.e., n), we can just use a for loop to iterate from 1 to n: import java. util. Scanner ; public class FizzBuzz { public static void main ( String [] args ) { Scanner s = new Scanner ( System. in); int n = s. nextint (); // get the integer for ( int i = 1; i <= n; i ++) { // what else? Now we just need to insert an if and else statements to check if n is divisible by 3, 5, or 15 (and then print the appropriate value). However, we cannot just do this: import java. util. Scanner ; public class FizzBuzz { public static void main ( String [] args ) { Scanner s = new Scanner ( System. in); int n = s. nextint (); // get the integer for ( int i = 1; i <= n; i ++) { if (i % 3 == 0) { System. out. println (" Fizz "); else if ( i % 5 == 0) { System. out. println (" Buzz "); else if ( i % 15 == 0) { System. out. println (" FizzBuzz "); The last clause will never be reached. If i is divisible by 15, then it is divisible by 3 or 5 as well. Therefore, it would have went inside one of the other conditionals. Therefore, we just need to move it to be the first conditional: import java. util. Scanner ; public class FizzBuzz { public static void main ( String [] args ) { Scanner s = new Scanner ( System. in); 27 28 28 int n = s. nextint (); // get the integer for ( int i = 1; i <= n; i ++) { if (i % 15 == 0) { System. out. println (" FizzBuzz "); else if ( i % 3 == 0) { System. out. println (" Fizz "); else if ( i % 5 == 0) { System. out. println (" Buzz "); There are other ways to do this - for example, we can just have the last 2 conditionals, but use print instead of println, and then add a newline afterwards. 6.7 Written Exercises 1. What are the 3 kinds of loops in Java? 2. What is the output of the following loop? How many times does the loop execute? int n = 979; for ( int j = 0; j <= n; j ++) { System. out. println (" Hello "); 3. What is the output of the following loop? How many times does the loop execute? int j = 1; int n = 5; while (j <= n) { System. out. println (" Hello "); n - -; 4. What is the output of the following loop? How many times does the loop execute? int n = 5; for ( int j = 1; j <= n; j += 3) { System. out. print (" Hello "); int k = j; while (k < n) { System. out. println (" Good Morning "); k ++; j - -; 5. What is the output of the following code? 29 29 String name = " Richard M. Nixon "; boolean startword = true ; for ( int i = 0; i < name. length (); i ++) { if ( startword ) System. out. println ( name. charat (i)); if ( name. charat (i) == ) startword = true ; else startword = false ; 6. What is the output of the following loop? How many times does the loop execute? int j = 1; while (j <= 11) { System. out. println (" Hello "); j = j + 3; 7. What is the output of the following code? int n = 1, i = 1; while (i < 7) { n = n * i; i += 2; System. out. print (n); 6.8 Programming Exercises 1. Write a loop that reads in int values until the user enters 0 and prints out how many values entered are greater than Write a loop that will print out every other letter in a String variable called str. For example, if the String was Hello There, then HloTee will be printed. 30 30 Introduction to Classes 7.1 Motivation Now that we understand how loops work, we want to be able to create our own classes! Just like the ones that we have been using, such as Scanner, String, Math, and others. 7.2 Class Structure A class follows the same format as we have been for our main programs. However, there does not have to be a main method in a class. The only requirement for main is that the class we run a program from contains a main method. A class contains what are called instance variables, a constructor, and 1 or more methods. But before we can talk about these, we need to cover visibility modifiers. 7.3 Visibility Modifiers We have been using public when we create our programs so far. Now we will cover what this means, and what other visibility modifiers are. They are, for any variable/method/class: public - any class can see it. private - only the class that contains it can see it. protected - only the class that contains it and any children that inherit from it can see it. Do not worry about this visibility modifier - we will not use it in this chapter. 7.4 Instance Variables Instance variables are variables that exist inside a class when they are created. We usually write instance variables to have a visibility of private, to enforce what is called encapsulation, which means that we hide data (the instance variables) that we do not want outsiders to change. For example, let s create a BankAccount class: public class BankAccount { In order to make an instance of the class, we need to create a constructor for the class, which executes code inside it when we use the new operator on the class, in the exact same way that we have used it for other Java-provided classes. Notes about the constructor: No return type Optional parameters Any number of constructors allowed as long as they differ in signature (number of arguments or different types of arguments). 31 The default constructor with no arguments is provided by Java if none is provided by the programmer. For example, let s modify our BankAccount class that has the name of the person with the account, and a starting balance. When we initialize our BankAccount object in the main method, we will use the new operator, which passes in the values supplied to name and startamount below: public class BankAccount { // visibility of public - need to see outside of class public BankAccount ( String name, double startamount ) { Now what do we do with these parameters? We need a way of saving them inside the class for later use. That is where instance variables come in. Let s create our instance variables with public visibility for now: public class BankAccount { public String personname ; public double balance ; // visibility of public - need to see outside of class public BankAccount ( String name, double startamount ) { personname = name ; // set name balance = startamount ; // set amount // optional : use this operator // this. personname = name ; // this references the BankAccount class when inside the class, and what comes after the dot references the instance variable with that name And in our main (or other that instantiates a BankAccount object) method: public class BankAccountTest { public static void main ( String [] args ) { BankAccount b = new BankAccount (" Jane ", 0. 0) ; Since we have declared our instance variables as public, we can modify the corresponding values of our instance to anything we want by using the dot operator, in the same way we use Math.PI on the Math class: public class BankAccountTest { public static void main ( String [] args ) { BankAccount b = new BankAccount (" Jane ", 0. 0) ; b. personname = " Another Name "; b. balance = ; 31 32 32 We can clearly see why this is not preferred. Therefore, we need to mark the visibility of our instance variables as private (and the operations above will result in a compile-time error): public class BankAccount { private String personname ; private double balance ; public BankAccount ( String name, double startamount ) { personname = name ; // set name balance = startamount ; // set amount This is a good start, but we want to be able to deposit or withdraw some amount into balance. Therefore, we need to use setters (also called mutators ) and getters (also called accessors ). Setters are about changing some internal value to a passed-in value, and getters are about getting internal values back to the user: public class BankAccount { private String personname ; private double balance ; public BankAccount ( String name, double startamount ) { personname = name ; // set name balance = startamount ; // set amount /* Getters have the form : public < Type > get < NameOfVar >() { return <NameOfVar >; */ // get the current balance public double getbalance () { return balance ; /* Setters have the form : public void set < NameOfVar >( < Type > other ) { < Instance Var > = other ; */ // set the balance to the input public void setbalance ( double other ) { 33 balance = other ; But this introduces the same problem as earlier - we can make our balance be any value we want. Therefore, we should get rid of the setter, and introduce a deposit method, which adds to the balance with the input. We can leave the getter because it does not modify the value of balance. public class BankAccount { private String personname ; private double balance ; public BankAccount ( String name, double startamount ) { personname = name ; // set name balance = startamount ; // set amount // get the current balance public double getbalance () { return balance ; public void deposit ( double amount ) { balance += amount ; And in main, we can use these methods accordingly: public class BankAccountTest { public static void main ( String [] args ) { BankAccount b = new BankAccount (" Jane ", 0. 0) ; b. deposit (50.0) ; System. out. print (b. getbalance ()); Notes about classes: A method (terminology to be covered in the next chapter) called tostring, which returns a String, is commonly implemented among programmer-created classes. The returned String is a textual description of the state of the class and instance variables. For instance, we could use our BankAccount class and create a tostring method that returns: Name: Jane Balance: 50.0 with the following code: public String tostring () { // return textual description String toreturn = ""; 33 34 34 toreturn += " Name : " + personname ; toreturn += "\n"; toreturn += " Balance : " + balance ; return toreturn ; And when the object is printed out, even without calling.tostring(), the textual description will be printed: // in main BankAccount b =...; System. out. print ( b); // calls tostring () automatically // equivalent to: System. out. print (b. tostring ()); Note: Not providing a tostring() method in a class, when printing an instance, will print a hash value (i.e. random letters and numbers) instead of what is expected, along with the name of the class. 7.5 Written Exercises 1. Which of the following enforces Encapsulation? a) Make instance variables private b) Make methods public c) Make the class final d) Both a and b e) All of the above 2. Use the following class to answer the questions below: public class Store { private int quantity ; private double price ; public Store ( int q, double p) { quantity = q; price = p; public int getquantity () { return quantity ; public void setprice ( double p) { price = p; public double calctotal () { return price * quantity ; 35 a) What is the name of the class? b) List all instance variables of the class. c) List all methods of the class. d) List all mutators in the class. e) List all accessors in the class. f) List which method is the constructor. 3. True or False? If no constructor is provided, then Java automatically provides a default constructor. 4. True or False? A method must have at least 1 return statement Programming Exercises 1. For the Store class in the Written Exercises above, do the following: a) Write a mutator for the quantity. b) Write an accessor for the price. c) Write a line of code that will create an instance called videostore that has quantity 100 and a price of d) Call the calctotal method with the videostore object (from part c) to print out the total. 2. Correct the following class definition if you think it will not work: public class Student { private String name, major ; public Student () { name = "??? "; major = " xxx "; public Student ( String n, String m) { n = name ; m = major ; public String getmajor () { return m; public String getname () { return n; 3. Implement a class called AsuStudent. The class should keep track of the student s name, number of classes registered, hours spent per week for a class (consider a student devotes the same amount of time for each of his/her classes per week). Implement a tostring method to show the name and number of classes registered by a student, a getname method to return the name of the student, a gettotalhours method to return the total number of hours per week, and a sethours method to set the number of hours the student devotes for each class. Introduction to Java Applications. 2005 Pearson Education, Inc. All rights reserved. 1 2 Introduction to Java Applications 2.2 First Program in Java: Printing a Line of Text 2 Application Executes when you use the java command to launch the Java Virtual Machine (JVM) Sample program Displays Introduction to Java Introduction to Java The HelloWorld program Primitive data types Assignment and arithmetic operations User input Conditional statements Looping Arrays CSA0011 Matthew Xuereb 2008 1 Java Overview A high Computer Programming I Computer Programming I COP 2210 Syllabus Spring Semester 2012 Instructor: Greg Shaw Office: ECS 313 (Engineering and Computer Science Bldg) Office Hours: Tuesday: 2:50 4:50, 7:45 8:30 Thursday: 2:50 4:50, Moving from CS 61A Scheme to CS 61B Java Moving from CS 61A Scheme to CS 61B Java Introduction Java is an object-oriented language. This document describes some of the differences between object-oriented programming in Scheme (which we hope) CS 106 Introduction to Computer Science I CS 106 Introduction to Computer Science I 01 / 21 / 2014 Instructor: Michael Eckmann Today s Topics Introduction Homework assignment Review the syllabus Review the policies on academic dishonesty and improper: Elements of Java Chapter 2: Elements of Java Basic components of a Java program Primitive data types Arithmetic expressions Type casting. The String type (introduction) Basic I/O statements Importing packages. 1 Introduction Lecture Set 2: Starting Java Lecture Set 2: Starting Java 1. Java Concepts 2. Java Programming Basics 3. User output 4. Variables and types 5. Expressions 6. User input 7. Uninitialized Variables CMSC 131 - Lecture Outlines - set Install Java Development Kit (JDK) 1.8 CS 259: Data Structures with Java Hello World with the IntelliJ IDE Instructor: Joel Castellanos e-mail: joel.unm.edu Web: Office: Farris Engineering Center 319 8/19/2015 Install Introduction to Java. CS 3: Computer Programming in Java Introduction to Java CS 3: Computer Programming in Java Objectives Begin with primitive data types Create a main class with helper methods Learn how to call built-in class methods and instance methods Chapter 2: Problem Solving Using C++ Chapter 2: Problem Solving Using C++ 1 Objectives In this chapter, you will learn about: Modular programs Programming style Data types Arithmetic operations Variables and declaration statements Common Introduction to C Programming Introduction to C Programming C HOW TO PROGRAM, 6/E 1992-2010 by Pearson Education, Inc. All Rights Reserved. 2.1 Introduction The C language facilitates a structured and disciplined approach to computer Java Review (Essentials of Java for Hadoop) Java Review (Essentials of Java for Hadoop) Have You Joined Our LinkedIn Group? What is Java? Java JRE - Java is not just a programming language but it is a complete platform for object oriented programming. Java Subset APPENDIX A AP Computer Science Java Subset The AP Java subset is intended to outline the features of Java that may appear on the AP Computer Science A Exam. The AP Java subset is NOT intended as an. Lecture 5: Java Fundamentals III Lecture 5: Java Fundamentals III School of Science and Technology The University of New England Trimester 2 2015 Lecture 5: Java Fundamentals III - Operators Reading: Finish reading Chapter 2 of the 2, 6.1. Example: A Tip Calculator 6-1 Chapter 6. Transition to Java Not all programming languages are created equal. Each is designed by its creator to achieve a particular purpose, which can range from highly focused languages designed for CS 111 Classes I 1. Software Organization View to this point: CS 111 Classes I 1 Software Organization View to this point: Data Objects and primitive types Primitive types operators (+, /,,*, %). int, float, double, char, boolean Memory location holds the data Objects A First Book of C++ Chapter 2 Data Types, Declarations, and Displays A First Book of C++ Chapter 2 Data Types, Declarations, and Displays Objectives In this chapter, you will learn about: Data Types Arithmetic Operators Variables and Declarations Common Programming Errors C CS 1124, Media Computation November 10, 2008 Steve Harrison Introduction to Java CS 1124, Media Computation November 10, 2008 Steve Harrison DrJava? DrJava is a free integrated development environment for doing Java programming From Rice University It is written Java Interview Questions and Answers 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write and compile the java Java Programming Fundamentals Lecture 1 Part I Java Programming Fundamentals Topics in Quantitative Finance: Numerical Solutions of Partial Differential Equations Instructor: Iraj Kani Introduction to Java We start by making a few Java CPD (I) Frans Coenen Department of Computer Science Java CPD (I) Frans Coenen Department of Computer Science Content Session 1, 12:45-14:30 (First Java Programme, Inheritance, Arithmetic) Session 2, 14:45-16:45 (Input and Programme Constructs) Materials Example of a Java program Example of a Java program class SomeNumbers static int square (int x) return x*x; public static void main (String[] args) int n=20; if (args.length > 0) // change default n = Integer.parseInt(args[0]); ,, Part I. Multiple Choice Questions (2 points each): Part I. Multiple Choice Questions (2 points each): 1. Which of the following is NOT a key component of object oriented programming? (a) Inheritance (b) Encapsulation (c) Polymorphism (d) Parallelism ****** Iteration CHAPTER 6. Topic Summary CHAPTER 6 Iteration TOPIC OUTLINE 6.1 while Loops 6.2 for Loops 6.3 Nested Loops 6.4 Off-by-1 Errors 6.5 Random Numbers and Simulations 6.6 Loop Invariants (AB only) Topic Summary 6.1 while Loops Many Learn the Java Programming Language Learn the Java Programming Language This portion of my site is dedicated to teach the basics of the Java programming language. It is geared towards non-programmers so if you already have some programming Chapter 3. Input and output. 3.1 The System class Chapter 3 Input and output The programs we ve looked at so far just display messages, which doesn t involve a lot of real computation. This chapter will show you how to read input from the keyboard, use, Variables, Constants, and Data Types Variables, Constants, and Data Types Primitive Data Types Variables, Initialization, and Assignment Constants Characters Strings Reading for this class: L&L, 2.1-2.3, App C 1 Primitive Data There are eight Java: Primitive Data Types, Variables and Constants Java: Primitive Data Types, Variables and Constants Introduction A primitive data type is a data type provided as a basic building block by a programming language. It is predefined by the programming language Introduction to Python WEEK ONE Introduction to Python Python is such a simple language to learn that we can throw away the manual and start with an example. Traditionally, the first program to write in any programming CS-201 Introduction to Programming with Java CS-201 Introduction to Programming with Java California State University, Los Angeles Computer Science Department Lecture I: Introduction to Computers, Programs, and Java Basic Computer Architecture: Binary CSCE 111 Exam 1 TRUE/FALSE CSCE 111 Exam 1 FORM B TRUE/FALSE 1. Java runs differently on different CPU architectures. F 2. A declared variable is always visible to the entire method in which it is declared. F 3. Because the operator Overview of a C Program Overview of a C Program Programming with C CSCI 112, Spring 2015 Patrick Donnelly Montana State University Programming with C (CSCI 112) Spring 2015 2 / 42 C Language Components Preprocessor Directives A Quick and Dirty Overview of Java and. Java Programming Department of Computer Science New Mexico State University. CS 272 Fall 2004 A Quick and Dirty Overview of Java and.......... Java Programming Enrico Pontelli and Karen Villaverde . Introduction Objectives Chapter 1: Introducing Java Chapter 1: Introducing Java 1. What is Java? Java is a programming language offering many features that make it attractive for mathematical illustration. First, it is a high-level language providing a Java Application Developer Certificate Program Competencies Java Application Developer Certificate Program Competencies After completing the following units, you will be able to: Basic Programming Logic Explain the steps involved in the program development cycle 1001ICT Introduction To Programming Lecture Notes 1001ICT Introduction To Programming Lecture Notes School of Information and Communication Technology Griffith University Semester 2, 2015 1 3 A First MaSH Program In this section we will describe a very A Comparison of the Basic Syntax of Python and Java Python Python supports many (but not all) aspects of object-oriented programming; but it is possible to write a Python program without making any use of OO concepts. Python is designed to be used interpretively. Fundamentals of Java Programming Fundamentals of Java Programming This document is exclusive property of Cisco Systems, Inc. Permission is granted to print and copy this document for non-commercial distribution and exclusive use by instructors Quick Introduction to Java Quick Introduction to Java Dr. Chris Bourke Department of Computer Science & Engineering University of Nebraska Lincoln Lincoln, NE 68588, USA Email: cbourke@cse.unl.edu 2015/10/30 20:02:28 Abstract These Visual Logic Instructions and Assignments Visual Logic Instructions and Assignments Visual Logic can be installed from the CD that accompanies our textbook. It is a nifty tool for creating program flowcharts, but that is only half of the story. Pemrograman Dasar. Basic Elements Of Java Pemrograman Dasar Basic Elements Of Java Compiling and Running a Java Application 2 Portable Java Application 3 Java Platform Platform: hardware or software environment in which a program runs. Oracle Introduction to C++ Programming Introduction to C++ Programming 1 Outline Introduction to C++ Programming A Simple Program: Printing a Line of Text Another Simple Program: Adding Two Integers Memory Concepts Arithmetic Decision Making: java Features Version April 19, 2013 by Thorsten Kracht java Features Version April 19, 2013 by Thorsten Kracht Contents 1 Introduction 2 1.1 Hello World................................................ 2 2 Variables, Types 3 3 Input/Output 4 3.1 Standard I/O................................................ Student Workbook for Murach s Java SE 6 Student Workbook for Murach s Java SE 6 Introduction for students... ii Chapter 1...1 Chapter 2...6 Chapter 3...14 Chapter 4...22 Chapter 5...29 Chapter 6...38 Chapter 7...47 Chapter 8...56 Chapter 9...65 Punctuation in C. Identifiers and Expressions. Identifiers. Variables. Keywords. Identifier Examples Identifiers and Expressions CSE 130: Introduction to C Programming Spring 2005 Punctuation in C Statements are terminated with a ; Groups of statements are enclosed by curly braces: { and } Commas separate ( Exercise 4 Learning Python language fundamentals Exercise 4 Learning Python language fundamentals Work with numbers Python can be used as a powerful calculator. Practicing math calculations in Python will help you not only perform these tasks, but also Lecture 2 Notes: Flow of Control 6.096 Introduction to C++ January, 2011 Massachusetts Institute of Technology John Marrero Lecture 2 Notes: Flow of Control 1 Motivation Normally, a program executes statements from first to last. Lecture 1 Introduction to Java Programming Languages: Java Lecture 1 Introduction to Java Instructor: Omer Boyaci 1 2 Course Information History of Java Introduction First Program in Java: Printing a Line of Text Modifying Our First Syllabus for CS 134 Java Programming - Java Programming Syllabus Page 1 Syllabus for CS 134 Java Programming Computer Science Course Catalog 2000-2001: This course is an introduction to objectoriented programming using the Java language. Strings. Java Primer Strings-1 Scott MacKenzie. String greeting; Strings Is a string an object or a primitive data type? This question has a clear answer a string is an object! however, the way strings typically appear in Java programs can lead to confusion. There are JAVA PRIMITIVE DATA TYPE JAVA PRIMITIVE DATA TYPE Description Not everything in Java is an object. There is a special group of data types (also known as primitive types) that will be used quite often in programming. For performance Computer Programming I Computer Programming I Levels: 10-12 Units of Credit: 1.0 CIP Code: 11.0201 Core Code: 35-02-00-00-030 Prerequisites: Secondary Math I, Keyboarding Proficiency, Computer Literacy requirement (e.g. Exploring PHP Tutorial From beginner to master PHP Tutorial From beginner to master PHP is a powerful tool for making dynamic and interactive Web pages. PHP is the widely-used, free, and efficient alternative to competitors such as Microsoft's ASP. SL-110: Fundamentals of Java Revision 15 October Sun Educational Services Instructor-Led Course Description Sun Educational Services Instructor-Led Course Description Fundamentals of Java SL-110 The Fundamentals of the Java course provides students, with little or no programming experience, with the basics of JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system. JAVA - QUICK GUIDE Copyright tutorialspoint.com What is Java? Java is: Object Oriented Platform independent: Simple Secure Architectural-
http://docplayer.net/18042927-Introduction-to-java-lecture-notes-ryan-dougherty-redoughe-asu-edu.html
CC-MAIN-2019-04
refinedweb
10,608
64.3
Mistakes”. Here is a link to the full documentation for pdb: In this article, you will familiarize yourself with the basics of using pdb. Specifically, you will learn the following: - Starting pdbin the REPL - Starting pdbon the Command Line - Stepping Through Code - Adding Breakpoints in pdb - Creating a Breakpoint with set_trace() - Using the built-in breakpoint()Function - Getting Help While pdb is handy, most Python editors have debuggers with more features. You will find the debugger in PyCharm or WingIDE to have many more features, such as auto-complete, syntax highlighting, and a graphical call stack. A call stack is what your debugger will use to keep track of function and method calls. When possible, you should use the debugger that is included with your Python IDE as it tends to be a little easier to understand. However, there are times where you may not have your Python IDE, for example when you are debugging remotely on a server. It is those times when you will find pdb to be especially helpful. Let’s get started! Starting pdb in the REPL The best way to start is to have some code that you want to run pdb on. Feel free to use your own code or a code example from another article on this blog. Or you can create the following code in a file named debug_code.py: # debug_code.py def log(number): print(f'Processing {number}') print(f'Adding 2 to number: {number + 2}') def looper(number): for i in range(number): log(i) if __name__ == '__main__': looper(5) There are several ways to start pdb and use it with your code. For this example, you will need to open up a terminal (or cmd.exe if you’re a Windows user). Then navigate to the folder that you saved your code to. Now start Python in your terminal. This will give you the Python REPL where you can import your code and run the debugger, pdb. Here’s how: >>> import debug_code >>> import pdb >>> pdb.run('debug_code.looper(5)') > <string>(1)<module>() (Pdb) continue Processing 0 Adding 2 to number: 2 Processing 1 Adding 2 to number: 3 Processing 2 Adding 2 to number: 4 Processing 3 Adding 2 to number: 5 Processing 4 Adding 2 to number: 6 The first two lines of code import your code and pdb. To run pdb against your code, you need to use pdb.run() and tell it what to do. In this case, you pass in debug_code.looper(5) as a string. When you do this, the pdb module will transform the string into an actual function call of debug_code.looper(5). The next line is prefixed with (Pdb). That means you are now in the debugger. Success! To run your code in the debugger, type continue or c for short. This will run your code until one of the following happens: - The code raises an exception - You get to a breakpoint (explained later on in this article) - The code finishes In this case, there were no exceptions or breakpoints set, so the code worked perfectly and finished execution! Starting pdb on the Command Line An alternative way to start pdb is via the command line. The process for starting pdb in this manner is similar to the previous method. You still need to open up your terminal and navigate to the folder where you saved your code. But instead of opening Python, you will run this command: python -m pdb debug_code.py When you run pdb this way, the output will be slightly different: > /python101code/chapter26_debugging/debug_code.py(1)<module>() -> def log(number): (Pdb) continue Processing 0 Adding 2 to number: 2 Processing 1 Adding 2 to number: 3 Processing 2 Adding 2 to number: 4 Processing 3 Adding 2 to number: 5 Processing 4 Adding 2 to number: 6 The program finished and will be restarted > /python101code/chapter26_debugging/debug_code.py(1)<module>() -> def log(number): (Pdb) exit The 3rd line of output above has the same (Pdb) prompt that you saw in the previous section. When you see that prompt, you know you are now running in the debugger. To start debugging, enter the continue command. The code will run successfully as before, but then you will see a new message: The program finished and will be restarted The debugger finished running through all your code and then started again from the beginning! That is handy for running your code multiple times! If you do not wish to run through the code again, you can type exit to quit the debugger. Stepping Through Code Stepping through your code is when you use your debugger to run one line of code at a time. You can use pdb to step through your code by using the step command, or s for short. Following is the first few lines of output that you will see if you step through your code with pdb: $ python -m pdb debug_code.py > /python101code/chapter26_debugging/debug_code.py(3)<module>() -> def log(number): (Pdb) step > /python101code/chapter26_debugging/debug_code.py(8)<module>() -> def looper(number): (Pdb) s > /python101code/chapter26_debugging/debug_code.py(12)<module>() -> if __name__ == '__main__': (Pdb) s > /python101code/chapter26_debugging/debug_code.py(13)<module>() -> looper(5) (Pdb) The first command that you pass to pdb is step. Then you use s to step through the following two lines. You can see that both commands do exactly the same, since “s” is a shortcut or alias for “step”. You can use the next (or n) command to continue execution until the next line within the function. If there is a function call within your function, next will step over it. What that means is that it will call the function, execute its contents, and then continue to the next line in the current function. This, in effect, steps over the function. You can use step and next to navigate your code and run various pieces efficiently. If you want to step into the looper() function, continue to use step. On the other hand, if you don’t want to run each line of code in the looper() function, then you can use next instead. You should continue your session in pdb by calling step so that you step into looper(): (Pdb) s --Call-- > /python101code/chapter26_debugging/debug_code.py(8)looper() -> def looper(number): (Pdb) args number = 5 When you step into looper(), pdb will print out --Call-- to let you know that you called the function. Next you used the args command to print out all the current args in your namespace. In this case, looper() has one argument, number, which is displayed in the last line of output above. You can replace args with the shorter a. The last command that you should know about is jump or j. You can use this command to jump to a specific line number in your code by typing jump followed by a space and then the line number that you wish to go to. Now let’s learn how you can add a breakpoint! Adding Breakpoints in pdb A breakpoint is a location in your code where you want your debugger to stop so you can check on variable states. What this allows you to do is to inspect the callstack, which is a fancy term for all variables and function arguments that are currently in memory. If you have PyCharm or WingIDE, then they will have a graphical way of letting you inspect the callstack. You will probably be able to mouse over the variables to see what they are set to currently. Or they may have a tool that lists out all the variables in a sidebar. Let’s add a breakpoint to the last line in the looper() function which is line 10. Here is your code again: # debug_code.py def log(number): print(f'Processing {number}') print(f'Adding 2 to number: {number + 2}') def looper(number): for i in range(number): log(i) if __name__ == '__main__': looper(5) To set a breakpoint in the pdb debugger, you can use the break or b command followed by the line number you wish to break on: $ python3.8 -m pdb debug_code.py > /python101code/chapter26_debugging/debug_code.py(3)<module>() -> def log(number): (Pdb) break 10 Breakpoint 1 at /python101code/chapter26_debugging/debug_code.py:10 (Pdb) continue > /python101code/chapter26_debugging/debug_code.py(10)looper() -> log(i) (Pdb) Now you can use the args command here to find out what the current arguments are set to. You can also print out the value of variables, such as the value of i, using the p for short) command: (Pdb) print(i) 0 Now let’s find out how to add a breakpoint to your code! Creating a Breakpoint with set_trace() The Python debugger allows you to import the pbd module and add a breakpoint to your code directly, like this: # debug_code_with_settrace.py def log(number): print(f'Processing {number}') print(f'Adding 2 to number: {number + 2}') def looper(number): for i in range(number): import pdb; pdb.set_trace() log(i) if __name__ == '__main__': looper(5) Now when you run this code in your terminal, it will automatically launch into pdb when it reaches the set_trace() function call: $ python3.8 debug_code_with_settrace.py > /python101code/chapter26_debugging/debug_code_with_settrace.py(12)looper() -> log(i) (Pdb) This requires you to add a fair amount of extra code that you’ll need to remove later. You can also have issues if you forget to add the semi-colon between the import and the pdb.set_trace() call. To make things easier, the Python core developers added breakpoint() which is the equivalent of writing import pdb; pdb.set_trace(). Let’s discover how to use that next! Using the built-in breakpoint() Function Starting in Python 3.7, the breakpoint() function has been added to the language to make debugging easier. You can read all about the change here: Go ahead and update your code from the previous section to use breakpoint() instead: # debug_code_with_breakpoint.py def log(number): print(f'Processing {number}') print(f'Adding 2 to number: {number + 2}') def looper(number): for i in range(number): breakpoint() log(i) if __name__ == '__main__': looper(5) Now when you run this in the terminal, Pdb will be launched exactly as before. Another benefit of using breakpoint() is that many Python IDEs will recognize that function and automatically pause execution. This means you can use the IDE’s built-in debugger at that point to do your debugging. This is not the case if you use the older set_trace() method. Getting Help This chapter doesn’t cover all the commands that are available to you in pdb. So to learn more about how to use the debugger, you can use the help command within pdb. It will print out the following: (Pdb) help Documented commands (type help <topic>): ======================================== If you want to learn what a specific command does, you can type help followed by the command. Here is an example: (Pdb) help where w(here) Print a stack trace, with the most recent frame at the bottom. An arrow indicates the "current frame", which determines the context of most commands. 'bt' is an alias for this command. Go give it a try on your own! Wrapping Up Being able to debug your code successfully takes practice. It is great that Python provides you with a way to debug your code without installing anything else. You will find that using breakpoint() to enable breakpoints in your IDE is also quite handy. In this article you learned about the following: - Starting pdbin the REPL - Starting pdbon the Command Line - Stepping Through Code - Creating a Breakpoint with set_trace() - Adding Breakpoints in pdb - Using the built-in breakpoint()Function - Getting Help You should go and try to use what you have learned here in your own code. Adding intentional errors to your code and then running them through your debugger is a great way to learn how things work!
https://www.blog.pythonlibrary.org/2020/07/07/python-101-debugging-your-code-with-pdb/
CC-MAIN-2021-31
refinedweb
1,991
70.23
SqLite allows you to store data in a file and query this data using SQL just as you would do with a database server. As an example if you want to manage your stock transactions selecting all buy transactions from a flat file is tedious. Using sqlite you can just issue something like select * from transactions where type='buy' and you do not need a database server. #include <QtSql> int main(int argc, char *argv[]) { QSqlDatabase db; db=QSqlDatabase::addDatabase("QSQLITE"); db.setDatabaseName("sqlite.dat"); if (db.open()) qDebug() << "success"; else qDebug() << "failed"; QSqlQuery query; query.exec("create table stocks(id int primary key, name varchar(20))"); db.commit(); db.close(); } QT += core gui sql TARGET = sqlite TEMPLATE = app SOURCES += main.cpp To build the example project, use the command qmake && make -j4 To run the example project, first delete sqlite.dat from your home directory. We do this to show that our example program creates it. rm ~/sqlite.dat Then run our example program: ./sqlite And you will find the database file in your home folder: ll /root/sqlite.dat -rw-r--r-- 1 root root 3072 Nov 10 10:37 /root/sqlite.dat You can now use the command sqlite3 to analyze your database file: # sqlite3 sqlite.dat SQLite version 3.7.8 2011-09-19 14:49:19 Enter ".help" for instructions Enter SQL statements terminated with a ";" sqlite> .schema stocks CREATE TABLE stocks(id int primary key, name varchar(20)); sqlite> .exit
http://techbase.kde.org/index.php?title=Development/Tutorials/SqLite&diff=67891&oldid=67323
CC-MAIN-2014-10
refinedweb
246
68.57
When. Here are some of the commonly used terminologies that you may not be familiar with, but they are not specific to Redux per se. You can skim through this section and come back here when/if something doesn't make sense. A pure function is just a normal function with two additional constraints that it has to satisfy: For instance, here is a pure function that returns the sum of two numbers. /* Pure add function */ const add = (x,y) => { return x+y; } console.log(add(2,3)) //5 Pure functions give a predictable output and are deterministic. A function becomes impure when it performs anything other than calculating its return value. For instance, the add function below uses a global state to calculate its output. In addition, the function also logs the value to the console, which is considered to be a side effect. const y = 10; const impureAdd = (x) => { console.log(`The inputs are ${x} and ${y}`); return x+y; } "Observable side effects" is a fancy term for interactions made by a function with the outside world. If a function tries to write a value into a variable that exists outside the function or tries to call an external method, then you can safely call these things side effects. However, if a pure function calls another pure function, then the function can be treated as pure. Here are some of the common side effects: Splitting the component architecture into two is useful while working with React applications. You can broadly classify them into two categories: container components and presentational components. They are also popularly known as smart and dumb components. The container component is concerned with how things work, whereas presentational components are concerned with how things look. To understand the concepts better, I've covered that in another tutorial: Container vs. Presentational Components in React. A mutable object can be defined as follows: A mutable object is an object whose state can be modified after it is created. Immutability is the exact opposite—an immutable object is an object whose state cannot be modified after it is created. In JavaScript, strings and numbers are immutable, but objects and arrays are not. The example demonstrates the difference better. /*Strings and numbers are immutable */ let a = 10; let b = a; b = 3; console.log(`a = ${a} and b = ${b} `); //a = 10 and b = 3 /* But objects and arrays are not */ /*Let's start with objects */ let user = { name: "Bob", age: 22, job: "None" } active_user = user; active_user.name = "Tim"; //Both the objects have the same value console.log(active_user); // {"name":"Tim","age":22,"job":"None"} console.log(user); // {"name":"Tim","age":22,"job":"None"} /* Now for arrays */ let usersId = [1,2,3,4,5] let usersIdDup = usersId; usersIdDup.pop(); console.log(usersIdDup); //[1,2,3,4] console.log(usersId); //[1,2,3,4] To make objects immutable, use the Object.assign method to create a new method or the all new spread operator. let user = { name: "Bob", age: 22, job: "None" } active_user = Object.assign({}, user, {name:"Tim"}) console.log(user); //{"name":"Bob","age":22,"job":"None"} console.log(active_user); //{"name":"Tim","age":22,"job":"None"} The official page defines Redux as follows: Redux is a predictable state container for JavaScript applications. Although that accurately describes Redux, it's easy to get lost when you see the bigger picture of Redux for the first time. It has so many moving pieces that you need to fit together. But once you do, I promise you, you'll start loving Redux. Redux is a state management library that you can hook up with any JavaScript library, and not just React. However, it works very well with React because of React's functional nature. To understand this better, let's have a look at the state. As you can see, a component's state determines what gets rendered and how it behaves. The application has an initial state, and any user interaction triggers an action that updates the state. When the state is updated, the page is rerendered. With React, each component has a local state that is accessible from within the component, or you can pass them down as props to child components. We usually use the state to store: Storing application data in a component's state is okay when you have a basic React application with a few components. However, most real-life apps will have lots more features and components. When the number of levels in the component hierarchy increases, managing the state becomes problematic. Here is a very probable scenario that you might come across while working with React. This is what I've personally experienced with React, and lots of other developers will agree. React is a view library, and it's not React's job to specifically manage state. What we are looking for is the Separation of Concerns principle. Redux helps you to separate the application state from React. Redux creates a global store that resides at the top level of your application and feeds the state to all other components. Unlike Flux, Redux doesn't have multiple store objects. The entire state of the application is within that store object, and you could potentially swap the view layer with another library with the store intact. The components re-render every time the store is updated, with very little impact on performance. That's good news, and this brings tons of benefits along with it. You can treat all your React components as dumb, and React can just focus on the view side of things. Now that we know why Redux is useful, let's dive into the Redux architecture. When you're learning Redux, there are a few core concepts that you need to get used to. The image below describes the Redux architecture and how everything is connected together. If you're used to Flux, some of the elements might look familiar. If not, that's okay too because we're going to cover everything from the base. First, make sure that you have redux installed: npm install redux Use create-react-app or your favorite webpack configuration to set up the development server. Since Redux is an independent state management, we're not going to plug in React yet. So remove the contents of index.js, and we'll play around with Redux for the rest of this tutorial. The store is one big JavaScript object that has tons of key-value pairs that represent the current state of the application. Unlike the state object in React that is sprinkled across different components, we have only one store. The store provides the application state, and every time the state updates, the view rerenders. However, you can never mutate or change the store. Instead, you create new versions of the store. (previousState, action) => newState Because of this, you can do time travel through all the states from the time the app was booted on your browser. The store has three methods to communicate with the rest of the architecture. They are: Let's create a store. Redux has a createStore method to create a new store. You need to pass it a reducer, although we don't know what that is. So I will just create a function called reducer. You may optionally specify a second argument that sets the initial state of the store. import { createStore } from "redux"; // This is the reducer const reducer = () => { /*Something goes here */ } //initialState is optional. //For this demo, I am using a counter, but usually state is an object const initialState = 0 const store = createStore(reducer, initialState); Now we're going to listen to any changes in the store, and then console.log() the current state of the store. store.subscribe( () => { console.log("State has changed" + store.getState()); }) So how do we update the store? Redux has something called actions that make this happen. Actions are also plain JavaScript objects that send information from your application to the store. If you have a very simple counter with an increment button, pressing it will result in an action being triggered that looks like this: { type: "INCREMENT", payload: 1 } They are the only source of information to the store. The state of the store changes only in response to an action. Each action should have a type property that describes what the action object intends to do. Other than that, the structure of the action is completely up to you. However, keep your action small because an action represents the minimum amount of information required to transform the application state. For instance, in the example above, the type property is set to "INCREMENT", and an additional payload property is included. You could rename the payload property to something more meaningful or, in our case, omit it entirely. You can dispatch an action to the store like this. store.dispatch({type: "INCREMENT", payload: 1}); While coding Redux, you won't normally use actions directly. Instead, you will be calling functions that return actions, and these functions are popularly known as action creators. Here is the action creator for the increment action that we discussed earlier. const incrementCount = (count) => { return { type: "INCREMENT", payload: count } } So, to update the state of the counter, you will need to dispatch the incrementCount action like this: store.dispatch(incrementCount(1)); store.dispatch(incrementCount(1)); store.dispatch(incrementCount(1)); If you head to the browser console, you will see that it's working, partially. We get undefined because we haven't yet defined the reducer. So now we have covered actions and the store. However, we need a mechanism to convert the information provided by the action and transform the state of the store. Reducers serve this purpose. An action describes the problem, and the reducer is responsible for solving the problem. In the earlier example, the incrementCount method returned an action that supplied information about the type of change that we wanted to make to the state. The reducer uses this information to actually update the state. There's a big point highlighted in the docs that you should always remember while using Redux: Given the same arguments, a Reducer should calculate the next state and return it. No surprises. No side effects. No API calls. No mutations. Just a calculation. What this means is that a reducer should be a pure function. Given a set of inputs, it should always return the same output. Beyond that, it shouldn't do anything more. Also, a reducer is not the place for side effects such as making AJAX calls or fetching data from the API. Let's fill in the reducer for our counter. // This is the reducer const reducer = (state = initialState, action) => { switch (action.type) { case "INCREMENT": return state + action.payload default: return state } } The reducer accepts two arguments—state and action—and it returns a new state. (previousState, action) => newState The state accepts a default value, the initialState, which will be used only if the value of the state is undefined. Otherwise, the actual value of the state will be retained. We use the switch statement to select the right action. Refresh the browser, and everything works as expected. Let's add a case for DECREMENT, without which the counter is incomplete. // This is the reducer const reducer = (state = initialState, action) => { switch (action.type) { case "INCREMENT": return state + action.payload case "DECREMENT": return state - action.payload default: return state } } Here's the action creator. const decrementCount = (count) => { return { type: "DECREMENT", payload: count } } Finally, dispatch it to the store. store.dispatch(incrementCount(4)); //4 store.dispatch(decrementCount(2)); //2 That's it! This tutorial was meant to be a starting point for managing state with Redux. We've covered everything essential needed to understand the basic Redux concepts such as the store, actions, and reducers. Towards the end of the tutorial, we also created a working redux demo counter. Although it wasn't much, we learned how all the pieces of the puzzle fit together. Over the last couple of years, React has grown in popularity. In fact, we have a number of items in the marketplace that are available for purchase, review, implementation, and so on. If you’re looking for additional resources around React, don’t hesitate to check them out. In the next tutorial, we will make use of the things we've learned here to create a React application using Redux. Stay tuned until then. Share your thoughts…
https://www.4elements.com/blog/read/getting-started-with-redux-why-redux
CC-MAIN-2019-51
refinedweb
2,076
57.37
Erik Hatcher wrote: >> So you believe that anything can go in the XML tags, no design >> or thinking is needed - because you could translate it with XSL or some >> tools will process it ? > > This is getting a bit exaggerated but I don't feel the syntax of an XML > descriptor is that relevant right now given the other issues on the > table. That's the main point I'm making with this. For Antlib ( i.e. having the task/types loaded ) - the only remaining issues that I know are the descriptor syntax and format ( and it seems most people want the XML, so the syntax remain the only problem in this space ), and the use of namespaces. For NS - it seems we can do it later. For roles - that's IMO a different problem. >>> But the current one does not support adding other components like >>> conditions, mappers, filters, and selectors. >> >> Does ant support this ? > > No, not currently in a pluggable manner. Isn't that the goal for > antlib? To load collections of ant components ( whatever ant define as component ). Not to define new component types. Are you saying that all those nice filters, selectors, etc can only be used if loaded by antlib ? You can define a task with <taskdef> in a regular ant file - why wouldn't you be able to define the condition without using an antlib ? Costin
https://mail-archives.eu.apache.org/mod_mbox/ant-dev/200304.mbox/%3Cb89eub$7kh$1@main.gmane.org%3E
CC-MAIN-2021-31
refinedweb
230
73.37
- - Advertisement 2D Camera Jitters By stitchs_login , in For Beginners Recommended Posts - Advertisement - Advertisement Popular Tags - Advertisement Popular Now - 12 By Stebssbets Started - 10 - 11 By ChaosEngine Started - 18 By cambalinho Started - 13 By HouseAndMoon Started Similar Content - By EddieK Hi I am having this problem where I am drawing 4000 squares on screen, using VBO's and IBO's but the framerate on my Huawei P9 is only 24 FPS. Considering it has 8-core CPU and a pretty powerful GPU, I don't think it is not capable of drawing 4000 textured squares at 60FPS. I checked the DMMS and found out that most of the time spent was by the put() method of the FloatBuffer, but the strange thing is that if I'm drawing these squares outside of the view frustum, the FPS increases. And I'm not using frustum culling. If you have any ideas what could be causing this, please share them with me. Thank you in advance. - By menyo I am trying to figure out a good component design for my item classes since otherwise it probably ends up in a hierarchy disaster. I will just be just using this to define my items in a data driven way. My items do not have a position or interact with the map, they are either on a character or on a tile in the map and that is where they are stored. So I created a blank interface and a couple implementations, nothing is set in stone but I think my concept is pretty solid and I'm looking for feedback from people with more experience on the topic since it would not be the first time I burry myself into something I cannot climb out of :). public interface ItemComponent { } public class WeaponComponent implements ItemComponent{ int damage; int range; float attackSpeed; String damageType; } public class ArmorComponent implements ItemComponent { int defense; String armorType; String bodyPart; } Easy enough, like most component systems they only add data the system in my case are the characters using the items, I could add functionality but that will probably complicate things once more components are added. When the character uses any item with the corresponding component I have access to the data, and that is all I currently need. A shield that could also be used as a weapon should be easy to model in. To know and find a specific type of item I implemented a Map that maps a String to a ItemComponent. public class Item { private String name; private int weight; private Map<String, ItemComponent> itemComponents = new HashMap<>(); public Item() { } public void addComponent(ItemComponent component) { itemComponents.put(component.getClass().toString(), component); } } A basic item that is used for crafting only would not have any components. For easy lookup I added a couple methods. public boolean hasComponent(Class c) { return itemComponents.containsKey(c.toString()); } public boolean isWeapon() { return hasComponent(WeaponComponent.class); } public boolean isArmor() { return hasComponent(ArmorComponent.class); } To instantiate items I will import all JSON data in a Factory pattern and clone the items. Since crafting is a thing I will add another Map to this that maps the items name to the recipe. public Item clone() { return new Item(name, weight, itemComponents); } public class ItemPrototype { private Item item; private Recipe recipe; public Item cloneItem(){ return item.clone(); } public Item createItem(List<Item> ingredients) { // Todo: Check ingredients. // Todo: Remove ingredients. return cloneItem(); } } public class ItemFactory { private static Map<String, ItemPrototype> itemPrototypes = new HashMap<>(); static { // Todo: Import items from JSON } public static Item createItem(String name, List<Item> ingredients) { // TODO: Error handling return itemPrototypes.get(name).createItem(ingredients); } public static Item createItem(String name) { // TODO: Error handling return itemPrototypes.get(name).cloneItem(); } } Here is how an item would look inside a JSON file. A simple rock would truncate everything except for it's name and weight unless it I decide it can be used as a weapon too. "Rifle" : { "item" : { "name" : "Rifle", "weight" : 3500, "itemComponents" : { "WeaponComponent" : { "damage" : 18, "range" : 20, "attackSpeed" : 10.0, "damageType" : "Piercing" } } }, "recipe" : { "ingredients" : { "Wood" : 1, "lense" : 1, "Steel Plate" : 4 } } } I love to hear what more experienced people have to say about this. There are not much examples to look at on internet except for a couple that go all the way down to engine level where basically everything is a entity. If I have success with this structure I definitely write a article about it. - By Honneamise Hello, :-) - By Ruzicar Hi folks, During a recent leave of absence for family reasons, I needed something to take my mind off my troubles. So I decided to learn Android development and create a game I've always wanted to play. "Borbudo" is available on the Google Play Store at: Very briefly, Borbudo is inspired by the old 80s games Time Bandits and Gauntlet, and in the future I hope to include lots of puzzles and quests in the spirit of Dungeon Master. Right now I confess that the game needs some re-work to create a unifying theme, but I think the alpha version available now is pretty solid. My game also features the music of Eric Matyas. I'd very much appreciate any comments (or even Patreon pledges). With many thanks, Rob Lehrbass - By Time4Tea This is linked to another question that I asked here a couple of days ago: I'm looking at making a client-server game with a game server programmed in Java. The game will be a 2D turn-based game (like a board game), with a maximum of around 50-100 games going on at any one time. So, the performance requirements are not very high. The reason I would like to use Java for the server are because I already have some familiarity with it and I would like the server to not be tied to one particular platform. I would also like to design it so that the client interface to the server is as generic as possible, so that the same server could be used with multiple different clients. For example, there might be a web-based client, or someone else might design a stand-alone 3D client application later on, using the same server. So, I am looking for some advice on where to start with this, as I have very little experience with coding servers. I was planning to use web sockets for the client-server connection, which apparently uses Java EE (Enterprise Edition), which seems to require the use of the GlassFish server. However, I have been advised that a fully-fledged application server, like GlassFish, may be overkill for a game server. So, here are my questions: Should I use something like GlassFish? Does it makes sense for the type of game server I am describing? If not, then what sort of networking protocol/library would experienced Java game designers recommend? Are there any existing, general-purpose Java game servers that exist, which I might be able to use as a starting point? (Or even free software/open-source client-server games?) Or, should I look at coding my own game server from scratch? In which case, again, what sort of connection type/library would be recommended? Does anyone know of any suitable introductory tutorials that deal with how to make this sort of game server in Java? I guess my priority is probably minimizing the learning curve and the amount of time/effort involved, over performance. How much effort is this sort of undertaking going to require? Thanks in advance! :-) - Advertisement
https://www.gamedev.net/forums/topic/692486-2d-camera-jitters/
CC-MAIN-2018-09
refinedweb
1,249
59.43
Ok, I was recently writing a small java app that would print out values according to the Collatz Conjecture. Collatz conjecture - Wikipedia, the free encyclopedia Anyway, I noticed that after a certain number of iterations (i.e. the number being checked) the app just kind of sits there. So what I did was write output to the console every 10,000 numbers. Well, up to 100,000 it works fine. If I try it with 1,000,000, then it gets up to about 113,000 and just kinda hangs. I'm trying to have it write out the "hailstone number" at the given position. Here's sample output: I also have the code below. I'm wondering if this is a variable problem, a structure problem, or if I stumbled across some kind of limit that Java has. I wrote this same app in C# and ran into the same issue. Anyhow, here's the code (yes, I know it could probably use a good refactoring): import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.io.Writer; public class HailstoneNumbers { private static Writer writer = null; public static void main(String[] args) throws IOException { long result = 0; System.out.println("Writing File."); try { writer = new BufferedWriter(new OutputStreamWriter( new FileOutputStream("C:\\hailstones.txt"), "utf-8")); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } for (int x = 1; x < 1000001; x++) { if (x % 10000 == 0) { System.out.println(x + " numbers written."); } try { result = calculateHailstone(x); } catch (Exception ex) { ex.printStackTrace(); System.out.println("An error has occurred."); } writeFile(x, result); } System.out.println("File Written."); writer.flush(); writer.close(); System.in.read(); } private static long calculateHailstone(int number) { long steps = 0; if (number == 1) { steps = 0; } try { while (number != 1) { if (number % 2 == 0) { number = number / 2; } else { number = (number * 3) + 1; } steps++; } } catch (Exception ex) { ex.printStackTrace(); System.out.println("An Error has occurred."); } return steps; } private static void writeFile(int position, long hailstoneNumber) { try { writer.write(position + "\t" + hailstoneNumber + "\r\n"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } Please note this is NOT a homework assignment. This was something I wrote just out of sheer curiosity. So, does anyone have any thoughts on why this functions the way it does?? I'm striving to become a better software engineer, and I'm trying to determine here if this is something I did or didn't do (or possibly did incorrectly). Thanks for any knowledge you may be able to pass along!
http://www.javaprogrammingforums.com/whats-wrong-my-code/33025-i-think-i-did-something-wrong-here-i-need-some-feedback.html
CC-MAIN-2015-35
refinedweb
448
52.66
I think I've found a bug in 2.2's TCP stack, in which sockets can get into FIN_WAIT1 with no timer and stay stuck indefinitely. Steps to reproduce seem to be basically as follows: From a client running 2.2.16, open a TCP socket to a server. Set TCP_CORK, write some data, exit. The exit ought to implicitly close the socket, but instead the socket goes into FIN_WAIT1 and never closes properly. netstat on the client shows tcp 0 44 192.168.0.146:1146 192.168.0.209:4200 FIN_WAIT1 off (0.00/0/0) As far as I can make out, this is a state that should never occur: if there is data still in the send queue, then there should always be a timer running to retransmit it and/or probe the remote machine for more window space. Also, I would think that in FIN_WAIT1 there ought to be a timer that will cause the FIN to be retransmitted in case it was lost. On the server: ngoh@xxxxxxxxxxxxxxx $ netstat -ton | grep 4200 tcp 0 0 192.168.0.209:4200 192.168.0.146:1146 ESTABLISHED off (0.00/0/0) So it looks to me like the server just does not see a FIN from the client. The server application (distccd) is just blocked in read(), waiting for more data or EOF. tcpdump seems to show that the client just never sends the FIN 22:16:21.690340 build03.foo.com.1146 > build04.foo.com.4200: S 1541177197:1541177197(0) win 32120 <mss 1460,sackOK,timestamp 1005928219[|tcp]> (DF) 22:16:21.690537 build04.foo.com.4200 > build03.foo.com.1146: S 1546103786:1546103786(0) ack 1541177198 win 32120 <mss 1460,sackOK,timestamp 1005835757[|tcp]> (DF) 22:16:21.690593 build03.foo.com.1146 > build04.foo.com.4200: . ack 1 win 32120 <nop,nop,timestamp 1005928219 1005835757> (DF) 22:16:21.691329 build03.foo.com.1146 > build04.foo.com.4200: P 1:1448(1447) ack 1 win 32120 <nop,nop,timestamp 1005928219 1005835757> (DF) 22:16:21.691822 build04.foo.com.4200 > build03.foo.com.1146: . ack 1448 win 31856 <nop,nop,timestamp 1005835757 1005928219> (DF) If the TCP_CORK is never inserted, or if the application removes the cork before exiting, then things work properly. Also, this works properly on 2.4.18. It seems that the problem is not to do with firewalling troubles or packet loss. This was originally observed by Hien D. Ngo on 2.2.16 and 2.2.19 while trying out my program distcc on some Red Hat 6.2 machines. All of the gory details are available here: I don't have any 2.2 machines myself, but if necessary I can install it and try to reproduce the problem. So I would guess that there is some kind of bug in tcp_snd_test()'s logic for deciding whether to send a packet. The comment there claims to handle this case of close() with cork in place, but it seems that it is not. (I don't really know if it's that function, it could be elsewhere.) The final statement is return ((!tail || nagle_check || skb_tailroom(skb) < 32) && ((tcp_packets_in_flight(tp) < tp->snd_cwnd) || (TCP_SKB_CB(skb)->flags & TCPCB_FLAG_FIN)) && !after(TCP_SKB_CB(skb)->end_seq, tp->snd_una + tp->snd_wnd) && tp->retransmits == 0); As far as I can see all of these are true, so either my assumptions are wrong, or this function is not itself the problem. We're OK on the first, because nagle_check will be 1. We're OK on the second because presumably TCPCB_FLAG_FIN is set. We're OK on the third because there's plenty of space in the window. And we should be OK on the fourth because the packet hasn't been retransmitted. I wonder if the transmit queue actually has a small data packet ahead of the FIN packet, and the data packet is not being sent and therefore jamming up the works? If that was true, and they somehow did not get combined, then... flags for that packet would not have FIN, and the length would be less than the mss_cache, so nagle_check would become 0. It wouldn't be the tail; the nagle check would be false, and it wouldn't be nearly full. So tcp_snd_test() would return 0. Anyhow, I hope you find it an interesting bug. Please cc me on replies and let me know if there's anything I can do to help. (Incidentally, distcc is pretty cool if you ever compile large programs, like, say, the kernel. On my 3 PCs it builds 2.6 times faster, and it's pretty trivial to install. Try it, you'll like it.) -- Martin
http://oss.sgi.com/cgi-bin/mesg.cgi?a=netdev&i=20020906071108.GC26914%40samba.org
CC-MAIN-2014-10
refinedweb
783
83.25
Hello, +1 with DDs views. Regards, Antoine -------- Original-Nachricht -------- Datum: Tue, 1 Aug 2006 08:04:57 -0500 Von: "Dominique Devienne" <ddevienne@gmail.com> An: "Ant Developers List" <dev@ant.apache.org> Betreff: Re: VOTE ant-vss antlib promote to antlib proper > > > I am +1 for moving VSS support into its own antlib. The only > > > problem is that adding the antlib to ANT_HOME/lib will not ensure > > > that existing build files will work, because to get the stuff > > > autoloaded, they need to declare it in a new namespace. Unless, > > > that is, the main defaults.properties file still declares the > > > existing task in its (new) location... > > > > > Good point, so if the vote passes, we should make sure that we > > implement the changes in a BWC way. > > +1 on making VSS an antlib. > > However, I'm not sure at all we should bind ourselves to moving things > to antlibs in a BC manner necessarily. One of the benefits to going > more towards releasing Ant as a smaller core and a set of antlibs is > to avoid trying to load a bunch of tasks (Jars) all the time, when a > fraction only is actually used. I personally don't think it's > unreasonnable to force <vss> users to explicitly load the antlib in > their build file, using XML NS or an explicit <antlib>. > > So, +1 on simply removing the vss entries to optional.properties, and > provide the antlib. --DD --------------------------------------------------------------------- To unsubscribe, e-mail: dev-unsubscribe@ant.apache.org For additional commands, e-mail: dev-help@ant.apache.org
http://mail-archives.apache.org/mod_mbox/ant-dev/200608.mbox/%3C20060801193913.81190@gmx.net%3E
CC-MAIN-2017-30
refinedweb
255
65.32
Bug #8125 lost-tuple bug and fix for Rinda::TupleSpaceProxy.take Description =begin Rinda::TupleSpaceProxy prevents tuple loss during #take by exposing a "port" object on the client that the remote side (the tuplespace server) pushes to, instead of relying on the method return value. Pushing to the port fails if the process that called #take has exited, so the tuple will not be deleted from the tuplespace server. However, if the process has not exited, and the thread that called #take was interrupted, the port still exists and accepts push requests (in the main drb thread). In this case the tuple is deleted on the server and not available on the client. This is frequently a problem when using irb and manually interrupting take calls. It would also be a problem when using timeouts. A concise reproduction of the problem is in the attached thread-int.rb. The bug can be fixed by the patch below, which replaces the port array with a custom object that rejects pushes if the call stack has been unwound. Note that this patch combines naturally with the faster take patch in #8119. diff --git a/lib/rinda/rinda.rb b/lib/rinda/rinda.rb index 18e284a..057c61a 100644 --- a/lib/rinda/rinda.rb +++ b/lib/rinda/rinda.rb @@ -206,6 +206,23 @@ module Rinda # TupleSpaceProxy allows a remote Tuplespace to appear as local. class TupleSpaceProxy - class Port - attr_reader :val + - def initialize - @open = true - end - def close - @open = false - end + - def push val - raise unless @open - @val = val - nil # so that val doesn't get marshalled again - end end ## # Creates a new TupleSpaceProxy to wrap +ts+. @@ -222,6 +239,19 @@ module Rinda end ## # Safely takes +tuple+ from the proxied TupleSpace. See TupleSpace#take. # Ensures that an interrupted thread will not become a lasting cause # of further data loss. + def take_safely(tuple, sec=nil, &block) port = Port.new @ts.move(DRbObject.new(port), tuple, sec, &block) port.val ensure port.close # don't let the DRb thread push to it when remote sends tuple end + ## # Takes +tuple+ from the proxied TupleSpace. See TupleSpace#take. def take(tuple, sec=nil, &block) =end Associated revisions History #1 Updated by Hiroshi SHIBATA over 2 years ago - Assignee set to Masatoshi Seki #2 Updated by Eric Hodel over 2 years ago - File rinda.rb.8215.patch added - Status changed from Open to Assigned I think the safe take should be the default take. I updated your patch and converted thread-int.rb into a test. #3 Updated by Eric Hodel over 2 years ago - File rinda.rb.8215.2.patch added Here is an updated patch that matches the rinda style and removes a leftover p #4 Updated by Eric Hodel over 2 years ago - File rinda.rb.8215.3.patch added Oops, I forgot to run all the tests, this fixes the remaining tests by restoring an accidentally deleted line. #5 Updated by Masatoshi Seki over 2 years ago - Assignee changed from Masatoshi Seki to Eric Hodel please commit it! #6 Updated by Eric Hodel over 2 years ago - Status changed from Assigned to Closed - % Done changed from 0 to 100 This issue was solved with changeset r39890. Joel, thank you for reporting this issue. Your contribution to Ruby is greatly appreciated. May Ruby be with you. Also available in: Atom PDF
https://bugs.ruby-lang.org/issues/8125
CC-MAIN-2015-48
refinedweb
554
65.01
Help.... Documentation Last thing written... if ever... First thing needed. I have been messing with formatting my code using numpy doc strings And! Not only that, your favorite Python Package Manager includes it in their python distribution so Sphinx can use it. So here is a little 'dirr' function I wrote since dir(object) returns a messy hard to read output in any form. Here is the documentation for the function. def dirr(obj, colwise=True, cols=3, sub=None, prn=True): """A formatted dir listing of a module or function. Source : arraytools module in tools.py, dirr def Return a directory listing of a module's namespace or a part of it if the `sub` option is specified. If `prn=True`, then it is simply printed. If False, then the string is returned. Parameters ---------- - colwise : `True` or `1`, otherwise, `False` or `0` - cols : pick a size to suit - sub : sub='a' all modules beginning with `a` - prn : `True` for print or `False` to return output as string Notes ----- See the `inspect` module for possible additions like `isfunction`, 'ismethod`, `ismodule` **Examples**:: dirr(art, colwise=True, cols=3, sub=None, prn=True) # all columnwise dirr(art, colwise=True, cols=3, sub='arr', prn=True) # just the `arr`'s (001) _arr_common arr2xyz arr_json (002) arr_pnts arr_polygon_fc arr_polyline_fc (003) array2raster array_fc (004) array_struct arrays_cols """ The key (apparently) is indentation, back-ticks and little tricks. In Spyder's help documentation, it looks like this. ( More on Spyder as an IDE for your work ) You can produce whole documentation for your modules or even single 'scripts' to accompany your code. And the function itself makes finding my own documentation easier Producing links to web links This may be a bit much, but your documentation can also provide links to http: sites to reference specific web pages from within your documentation. Here is an example. The key is to provide a - link number ... [1] - a name for the link... with trailing __ - and the actual link itself. The **text** provides bold highlighting. The [1] on line 6, is the first link with line 7 being the link name in back-tics and trailing __. Line 9, with the leading __ is the actual link itself. What is show is a snip of the whole link list shown below. Simpler option You might need a simpler documentation example References: ----------- `<- sequences-elements-from-an-array-in-numpy>`_. `<- condition#50551924>`_. This consists of `< at the start and >`_. at the end with the link in between. This yields... Finally Remember, documentation is important. If not for yourself, for someone else. Ha ha..."Last thing written... if ever... First thing needed." So true!
https://community.esri.com/people/Dan_Patterson/blog/2018/03/27/script-documenting-it-is-all-in-the-docs
CC-MAIN-2018-39
refinedweb
445
66.03
C# Corner Take advantage of C#'s Item Templates to automate tasks that you find yourself having to perform on a regular basis.. One of the most common ways to automate tasks is to create new class Item Templates in Visual Studio. In this article, I'll show you how to recognize when Item Templates are the best way to automate a task, how to create Item Templates, and how to install them. I'll also briefly touch on how to update the standard templates, if you need to change those. You probably use the default Item Templates everyday: new class, new form, new control, and so on. If you do anything sophisticated, or your development shop has any form of standards, you likely need to make changes to the generated code immediately. Are those immediate changes repetitive? Do you make the same changes every time? If the answer to any of these questions is yes, you might be able to save time by creating a new Item Template. My first Item Template added a copyright notice to the top of each class. Most customers I work with have some standard text they want in each source file. It's annoying to do extra work for each customer, such as adding that copyright notice every time. Of course, you can add snippets, or create a macro to add the copyright information to each file. But that's an extra step. A better approach is to create a new class template that contains the copyright information. This is your first Item Template, so let's do it the easy way using Visual Studio's Export Template wizard, and then make some modifications by hand. Create a new class library project in Visual Studio called "Template One": using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace TemplateOne { public class Class1 { } } All you need to add initially is the copyright notice. Add the extra comments at the beginning of the file to suit your standard and then save the file (see Listing 1). You can learn the basics of creating Item Templates by leveraging Visual Studio's Export Template wizard. This wizard will save almost any code element you choose as an Item Template. Select Class1 to be saved as a template. Add all the standard references as part of the template in the Export Template Wizard. You'll get a warning displayed when you add System.Core and System.Xml.Linq because these assemblies are 3.5 specific, but you'll fix this error later. Next, pick an icon. I've made several versions of the copyright template, one for each of the customers I work with. I replace the logo in each of these templates with the logo for that customer. For the sample, I used the Visual Studio Magazine logo. There are a lot of templates and I find that creating a custom logo, even if your graphic design skills aren't great, can provide visual cues to help you find specific Item Templates quickly. Give your Item Template a name and a description on the final page of the wizard (see Figure 1). That's it, you now have a simple template that creates a class similar to the VS.NET class template, but with your standard copyright information. Modify the Exported Template Note that I said the simple template is similar to the VS.NET class template. The template language is quite a bit richer than what the default wizard uses to create items. The Export Template wizard is a good place to start, and it provides some good procedures to use, but you should make some changes to the exported template before you use it in a production app. The wizard puts two copies of your Item Template on your machine. Both copies are under your Documents\Visual Studio 2008 directory. One is under My Exported Templates. This directory will contain every template you ever create with the export template wizard. The other copy, the one Visual Studio reads, is under Templates\ItemTemplates. Be sure to unzip the copy in My Exported Templates so you can examine what the wizard creates for you. Visual Studio packages three files together in the template: class1.cs, _TemplateIcon.ico, and MyTemplate.vstemplate. The first thing you should do is examine class1.cs. Remember the warning you received for including the System.Core and System.Xml.Linq assemblies in your using statements. The error was triggered because including these assemblies causes errors when you include your Item Template in a project that targets the .NET 2.0 or 3.0 Framework. The Item Templates installed with Visual Studio support macros that work around that limitation, but these aren't added when you export user-defined templates. You can fix errors caused by including 3.5 namespaces by adding another macro in the template class, class1.cs. Wrap the using statement in an if conditional that checks the target framework: $if$ ($targetframeworkversion$ == 3.5)using System.Linq; $endif$using System.Text; The macro language is a bit ugly in terms of the whitespace. If you leave extra CR/LF pairs in the macro, those blank lines show up in your new class when you create a new item from your template. The macro processing preserves any formatting around macro keys in case you've used macros in logic where whitespace and line breaks could be significant. For that reason, you need to write your macros such that the macro processing produces the code formatted for your style guidelines. You can also remove the public access modifier from the class. My own preference is to use the default access (internal) and make it an explicit developer choice to create a public class. There's nothing magical about the name of the source file. Save your changes and rename the file to something that makes more sense to you. Then do the same with the icon file, giving it a name that matches its source. Next, you need to edit the vstemplate file. This is an XML file that describes how Visual Studio should process the template, as well as all the parts that make up the template itself. Editing this file controls everything else in your Item Template. Before you do anything else, change the version attribute in the VSTemplate element from 2.0.0 to 3.0.0. The Visual Studio team added new capabilities to the macro language, but these new capabilities are only parsed in the 3.0.0 version of Item Templates. If you forget this change, the $if$ conditional you added to your .cs file won't be parsed, and the $if$, $endif$ will end up in your source code. Begin by changing the template to reflect the filename changes you made earlier. Near the top of the file, you'll find the <Icon> element. Change that element to reflect the changed name of the icon file: <Icon>vsm.ico</Icon> Next, you need to change the ProjectItem element. This is a bit more complicated than what we've discussed so far. The text for the element is the name of the .cs file that contains the item. There's also an attribute that you need to modify. The TargetFileName attribute contains the name of the file as it should be added to your project. Normally, it would be something like class1.cs. You can change that to meet your project standards (for example, MyCompanyNameClass1.cs). You control the target file name through the DefaultName element later. Leave it as it is now. Visual Studio adds numeric constants to the file name each time you insert the item in a project. The final version of the Project element looks like this: <ProjectItem SubType="Code" TargetFileName="$fileinputname$.cs" ReplaceParameters="true"> SRTClass.cs </ProjectItem> You'll want to edit three more elements near the top of the file: the DefaultName element, the Name element, and the Description element. The DefaultName element gives the name the file should be given when that element gets inserted into your project. Remember that, by default, the class name and the file name share the same base class. This element can control the class name for the same reason. You can change the Name element to whatever you want displayed in the Insert Item dialog. You can also update the Description element in this file (see Listing 2). Now copy the file to the Templates directory, or the VisualC# subdirectory under templates, so you can begin using it. The new Item Template shows up at the bottom of the "My Installed Templates" list when you go to Insert Item on any C# project. One of the best ways to learn about the capabilities of these Item Templates is to look at the Item Templates that are installed with Visual Studio. These are all simple .ZIP files, and you can copy them, open them up, and look at them for inspiration when building your own templates. You can modify them in place and change their behavior, but I prefer making new versions for my own extensions. That way, the original behavior is still in place. This examination of the Visual Studio Item Templates should provide some good ideas on how to go about automating common tasks. You can also create your own Interface Template using this article's sample class as a model. The cool part about the techniques demonstrated is just how easy they are to take advantage of, and how much mileage you can get from them in terms of automating tasks you need to do with any regularity. About the Author Bill Wagner, author of Effective C#, has been a commercial software developer for the past 20 years. He is a Microsoft Regional Director and a Visual C# MVP. His interests include the C# language, the .NET Framework and software design. Reach Bill at wwagner@srtsolutions
https://visualstudiomagazine.com/articles/2008/09/01/define-your-own-item-templates.aspx
CC-MAIN-2019-43
refinedweb
1,657
74.39
Recursion public class Solution { public boolean isValidBST(TreeNode root) { return isValid(root, null, null); } private boolean isValid(TreeNode p, Integer low, Integer high) { if (p == null) { return true; } return (low == null || p.val > low) && (high == null || p.val < high) && isValid(p.left, low, p.val) && isValid(p.right, p.val, high); } } In a BST, a left child node is smaller than its parent and a right child node is always greater than its parent. The solution is based on this property. In the isValid function, we recursively check if a node has a value between low and high. There is an edge case where a node may have a value equal to Integer.MIN_VALUE or Integer.MAX_VALUE. So we use null to represent the infinity. Time Complexity: O(n) Extra Space: O(1) In-Order Traversal public class Solution { private TreeNode prev; public boolean isValidBST(TreeNode root) { prev = null; return isMonotonicIncreasing(root); } private boolean isMonotonicIncreasing(TreeNode p) { if (p == null) { return true; } if (isMonotonicIncreasing(p.left)) { if (prev != null && p.val <= prev.val) { return false; } prev = p; return isMonotonicIncreasing(p.right); } return false; } } If the tree is a valid BST, its elements should strictly follow an increasing order within an in-order traversal. We can use this property to solve the problem. To learn more about in-order traversal, please check out this link. We define prev to keep a track of the previous element in the in-order traversal. Whenever we detect that there exists a TreeNode p that is smaller than prev, we know the tree is not a valid BST. Time Complexity: O(n) Extra Space: O(1) Discussion
https://dev.to/algobot76/leetcode-98-validate-binary-search-tree-4o29
CC-MAIN-2020-45
refinedweb
272
58.58
Hi, Developers When I click save button to save the new capturing information on cache server pages then following error pops up. JavaScript exception was caught during execution of Hyper Event: Syntax Error: Expected. Regards Godfrey Hi, Developers When I click save button to save the new capturing information on cache server pages then following error pops up. JavaScript exception was caught during execution of Hyper Event: Syntax Error: Expected. Regards Godfrey Hi Developers! Recently we published on Docker Hub images for InterSystems IRIS Community Edition and InterSystems IRIS Community for Health containers. What is that? There is a repository that publishes it, and in fact, it is the same container IRIS Community Edition containers you have on official InterSystems listing which have the pre-loaded ObjectScript Package Manager (ZPM) client. So if you run this container with IRIS CE or IRIC CE for Health you can immediately start using ZPM and install packages from Community Registry or any others. It's really handy if you want to test a new interesting ZPM package and not harm any of your systems. Suppose, you have docker-desktop installed. Pull the image: Hi All, We have been using DeepSee which has been the integrated Analytic Dashboard built over Cache Cubes. It works fine but it's visual capabilities are limited and most probably is getting phased out. If I am not wrong, Tableau is the suggested alternative to DeepSee . It is expensive and a big and considerable shift from existing technology I wanted to get an opinion of the community as to these few key points - What other BI tools others have been using with IRIS and what have been their experience - For which tools are the best inbuilt support / api's avaialble in IRIS Hi All, We have few queries which are simple selects . For simplicity let's say there is a query that joins two tables and gets few columns and both tables have no indexes. Select Tab1.Field1, Tab2.Field2 From Table1 Tab1 Join Table2 Tab2 On Tab2.FK = Tab1.PK When we do query plan for this it shows approx 6 million, however if we make a simple adjustment to the query If you are seeing this error during import: ERROR #6301 Line: 2 Offset: 118 This does not appear to be a Cache exported file, unable to import. This error is caused by exporting from InterSystems IRIS and trying to import into Caché. If you plan on exporting from IRIS to Caché, you can use the following qualifier to export your classes so that Caché does not throw an error on import: w $SYSTEM.OBJ.Export(<items>,<filename>,"/exportversion=cache2018.1") While I can query the HL7 message class EnsLib.HL7.Message (EnsLib_HL7.Message for SQL) to my heart's content in the SQL Shell or the Management Portal's SQL page, I can't seem to SELECT anything other than ID/%Id from an ADO/ODBC client. Properties such as TimeCreated, Name, MessageTypeCategory, etc. all seem to prevent the query from ever completing EXCEPT when I provide the ID as part of the WHERE criteria. This works fine in the Management Portal and Shell: I am trying to install Cache version 2018.1.0.184.0 on a Windows 10 System and i keep running into Permission errors during installation. I am getting "Error 1406 Could not write value to key \SOFTWARE\Intersystems\\Classes\CLSID\{D11481CD-3B24-42E1-A20A-D179CDB6BEC5}\InstallCount" I am signed in as an Administrator, i am running the installer as an administrator and i have edited permissions in the Registry to the referenced keys and i still can't get this to install. Has anyone run into this before and have some advice? I am pulling my hair out over here. Hi Developers, New video, recorded by @Benjamin De Boe, is already on InterSystems Developers YouTube: ⏯ Python and InterSystems IRIS Hello Everyone I use VB.NET to dev. some program for query data Code in VB like this Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click AxVisM1.MServer = "CN_IPTCP:myserver[1972]" AxVisM1.NameSpace = "LABDATA" AxVisM1.Code = "s err="""",err=$$select^LVBEPVIS(""" & ln & """)" AxVisM1.Execute(AxVisM1.Code) tmptxt = AxVisM1.PLIST.ToString messagebox.show(tmptxt) Beginning with I currently have a batch job that performs many functions. Two of them are below. I was wondering how this can be done in a custom class mv $TEMPDIR/$FILE $TEMPDIR/$FILEa"_$DATESTAMP.txt" mv $TEMPDIR/$FILE1 $TEMPDIR/$FILE1a"_$DATESTAMP.txt" mv $TEMPDIR/$FILE2 $TEMPDIR/$FILE2a"_$DATESTAMP.txt" mv $TEMPDIR/$FILE3 $TEMPDIR/$FILE3a"_$DATESTAMP.txt" mv $TEMPDIR/$FILE4 $TEMPDIR/$FILE4a"_$DATESTAMP.txt" #Gzip files find $TEMPDIR -type f ! -iname '*gz' -exec gzip '{}' \; Thank you This is a lesson learned, which I would like to share with community. Recently I ran into an issue, where I was using %ConstructClone and it kept cloning extra records, which were not needed. The record for which I was trying to run a clone had many-to-one relationships. The solution to this issue was using param -1. If you run %ConstructClone(-1) it will not clone relationships, but rather just clone single oref as desired in this case. I hope this information helps someone who is working with similar records. This series of articles would cover Python Gateway for InterSystems Data Platforms. Execute Python code and more from InterSystems IRIS. This project brings you the power of Python right into your InterSystems IRIS environment: The plan for the series so far (subject to change). The Jupyter Notebook is an open-source web application that allows you to create and share documents that contain live code, equations, visualizations and narrative text. This extension allows you to browse and edit InterSystems IRIS BPL processes as jupyter notebooks. Hello community, I'm new to Objectscript and Intersystems development. I've read documentation and some examples and succeded to import my Java class file into HealthShare using the Java Gateway Service. To import my class i tryed both methods (Wizard, or scripting) with success. Everything works great, i see my imported class inside the namespace, and i can call the methods. I used the soap wizard to create a web client based on the wsdl. I was able to get a valid response back, and now it looks like the error is in decrypting the soap message response "inbound" Working on a project to call a web service and the soap header has custom header elements that need to be signed. i reviewed the %soap.inc and didn't see any appropriate macro EBS and IDP elements need to be signed here's a provided header sample this a sample output that I created. How do I rename class programmatically? This discussion touches on data move which, is not a concern in my case (BPL renames). I also don't care about external references. The best I got is: Are there any better alternatives? Hi Community, 2019 was a great year full of video content for InterSystems Developers. Already 200 Videos on our InterSystems Developers YouTube Channel, and the number of subscribers has doubled since the previous year! Almost 57K Views and 5,1K hours of Watch Time in 2019! Thank you, our dear subscribers, so we understand that our video channel is valuable to you! Now let's take a closer look at the most popular videos on InterSystems Data Platforms over the past year. We want to be able to dispatch based on the IP address who connected to a TCP Inbound adapter. The address is in ..Adapter.%outIPAddr when the connection is made and reported with $$$LOGINFIO() but by the time OnProcessInput() is called the value is blank. When I tried to migrate one of ZEN applications to IRIS from 2018.1 I'm faced with the issue with Login Page, in this case used some ZEN page, completely customized. But when a user tries to get access, he gets the error like below. The requested URL /csp/user/User.Login.cls was not found on this server. I tried to test it with a fresh just created login page class Class User.Login Extends %CSP.Page { ClassMethod OnPage() As %Status { &html<<h1>Hello</1>> Quit $$$OK } } Set it to /csp/user application as Login page, and I: cache 2017.2.1 (Build 801_3) when I look into the "sql statements" ( sql page of the management portal ) I have lots of old statements with a lot of them frozen. many of them are %sqlcq routines (I believe these are the SLQ's I run when testing/running random SQL queries in the sql page. ) I can clearly see where I can click on an individual query and untick an individual query to unfreeze it. or delete it. but thats a painful slow process. I can't see anywhere to delete/change multiple queries A unit of ObjectScript code (a ClassMethod, say) may produce a variety of unexpected side effects by interacting with parts of the system outside of its own scope and not properly cleaning up. As a non-exhaustive list, these include: Hi Developers! Often when we install a code package we want to make some post-install settings, e.g. call to a method, set up a configuration file. This article describes how to do this with the ObjectScript Package Manager. To make any post-install calls you need to add <Invoke> elements into <Invokes> tag to the module.xml. Each <Invoke> element can have nested <Arg> elements if you want to pass params to the method: Hi Community, Please welcome the new video on InterSystems Developers YouTube Channel: ⏯ Operationalizing "Machine Learning" Experiences From the Field I would like a REST client to be able to send a custom header with the http request, for example "APPLICATION-ID". This can be seen in the CSP gateway trace but I have tried using %request.GetCgiEnv("HTTP_APPLICATION-ID") in various formats and parts of the classes but cannot work out where I can get this. Documentation says this should work but is for normal CSP pages. Any ideas? Is there a way to get dynamic object from iterator? set arr=[1,2,3] set iter=arr.%GetIterator() I pass iterator several frames down and I'd rather avoid passing both the array and iterator, but for debugging I need to access original object in a situation where only iterator is available. Is there a way to do it? This repository is a go-public that builds on the already existing InterSystems-internal Convergent Analytics community and InterSystems-private MLToolkit repo (remains active and contains the most recent information for external ML Toolkit users - request memebership by writing us at MLToolkit@intersystems.com). This repo embraces more than ML Toolkit, we would like to host any discussions, publications, projects that add up in what we call convergent analytics approach. Welcome! I have to write a DTL with the Data Transformation Builder to convert messages from HL7 ORU R01 v2.1 to HL7 ORU R01 v2.5. The incoming messages contain a text in OBX-5. This text contains LF characters (only LF - Segment separator is CR). Therefore it is not possible to parse the incoming message. While testing the transformation the OBX Segment ends at the first occurence of LF. Is there a way to replace the LF character before parsing? example: source: OBX||FT|ltest1|| first line second line … last line ||||||F| target: Hello, I need to use IRIS to connect to an MSSQL base. It has to be done via ODBC, I can't use JDBC at this time by client option. I am trying to use Microsoft Driver libmsodbcsql-13.1.so.9.2 But I can't, my attempts result in: Connection failed. SQLState: () NativeError: [11001] Message: I have done all DSN configuration, and my configuration is listed in SQL Gateway Connections. I know it's working, because when I run a test with isql I have the information that connects to the bank.
https://community.intersystems.com/?period=month
CC-MAIN-2020-05
refinedweb
2,004
63.8
SpeedLerp Author: Eric Haines (Eric5h5) Description In Unity 2.6, several functions, namely Vector3.Lerp, Vector4.Lerp, and Color.Lerp, were sped up a fair amount compared to the previous versions of Unity. Unfortunately, they—along with other Lerp functions—still aren't as fast as they could be. Perhaps this will be changed in the future, but as of Unity 3.5, replacing these with user-made functions results in a noticeable speed increase. "Noticeable" is relative, though...in general usage, it's unlikely to be worth the bother of using this script. On the other hand, if you're running routines that operate on large datasets and/or typically loop hundreds of thousands of times or more, then it can be worthwhile. Basically, any time you really want to squeeze more speed out of your code. This also adds two new functions: Vector2Lerp and SuperLerp. (Vector2.Lerp was added in Unity 3.0, but this implementation is a little faster.) Usage Put the MathS script in Standard Assets; this way it can be called easily from Javascript and Boo (if you're not using Standard Assets, you'll have to make this folder). Several of the functions are drop-in replacements...Mathf.Lerp, for example, can be replaced with MathS.Lerp and nothing will change except for faster operation. (As in the iPhone 3GS, the "S" stands for "Speed". Cheesy, eh?) The directly replaced functions are: MathS.Lerp, MathS.InverseLerp, and MathS.SmoothStep. In addition, you can replace Color.Lerp with MathS.ColorLerp. Vector3.Lerp can be replaced with MathS.Vector3Lerp. Vector4.Lerp can be replaced with MathS.Vector4Lerp. New Functions Vector2.Lerp doesn't exist prior to Unity 3.0, but is included here in case you need it: static function Vector2Lerp (from : float, to : float, value : float) : Vector2 Linearly interpolates between two vectors: from towards to by amount value, where value is clamped between [0...1]. Another new function is MathS.SuperLerp. This takes the form: static function SuperLerp (from : float, to : float, from2 : float, to2 : float, value : float) : float It's the equivalent of doing this: Mathf.Lerp (from, to, Mathf.InverseLerp (from2, to2, value)) In other words, it's like Lerp, except the control parameter is an arbitrary range instead of only 0 through 1. The arbitrary range itself is controlled by value, which is clamped between from2 and to2. The reason for using SuperLerp is that it's faster and a little simpler than using the Lerp/InverseLerp combo. An example of usage, which would be useful for underwater effects: <javascript>function Update () { // Lerps fog density from .02 when player is at y position 0 and above, // though .4 when player is at y position -100 and below RenderSettings.fogDensity = MathS.SuperLerp(.02, .4, 0.0, -100.0, transform.position.y); }</javascript> Unclamped Variations Namely: MathS.LerpUnclamped, MathS.InverseLerpUnclamped, MathS.SmoothStepUnclamped, and MathS.SuperLerpUnclamped. As the names suggest, these are unclamped versions of the respective functions. Normally with Lerp and SmoothStep, the control (third) parameter is clamped between 0 and 1. With InverseLerp, the third parameter is clamped between the first two, and with SuperLerp, the fifth parameter is clamped between the third and fourth. But with the unclamped versions, there are no contraints. Other than that, they work the same. For example: <javascript>var foo = MathS.LerpUnclamped (100.0, 200.0, .5);</javascript> As for the purpose, as you might guess, this is in the interest of still more speed. For example, if your code using Lerp is written in such a way that it guarantees the control parameter is never below 0 or above 1 anyway, then there's no reason for the Lerp function to waste time checking this every time it's called. Warning: since there is no clamping, control values outside the 0..1 range will naturally return incorrect values. In the above example, using 1.5 instead of .5 will result in 250, instead of 200 like you'd normally get with Lerp. Of course, it's possible for this to actually be a feature rather than a limitation, depending on what you want to do with your code. If you're wondering why there are no unclamped versions of ColorLerp, Vector3Lerp, and Vector4Lerp, see the benchmarks below...for some quite strange reason, the unclamped versions are actually a little slower. So there doesn't seem to be much point in including them. Benchmarks The numbers below were generated by a simple loop iterating 10 million times, with an even mix of control variables inside and outside the allowed ranges. For example, Mathf.Lerp (100.0, 200.0, .5) and Mathf.Lerp (100.0, 200.0, 1.5). The tests were run a number of times and the results were averaged from all runs. Actual speed differences ouside of synthetic benchmarks will, of course, depend on a number of factors, such as what else your code is doing, CPU speed and type, version of Unity, etc. Making your own tests is encouraged in order to confirm that using this script is actually beneficial for your projects. (One of my apps makes heavy use of SuperLerp in particular, and switching from Mathf.Lerp/InverseLerp to the MathS.SuperLerp function was a big reason for some substantial speed gains between versions—the 3.5X faster rate does in fact seem to apply.) C# - MathS.cs <csharp>using UnityEngine; public class MathS { public static float Lerp (float from, float to, float value) { if (value < 0.0f) return from; else if (value > 1.0f) return to; return (to - from) * value + from; } public static float LerpUnclamped (float from, float to, float value) { return (1.0f - value)*from + value*to; } public static float InverseLerp (float from, float to, float value) { if (from < to) { if (value < from) return 0.0f; else if (value > to) return 1.0f; } else { if (value < to) return 1.0f; else if (value > from) return 0.0f; } return (value - from) / (to - from); } public static float InverseLerpUnclamped (float from, float to, float value) { return (value - from) / (to - from); } public static float SmoothStep (float from, float to, float value) { if (value < 0.0f) return from; else if (value > 1.0f) return to; value = value*value*(3.0f - 2.0f*value); return (1.0f - value)*from + value*to; } public static float SmoothStepUnclamped (float from, float to, float value) { value = value*value*(3.0f - 2.0f*value); return (1.0f - value)*from + value*to; } public static float SuperLerp (float from, float to, float from2, float to2, float value) { if (from2 < to2) { if (value < from2) value = from2; else if (value > to2) value = to2; } else { if (value < to2) value = to2; else if (value > from2) value = from2; } return (to - from) * ((value - from2) / (to2 - from2)) + from; } public static float SuperLerpUnclamped (float from, float to, float from2, float to2, float value) { return (to - from) * ((value - from2) / (to2 - from2)) + from; } public static Color ColorLerp (Color c1, Color c2, float value) { if (value > 1.0f) return c2; else if (value < 0.0f) return c1; return new Color ( c1.r + (c2.r - c1.r)*value, c1.g + (c2.g - c1.g)*value, c1.b + (c2.b - c1.b)*value, c1.a + (c2.a - c1.a)*value ); } public static Vector2 Vector2Lerp (Vector2 v1, Vector2 v2, float value) { if (value > 1.0f) return v2; else if (value < 0.0f) return v1; return new Vector2 (v1.x + (v2.x - v1.x)*value, v1.y + (v2.y - v1.y)*value ); } public static Vector3 Vector3Lerp (Vector3 v1, Vector3 v2, float value) { if (value > 1.0f) return v2; else if (value < 0.0f) return v1; return new Vector3 (v1.x + (v2.x - v1.x)*value, v1.y + (v2.y - v1.y)*value, v1.z + (v2.z - v1.z)*value ); } public static Vector4 Vector4Lerp (Vector4 v1, Vector4 v2, float value) { if (value > 1.0f) return v2; else if (value < 0.0f) return v1; return new Vector4 (v1.x + (v2.x - v1.x)*value, v1.y + (v2.y - v1.y)*value, v1.z + (v2.z - v1.z)*value, v1.w + (v2.w - v1.w)*value ); } }</csharp>
http://wiki.unity3d.com/index.php?title=SpeedLerp&oldid=12494
CC-MAIN-2013-20
refinedweb
1,336
66.94
Go Syntax Go Syntax A Go file consists of the following parts: - Package declaration - Import packages - Functions - Statements and expressions Look at the following code, to understand it better: Example import ("fmt") func main() { fmt.Println("Hello World!") } Example explained Line 1: In Go, every program is part of a package. We define this using the package keyword. In this example, the program belongs to the main package. Line 2: import ("fmt") lets us import files included in the fmt package. Line 3: A blank line. Go ignores white space. Having white spaces in code makes it more readable. Line 4: func main() {} is a function. Any code inside its curly brackets {} will be executed. Line 5: fmt.Println() is a function made available from the fmt package. It is used to output/print text. In our example it will output "Hello World!". Note: In Go, any executable code belongs to the main package. Go Statements fmt.Println("Hello World!") is a statement. In Go, statements are separated by ending a line (hitting the Enter key) or by a semicolon " ;". Hitting the Enter key adds " ;" to the end of the line implicitly (does not show up in the source code). The left curly bracket { cannot come at the start of a line. Run the following code and see what happens: Example import ("fmt") func main() { fmt.Println("Hello World!") } Go Compact Code You can write more compact code, like shown below (this is not recommended because it makes the code more difficult to read):
https://www.w3schools.com/go/go_syntax.php
CC-MAIN-2022-40
refinedweb
254
77.03
#21 Posted 28 October 2004 - 08:19 PM #22 Posted 28 October 2004 - 08:44 PM? #23 Posted 28 October 2004 - 10:17 PM bladder said: class Foo { Foo() { // Hello world! } }; static Foo *fooConstructor() { return new Foo(); }fooConstructor can be used as a pointer, passed around to create the object we want without keeping track of the actual type of object we need. I don't recommend this approach if you can avoid it though. I once had to use it to construct an object from assembly code. I searched for several days how to get the pointer of the constructor into the assembly code, until I realized how simple it was... #24 Posted 29 October 2004 - 02:53 AM Dia Kharrat said:? Q1) const char* is a pointer to constant data; char const* is also a pointer to "char const" ie: to constant data. Thrid one is a constant pointer to data (data can be changed but not pointer). Q2) Because the derived class hasnt been created yet? Q3) If you have the following situation Renderer* r = new D3DRenderer(); delete r; If you want r~D3DRenderer to be called then ~Renderer better be virtual. - Me blog #25 Posted 29 October 2004 - 03:52 AM Q 000) What's the difference between 'char* = "bah"' and 'char[] = "blah"'? Besides the difference between "blah" and "bah"? I'm guessing that the second one is not null-terminated, am I right? Q 005) What's the maximum value x can contain? unsigned int x:5; My guess is 31. The ':5' limits it to using 5 bits, correct? Q 018) What does the following macro do? #define macro(x, y) (int)(&((x*)0)->y) That's kinda cool, actually.. #26 Posted 29 October 2004 - 05:51 AM But as for your answer, no, they are both null terminated. The difference is that char[] allocated memory for 'x' number of characters (5 in this case) whereas char* just allocated memory to store a pointer, and *assumes* that it points to a valid string of characters. Furthermore, char[] does not point to const data and is more solid then char*. char* may point to const data, or it may not. for example try doing this: char a[] = "blah"; char* b = "blah"; strcpy( a, "halb" ); // will not crash strcpy( b, "halb" ); // most probably will crash. Quote - Me blog #27 Posted 29 August 2005 - 04:43 AM #28 Posted 29 August 2005 - 09:13 AM cdgray said: Don't post to topics that are almost a year old unless you have a really good reason. Saying you enjoyed the thread isn't. He who knows not and knows that he knows not is ignorant. Teach him. He who knows not and knows not that he knows not is a fool. Shun him. #29 Posted 02 September 2005 - 10:33 AM Q 000) The first defines a pointer to some statically allocated buffer, the second defines an array of 5 chars in the current scope. Q 001) Use functions (primarily used for operators) defined in the same namespace as the type you use the operators on. Without koenig look-up, this wouldn't work: #include <iostream> #include <string> int main () { std::string blah ("blah"); std::cout << blah; }because the operator << (ostream &, const string &) is defined in the std namespace, and you're not explicitely importing everything from the std namespace into the global namespace using a using directive (using namespace std;) Q 002) template<class T> void foo(T * t); // #1 template<class T> void foo(const T * t); // #2 int main() { const int i = 3; foo(i); // calls #2 with T=int -not #1 with T=const int- because it is more specialized } Q 003) While primarily used to construct an object in a given piece of memory using a void * as second argument to new, it is practically any defined new operator with more than 1 parameter char buf[sizeof(MyClass)]; new (buf) MyClass (123); // constructs a MyClass inside buf. Q 004) It is called when the constructor throws an exception when constructed using a placement new operator Q 005) 31 Q 006) Depends on the actual bitsize of short so this question is unanswerable, but assuming it's 16 it will output "==" and a newline. Q 007) Nittpick answer: an incomplete if statement evaluates to nothing but a compile error Serious answer: When x is some value type that evaluates to 1 or true (or when x is of some type T for which operator==(T, T) and operator==(bool, T) are defined and the latter returns true for some value of x Q 008) I'll ignore the custom types for x for now, x can be anything but a value that evaluates to 0 or false. Q 009) Undefined. Q 010) "0", followed by a newline, followed by "1", followed by a newline. Q 011) By using a placement new and an explicit destructor call: MyClass * c = new (buffer) MyClass; c->~MyClass(); Q 012) Yes. Q 013) A template specialization is a specialization of a template for a specific set of template parameter values. Partial specialization is a form of template specialization where a class (or struct) is specialized but not for a complete set of explicit template parameters. template<class T> struct MyType { }; template<class T> struct MyType<T *> { }; // partial specialization for all pointers template<> struct MyType<bool *> { }; // explicit specialization for bool* Q 014) int MultiplyBy321(int val) { return (val << 8) + (val << 6) + val; } Q 015) template <class T> struct TypeTraits { static const bool isConst = false; // you probably want more definitions here }; template<class T> struct TypeTraits<const T> { static const bool isConst = true; }; template<class T> void foo() { if (TypeTraits<T>::isConst) std::cout << "T is const" << std::endl; else std::cout << "T is not const" << std::endl; }Or you could use the TypeTraits<T>::isConst as a template parameter to do more compile-time logic. Q 016) Polymorphism, defining a derived type with more specialized functionality. Because a derived class inherits everything from it's base, it can be seen as a base. Q 017) std::ostringstream output; std::ifstream input ("file.txt"); output << input.rdbuf();output.str() now returns a std::string with the contents of the file, assuming everything worked out fine (you should check for errors on input) Q 018) It returns the offset of a member in a struct/class. Note that this doesn't work if y is a bitfield or a type with an operator & that doesn't what you expect. - Currently working on: the 3D engine for Tomb Raider. #30 Posted 30 May 2012 - 02:21 PM .oisyn, on 02 September 2005 - 10:33 AM, said: Why is int x = 2; x += x++;Why is the value of x undefined, exactly? Isn't this defined by operator precendence? #31 Posted 30 May 2012 - 06:50 PM int x = 2; int tmp = x; x = tmp + 1; x += tmp; // x == 5 // or int x = 2; int tmp = x; x += tmp; x = tmp + 1; // x == 3 - Currently working on: the 3D engine for Tomb Raider. #32 Posted 01 June 2012 - 01:43 PM bladder, on 28 October 2004 - 12:09 PM, said: The funny (sad?) thing about a quiz like that is that you can find people who can answer all these didactic questions, yet still would not be able to code their way out of a box. 1 user(s) are reading this topic 0 members, 1 guests, 0 anonymous users
http://devmaster.net/forums/topic/1402-dare-to-test-your-c-knowledge-here/page__st__20__p__10318
CC-MAIN-2013-20
refinedweb
1,246
66.07
Introduction With the growing popularity of social networking websites such as Facebook and Twitter, more and more websites are integrating them in their pages. Facebook and Twitter Helpers for WebMatrix allow you to easily integrate the respective applications into ASP.NET MVC Razor based websites. Helpers are basically ready pieces of code that allow you to reuse the code in your pages with only a few lines of code from your side. These easy to use helpers make it possible for developers to achieve Facebook and Twitter integration without the need to know the background technical details. This article is intended to give you an overview of Facebook and Twitter Helpers for WebMatrix and how to install and use them in ASP.NET MVC 3 websites. Overview of Facebook and Twitter Helpers Facebook Helper for WebMatrix allows you to integrate Facebook Social Plugins into your website. The Facebook Social Plugins include the Like button, Comments, Activity feed and more. Depending on the social plugins you wish to use, you may need to call initialization code before using that plugin. Of course, not all social plugins require initialization. In the examples discussed later in this article you will use both types of the plugins. Installing Facebook and Twitter Helpers in a WebMatrix Site In order to use the Facebook and Twitter Helpers for WebMatrix, you need to install them in a WebMatrix website. Let's see how to install them by creating a new website in WebMatrix. Open WebMatrix and select New Site > Site from Template. Then create a website named SocialPluginsDemo based on Starter Site template. Figure 1: Open WebMatrix and select New Site > Site from Template Once the website is created click on the Files option and you should see a list of files as shown below: Figure 2: A list of file options Now click on the Site option and locate the "ASP.NET Web Pages Administration" option. Create a password as suggested by the on-screen prompt and log into the administration area. Search for Facebook and Twitter keywords and you should see Facebook and Twitter Helpers listed as shown below: Figure 3: ASP.NET Web Pages Administration Figure 4: Facebook and Twitter Helpers NOTE: There are three separate helpers - Facebook Helper, Twitter Helper and ASP.NET Web Helpers Library - in the list. The ASP.NET Web Helpers Library also includes many additional helpers. For the sake of this article you will use Facebook Helper and Twitter Helper. Click on the Install button to install both of the helpers to your website. Installing both of the helpers will add certain files to your website. Figure 5: Installing both of the helpers will add certain files to your website Notice the NuGet packages added to the website and also the additional folders (such as Facebook). Now you are ready to use Facebook and Twitter Helpers in your website. Using the Features of Facebook Helper Now that you have successfully installed Facebook and Twitter Helpers, let's use Facebook Helper to render a Like button, display activity feed and to display a Comments box. The first two features don't need any kind of initialization whereas displaying Comments box requires initialization. Open Default.cshtml file and add the following code to it: <h2>Like this page? Click on the Like button below...</h2>@Facebook.LikeButton() <h2>Activity feed</h2> @Facebook.ActivityFeed("some_website_url_here") The above code makes use of two social plugins of Facebook Helper - the Like button and Activity feed. The Like button social plugin renders a Like button in your web page whereas the Activity Feed plugin displays stories when users like content on your site and when users share content from your site to Facebook. Change the URL of the website to suit your setup and run the web page. If everything goes fine your page should resemble the following figure: Figure 6: The Facebook Like button and Activty feed Notice how the Like button and Activity Feed box are rendered in the web page. Next, let's add a Comments box to the same web page. Displaying a Comments box requires initialization and requires a few extra steps from your side. Firstly, visit Facebook Developer's web page and create a new Facebook application. We won't discuss the process of creating a new Facebook application here. All you need to work further with this example is your Facebook application's ID (App Id) and Secret (App Secret). Once you have those details, add the following lines of code to Default.cshtml file: <h2>Comments</h2> @{Facebook.Initialize("your_app_id_here", "your_app_secret_here");} @Facebook.GetInitializationScripts() @Facebook.Comments() The Initialize() method initializes the Facebook helper with your application settings. Make sure to replace your Facebook application's ID and application's secret key. The GetInitializationScripts() method initializes the Facebook JavaScript SDK to be able to support the XFBML tags of the social plugins. Finally, the Comments() method renders the comments box in your web page. There is one more thing you need to do before running the web page. Open the layout file of the web site and modify the <HTML> tag as shown below: <html lang="en" @Facebook.FbmlNamespaces()> The FbmlNamespaces() method emits certain FBML related namespaces. That's it! Run the web page again and you should see Comments box like this: Figure 7: Facebook Comments box Using the Features of Twitter Helper Now let's put Twitter Helper to use and render some Twitter specific features. We will render the following features of Twitter on the page. - Display profile box for a Twitter user - Search tweets and display the search results in a box - Display a Follow button - Display a Tweet button Add another ASP.NET web page (.cshtml) to the website and key in the following code: <h2>My Twitter Profile</h2> @Twitter.Profile("twitter_username_here") <h2>Search results for #aspnet</h2> @Twitter.Search("aspnet") <h2>Follow Me</h2> @TwitterGoodies.FollowButton("twitter_username_here") <h2>Tweet Something</h2> @TwitterGoodies.TweetButton(TwitterGoodies.DataCount.Horizontal, "Social Networking WebMatrix Tips", "", TwitterGoodies.Languages.English, "twitter_username_here") The above code makes use of Twitter helper. The usage of various helper methods is straight forward and self-explanatory. For example, Profile() method displays a profile box for a specified Twitter user as shown below: Figure 8: Twitter Profile Box Similarly, TweetButton() method that accepts tweet text, URL, language and user displays a Tweet button. Clicking on the Tweet button opens a dialog for entering the tweet. Figure 9: Tweet Dialog Box Summary Facebook and Twitter helpers for WebMatrix allow you to integrate social plugins and features of the respective sites into your own website. The Like button, Comments box, Twitter profile, Tweet button and more can be added to your web page with just a few lines (often single!) of code. In order to use these helpers you need to install them to your WebMatrix website and then consume the respective helper methods. veryPosted by jaya on 01/10/2013 02:38pm very help fulReply
https://www.codeguru.com/csharp/article.php/c19285/Using-Facebook-and-Twitter-Helpers-in-WebMatrix.htm
CC-MAIN-2018-51
refinedweb
1,159
55.34
Writing POST request We use POST method when we have to submit some data that will make some changes in webserver. Inorder to invoke a POST request,specify the method attribute of html form as POST. Upon submission of form POST method will be called. The above html form contain a textbox to read name. Now let’s look how to read the name entered into the textbox from inside a POST method. def POST(self): name = web.input() return 'Entered name is '+name.user Note that the ‘user’ is the name attribute of textbox. Usually we pass our values through ‘web.websafe()’ function due to security reasons. ( web.websafe(name.user)) Redirect to a new page after POST def POST(self): name = web.input() f = open("file.txt","a") f.write(name.user) f.write("\n") f.close() raise web.seeother('/names') The above function describe two attributes. First one is, how to write the input value into a file, and the second is how to redirect to a new page from a POST method. Inorder to write into a file just open file in append mode.This is to write all names in each submission. Then write into file using write attribute of file. Inorder to redirect to a new page we use web.seeother() function. Pass the url of page as arguement inside the function call. Here I have given the url ‘/names’ which contain all the names entered through textbox.
https://jineshpaloor.wordpress.com/2011/07/14/web-py-some-quick-references/
CC-MAIN-2017-22
refinedweb
244
77.74
How to Connect to the Outbrain API - Authenticate using Python There are thousands of reasons why you would want to connect to the Outbrain Amplify API. Regardless of yours, you will first need to go through the authentication. Here’s our guide of how to. This is a part in our series of how to leverage the APIs of Native Advertising Platforms for smarter campaign management and reporting. A while back we wrote an article on the authentication process and how to connect to the Taboola API using python. Make sure to also check that out if you looking to work their API. Similarly to then, we will be using python through Jupyter Notebook. For reference, here’s the API documentation for Outbrain Whether you’re annoyed by the manual effort of uploading piles of images and headline combinations or frustrated by not being able to structure reporting data the way you need it. The Outbrain Amplify API will help you maintain your sanity. How do you get started with it though? Access to the Outbrain API - Do you have it? In order to be able to use the Outbrain Amplify API as an advertiser you first need to get approval from Outbrain. If you don’t yet have it but already have an advertiser account for Outbrain, you can request Outbrain API access here. However, it might be faster and simpler to just directly ask your Outbrain account manager for access instead. If you are unsure if you already gotten approved for using the API or not. There is one easy way to check it. Log into your account on my.outbrain.com. In the top right corner it should say: Logged in as name@email.com. Click on it and check if Amplify API Token appears in the drop down menu. See screenshot below. If it’s there you have already been approved for using the API and can move to the next step. Otherwise get in touch with your account manager or use the link above to request it. You can actually use the link from this drop down to generate a Token directly in the interface that can be used for the API. As most likely, you would want to avoid manually logging in to the interface and collecting the Token when using the Outbrain API We are however going to explain how to generate one directly in the API. The Outbrain Amplify API Token What is the Outbrain API Token The Outbrain Amplify API Token needs to be included in every request that you make to their API. It is what is telling the API which user the request is coming from and that you actually are allowed to make a request on the behalf of a certain marketer account. Understanding how users and marketers are structured for Outbrain is not relevant for the scope of this guide. But if you are interested, we have a more detailed explaination on Outbrain users and marketers in our article on the Outbrain Marketer ID. The Token is then representing your credentials as a logged in user. There are a few things to keep track of regarding the Outbrain Token: - Once you generate a new Token, it is valid for 30 days - You can keep generating new Tokenswith the previous still working. - Important - only two new can be created per hour. In other words, keep track of them and try to avoid unnecessarily generating new Tokens. Frustrating to wait for an hour before you can continue working. - The Outbrain APIis restricted to 30 requests per second and Token. This is more than enough for almost all intents and purposes. How to generate an Outbrain API Token We already covered one of the two ways of creating an Outbrain Token, manually from the user interface at my.outbrain.com. Now, more interestingly, how do you do it directly from the API. Start up Jupyter Notebook, or whichever IDE you are using to run Python. And let’s import the same packages we used for the guide of how to access the Taboola API. import requests import json Run it by holding shift and clicking enter. If there are no errors if should look something like the following screenshot: We will now need to define the Outbrain API url, and the username and password that is used to login to your Outbrain account. The Outbrain API is always using the as it’s base and different extension for various purposes. The relevant for authenticating and generating a Token, and thus for us now, is url = '' username = 'name@email.com' password = 'xxxxxxxxxxxx' Then we are going to make a GET request to the /login resource using our username and password. These are passed using HTTP Basic Authentication. No worries if you don’t know what this is, you don’t need to for now. The request will then look like this: response = request.get(url + '/login', auth=requests.auth.HTTPBasicAuth(username, password)) Let’s check whether we got request succeeded and what the response was. response.ok response.json() You should now have the following output. The True from testing response.ok indicates we got a 200 Status Code (working like expected). In case it returns False there will likely be a message in the response from response.json() that says what went wrong. We now successfully authenticated and generated a Token. It is part of the reponse and called OB-TOKEN-V1 (Outbrain Token version 1) This should be used for all subsequent requests to the Outbrain Amplify API. But first, let’s save it. token = response.json()['OB-TOKEN-V1'] Now let’s see it in action! Master Advertising On Outbrain Register for the ultimate native advertising course and get exclusive insights into building successful Outbrain campaigns. Testing the Outbrain Amplify Token With the Outbrain Token in hand, you can now make requests to the API for your user. Let’s see how the Token used in a request and confirm that it works. We will test listing the ‘marketers’ connected to this specific user that we just authenticated. To do that we use the /marketers resource. The request will look like this: response = requests.get(url + '/marketers', headers={'OB-TOKEN-V1': token}) The Token saved from previously is now included in the headers of the request. Again checking if the request was okay and what the response is: response.ok response.json() This should give you that response.ok returns True again and one or more marketers listed in the reponse from response.json(). Then it is working like it should and your result are looking something like: What’s your next step? If you got through the previous step, you now have access to Outbrain’s API and can start playing around. Regardless of whether you want to use it for checking the approval status of new creatives or collecting reporting data. Just keep including the Token in the header of all future requests, and generate a new one whenever needed. What do you want to use the Outbrain Amplify API for? Share with us on Linkedin or Twitter, and let us know if there’s something you would like us to focus on in a future article. Thanks for reading our guide on how to connect to the Outbrain API. We will keep releasing similar articles on how to take advantage of the APIs of Native Platforms. Check out the Outbrain API documentation for more information on specific requests. If you are looking for a better way to work with, manage and optimize campaigns across native advertising platforms, check out our native advertising management platform. We integrate with the largest networks and offer on top features and insights.
https://joinative.com/outbrain-amplify-api-python-connect
CC-MAIN-2022-05
refinedweb
1,292
64
OpenJDK: More Speed, Less Haste OpenJDK: More Speed, Less Haste A fast release cadence provides the ability to add features without casting them in stone, making them part of the Java SE standard. Join the DZone community and get the full member experience.Join For Free It's now over two years since the release of JDK 9, and with it, the switch to a time-based rather than feature-based release schedule. It seems incredible that it took very nearly eleven years to get from JDK 6 to JDK 9, yet in just over two years, we've gone from JDK 9 to JDK 13. Each release under this new strategy provides a smaller set of features than we had in the old major release approach. What we're seeing, though, is the overall rate of change is faster than it's ever been, which is a significant advantage for keeping Java vibrant and attractive to developers. You may also like: Love it or Hate it, Java Continues to Evolve One of the things that is now possible with a fast release cadence is the ability to add features without casting them in stone by making them part of the Java SE standard. In JDK 9, the introduction of the module system provided incubator modules. Quoting the summary directly from JEP 11, where they are defined: "Incubator modules are a means of putting non-final APIs and non-final tools in the hands of developers, while the APIs/tools progress towards either finalization or removal in a future release." API development is a tricky business, and exponentially so when you're dealing with the most popular programming platform on the planet. Ken Thompson, one of the original developers of UNIX, was once asked what he would do differently if he were redesigning the UNIX system. His reply was: "I'd spell creat with an e." Because of Ken's choice in the late 1960s, we forever have to misspell create when using that system call. The first incubator module was for the HTTP/2 protocol support. If you read through JEP 321, which brought this API into the standard, there were several changes between the initial and final API. APIs, in some ways, are easier to introduce than change because the package namespace can be changed relatively easily. In the case of HTTP/2, the incubator package was jdk.incubator.http, and this was migrated to jdk.net.http in JDK11. Language and VM features are a harder thing to introduce without making them part of the standard, but that is what we now have with Preview Features. Again, quoting from JEP 12, where they are defined: ." An important distinction to make here is that these are not beta features in the normal sense. As the JEP says, these are complete features, just not permanent. The first Preview Feature was included in JDK 12 in the form of Switch Expressions (defined in JEP 325). This is a great feature that allows us to significantly reduce the boilerplate code associated with a switch statement and reducing potential bugs. This is achieved by eliminating the need for an explicit break in each block of case statements and allowing a single assignment of the return value, eliminating the need to remember to do this in each block of case statements. As a preview feature, this is not included by default (since it's not part of the standard). Additional command-line flags must be used for both compilation and with the Java runtime to make it clear that you want to use this feature (-enable-preview). The switch expression is an excellent example of the benefit of this concept. In the initial implementation, the new and old switch syntax could be combined in something like this: int a = switch(b) { case 1: break 5; case 2: break 9; default: break 0; } A break is used here with a numeric value, which is what will be returned from the switch expression. A break can also be used with a label, but since a label cannot be a number (or start with a number), the syntax does not cause a problem. However, feedback led to a decision to drop the use of break and replace it with yield to make it clearer (see JEP 354). In JDK 13, JEP 355 (Text Blocks) was included, which was another preview feature. Aside from the technical details, this feature was interesting because it also included API changes. Three methods were added to the String class (stripIndent, translateEscapes, and formatted). Because these are part of an existing class, an incubator module can't be used (it would also be excessive for three methods). As a result, these three methods were immediately deprecated so that they could be removed in a subsequent release. The trend of incubator modules and preview features is continuing, and JDK 14 will have no less than five of them, as well as switch expressions becoming standard: - JEP 305: Pattern Matching for instanceof (Preview) - JEP 343: Packaging Tool (Incubator) - JEP 359: Records (Preview) - JEP 361: Switch Expressions (Standard) - JEP 368: Text Blocks (Second Preview) - JEP 370: Foreign-Memory Access API (Incubator) Looking at the history of Java, it's easy to wish that we'd had these capabilities right from the very beginning (several features and APIs that could have benefitted from changes based on feedback). However, with multi-year release development cycles, this is not practical. Moving to the twice-yearly JDK release has not just provided more features more quickly but allowed the OpenJDK developers to deliver features in the form that is most useful for developers. Let's see what incubator modules and preview features we get in the future. Further Reading Love it or Hate it, Java Continues to Evolve Welcoming the New Era of Java OK, Java Is Still Free. But Which Version Do I Use and Recommend to My Clients? Published at DZone with permission of Simon Ritter , DZone MVB. See the original article here. Opinions expressed by DZone contributors are their own. {{ parent.title || parent.header.title}} {{ parent.tldr }} {{ parent.linkDescription }}{{ parent.urlSource.name }}
https://dzone.com/articles/openjdk-more-speed-less-haste
CC-MAIN-2020-05
refinedweb
1,026
58.11
A Look Inside FUSE ESB 4: An OSGi-Based Integration Platform A Look Inside FUSE ESB 4: An OSGi-Based Integration. Well, this is almost true. By default the following Camel components are installed with the Camel feature: In the simple file example we used the Camel file component. As you can see on the Camel website, there are a lot of other Camel components available (). So if we would like to use the Camel JMS component in the FUSE ESB we should do an additional installation. But the Camel JMS component is not available by default in the features list. To make other Camel components available in the features list we should add a features URL where the provisioning component can retrieve the additional components. Execute the following command to do this using a URL that matches the version of FUSE ESB that you are using: features addUrl When we execute the ‘features list’ command now, a large number of additional Camel components is available to install, including the Camel JMS component. So to enable the Camel JMS component functionality just execute the ‘features install camel-jms’ command. So now let’s look at a bit more complex example using the Camel Java DSL implemented with an OSGi bundle. Deploying an OSGi bundle In the first example we showed how to use the Camel Spring XML configuration. But when we want to implement a Camel Java DSL route or use Java beans in the integration logic, we need another deployment mechanism. In FUSE ESB 4 the most obvious choice would be an OSGi bundle utilizing the Spring dynamic modules (Spring DM) framework. Figure 3 shows an example we’ll implement with an OSGi bundle. Figure 3 Camel example that consumes a JMS message and validates it against an XML Schema definition. There is a standard target queue and an error queue in case of validation errors. We’ll implement a ValidationRouter class with the Camel Java DSL that consumes a hello message from the camel.jms.in JMS queue. The message exchange will be logged and then it will be validated against the hello.xsd XML Schema definition file. When there are no validation errors, the hello message will be sent to the camel.jms.out queue and in the case of validation errors, the message will be forwarded to the camel.jms.error queue.. In the first two examples we focused on the Camel functionality available in FUSE ESB. But FUSE ESB also provides an easy to use definition for web services with Apache CXF. But to communicate between Camel routes and these web services we need an interaction layer. So we need a bus inside the ESB, which is named the NMR in FUSE ESB 4. Introducing the NMR The NMR project enables the interaction between different components in the OSGi container. This is quite similar to the normalized message router which is defined in the JBI specification, but it’s more flexible and not only dedicated to JBI. The main purpose of the NMR is to mediate between service consumers and service providers. In the example shown in figure 5, you can see that the NMR can be used to communicate between a Camel route definition and a JAX-WS endpoint. This example is provided with FUSE ESB 4 with the name cxf-camel-nmr. Figure 5 An overview of the cxf-camel-nmr example provided with FUSE ESB 4. This example shows the use of a NMR to mediate between a Camel route and a JAX-WS endpoint. For a change we don’t trigger the integration logic with a file or a JMS message in the cxf-camel-nmr example, but with a timer. The timer is defined as part of the Camel route definition. Then a Spring bean, MyTransform, is invoked with its transform method, which basically returns the message that can be sent as a request to the web service. Then the web service is invoked via the NMR and the result is passed on, again to the MyTransform Spring bean, which logs the web service response with the display method. Now let’s take a look at the XML configuration in listing 5. Listing 5 The XML configuration for the Camel route and JAX-WS endpoint definition. <beans xmlns="" xmlns:xsi="" xmlns:osgi="" xmlns:camel-osgi="" xmlns:jaxws="" xsi: <import resource="classpath:META-INF/cxf/cxf.xml" /> <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" /> <import resource="classpath:META-INF/cxf/transport/nmr/cxf-transport-nmr.xml" /> <import resource="classpath:org/apache/servicemix/camel/nmr/camel-nmr.xml" /> <camel-osgi:camelContext <!-- Route periodically sent events into the NMR --> <route> <from uri="timer://myTimer?fixedRate=true&period=5000&exchangePattern=InOut" /> <bean ref="myTransform" method="transform"/> <to uri="nmr:{}HelloWorldImplPort"/> <bean ref="myTransform" method="display" /> </route> </camel-osgi:camelContext> <bean id="myTransform" class="org.apache.servicemix.examples.cxfcamel.MyTransform"> <property name="value"> <value><![CDATA[ <soap:Envelope xmlns: <soap:Body> <ns1:sayHi xmlns: <arg0>Guillaume</arg0> </ns1:sayHi> </soap:Body> </soap:Envelope>] ]></value></property> </bean> <jaxws:endpoint </beans> We’ll start with the timer definition in the Camel route. The timer triggers the Camel route at a fixed rate of 5 seconds and produces an InOut exchange pattern. We need this InOut exchange pattern to communicate with the web service, because we need to send a request (In) and receive a response (Out). In the next step the transform method of the MyTransform Spring bean is invoked. In listing 6 we’ll look at the implementation of the MyTransform class in detail, but this method returns the SOAP envelope as configured with the value property of the myTransform Spring bean definition. So this produces a message with an element of sayHi and a value of Guillaume. Then the hello world web service is invoked which is configured with the jaxws:endpoint. We’ll look at the implementation of the HelloWorldImpl in listing 7, but this method returns the obvious “hello” message. Then the MyTransform bean is called again, but now with the display method, which logs the web service response. Notice that we need to import several XML files at the top of the XML configuration file, to initialize Apache CXF and the NMR.The implementation of the MyTransform class is shown in listing 6, but this will not be too complex. Listing 6 The MyTransform implementation which produces the web service request and logs the response. package org.apache.servicemix.examples.cxfcamel; import java.util.logging.Logger; import javax.xml.transform.Source; import org.apache.camel.converter.jaxp.StringSource; import org.apache.camel.converter.jaxp.XmlConverter; public class MyTransform { private static final transient Logger LOG = Logger.getLogger(MyTransform.class); private String value; public Object transform(Object body) { LOG.info(">>>> " + value); return new StringSource(value); } public void display(Source body) throws Exception { String str = new XmlConverter().toString(body); LOG.info("<<<< " + str); } // omitted the getter and setter for the value property } The HelloWorldImpl class is very simple and is annotated with the @WebService annotation which sets the web service interface class, which just defines the sayHi method in this example. To run this example you can use the provisioning component in FUSE ESB. Just execute the features install examples-cxf-camel-nmr command and the example will automatically be made active, so the timer will produce a new InOut exchange every 5 seconds. In the first three examples we mainly focused on the Camel, CXF and NMR functionality available in FUSE ESB. But we can also use the JBI components that were already available in the version 3. Let’s implement an example where we create an OSGi bundle that’s using JBI components and the Camel functionality we already used. Using JBI components in an OSGi bundle In the second example we used the JMS functionality provided by Camel. But as you may know, ServiceMix also offers JMS functionality via the JMS binding component. You are free to choose your favorite JMS implementation when using FUSE ESB 4, but the JBI components often provide additional functionality on top of the functionality provided by the corresponding Camel components. In FUSE ESB 3 we had to construct a service assembly and implement service units to use the JBI binding components and service engines. In FUSE ESB 4, we can also use an OSGi bundle with a single XML configuration file, just like we did in the earlier examples, to make use of the JBI components provided by ServiceMix. This eases our effort to develop an integration solution using these JBI components. Be aware that not every JBI component available in FUSE ESB 3 has been made OSGi-ready yet, for example the Apache Ode BPEL service engine can only be used with a service assembly deployment model and the same goes for the JSR181 service engine. In the next example we’ll configure the File binding component using Camel routing functionality to show the new OSGi bundle deployment model capability for the use of JBI components. A schematic overview of the example is shown in figure 6. Figure 6 A simple example using the File binding component to show the OSGi bundle deployment model for JBI component configurations. The main difference with the other examples is that we mainly used Camel functionality there. In this example there is a file poller component which consumes files from the insuranceIn directory and forwards the file contents as a JBI message to the Camel route definition. Then the Camel route definition sends the message on to the file sender, which writes a new file to the insuranceOut directory. To keep things simple we only used the file binding component, but you can imagine that you use all the JBI components which are available in FUSE ESB 4. Let’s look at the implementation of this simple example. First, the XML configuration of the file poller and sender and the Camel route definition is shown in listing 8. Listing 8 The XML configuration that defines a file poller, file sender and a Camel route. <?xml version="1.0"?> <beans xmlns="" xmlns:util="" xmlns:xsi="" xmlns:file="" xmlns:camel="" xmlns:osgi="" xmlns:esb="" xmlns:camel-osgi="" xsi: <camel-osgi:camelContext <package>com.fusesource.camel</package> </camel-osgi:camelContext> <file:poller <file:sender <osgi:reference <bean class="org.apache.servicemix.common.osgi.EndpointExporter" /> </beans> The Camel route definition is already shown in a previous example. What’s new here is the file poller and file sender definition. For JBI components you always have to configure a service and endpoint name because this uniquely identifies the JBI component in the container. For the file poller a targetService attribute is configured which defines the target component where the consumed file content is sent to. So this makes sure that the file content is sent to the Camel router. In addition to the file poller and sender, we need to define an EndpointExporter bean that registers the poller and sender service and endpoint name in the OSGi registry. We also need to define an OSGi reference with an identifier of jbi, which enables the Camel route definition to talk with the JBI components. In the RouteBuilder class shown in listing 9, this jbi identifier is used.. }}
https://dzone.com/articles/fuse-esb-4-osgi-based
CC-MAIN-2018-43
refinedweb
1,873
53.81
QML OUTFOCUS DETECTION Hi , Is there some way that I can detect mouse click outside any focussed element.So that I can do some thing when such an event occurs. Say for example , I have a Text input field, when it's in active state, the users clicks outside the textInput field ,anywhere on the screen ,other than inside of that text field.How to handle this situation. Thanks in Advance For outside area you can define the MouseArea and handle the appropriate signals. Thank You sir. Will try the same. there is a signal called onExited, I think that should solve my problem. if you want to catch the mouseHover then onExited will help you. For this you need to set hoverEnabled to true in MouseArea. This is the code that I'm using . The problem with using mouse area is that , If mouse area is set to entire screen i'm not able to edit TextField. When I'm editing text, on clicking anywhere on the screen other than than text Input Field, I want my timer to restart.Not able to achieve this import QtQuick 2.9 import QtQuick.Window 2.3 import QtQuick.Controls 2.2 Window { id:root visible: true width: 640 height: 480 title: qsTr("Timer") property bool blink:false property int blinkInterval:10000 TextField { id:textField width:100 height:100 text: "test" onTextChanged: { reset() } background: Rectangle{ id:back color: "white" width:100 height:100 //anchors.fill: parent ColorAnimation on color{ from: "blue" to: "white" duration: 500 running:root.blink loops: 30 onStopped: { console.log("Focus value:" + textField.focus); textField.focus=false ; } } } } function reset(){ timer.restart() root.blink=false back.color="white" } Timer{ id:timer running: textField.focus repeat: false interval: root.blinkInterval onTriggered: { root.blink=true } } MouseArea{ anchors.fill:parent onClicked: { console.log("Mouse Clicked") if(textField.focus === true) { //If clicked anywhere ,other than textinput field(Not handled the textInput area yet) //then reset the timer reset(); } } } } I'm giving you some sample piece handle the mouse events appropriately. Check and adjust the same to your program. Rectangle { width: 400;height: 400;color:"red" MouseArea{ anchors.fill: parent //enabled: false hoverEnabled: true onClicked: { console.log("Go to hell") } onEntered:{ } onPositionChanged:{ //console.log(" Pos changed ="+mouse.x + " Y ="+mouse.y) var point = Qt.point(mouse.x,mouse.y) if (t.contains(point)) { console.log("I am inside the text field") } } } TextField{ id : t text: "Welcome" hoverEnabled: true } } Did the solution worked for you ? If it worked move the issue to SOLVED state. It helps others. - Shrinidhi Upadhyaya last edited by Hi @Madesh-R , sorry for the late answer,but if instead of handling the cordinates and the position in the mouseArea,i guess the below code is a more optimal way, TextField { id:textField width:100 height:100 z: 1 focus: activeFocus } MouseArea { anchors.fill: parent z:0 onClicked: { console.log("Hello") forceActiveFocus() } }
https://forum.qt.io/topic/97262/qml-outfocus-detection/
CC-MAIN-2020-05
refinedweb
479
61.53
< Modularity | Development Revision as of 11:09, 16 November 2016 Contents - 1 Abstract - 2 Systems - 3 Services - 3.1 The input - 3.2 The message bus - 3.3 The module builder - 3.4 The module knower - 3.5 The compose magic - 3.6 The update system and distribution - 3.7 Miscellanous Abstract The purpose of this document is to describe systems and services used for generic Modularity development, research and possibly future infrastructure deployments, and is intended as a reference guide for the involved engineers and the so-called doers-of-things. If you're new to Modularity, start with the following instead: Systems We use a number of systems for Modularity work. Some of those are dedicated installations for our cause, some are generic and shared with other Fedora initiatives. This section focuses on the former. dev.fed-mod.org The main and currently the only dedicated system we have. This is an OpenStack instance running Fedora. In case the dev.fed-mod.org domain name no longer works, the IPv4 address is 209.132.184.168. We use a shared user account named fedora. If you need access, contact any of the current engineers and provide them with your public SSH key. Automatic COPR rebuilds We run automatic COPR rebuilds of certain modularity projects (fm, modulemd and modulemd-resolver) with a cron job every 15 minutes. Edit ~fedora/rebuild_packages.sh to add yours. Automatic documentation rebuilds We also run automatic readthedocs.org documentation builds every 15 minutes for fm and modulemd with simple cron jobs. Metadata service The metadata-service is deployed on this system and handles all ^/fm/(.+) HTTP requests. This API isn't really defined yet. Browse the project's sources to see how it works. Status reports and agile tools Our Taiga status reports are also hosted on this sytem and regenerated every 15 minutes, again, with a cron job. Other agile tools such as the Modularity Bot or sprint-tools for Trello/Taiga synchronization are also hosted here. See ~fedora/fm-trello-taiga-sync, ~fedora/sprint_tools and the various related cron jobs. Webhosting in general The host is running a generic httpd webserver. The configuration is kept in /etc/httpd/conf.d/fm.conf and we use the default web root for our stuff, /var/www/html. For example, the experimental modules repository is hosted there. Feel free to use this for whatever you need. However, keep in mind the available disk space on this machine is fairly limited. Services The high-level purpose of the majority of the services listed below is described in the Modularity/Infra document. The input Module input data consists of two main parts — the module definition file in the modulemd format and the components, such as RPMs (coincidentally the only format we currently support but expect that to change at some point in the future). In Fedora, both the modulemd files and the components' SPEC files are stored in dist-git and the associated ACLs are stored in pkgdb (Package Database). We use namespaces to distinguish between modules and RPMs in those two systems, aptly named modules and rpms. dist-git For development and testing purposes we use the staging dist-git instance which supports the above mentioned namespaces. The recommended way to interact with dist-git is using the fedpkg tool and configuring it to interact with this instance. Once you have installed fedpkg, edit /etc/rpkg/fedpkg.conf (or wherever your fedpkg.conf is located) to change all occurrences of the default pkgs.fedoraproject.org to pkgs.stg.fedoraproject.org. Here is an example: Install pag via $ sudo dnf install -y pag. Once you have done this, download and set up the custom rpkg repo: $ cd /tmp $ pag clone karsten/rpkg $ cd rpkg/src Next, set fpkg to point to stg/rida. To do this, add fedpkg-stage.conf to /tmp/rpkg and input the following content: [fedpkg]-stage.conf build_client = koji clone_config = bz.default-tracker bugzilla.redhat.com bz.default-product Fedora bz.default-version rawhide bz.default-component %(module)s sendemail.to %(module)s-owner@fedoraproject.org distgit_namespaced = True ridaurl = Next, get the sources: $ fedpkg --config /etc/rpkg/fedpkg-stage.conf co modules/testmodule --anonymous Here, --anonymous is used in case you are not a packager on stg envt. Now build: $ cd testmodule $ fedpkg --config /etc/rpkg/fedpkg-stage.conf module-build Next, review the BPO overview, then check the logs (in case that nothing happens). All repositories dumped by pungi-signed-repo pkgdb A staging pkgdb instance is also available, storing the modules' ACL entries. Contact people with the admin ACL privileges for the given module for commit access. Contact User:Ralph if you need a new module pkgdb entry & dist-git repository. The message bus We expect to use fedmsg extensively for inter-component communication in all stages of module build, testing and distribution. However, since we don't do any of those things yet, there's not much to say about this. Read the upstream documentation to see what Fedora Messaging is about. The module builder The module builder consists of three main components: the build orchestrator, the koji build system and the pungi compose tool. The basic, overly simplified idea of building modules is: - The client (e.g. the module packager) contacts the orchestrator and requests a build. - The orchestrator does all the heavy lifting -- prepares the buildroot as a koji target, clones and builds all the components in koji in the correct order, run CI checks for components and modules, tracks the build states and rebuilds all dependant modules, if required. - After every module build, the orchestrator notifies pungi which in turn creates module deliverables. There are still many open questions regarding this process. We will fine-tune the details on the go. orchestrator The orchestrator is a service with a publicly available interface that the clients can interact with, for example by issuing fedpkg module-build as a module packager, that orchestrates the complete build of modules as noted above. Note the orchestrator doesn't yet exist and although we don't have any specific design in mind, we expect to have something ready in the near future. The orchestrator will emit fedmsg messages to interact with other infrastructure components. It will work with PDC to both store (via pdc-updater) and retrieve module dependency graphs. It will also require its own database to track module build states. The public interface will not be an XMLRPC. And the service will most likely be hosted on dev.fed-mod.org. koji The module RPM content will be built in koji. The current idea is to use koji tags and targets to represent modules and tag inheritance to define buildroots for RPM components. The orchestrator needs to be able to manage these. We expect to use the staging koji instance once we have a usable and somewhat stable orchestrator. Until then, and to allow more flexibility when developing against koji, we also have our own Fedora 24-based koji virtual machines you can play with. They're too large to be shared on dev.fed-mod.org. Contact User:Psabata if you're interested in getting them. pungi Once all the components in the module are built, the orchestrator will signal pungi to create deliverables, such as RPM repositories or container images, from the respective koji tags. pungi will also store compose information in PDC (again, via pdc-updater), push the deliverables to mirrors (either directly or via an update system) and interact with various other currently nonexistent RCM tools. We're considering putting all or most of this functionality directly into koji. The module knower We would like to store certain practical bits about modules in PDC (Product Definition Center) so that it can be easily viewed and queried by both humans and other infrastructure tools. Specifically, we're interested in two kinds of information: - Source inter-modular dependencies — useful for tracking what modules need to be rebuilt - Compose information — for listing contents of deliverables The first use case requires a new data type to be created in PDC. PDC There's a staging PDC instance available we hope to use later in the development cycle. We might set up our own instance on dev.fed-mod.org, if necessary. pdc-updater pdc-updater is a simple, stateless service that responds to fedmsg events and populates the PDC database. It already exists but needs some patching to support the new data type we require. It is unclear whether a staging pdc-updater is available. We might as well deploy our own on dev.fed-mod.org. The compose magic Once built, modules could be composed into products such as Fedora Workstation, Fedora Server or maybe even anything the user defines either for integration QA purposes or building custom-tailored system images for and by the end users. See the Modularity/Infra document for more information about these concepts. CaaS CaaS is not yet properly designed or implemented. Therefore we haven't thought about deployment either. Pixie dust The same for the so-called Pixie dust. The update system and distribution Both modules and module composes will need to be held by some unspecified service before they get pushed to the master mirror. This is necessary for two reasons: - Human testing — verifying the builds and composes work fine beyond the capabilities of our CI - Pushing mass rebuild results as one update — simply to avoid broken states on the end users' systems This might be implemented by patching the current Fedora update system and/or introducing yet another service/layer. We could use the staging bodhi instance for development. Note we have no staging mirrors or systems capable of serving this kind of content at the moment. Miscellanous We also use a number of other systems and services. pagure.io All of our own code is hosted at pagure.io. Many of the projects grant commit access to the @modularity group. If you'd like to a part of it, just ask any of the current members to add you. COPR There's a @modularity project space on COPR where we build & share our tools such as fm, modulemd or modulemd-resolver. All modularity-wg FAS group members should have permissions to create new projects there. Contact any modularity-wg sponsor or administrator to join the group. Jenkins We have a number of Fedora Infra Jenkins jobs set up for the CI of our tooling. Contact User:James if you'd like something added there. GitHub In order to collect our changes and submit them as pull requests, we have our own forks for some projects which are hosted on GitHub. For grooming prior to submitting things upstream (e.g. reviewing and merging pull requests from individual contributors against our forks), contributors are added to the committers team in the fedora-modularity organization. Please ping Nils Philippsen (github) to get yourself added. Our forks:
https://fedoraproject.org/w/index.php?title=Modularity/Development/Developer_Notes&diff=prev&oldid=480245
CC-MAIN-2018-43
refinedweb
1,823
56.76
Back in December, I blogged about a hotfix for the vector<function<FT>> crash in VC9 SP1. An observant reader, User, commented that the hotfix had been packaged incorrectly. We’ve fixed this problem, and you can now download the repackaged hotfix. Stephan T. Lavavej Visual C++ Libraries Developer Join the conversationAdd Comment PingBack from Why did it take over three months to fix the fix, especially if it was just an error with the packaging/installer? "Long test cycles" don’t seem like a good reason considering the bugs which still slip through (e.g. the first fix not working). I wish MS would react to these problems more rapidly. By all means take time to do a good amount of testing, but testing for three months gives you diminishing returns and still does not (and cannot) find all the problems. It’s inevitable that problems will slip through occasionally and when they do we shouldn’t have to wait *another* three months for them to be fixed. If this was the only example of a fix-fix taking three months (or more) then I’d assume something just went wrong and wouldn’t complain but it seems to be a common occurrence across multiple Microsoft products. I’m not having a go at the VC team in particular as it’s not just them. MS as a whole really need to improve on how they do testing and releases. And that may mean testing *less* and being prepared to deal with problems quickly. Other examples which spring to mind: The amount of time it took for the data corruption bug in Windows Home Server — which was known about when it was still in beta — to be solved (one year). Or the way the mid-2008 Vista Media Center roll-up regressed back to XP’s behaviour of unpausing/restarting video when the screen saver kicked in, which was not fixed for three months, and when a fix finally arrived it didn’t actually fix all occurrences of the problem (we’re still waiting!). I have VS2008 failed install!! failed message: MSI (s) (28:AC) [15:53:49:447]: Machine policy value ‘DisableUserInstalls’ is 0 MSI (s) (28:AC) [15:53:49:497]: End dialog not enabled MSI (s) (28:AC) [15:53:49:497]: Original package ==> C:WINDOWSInstaller2873d25.msi MSI (s) (28:AC) [15:53:49:497]: Package we’re running from ==> C:WINDOWSInstaller2873d25.msi MSI (s) (28:AC) [15:53:49:737]: APPCOMPAT: looking for appcompat database entry with ProductCode ‘{80C06CCD-7D07-3DB6-86CD-B57B3F0614D8}’. MSI (s) (28:AC) [15:53:49:737]: APPCOMPAT: no matching ProductCode found in database. MSI (s) (28:AC) [15:53:49:747]: MSCOREE not loaded loading copy from system32 MSI (s) (28:AC) [15:53:50:108]: Opening existing patch ‘C:WINDOWSInstaller223472d.msp’. MSI (s) (28:AC) [15:53:50:118]: Opening existing patch ‘C:WINDOWSInstaller2234730.msp’. MSI (s) (28:AC) [15:53:50:118]: Opening existing patch ‘C:WINDOWSInstaller223472f.msp’. MSI (s) (28:AC) [15:53:50:118]: Opening existing patch ‘C:WINDOWSInstaller223472e.msp’. MSI (s) (28:AC) [15:53:50:138]: Machine policy value ‘AllowLockdownBrowse’ is 0 MSI (s) (28:AC) [15:53:50:138]: Machine policy value ‘DisableBrowse’ is 0 MSI (s) (28:AC) [15:53:50:138]: File will have security applied from OpCode. MSI (s) (28:AC) [15:54:24:167]: Original patch ==> d:d66c505f428edcefd3abbe7c178ae6VS90SP1-KB962219-x86.msp MSI (s) (28:AC) [15:54:24:167]: Patch we’re running from ==> C:WINDOWSInstaller41d7a.msp MSI (s) (28:AC) [15:54:25:248]: SOFTWARE RESTRICTION POLICY: Verifying patch –> ‘d:d66c505f428edcefd3abbe7c178ae6VS90SP1-KB962219-x86.msp’ against software restriction policy MSI (s) (28:AC) [15:54:25:248]: SOFTWARE RESTRICTION POLICY: d:d66c505f428edcefd3abbe7c178ae6VS90SP1-KB962219-x86.msp has a digital signature MSI (s) (28:AC) [15:54:26:079]: SOFTWARE RESTRICTION POLICY: SaferIdentifyLevel reported failure. Assuming untrusted. . . (GetLastError returned 5) MSI (s) (28:AC) [15:54:26:089]: The installation of d:d66c505f428edcefd3abbe7c178ae6VS90SP1-KB962219-x86.msp is not permitted due to an error in software restriction policy processing. The object cannot be trusted. Hi dvy, this KB article might help: — SvenC @Leo: Probably it took 3 months because these days, their installers have become pretty much the most complicated (and slowest) product MS has. C++ compilers and operating systems are trivial compared to the way they make installers… 😉 Although of course, I can hardly blame the VC++ team for that… 🙂 Thanks for the re-release, it certainly helps with a number of pieces of code I have. There still seems to be a problem with the tr1::result_of machinery. The following code fails to compile, but it should (it does with boost). It seems to add a reference to all the arguments its passed. #include <functional> template <class T> struct some_nested_result { template <class> struct result; template <class Func> struct result<some_nested_result(Func)> { typedef typename std::tr1::result_of<Func(T)>::type type; }; }; int main() { typedef std::tr1::function<int (int)> f; typedef std::tr1::result_of<some_nested_result<int>(f)>::type type; return 0; } I’ve posted a connect issue on this. Should have some feedback shortly. Thanks again for all the effort getting TR1 in to MS. This hotfix seems to make intellisense always freeze the editor for a few seconds when typing an identifier. Anyone know how to fix it? [njoubert] > There still seems to be a problem with the tr1::result_of machinery. (This wasn’t affected by the hotfix.) Thanks for the bug report. It’s Dev10#641210 in our internal database, currently assigned to me. It won’t be fixed in VC10 Beta 1, but (no promises) I believe that we’ll be able to fix it in Beta 2. [anon] > This hotfix seems to make intellisense always freeze the editor for a > few seconds when typing an identifier. Anyone know how to fix it? I talked to one of our Intellisense testers, and we’re not sure what’s going on here. (This hotfix affects the libraries only, not Intellisense.) Our best guess is that your NCB file has gotten corrupted. Try closing the IDE, deleting your NCB file, and seeing if the problem goes away. If it doesn’t, please E-mail me at stl@microsoft.com , and I’ll put you in touch with the right people. Stephan T. Lavavej Visual C++ Libraries Developer Wow – that’s some Super-Deluxe support anon is getting… Is anon really billg? Is there a re-distributable available for the newer runtimes? njoubert, Yes, the new QFE has an updated version of all the VC redistributables (vcredist_*.exe, msms and dlls). George Mileka Visual C++ Libraries
https://blogs.msdn.microsoft.com/vcblog/2009/03/25/repackaged-vc9-sp1-hotfix-for-the-vectorfunctionft-crash/
CC-MAIN-2017-22
refinedweb
1,105
64.41
We use the new Asynchronous Agents Library in Visual C++ 2010 to solve the classic Dining Philosophers concurrency problem. Rick Molloy MSDN Magazine June 2009 Read more! See how Windows Forms applications can be adapted to use the new .NET Add-in framework (System.AddIn) this month. Mueez Siddiqui MSDN Magazine July 2008 This is Part 2 of a multipart article series on Windows 7. The focus of Part 2 is the Windows 7 taskbar. Yochay Kiriaty & Sasha Goldshtein MSDN Magazine July 2009 Howard Dierking talks to the inventor of C++, Bjarne Stroustrup, about language zealots, the evolution of programming, and what’s in the future of programming. Howard Dierking MSDN Magazine April 2008 In this article, author John Torjo presents a guide to his C++ GUI library called eGUI++ and explains how it makes user interface programming easier. John Torjo MSDN Magazine June 2008 Paul DiLascia MSDN Magazine July August This month Paul DiLascia codes some Microsoft Office-style dialog box features. HKEY_CLASSES_ROOT\.htm="htmlfile" [HKEY_CLASSES_ROOT\htmlfile\shell\open\command] @="\"C:\\PROGRA~1\\INTERN~1\\iexplore.exe\" -nohome" [HKEY_CLASSES_ROOT\htmlfile\shell\open\command] @="\"C:\\PROGRA~1\\NETSCAPE\\netscape.exe\". // handle WM_SETCURSOR in button class BOOL CMyButton::OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT msg) { ::SetCursor(m_hMyCursor); return TRUE; } // in app's main rc file #include "libres.h" // ID symbols #include "libres.rc" // resources // in libres.h #ifndef LIBBASEID #define LIBBASEID 2000 // or whatever #endif #define IDR_FOO (LIBBASEID+1) #define IDR_BAR (LIBBASEID+2) // and so on â¢â¢â¢ // In app.rc #define LIBBASEID 3000 #include "libres.h" #include "libres.rc" BOOL SomeLibFn(...) { DialogBox(..., IDR_FOO, ...); } BOOL SomeLibFn(..., UINT nDlgID) { DialogBox(..., nDlgID, ...); } // in header file extern UINT LibBaseId; #define IDR_FOO (LibBaseId+1); #define IDR_BAR (LibBaseId+2); // and so on â¢â¢â¢ // in your main lib module UINT LibBaseId = 2000; // in libres.h #ifdef RC_INVOKED #ifndef LibBaseId #define LibBaseId 2000 #endif #else extern UINT LibBaseId; #endif #define IDR_FOO (LibBaseId+1); #define IDR_BAR (LibBaseId+2); // and so on â¢â¢â¢ // in libres.h #define IDR_FOO "MyApp_IDR_FOO" #define IDR_BAR "MyApp_IDR_BAR" â¢â¢â¢ //etc. From the January 2001 issue of MSDN Magazine
http://msdn.microsoft.com/en-us/magazine/cc301397.aspx
crawl-002
refinedweb
349
50.43
On Thu, 2011-05-12 at 22:01 +0100, Konrad Rzeszutek Wilk wrote:> On Wed, May 11, 2011 at 04:02:12PM +0100, Ian Campbell wrote:> > On Thu, 2011-05-05 at 19:11 +0100, Konrad Rzeszutek Wilk wrote:> > > This is the host side counterpart to the frontend driver> > > in drivers/block/xen-blkfront.c. The PV protocol is also implemented by> > > frontend drivers in other OSes too, such as the BSDs and even Windows.> > > > > > The patch is based on the driver from the xen.git pvops kernel tree but> > > has been put through the checkpatch.pl wringer plus several manual> > > cleanup passes. It has also been moved from drivers/xen/blkback to> > > drivers/block/xen-blback.> > > > > > Signed-off-by: Konrad Rzeszutek Wilk <konrad.wilk@oracle.com>> > > > Reviewed-by: Ian Campbell <ian.campbell@citrix.com>> > > > Not much to say below, mostly minor nits really.> > Thanks for reviewing it. I believe I've taken all your apt comments> in consideration. Will post the v3.2 shortly.> > > > +/*> > > + * Function to copy the from the ring buffer the 'struct blkif_request'> > > > Is the blkif namespace fair game? (I was asked to change netif is all)> > It is shared with the frontend driver. I can definitly change it> but was thinking to do it once it is in the tree - that way it can> be one patch for both of them without having to worry about carrying> two branches for blkfront.Sounds reasonable to me!Ian.
http://lkml.org/lkml/2011/5/13/43
CC-MAIN-2015-11
refinedweb
240
75.2
Hurry resource for JQuery-utils Project description hurry.jqueryutils How to use? You can import hurry.jqueryutils from hurry.jqueryutils and .need it where you want these resources to be included on a page: from hurry.jqueryutils import jqueryutils .. in your page or widget rendering code, somewhere .. jqueryutils.need() This requires integration between your web framework and hurry.resource, and making sure that the original resources (shipped in the jqueryutils-build directory in hurry.jqueryutils) 0.8.5.1 (2010-08-20) - Initial public release, releasing jqueryutils 0.8.5.1. Download Project details Release history Release notifications Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/hurry.jqueryutils/
CC-MAIN-2018-39
refinedweb
119
54.49
Managing and displaying large amounts of data: Using QListView, QListBox and QIconView In most of the cases it's quite obvious how to use these three classes and display data in it. But when it comes to displaying larger amount of data it helps a lot if the programmer knows how these classes work internally to be able to use them better, as they offer already some optimations (and also I'm tired of telling the same things again and again :-) Finally these three classes are quite consistent in Qt 2.1, so most of the things I will tell here apply to all of them. First I'll tell some stuff about the basics and later on some more fency stuff is coming. NOTE: Never use QTableView to write a widget for displaying large amounts of data. In most cases one of the classes mentioned here should fit your needs. If this is not the case and you need to write your own class, use QScrollView as baseclass. Although in the first impression QTableView often looks like a good choice later on you will find out that this was not the case, and QScrollView fits better. All classes contain a number of items. To insert such an item it's the easiest way to use the related item class (QListViewItem, etc.). To insert such an item create a new instance and specify the view in the constructor of the item. That's all and nothing special so far. Now when it comes to inserting lots of items at once (e.g. using a loop) I have seen people playing around with timers and other paint optimations the avoid that the views repaint its contents too often (this means that the views don't do a repaint for each item insertion). But the programmers which use these classes don't need to do that at all, the views already do exactly that type of timer magic. So If you do e.g. QIconView *view = .... // something for ( int i = 0; i < 2000; ++i ) { (void)new QIconViewItem( view, QString( "Item %1" ).arg( i ) ); the iconview will not do a repaint for each new inserted item, but it will only do a repaint after the loop terminated. So inserting will not flicker or be slow. The same applies for QListBox and QListView. So, don't do any timer magic of your own, the views do that for you! This means the views internally delay the repaint after inserting a new item using a QTimer. Now when a new item is inserted this timer is stopped and restarted. So, if lots of items are inserted, this repaint timer is stopped and restarted all the time and it never comes to a repaint until the last item has been inserted and some milliseconds elapsed. To remove an item, you don't need to use any methods of the view or so. Just delete the item using the delete operator. The destructors of the items do all the needed work. Now, in some cases you might still want to disable repainting (updating) the view yourself. This can be done using setEnableUpdates( bool ). But remember, all three classes are derived from QScrollView, so you have do enable/disable updating of the viewport!. So do e.g. myView->viewport()->setEnableUpdates( FALSE ); // .... myView->viewport()->setEnableUpdates( TRUE ); Finally also all three view classes have a set of consistent signals. This means each class has some specific signals + some general signals. Most of the time you will use some of the general signals, as these are the signals which are emitted on special mouse and key events. I leave out here the arguments, as they differ a bit depending on the view. But in most signals you get a pointer In other words, Single is a real single-selection view, Multi a real multi-selection view, and Extended a view where users can select multiple items but usually want to select either just one or a range of contiguous items, and NoSelection is for a view where the user can look but not touch. Because of compatibility reasons the enum with the selection modes has not been moved to the Qt namespace. So, each view class contains an enum with the same selection modes, which meas for setting a selection mode you have to use <TheViewClass>::<SelectionMode> (e.g. iconview->setSelectionMode( QIconView::Extended ) ).
http://techbase.kde.org/index.php?title=Development/Architecture/KDE3/Data_Views&oldid=6999
CC-MAIN-2014-15
refinedweb
732
69.52
This source code shows how to use the Sencha Touch Ext.XTemplate: Short source code examples. The following Python example shows how to split a string into a list, get the second element from the list (which happens to be a long), and convert that string to a long value: line = 'Foo bar baz|1234567890' ts = line.split('|', 1)[1] t = long(ts) I needed to do this for my Radio Pi project, and this code worked out well. Here’s an example of how to print the formatted time in Python: import time print time.strftime("%a, %b %d %I:%M %p") That code results in the following output: Thu, May 29 11:26 AM To see what’s running on a Mac OS X port, use this lsof command: $ sudo lsof -i :5150 This command shows what’s running on port 5150. Just change that to whatever port you want to see. To build a Sencha ExtJS application, move to your project’s root directory, then run this command: $ sencha app build Assuming that the build works fine, you can test the production build in your browser at a URL like this: I just tried a quick test of transparency/translucency on Mac OS X using Java, and in short, here is the source code I used to create a transparent/translucent Java JFrame on Mac OS X 10.9: Here are a few examples of how to set the Font on Java Swing components, including JTextArea, JLabel, and JList: // jtextarea textArea.setFont(new Font("Monaco", Font.PLAIN, 20)); // jlabel label.setFont(new Font("Helvetica Neue", Font.PLAIN, 14)); // jlist list.setFont(new Font("Helvetica Neue", Font.PLAIN, 12)); A test application You can use code like the following Scala code to easily test different fonts. Modify however you need to, but it displays a JFrame with a JTextArea, and you can change the font on it: If you want the horizontal and/or vertical scrollbars to always show on a Java JScrollPane, configure them like this: scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS); scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); Other options are: HORIZONTAL_SCROLLBAR_AS_NEEDED HORIZONTAL_SCROLLBAR_NEVER and: I just learned how to send STDOUT and STDERR to a file in a Java application (without using Unix shell redirect symbols). Just add these two lines of code to the main method in your Java (or Scala) program: System.setOut(new PrintStream("/Users/al/Projects/Sarah2/std.out")); System.setErr(new PrintStream("/Users/al/Projects/Sarah2/std.err")); Then when you use: System.out.println("foo"); or Nothing major here, I just wanted to note the use of several scalacOptions in the following build.sbt example:): I learned today that you break out of a Sencha ExtJS Store each loop by returning false from your function. This code shows the technique: Sencha ExtJS - How to dynamically create a form textfield (Ext.form.field.Text) Without much introduction, here’s a large block of Sencha ExtJS controller code. The code needs to be cleaned up, but at the moment it shows: The following code shows how to dynamically create a Sencha ExtJS form textfield, i.e., a Ext.form.field.Text field. Maybe one of the best things about this example is that it shows how to get input focus on a textfield: Without any significant introduction, here are some more Sencha ExtJS code examples. I’m just trying to make my example code easier for me to find; if it helps you, that’s cool, too. The following code shows: Here are two Sencha ExtJS Ext.Ajax.request JSON POST and GET examples. The first one shows how to add a Stock by getting all of the values in a Sencha form (Ext.form.Panel). Keys that I learned recently are: formPanel.getForm()gets the form (Ext.form.Basic) Ext.JSON.encode(formPanel.getValues())JSON encodes all of the form values Here’s the code: onStockFormKeyPress: function(textfield, event, options) { if(event.getKey() == event.ENTER) { Ext.Msg.alert('Keys','You pressed the Enter key'); } } This function is called when the keypress event is handled in the init function of my controller class: Sencha ExtJS Ext.Msg.show examples Here’s a simple Sencha Ext.Msg.show example: Ext.Msg.show({ title: 'Dude', msg: 'Dude, you need to select at least one link.', buttons: Ext.Msg.OK, icon: Ext.Msg.WARNING }); I’ll add more Ext.Msg.show examples here over time.
http://alvinalexander.com/source-code-snippets?page=8
CC-MAIN-2017-17
refinedweb
735
63.39
? The command is "move_to" not "moveto". Note the underscore. Some more info: The chord does work, it's the first command that doesn't - presumably the second masks the first? Either way, I do see: command: moveto {"to": "hardbol"} but the command doesn't work - the cursor stays put. If I remove the chord command, the hardeol command surfaces instead, but the cursor doesn't move to the end of the line. Are 'hardbol' and 'hardeol' deprecated in ST3? ...ah crap, I missed the underscore. Thank you. I still have the problem where the latter command masks the prior one. Is there any way to get the plain shift-space to move to the end of the line, and the quick shift-space,shift-space to go to the beginning? Hmm, not sure why that happens. But you can use a simple plugin. I only minimally tested this though. You can adjust that "500" to something a time you feel is "fast enough". Note that is in milliseconds. import sublime import sublime_plugin import time class MyMoveToCommand(sublime_plugin.TextCommand): last_run_time = 0 def run(self, edit): view = self.view run_time = int(round(time.time() * 1000)) if run_time - self.last_run_time > 500: view.run_command("move_to", {"to": "hardeol"}) else: view.run_command("move_to", {"to": "hardbol"}) self.last_run_time = run_time Then in your key map you will have { "keys": "shift+space"], "command": "my_move_to"} ] Ha! That's perfect, thank you!
https://forum.sublimetext.com/t/solved-st3-keybind-doesnt-work-bug-or-bad-config/9368/4
CC-MAIN-2016-18
refinedweb
231
70.8
Python in a Nutshell 246 Written by my favorite author and Pythonista, Alex Martelli, this book manages to fill three roles in extremely pleasing fashion. First and foremost to me, it is a great read, straight through. Mr. Martelli's prose is always sparkling and always keeps the reader interested. No matter how many Python books you have read, you will learn some nuances from this book, and it is about the best review of the whole Pythonic subject matter that I can imagine. While there is absolutely no fluff whatsoever in these 636 pages, it still makes for rather easy reading because the explanations are so clearly thought out and explored as to lead one gently to understanding, without in any way being verbose. It is obvious that Alex Martelli took his time and put in sufficient thought, effort, and intellectual elbow-grease to make this work a classic for all time. Secondly, this book is the ultimate Pythonic reference book, the best fit to this role I have yet seen. You will keep this book in the most cherished spot on your book shelf, or else right at your side on your computer desk, because you can almost instantly find any topic on which you need to brush up, in the midst of a programming project. Third, Python in a Nutshell is the most up-to-date book on Python (as of April 2003) and includes the best and most complete expositions yet on the new features introduced in Python 2.2 and 2.3. These topics are not only covered in depth, they are integrated into the text in their proper positions and relationships to the language as a whole. They are explained better here than I have seen anywhere else, so much so as to make them not only understandable to me (a duffer), but indeed so that they appear seamlessly Pythonic, as if they had been a part of the language since version 1.0. Topics explored in depth include new style classes, static methods, class methods, nested scopes, iterators, generators, and new style division. List comprehensions are made not only comprehensible but indeed intuitive. The book is surprisingly complete. It covers the core language as well as the most popular libraries and extension modules. It is difficult to choose any one portion of the book to highlight for extra praise, as all topics are treated so well. It is a complete book, the new definitive book about Python. Everything about this book speaks of quality. In addition to the top notch writing and editing, O'Reilly really did the right thing and published this book printed on the highest quality paper, paper so thin that the 636 pages are encompassed in a book much thinner than one would expect for such a size, but strong enough to resist wear and tear. The text is most pleasing to the eye. Holding the book, and turning its pages, gives one a feeling of satisfaction. Any job worth doing is worth doing well. Alex Martelli and O'Reilly have done justice to a topic dear to our hearts, the Python programming language. Perhaps, in years to come, the passage of time may make this book to be no longer the most up-to-date reference on the newest features added to Python. But time can not erase the quality craftsmanship and the shear joy of reading such a well thought out masterpiece of Pythonic literature. You can purchase Python in a Nutshell from bn.com. Slashdot welcomes readers' book reviews -- to see your own review here, read the book review guidelines, then visit the submission page. Ron Stephens would also like you to check out Python City, with "27+ reviews of books about Python. 67+ links to online tutorials about Python and related subjects Daily newsfeed of Pythonic web articles, new sourceforge projects, etc." Nutshell?!? (Score:5, Funny) That's a pretty goddam big nutshell, if you ask me! You ain't seen nothing yet. (Score:5, Funny) Re:Nutshell?!? (Score:2) Or some pretty big nuts. We learned bits and pieces of Python in an Imperative Languages course I took for my CS degree. Enjoyed it, the very little that we covered. I wish the prof had paid more attention to Python than Pascal for that course, but Pascal was his favorite, so that idea got shot down quick ... Re:Nutshell?!? (Score:2) Re:Nutshell?!? (Score:2) Gentoo Zealot translator! (Score:2, give Where's the review? (Score:5, Insightful) Could the author please respond in this thread and give some examples of the new content, rather than just "covers it all"? Re:Where's the review? (Score:4, Insightful) I mean Martelli's the man and all, but don't drop shit like: * "Perhaps the best book about Python ever written" * "my favorite author * "Mr. Martelli's prose is always sparkling and always keeps the reader interested" * "It is obvious that Alex Martelli took his time and put in sufficient thought, effort, and intellectual elbow-grease to make this work a classic for all time." * "You will keep this book in the most cherished spot on your book shelf" * "It is difficult to choose any one portion of the book to highlight for extra praise, as all topics are treated so well." * "Everything about this book speaks of quality." * "Holding the book, and turning its pages, gives one a feeling of satisfaction." * "Time can not erase the quality craftsmanship and the shear joy of reading such a well thought out masterpiece of Pythonic literature." People want to know "What's good and bad about this book" and not "How many ways can I kiss ass". Re:Where's the review? (Score:2) And now for something completely different... (Score:4, Funny) If I had the time I'd come up with it, and I'm sure it would be the funniest joke in the world, much better than the German joke, "two peanuts were walking down the street and one was assorted". Unfortunately, I have to go out for a silly walk, and then onto a mouse club, so I'll have to leave it to someone else to inject some much needed hilarity into these proceedings. Re:And now for something completely different... (Score:3, Informative) I believe you're going for "one was assaulted" (a salted...*zing*) Re:And now for something completely different... (Score:2) Re:And now for something completely different... (Score:2) "Two peanuts were walking down the Strasse. One was assaulted A (hopefully) unbiased opinion on Perl v. Python (Score:5, Insightful) First of all, I don't want to offend anyone, but Perl really is an example of the most horrible way to design a language. I say "design" with tongue-in-cheek, because the language wasn't really designed so much as thrown together from pieces of odd scripting languages (many of which should have been put to rest long ago). The implementation itself is rather unfortunete; because of how it's built you can't really implement perl in terms of itself (well I suppose you could, but not with a slight measure of self-respect), the entire system needs to be scrutinized by security experts before any program written in Perl can be considered secure, and it is doubtful that Perl will ever be re-implemented ever again. That being said, Perl is at least useful for many things ("practical," I believe it's called). People always tell me how they use it for system-administration tasks (for some reason I don't seem to engage in enough adminitration tasks to require perl's help, or if I do they're all suitibly mundane), and it does have an impressive ability to cope with string data (not something I'd base a language on, but at least it stopped people from using SNOBOL). Now Python on the other hand is almost completely a different story. It's supremely orthagonal and elegant in its design, with support for functions as first-class types, an enforcement of clean coding standards through whitespace sensitivity (most Perl coders object vehemently to this because it infringes on their ability to write really ugly code), etc. But the problem is that Python suffers from a lot of Perl's problems and adds a few of its own: you can't implement it in itself, it has no strong typing (even Perl's use strict is ridiculously better), an OO system with no support for data hiding, etc.. As a beginner's language it's ideal, but that's not going to help it be taken seriously when it comes to real computing tasks. If the python developers made some tweaks to the type system and added a real compiler, then I would advocate that most software engineering be moved there. As it stands it's an original language which is a lot of fun to program in, and still has lots of unmapped potential to it. So where does that leave us, now that I've managed to piss EVERYBODY off? Well, I guess I conclude by saying that if you read this and got a sudden urge to throw a molotov cocktail through my window, then you're really taking one language too seriously. If you blind yourself so much that you can't see the faults in Perl or , then you're really no use to anyone in your community, in particular the users who depend on you to build solid, well-rounded applications. Don't be a Python zealot or a Perl zealot; be a programming zealot, learn as many languages as possible, and which one to use in a given situation. That's all I have to say. Perl v. PHP (Score:2, Insightful) what, PHP doesn't suffer from the same problems as perl? whitespace? data hiding? real objects? people use these languages because the fluidity at which they can be written (albeit crappily). conversley, a good programmer will write good code regardless of the pro-active design constraints imposed by the language. etc. excellent troll btw! Re:A (hopefully) unbiased opinion on Perl v. Pytho (Score:5, Insightful) The biggest problem with Python, IMHO, is the online documentation. It's the worst I've ever seen, so abstract that it's of no use to anyone except maybe as a reference for someone who wants to write real documentation. I can only assume that like Python itself, the documentation is the result of an author who wanted to do things "the best" way, without being willing to look outside his own head to determine what that might be. For the language itself, the result was okay - if slightly annoying at times. For the documentation, it's unacceptable. New and different languages can be learned. But with indecipherable and oddly-organized documentation, that's very difficult to even start doing. I had several "false starts" with Python, abandoning it quickly because the documentation (and installation process) were so opaque. If not coerced by my employer into giving it another try, I never would have touched it again. The only reason I stuck with it this last time was because my employer had a stack of Python books for me to use. In the "heavy scripting" domain, I've put a lot of time into Perl, Python, and PHP. PHP's online documentation is the exact opposite of Python's; entirely focused on the practical, with lots of examples and very little theory or background. Perl's is somewhere in the middle. Overall, as a learner I found Perl's documentation to be the best, and as an advanced developer I find PHP's to be supreme, bar none. Python's is a disgrace, useful to neither beginning nor advanced users. It's great that people are writing good books about the language. But in this day and age, it shouldn't be necessary to buy a book just to make sense of an open-source tool. Re:A (hopefully) unbiased opinion on Perl v. Pytho (Score:2, Interesting) Re:A (hopefully) unbiased opinion on Perl v. Pytho (Score:3) It's, for the most part, fine. Yes, there ARE some holes here and there, as there are with a lot of the Re:A (hopefully) unbiased opinion on Perl v. Pytho (Score:3) I find that there are 2 (if not many more) kinds of documentation. Documentation that is meant to be read (more like a book), and documentation that is meant to be used (looked up while using like manpages and msdn). I believe that Python is that of t Re:A (hopefully) unbiased opinion on Perl v. Pytho (Score:2) I just don't see the problem. Re:A (hopefully) unbiased opinion on Perl v. Pytho (Score:2, Interesting) I didn't have any problem with false starts, I went to the python website one day to check it out and the next day I went to one of the online books about python they linked to and I learned a shitload and within a couple hours I began to appreciate and love Python. Re:A (hopefully) unbiased opinion on Perl v. Pytho (Score:2) Yep, I've come to those exact same conclusions. Take a look at the "win32*" API docs hosted at ActiveState, for example win32net.DriveAdd() The docs basically say "Wrapper for the win32 call -- see MSDN for details". No examples of usage? Thanks! OK, I go to MSDN and see a C data struct for arguments Pet Python problems (Score:2, Offtopic) - Python has 'break' and 'continue' like C. But these only affect the innermost loop. Is there a way to break out of an enclosing loop? (In Perl you can label a loop and then say 'next LABEL', etc.) - Failing that, is there a way to get goto statements in Python? They can sometimes be an elegant way to express somethin Re:Pet Python problems (Score:3, Informative) Objects are already passed by reference. You can't change strings because they are an immutable type. If you need references, you can use the weakref module, or create your own wrapper class (delegating accesses to the underlying object). you can define named functions in-line, that work as closures (i. e. usin Re:Pet Python problems (Score:3, Informative) Usually solved by a try/except clause when needed - which it seldom is. - How can I pass a variable by reference? EVERYTHING is a reference. You pass nothing but references. If you call foo(bar), foo will have a reference to the exact same object as bar pointed to. The fact that you can not modify a string p Re:Pet Python problems (Score:2) The usual idiom seems to be: while 1: if exitCondition: break Re:Pet Python problems (Score:5, Informative) Like Java and Lisp -- and unlike Perl -- Python has exception handling. The structured way to get out of an inner loop is the same as the structured way to get out of a deeply nested function call: raise an exception, and trap it at the higher level where you want to "go to". In Python, everything is a reference, but strings are immutable objects. There's no such thing as "modifying the string passed in" -- all the built-in string functions return a new string. However, for mutable types such as lists and dictionaries, functions can certainly modify their arguments, as in this example: Especially since I have some Scheme in my programming background, this is a quirk I find annoying about Python: lambda is underpowered. It's comparable to the old BASIC "DEF FN" in that it allows only expressions, not statements, in the lambda-body. However, you can do what you want by defining a function with a temporary name, using def, and returning it. (In Python it is perfectly valid to have function definitions inside other function definitions, and it does what you expect: defines functions whose names have local scope, but can be returned.) You can also create callable classes, which act like functions instead of object factories. There's an implementation of curry for instance in the Python Cookbook, which does this. Check it out. [activestate.com] There is neither a do/while nor a repeat/until in Python. Again this is something I don't agree with, but the argument is that this keeps the number of redundant keywords down. The convention is to use while loops and escape with break when necessary. Re:Pet Python problems (Score:3, Informative) Perl has exception handling with die/eval. Here is an article [perl.com] about it. Re:Pet Python problems (Score:2) If you're going to use it for that, take a careful look at the documentation for eval: notably, what do you want to do with __DIE__ hooks? There's more than a bit of anti-structured "action at a distance" going on there. Something else to note is that Python and Java exceptions work hand-in-hand with the call stack, and provide useful stack backtraces if you bomb out. ISTR backtraces are an extra you have to ask for in Perl -- the Carp module's confess, if Re:Pet Python problems (Score:2) -Dom Re:Pet Python problems (Score:2) Exception handling to break out of a loop - hmm, yes, I hadn't thought about that. It does seem a bit OTT to raise and catch an exception just for that - a whole 'try/except' block when a simple 'continue LABEL' would have sufficed - but whatever. OK, I think I understand what is happening with strings. If they are immutable then there is no way to implement a function l Re:Pet Python problems (Score:2) That's right. The equivalent in Python is "foo = rstrip(foo)", which does rebind foo to a new string. What you did was create a new name x, local to the scope of g. If what you're after is to retain data among several calls, a class is probably what you want. It can be callable (as in the c Re:Pet Python problems (Score:2) x = 50 def g(): x = 40 g() print x f() > This prints '50', showing that g() cannot access the variable in its enclosing scope. > It's not a closure in the true sense. > The only way I could find to make this work was to resort to global variables - gah! That's the intended behaviour. You can make x a static variable of f: def f(): f.x = 50 def g(): f.x = 40 g() print f.x f() If you don't want it static, create a new object to hold it (or store it on g, etc). Re:Pet Python problems (Score:2) The problem though is similar to what you alluded to with passing variables into functions and wanting the functions to modify them; when in the inner function you say "x = 50", you're rebinding the local-to-g version of x. The end result is that the outer x is then not repointed to the new object. (See the PEP for why, or look at the appropriate part of the "what's new" document [python.org]) In any c Re:Pet Python problems (Score:2) FWIW Guido has said that in Python 3 (still a ways off) that all strings are going to be Unicode, and for binary/byte data they'll be a buffer object (I don't think related to the current buffer object) that will be mutable, since this is typically more useful for byte data. For now strings of bytes and strings of char Re:Pet Python problems (Score:5, Informative) Throw an exception and catch it whereever. Eg: How can I pass a variable by reference? For example, to take a reference to a string, pass it to a function and have that function modify the string passed in. Everything is always passed by reference. You can't modify a string because strings are immutable. The 'lambda' keyword won't accept assignment or even sequencing inside the function body. So anonymous functions you might want to pass around can't do much beyond trivial operations. lambda is a short-hand for def. Use that if the body isn't a simple expression: Is there a do/while statement in Python? Some python tutorials I wrote: Python for BASIC programmers [sourceforge.net] Writing GTK applications in python [sourceforge.net] Re:Pet Python problems (Score:2) def fn (a): _ a[0] = 'Goodbye' a = ['Hello'] fn (a) print a # This will print goodbye However, it's VERY rare that you need to use pass by reference. Instead, consider using multiple return values. (Underscore used to force indentation) Re:Pet Python problems (Score:2) Throw an exception and catch it whereever. Eg: Dude... that's disgusting, not to mention raping the exception system. Exceptions are meant to handle errors. PHP fixes the break/continue problem by giving those operators a parameter. So if you want to continue 2 loops up, you say "continue 2;". Gah. Now I know why I don't use Python. Re:Pet Python problems (Score:2) "continue 2" on the other hand, almost makes me puke, requires a lot more careful tracking of changes in the code, and makes every piece of code tightly-coupled with every other. Puke. Now I know why I don't use PHP. Re:A (hopefully) unbiased opinion on Perl v. Pytho (Score:3, Insightful) You have a point there, but I'd put it in a slightly different way. I'd not tell people to learn as many languages as possible, but rather learn programming and its basics (knowing the architecture behind the scenes, the CPU, is really a lot of fun). There isn't much point in knowing every programming language, but a much better deal to know the syntax used in Re:A (hopefully) unbiased opinion on Perl v. Pytho (Score:5, Insightful) In general, I've noticed Python makes writing programs very fast and very easy to modify later to add new features. It takes me a little longer to write equivilent programs in Perl, but the Perl programs probably run a little faster although they take a bit more effort to modify later. Finally, if I really need a program to run very fast, I can port it to C where it'll run extremely fast, but that will naturally take the longest to write and modify. Having said all that, I use Python programs for those day-to-day administration duties where plenty of tweaks are required. Python works great for CGIs too, and should scale up to a reasonable load. But, if speed or extreme scalability are a requirement, porting a Python prototype over to C is often a good idea. Still, I have no shortage of tasks that require quick programming but don't require great speed - and Python fits those quite well. But if I could compile it to native code, now that would be pretty sweet. Python's niche (Score:2, Interesting) Extending Python with C (Score:2, Informative) If you need more speed than native Python provides, you can always write code in C and wrap it so it is callable from Python. The wrapping is really easy to do, once you have understood the general concepts involved in it. The product I currently work on has about 10000 lines of C code (crypto and networking) which is used this way, and it works perfectly. For more information about extending Python with C, see: Extending and Embedding the Python Interpreter [python.org] Python/C API Reference Manual [python.org] Re:A (hopefully) unbiased opinion on Perl v. Pytho (Score:2, Informative) Actually, one of these is being worked on: There's an active project to write Python in itself. I believe they're taking the same tack as Squeak. John Roth Writing a language in itself (Score:3, Insightful) I won't claim to understand it. It certainly doesn't do anything for the general populace. It ought to be Re:Writing a language in itself (Score:2) E.g.: You don't really need to implement much more than Boolean logic. Numbers can be made from vectors of booleans... etc. Re:Writing a language in itself (Score:3, Insightful) You're right. But I wasn't really addressing this. By implementing a "language in itself", I was really referring to more dynamic languages like Python, Perl, TCL, LISP, Smalltalk, etc. A Pytho Re:A (hopefully) unbiased opinion on Perl v. Pytho (Score:5, Insightful) Uhh.... you are seriously misinformed. data hiding: trivial to implement by overriding the standard accessors and limiting the set of things that can be accessed externally. Since you have full access to the scope and stack, you can even limit things in a fashion similar to java's private/public/protected. I have used this many times to force attributes to be set only through a particular path that involves certain chunks of business logic. implement it in itself: Not sure what your point is, but you can certainly implement the Python VM in itself. The Python VM is actually quite portable as is demonstrated by the excellent Java based implementation found in Jython. strong typing: yes -- python has no strong typing, but it is trivial to check types and constrain APIs to particular types. At times, it would be nice to have strong types, but weak typing also has some extremely powerful uses and patterns. Too dog slow? Uh, no. See the Twisted project for an example of an "internet event server" whose web server implementation is faster-- and more flexible-- than apache. Not that apache is fast, mind you, but something that is faster than apache while maintaining flexibility can certainly claim to have better performance than the server used by, what, 50+% of the world's web servers? Python scales well, it is extremely reliable, and has excellent performance for an interpreted language. Python is used in many mission critical situations in both commercially saleable products as well as in embedded markets. Personally, I have built trading systems in Python. If you have ever been around a Trader when their technology doesn't work, you know that using technology that is fundamentally broken is exceedingly unpleasant (unless you enjoy being yelled at and having heavy things thrown at you). Python proved to be extremely reliable and allowed us to roll out new versions of the software very rapidly. Note that I am not a Python Zealot -- I program in some random combination of Python, C, Objective-C, Java and Lisp on a daily basis. Of all the languages, I prefer to use Python because I can get things done more quickly and with lower maintenance costs than any of the other languages. However, I'm not going to berate a client simply because they insist on using Java-- and certainly not if they have a good reason for doing so.... Until people start using PHP? (Score:3, Informative) Re:A (hopefully) unbiased opinion on Perl v. Pytho (Score:4, Insightful) How is the ability to write a Python compiler in itself practially relevant to most users? Lack of strong typing and no support for data hiding can be thought of as a feature by those so inclined. This is just analogous to objections against 'whitespace sensitivity'. I more closely agree with one of the replies: that Python suffers from horrible documentation. I recommend looking at ActiveState Python for a slight improvement from the web manual. Some _personal_ highlights using python: - learning curve duration: 1.5 hours to start writing moderate complexity RE file parsing scripts. - ability to write a cgi enabled http server in approx 3 lines of code - ability to write a decent cross-platform opengl demo in approx 200 lines of code. using PyGame, PyOpenGL, Numeric etc. Also, please just ignore the zealots, don't acknowledge them with so much disclaimer. all the best, mbaranow Re:A (hopefully) unbiased opinion on Perl v. Pytho (Score:2) Sorry, but this is just baiting. My problem with a lack of block endings is that it makes it hard to see a complete or incomplete block when there is a Re:A (hopefully) unbiased opinion on Perl v. Pytho (Score:2) You need to divide into smaller, more trivial pieces of code. Python is so expressive that functions/methods rarely need to exceed 5-8 lines. Show me any example of a long Python function where you have experienced what you speak of, and I'll explain how and why its too long. Re:A (hopefully) unbiased opinion on Perl v. Pytho (Score:2, Interesting) That being said, Perl is at least useful for many things ("practical," I believe it's called). Python is useful for many things as well, as evidenced by the number of people who use it, including Boeing, Disney, Hewlett-Packard, Industrial Light & Magic, Intel, JPL, Lawrence Livermore Labs, NASA, and Yahoo. Programmers at places like these are usually allowed to make their own decsions about their tools, and they chose Python. These guys are good. They don't use tools that they don't like. This is no Re:A (hopefully) unbiased opinion on Perl v. Pytho (Score:4, Insightful) Other than Performance? and adds a few of its own: you can't implement it in itself Hmm? Its quite trivial to parse Python code in Python, and its qutie trivial to interpret it with Python code, so where's the problem? it has no strong typing (even Perl's use strict is ridiculously better), You're confusing "strong typing" with "static typing". Python has no Static Typing, but indeed has Strong Typing (try '5 + "Hello"' in your Python interpreter). Perl, on the other hand, has no strong typing at all ("Hello" + 5 is perfectly valid in Perl, albeit senseless). Not having Static Typing is not a bad thing - its a concious decision by the language designers. The designers of Python wanted the language to be just-explicit. If you want the program code to express an idea, you express it once - Which is more than implicit, and less than redundant. Static typing is redundant - and avoided in Python as a design goal of minimizing programming time of any task. Another idea behind the lack of static typing is that all lines of code MUST run at least once anyway for any minimal level of reliability, so the compilation-level check adds no value. an OO system with no support for data hiding, etc. etc. Python supports data-hiding, but simply does not enforce it. This is because Python is not a BDL (Bondage and discipline langauge). Instead, there are extremely well-established and documented Python conventions. The prefix underscore that denotes private/protected, The double underscore that denotes private (avoiding namespace clashing by name mangling),. Python isn't a niche language. Its a general-purpose language - and no - its far from being too slow for real CS applications. That's why its successfully used in Search engines, 3d engines, system administration, compilers, games, etc. As a beginner's language it's ideal, but that's not going to help it be taken seriously when it comes to real computing tasks. Python is taken very seriously in many many places, with increasing seriousness. If the python developers made some tweaks to the type system Like what? Static typing conflicts with the Python design goals. and added a real compiler Python already has the Jython compiler to Java, psyco compiler to native code, and others. then I would advocate that most software engineering be moved there. Many already advocate it for all software engineering except for the inner loops which are exported to Python from C code. This proves for many people to be the most effective way to write fast, reliable maintainable code. As it stands it's an original language which is a lot of fun to program in, and still has lots of unmapped potential to it. The unmapped potential is discovered by more people every day Very Pythonic (Score:3, Informative) Also, in response to an earlier post, the fries are spelt Julienne. And are damn tasty. I was surprised, but... (Score:5, Informative) I am normally never disappointed with an O'Reilly book, but I was in this case. I hope it's not the start of a trend for them... Re:I was surprised, but... (Score:2) It looks to me like when they "updated to Python 2.1", they forgot to also upgrade to "book 2.1". Fair warning! Re:I was surprised, but... (Score:2) Sorry 'bout that. I still find [python.org] a better source of information. Re:I was surprised, but... (Score:3, Informative) The Quick Python Book by Harms and McDonald This one covers a quite older version of python (1.5), but is a good tutorial nonetheless. Programming Python by Mark Lutz A very good book to see python in action. Python Standard Library by Fredrik Lundh A very good reference book for some things not covered by Python Essentials (ex htmllib) However, I would greatly avoid the Python Pocket Reference (also by Lutz) just because it doesn't have an index to modules... Re:I was surprised, but... (Score:3, Interesting) One of the hardest things for Python authors to deal with is the constant evolution of the language. For example, the move from the string module to string object methods was a huge change and "Programming Pythonic? (Score:2, Funny) Would you wish to repeatedly read "Ceeish", "Fortranish", "Javanical", "Perlectic", etc? Mildly witty the first time, bleedin' annoying the fourth or fifth. Thank you. Pythonic (Score:4, Informative) Re:Pythonic (Score:2) From the code point of view (as opposed to the overhead API view that your statement takes), a pythonic block of code is one that uses language elegantly: xf = [ x.f() for x in l ] For example, this list-condensation is quite pythonic. It puts the return values for all of x.f() in l into xf. How much Java code did that take again? Re:Pythonic? (Score:2) Re:Pythonic? (Score:2) Oh, well. (Score:5, Insightful) 636 PAGES. This review is quite positive. I'm sure some faults could be found in this book, but suppose for a moment that I take your word for it and assume that this book is perfect. In such a case, I wish that more programming books would be published like this one. I don't currently use Python in my work but I increasingly find that language reference and instruction books are either too darn complicated or too darn simple. You either have to be a complete idiot, who has never seen a computer, let alone programmed one, in order to read a book written for such idiots; or you have to be an unnaturally staid and steadfast compiler writer to understand the endless maze of technical details published into thick volumes intended for such stalwart masters. I find that some of the slimmer, older volumes on C are written in a very readable fashion that require neither of the above virtues. However, newer books make the subject too complicated. Books on C++ are beyond help. Sometimes I wonder if our programming languages are much too complicated and perhaps should be reduced to a small number of basic elements, such elements being combined through the use of multiple languages in order to accomplish a specified goal. On the other hand, doing so will make development much too difficult. As such, it is up to the authors of explanatory volumes to make available a desired level of detail while keeping the material readable. It is this balance that I seek in programming books. Until then, well, I'll have to keep writing small "test" programs to probe the features of the language and of the compiler. Oh yeah... and of course, I would like these volumes to be of allowable length for reading in an afternoon or so. 636 pages sounds like a good length. Re:Oh, well. (Score:3, Insightful) Re:Oh, well. (Score:2) Bingo! You have hit on a major problem that I never see in essays on "why software sucks". When documentation is missing, wrong, vague, or incomplete then the best you can do is test things until you get a "works for me" (the general "you", not specifically the poster of the parent). So what's the problem? If you use trial-and-error to get something working, you can't tell whether Re:Oh, well. (Score:2) Language documentation should effectively explain the language to a real human (not a staid and steadfast compiler writer) who actually needs to use the language (and not someone who doesn't know how to use a mouse but feels they should learn to program). Library documentation, on the other hand, should be extremely detailed. First, a description of the theory behind the library's design should be provided, Medical Anomaly? (Score:5, Funny) Heres some useful python links (Score:3, Informative) O'Reilly's "Nutshell" books are their worst (Score:5, Insightful) Learning Python was great, as was the Python Cookbook. They had something to offer beyond a documentation of Python features (an explanation and an exploration of them, respectively). Unless you have no internet connection or just greatly prefer dead trees, I can't see why you'd get any of the "brown" books. Has anyone here been pleased with O'Reilly & Associates' ever-present "... in a Nutshell" books? I'd be curious to hear what the appeal is. Re:O'Reilly's "Nutshell" books are their worst (Score:2, Insightful) I have a Java Nutshell book and a Linux Nutshell book. The Java Nutshell is next to useless since Sun's Java Documentation is superb and is easier to navigate. The Linux Nutshell book is extremely handy since I'm not aware of any comparable online reference and there are so many obscure commands with random syntax to wade through. So, you would probably find subjects with useful Nutshell books lack a strong, easy to navigate online referenc Java *Examples* in a Nutshell (Score:2) I didn't much care for the Java in a Nutshell but did like the companion volume, Java Examples in a Nutshell. It's the closest that I could find to a "Java Cookbook"-- every other Java book just rehashes the documentation, assuming that if your problem were a common problem, it would be covered in the stock API already. Re:Java *Examples* in a Nutshell (Score:2) The correct approach (ex cathedra): 1) Examples need to be combined with the language, not in a separate book. 2) The book should be about 400-500 pages. If it's longer, you need to Re:O'Reilly's "Nutshell" books are their worst (Score:2) So it really depends on the author and the subject. I don't own Perl in a Nutshell, or Java in a Nutshell though I've programmed in both of those languages, but I bought SQL in a Nutshell because it's well-written, concise, and I have my documentation f No... (Score:2, Funny) "Help! I'm in a nutshell! How did I get in this awfully big nutshell? What kind of nut has a shell like this?" How much does it cost to advertise on Slashdott? (Score:5, Funny) The Best Intro to Python (Score:5, Informative) Python Essential Reference (Score:3, Informative) Then there is Appendix A which gives a short description of all built in functions and exceptions followed by concise descriptions of most of the standard python modules circa 1.5.2 (the newer edition is probably 2.0-ish) that are detailed enough to use as reference. Appendix A also has short examples and detailed explanations with background information where it is beneficial in the descriptions. The module reference is divided into topical sections such as string modules, networking modules, and threading modules and modules with related or complimentary functionality are cross referenced. Finally there is a short Appendix B that explains how easy it is to extend python with C modules and even a bit of how to embed the python interpretter into your own programs and libraries! Most importantly the book is only 274 pages and has a very useful index when you want to use it as a reference. Together with the online documentation at this book is invaluable to me. Better review of the same book (Score:2, Informative) Explain Python to me (Score:2, Insightful) Combines the flexibility of syntax of C with the efficiency of Javascript. Python can't realistically support Lisp-style macros, doesn't support true closures, and many other things of Goodness that make Lisp languages so good for rapid coding. On the other hand, Python's dynamicism makes it very very slow. It's bad enough that the Python zealots [twistedmatrix.com] apparently don't know how to program Java -- as minor corrections to their broken test code result in Java code that just stomp Re:Explain Python to me (Score:2, Insightful) > other things of Goodness that make Lisp languages so good for rapid coding. Strange that Python doesn't support Fortran type line numbers or BASIC type OPEN statements either. If you want to use Lisp, use Lisp. Python is its own animal. > Python is slow. So we have a slow language. So what? Exactly. So what. The speed of the interpreter is usually not the bottle-neck in most app domains. If it is, use Re:Explain Python to me (Score:2) Supporting real closures that allow messing of the enclosing function's namespace with new references is a problem because Re:Explain Python to me (Score:2, Insightful) Not having macros was a deliberate design decision. One of Python's key stengths is easy readability and adding the ability to add/modify language contructs might compromise this. A good, scientifically-oriented numerical facility. What facilities are you looking for, in particular? Python has a double-precision floating point type, unbounded integers and complex numbers as part of the core language. Are you looking for so Re:Explain Python to me (Score:2) rationals are soon to be added to Python, and can for now be implemented in the form of two arbitrarily long objects. fractions are doubles. complex numbers exist in Python even in the syntatic level (try evaluating "4+6j", or "1j**2"). What do you mean by supertypes here? Python's closure handling is broken; it can't even handle simple nested lexical scoping. This can be quite a big deal for writing Dive Into Python (Score:2, Redundant) I've got to recommend Dive Into Python [diveintopython.org] as a great, free, online Python book. (PS. I own the dead-tree version of Python in a Nutshell, I think the above is nice to use as a while-programminng guide) Alternative Recommendations (Score:3, Informative) I concur with other posters that the "Essential Reference" (white and red from New Riders, written by D. Beazley who did SWIG) is an awesome book. It is concise, making it a good reference. I wouldn't think it was a good book for those who have never programmed. If you have some programming experience, though, I expect you'll appreciate this book. The "Quick Python" book from Manning is nice, too. This was my wife's preferred book for learning Python. I've looked through it a bit, and it seems decently concise but with more explanation than "Essential Reference". I used its section on extending Python through C, and found it very useful. That section didn't have everything bit of reference that I needed for conversion specifiers, but their examples were dead-on what I needed to get started. I recently finished reading through "How to Think Like a Computer Scientist: Learning With Python" from Green Tea Press. This book is not a complete reference or guide for Python, nor will it be particularly 'useful' for people who have taken university-level programming and data structures classes. However, it seems to be an AWESOME book for people who don't yet program, or whose only experience is web programming or VB or Perl programming (I'm not saying those things are bad, but very often they don't encourage reasonable programming discipline and methodology). I write "it seems" only because I'm not a beginner or an instructor for intro to programming courses. This book ("How to Think...") is aimed at classroom use, so it doesn't include info about installing Python or starting the Python interpreter under Windows, etc. It does preach solid computer science. Parts of their approach seemed a bit unusual to me, compared to my more classical training, but after a few gripes I always was forced to conclude that their approach was valid and as concise and clear as it could be. The authors are aware of the book being used in high schools and community colleges. I expect that mature students, or any adult intrested in learning proper programming, would benefit from starting with this book. -Paul Komarek Re:Alternative Recommendations (Score:3, Informative) Mark Lutz actually has two noteworthy Python books, "Programming Python" and "Learning Python." "Programming Python" would be the thick book you re Essential Reference / New Riders (Score:2) The only Python book I read now is the New Riders title. I can find just about anything in it as fast as I can search Google. OK, *almost* as fast. Another alternative to Learning Python (Score:2) Learning Python is getting rather dated (version 1.5 or sumthin). As an alternate, I can recommend Peachpit's Visual Quickstart Guide Python by Chris Fehily. It's a thorough, well designed introduction for people who like to learn while doing. Most of the examples are done at the interactive prompt. The chapters are well laid out and progress rationally: the separate chapters on Numbers, Strings, Lists, and Dictionaries are followed by Control Statements. Eventually Modules, Clas Re:Alternative Recommendations (Score:2) -Paul Syntactically Significant Whitespace - YUCK!!! (Score:2) With braces, as in perl or C, I can bounce on the % key and find the ends of a block unequivocally. I can cut and paste from one editor to another, and it still works. I can change tabstops and everything still works. Re:Syntactically Significant Whitespace - YUCK!!! (Score:2) As for tabstops - that's indeed a problem with Python, one a Python programmer should be aware of. However, once the Python programmer is aware of this problem, its not really serious, because rarely will indentation problems result in anything other than IndentationError raised, and you can simply search-replace all tabs to 4 or 8 spaces, or vice versa. The Re:Python == Snake Oil (Score:2) As opposed to what? (If you say "Perl" or "C++", you may well have found the fatal joke from the Monty Python sketch.) Re:Python == Snake Oil (Score:2) I know tons of people who think that Python is the best thing since sliced bread, though my personal preference leans towards PHP. But then again, I'm only working with web interfaces currently, so (IMO) PHP is a tad better-suited to that. Re:question on python's implementation (Score:4, Informative) HTH It depends on the python version (Score:2, Informative) As for your actual question: range does generate the entire list. xrange generates an object instead that calculates the items on the fly. Newer versions of python will be changing things (if Re:geeez (Score:2) Maybe too much. I don't think I'd want to borrow it after he's had it. Re:Tabs (Score:2)
http://developers.slashdot.org/story/03/04/13/2227208/python-in-a-nutshell
CC-MAIN-2013-20
refinedweb
7,993
70.73
This is a simple illustration of using ThreadPool to parallelize downloads. Assumes that bandwidth is not the limiting factor, in which case concurrency doesn't help. import requests from multiprocessing.pool import ThreadPool Test a simple request to my slow server It just replies to any request for /NUMBER with the number requested, but the server is artificially slow in its handling of requests. %time r = requests.get("") r.content CPU times: user 18.1 ms, sys: 4.54 ms, total: 22.6 ms Wall time: 224 ms '10' Our test function downloads the URL for a given ID, and parses the result (casts str of int to int). def get_data(ID): """function for getting data from our slow server""" r = requests.get("" % ID) return int(r.content) Now test using a threadpool to get the data, using a varying number of concurrent threads IDs = range(128) for nthreads in [1, 2, 4, 8, 16, 32]: pool = ThreadPool(nthreads) tic = time.time() result = pool.map(get_data, IDs) toc = time.time() print "%i threads: %3.1f seconds" % (nthreads, toc-tic) 1 threads: 26.2 seconds 2 threads: 13.3 seconds 4 threads: 6.7 seconds 8 threads: 3.4 seconds 16 threads: 1.8 seconds 32 threads: 1.1 seconds
http://nbviewer.ipython.org/gist/minrk/6407393/threadpool.ipynb
CC-MAIN-2014-42
refinedweb
209
71
1 /* Implementation of gettext(3) function. 2 Copyright (C) 1995, 1997, 2000, 2001 Free Software Foundation, Inc. 3 4 This program is free software; you can redistribute it and/or modify it 5 under the terms of the GNU Library General Public License as published 6 by the Free Software Foundation; either version 2, or (at your option) 7 any later version. 8 9 This program 15 License along with this program; if not, write to the Free Software 16 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, 17 USA. */ 18 19 #ifdef HAVE_CONFIG_H 20 # include <autoconf.h> 21 #endif 22 23 #ifdef _LIBC 24 # define __need_NULL 25 # include <stddef.h> 26 #else 27 # include <stdlib.h> /* Just for NULL. */ 28 #endif 29 30 #include "gettextP.h" 31 #ifdef _LIBC 32 # include <libintl.h> 33 #else 34 # include "libgnuintl.h" 35 #endif 36 37 /* @@ end of prolog @@ */ 38 39 /* Names for the libintl functions are a problem. They must not clash 40 with existing names and they should follow ANSI C. But this source 41 code is also used in GNU C Library where the names have a __ 42 prefix. So we have to make a difference here. */ 43 #ifdef _LIBC 44 # define GETTEXT __gettext 45 # define DCGETTEXT __dcgettext 46 #else 47 # define GETTEXT gettext__ 48 # define DCGETTEXT dcgettext__ 49 #endif 50 51 /* Look up MSGID in the current default message catalog for the current 52 LC_MESSAGES locale. If not found, returns MSGID itself (the default 53 text). */ 54 char * 55 GETTEXT (msgid) 56 const char *msgid; 57 { 58 return DCGETTEXT (NULL, msgid, LC_MESSAGES); 59 } 60 61 #ifdef _LIBC 62 /* Alias for function name in GNU C Library. */ 63 weak_alias (__gettext, gettext); 64 #endif
https://fossies.org/linux/tin/intl/gettext.c
CC-MAIN-2020-29
refinedweb
288
74.19
so i been using i/o streams and i understand how to open, check to see if file fails and close files but i cannot understand how to change it to something new i g2 do these, Change dashes to spaces. Change all characters to lowercase. Change digits to * (asterisks). Display these two totals after processing the file: Count all spaces written to the output file. Count all alphabetic characters written to the output file. any hints or tips or any help would be greatly appreciated. so here the start of my code #include <iostream> include <iomanip> #include <fstream> #include <cstdlib> #include <cctype> using namespace std; void editFile(ifstream& infile, ofstream& outfile); int main() { ifstream infile; ofstream outfile; cout << "Editing file will now begin.\n"; //textin file infile.open("C:\\textin.dat");//home //infile.open("F:\\cins 225\\textin.dat");//away if (infile.fail()) { cout << "Input file has failed to open, now exiting.\n"; system("pause"); exit(1); } //textout file outfile.open("C:\\textout.dat");//home //outfile.open("F:\\cins 225\\textout.dat");//away if (outfile.fail()) { cout << "Output file has failed to open, now exiting.\n"; exit(1); } //editFile(infile, outfile); //char next; //infile.get(next); //while (next != '.' ) //{ // if (next == '-' ); // { // outfile << " "; // } // if(next = isalpha) // { // next = tolower(' '); // } //} infile.close( ); outfile.close( ); cout << "Editing file will now end.\n"; system("pause"); return 0; } btw in the file its says it-is a-CaPital Mistake tO-theorize Before-one has DatA123. and i have to change that
https://www.daniweb.com/programming/software-development/threads/117498/i-o-streams
CC-MAIN-2017-30
refinedweb
245
60.72
Catch bugs earlier with assertions Klaus Wittlich is a senior developer and in-house teacher for software technology at SAE IT-systems in Cologne, Germany. He can be reached at klaus_wittlich@sae-it.de. A common technique for catching bugs at runtime is by using assertions, which check invariants at runtime. If an invariant is known at compile time, the compiler can check it and you know about the inconsistency after compiling. A typical application for this case is the exact number and order of elements of an array. You save time by not having to link and run the program to catch the error. Moreover, you can use compile-time assertions for some documentation purposes. Sometimes they are a better choice than switch-case statements, because they lower the risk of forgotten cases. All techniques described in this article have been succesfully used during a project developed with VC++ 2003. Basic Compile-Time Assertions One of the simplest compile-time assertions is based on using the #if/#endif couple. In this code, if someone changes M, the code will not compile: #define M 5 #if M != 5 illegal statement #endif Another idea is based on illegal array ranges if a condition is not fulfilled [1]. The principle is: int ai[COND ? 1 : -1]; where COND is a condition that is evaluated at compile time. If COND evaluates to true, the expression COND ? 1 : -1 evaluates to 1, otherwise to -1. -1 is an illegal array size, so the compiler will throw an error. If you replace -1 with 0, some compilers will only raise a warning. This way, you can tune your compile-time assertions, reporting only warnings or full errors. It might seem that this method wastes space. You will pay if you use that line of code in a function, but not if that line of code occurs in a structure that is never used. Keep in mind that you can define structures within functions. If an object of that type is never used, there will be no bloat. Instead of using the naked array in a function, you can enclose it in a local class that is never used: class NeverUsed{ int ai[COND ? 1 : -1 ];}; If class NeverUsed is never used to instantiate an object, there will be no bloat caused by this code. Another idea for compile-time assertions is to use the size of an incomplete defined type in case of an error and the size of a fully defined type otherwise [1]. You can easily use templates for this purposedependent on the template parameter, you have either a complete or incomplete type. For example: template <bool> class OnlyTrue; template <> class OnlyTrue<true> {}; OnlyTrue<true> is a type of known size and OnlyTrue<false> has unknown size, so sizeof(OnlyTrue<true>) can be evaluated while sizeof(OnlyTrue<false>) cannot. What about the costs if you use this within a function? A statement such as: 27; is a legal statement and is optimized away by the compiler, so you have nothing to pay for it, either in execution time or memory. To be lazy, we make a macro: #define CTA(X) sizeof(OnlyTrue<(bool)(X)>) Please note that the macro is not terminated by a semicolon, so you can use it within structures if necessary, too. This can be useful in cases I will describe later in this article. The OnlyTrue template was designed by the following principle: Give an incomplete type definition of a general template and offer a complete type definition for those specializations you desire. You can also go for the opposite design philosophydefine a complete type of a generalized template and define incomplete specializations. For example: template<int> class AvoidN {}; template <> class AvoidN<17>; Here, AvoidN17<17> is forwarded. sizeof(AvoidN<N>); will not compile only if N == 17. You can easily add more numbers or enum values to be avoided. They may be shared over more than one header filethis is more flexible than checking all illegal numbers individually, like this: sizeof(OnlyTrue<N!=17 || N != 25 || N != 37 || ...>); This becomes unreadable if you have a large set of forbidden numbers. Moreover, if you need this long or condition in more than one place, you should avoid code multiples. One obvious use of compile-time assertions is to check versions of a library you include (or something else). You only need to provide a dummy function and test the version at compile time: void foo() { CTA(VERSION == CURRENT_VERSION); } Sometimes compile-time assertions are a better choice than documentation. Here is an example from my own experience: Within a large software project, you have a lot of classes and a lot of functions that deal with them. For example, one displays your class on the screen, another reads your class from a database. If you add a new member to your class, you'll need to touch all functions that deal with your class. Compile-time assertions are helpful here to show you all functions to touch. You add a version to your classes and let the compiler check them: struct MyClass { enum {VERSION = 1}; .... void foo(MyClass* p) { CTA(MyClass::VERSION == 1); If you now add a new member to MyClass and change VERSION to 2, foo will not compile. But if you change the version request in foo and add code for your new member, a reader of your source code can now see that foo is adjusted to version 2 of your class and was not overlooked. Checking Arrays Compile-time assertions can check your hard-coded arrays for proper size and even for the proper order. You can often use these techniques to avoid switch/case constructs where cases may be easily forgotten. Often, such constructs are related to enums. Here's a short example. You use a typical enum: enum E { e0, e1, e2, e_Last} e0, e1, and e2 are important for the modeling of your real problem, and e_Last is important for the compile-time assertions. If you add a new enum to your list, you must add it before e_Last. e_Last is the count of your enums. To count the elements of an array, we use: #define ELEMENT_COUNT(X) (sizeof(X)/sizeof(X[0])) Please note that X must not be a pointer here. You would get sizeof the pointer in the nominator, not sizeof what the pointer points to. Now we want a function that returns a text for each E. Instead of implementing a switch/case, you can use a hard-coded array: const char * foo(E e) { static const char * ret[] = { "Text 0","Text 1","Text 2" }; CTA(ELEMENT_COUNT(ret) == e_Last); return ret[e]; } In the previous case shown, the world is small and easily comprehensible. But if you have large arrays, the probability for mistakes grows. You need a technique to find the places of insertions easily and to check for the right order. Instead of an array of const char * we use a struct that combines a check field and a char *. The first enum must be zero and we need a compile-time assertion to test that. The difference between successive enums must be 1. With the principles just shown, the following code should make sense: template <int> struct IsZero; template <> struct IsZero<0> {}; #define IS_ZERO(X) (sizeof(IsZero<(X)>)) template <int> struct IsOne; template <> struct IsOne<1> {}; #define IS_ONE(X) (sizeof(IsOne<(X)>)) With that combination, we can write a much safer version of foo: const char * foo(E e) { struct t_ret {size_t NotUsed; char * text;}; static const t_ret ret[] = { {IS_ZERO(e0), "Text 0"}, {IS_ONE(e1-e0), "Text 1"}, {IS_ONE(e2-e1), "Text 2} } ; CTA(ELEMENT_COUNT(ret) == e_Last); return ret[e].text; } Be aware that there will be a cost in static memory for the compile-time assertions, so this technique might not be your best choice when memory is scarce. Often you need to do something dependent on your enum values. I showed how to use structs with text. Instead of text you can use function pointers, or functor pointers instead of calls. Functors have the advantage that you can write them as local functions with different parameter sets. This way, you can get a compile-time checkable alternative choice to the switch/case statement. Some Drawbacks Not everything that is known at compile time can easily be checked in a useful way by a compile-time assertion. One example is hard-coded text. The following will not work in the desired way: CTA("Text 1" == "Text 2"); Another drawback is the use of functions in a table instead of a switch statement. Functions have an associated call overhead that code in the switch statement does not have. Therefore, they are a little slower than a switch statement. Example For more example code that demonstrates the techniques described in this article, see file "SampleCode.cpp" in the code for this article at. References - Alexandrescu, Andrei. Modern C++ Design, Addison-Wesley, 2001. CUJ
http://www.drdobbs.com/compile-time-assertions-debugging/184402051
CC-MAIN-2015-14
refinedweb
1,497
62.27
Attachment 'rmqa-20100527.txt'Download 1 [2010-05-27 16:00:26] <mark> OK, it's 9:00 AM in California, so let's get started. 2 [2010-05-27 16:00:40] <mark> Richi, Joseph (jsm28), and I are here. Jakub can't join us today, unfortunately. 3 [2010-05-27 16:00:57] <mark> With IRC, it's hard to avoid everyone talking at once and it's hard to know when people are done talking. 4 [2010-05-27 16:01:11] <mark> So, let's try to ask one question at a time, and then let's say "DONE" when we're done. 5 [2010-05-27 16:01:24] <mark> Who wants to lead off with a question? 6 [2010-05-27 16:01:31] <mark> If nobody speaks up, we'll take some off the Wiki page. 7 [2010-05-27 16:01:42] =-= richi has changed the topic to ``RM Q&A'' 8 [2010-05-27 16:02:11] <mark> Deafening silence. OK, let's start with this one: 9 [2010-05-27 16:02:18] <mark> What would be your response to a proposal for more frequent releases (every 6 months, say) with at most 2 major changes merged from reasonably-stable development branches (i.e. stricter merge criteria)? 10 [2010-05-27 16:02:24] <mark> richi, jsm28: Do you want to answer? 11 [2010-05-27 16:02:34] <jsm28> I don't believe we are currently effective at stabilizing trunk quickly enough for such a six-month cycle to work. 12 [2010-05-27 16:02:35] <richi> I'll try to answer 13 [2010-05-27 16:02:40] <richi> agreed 14 [2010-05-27 16:02:47] * mark too 15 [2010-05-27 16:02:53] <jsm28> Also, I think too much emphasis is being given here and in the written plan to branches - to how something is developed rather than how stable or risky it is. We should be assessing stability and risk rather than trying to work out what is or is not a "major change", or whether a sequence of large but incremental changes towards a particular goal counts as one change or more than one. 16 [2010-05-27 16:02:58] <stevenb> that question is mine, btw 17 [2010-05-27 16:03:05] <jsm28> DONE. 18 [2010-05-27 16:03:17] <mark> OK, what about this follow-on question: 19 [2010-05-27 16:03:23] <mark> What would be your response to a proposal for a development plan where to be merged branches *must* be in good enough shape for merging in stage 1 (i.e. meet merge criteria) before stage 3 of the *active* release cycle begins? 20 [2010-05-27 16:03:48] <jsm28> Again, I think this has too much emphasis on how something is developed. If something is ready it doesn't matter whether it too two weeks or two years to develop. If it's been around a long time, if anything it's likely to need *more* work to make it merge-ready because of needing updates for global cleanups that have been made in GCC since it branched off. 21 [2010-05-27 16:03:56] <jsm28> DONE. Anyone else want to comment? 22 [2010-05-27 16:03:59] <stevenb> yes 23 [2010-05-27 16:04:03] <richi> that's putting developers off which we want to attract instead. Less rules please. 24 [2010-05-27 16:04:11] <mark> stevenb: OK, go ahead. 25 [2010-05-27 16:04:17] <stevenb> the point is that too much work ends up done in stage1 that should have been ready before the merge 26 [2010-05-27 16:04:31] <stevenb> very few of the latest big branch merges were ready 27 [2010-05-27 16:04:41] <stevenb> and that is one of the reasons why the 6 month cycle doesn't work 28 [2010-05-27 16:04:49] <jsm28> That sounds like we aren't assessing stability/risk well enough. 29 [2010-05-27 16:04:54] <mark> stevenb: I think I'd like to see branches more ready before merging -- but not necessary before stage 1. 30 [2010-05-27 16:05:11] <jsm28> If we can define what makes a patch ready, we don't need a rule about it being ready N months beforehand. 31 [2010-05-27 16:05:20] <mark> I think the problem is that we're pulling branches in before they're mature. 32 [2010-05-27 16:05:21] <stevenb> that's also good 33 [2010-05-27 16:05:22] <richi> stevenb: there is also the risk that nobody fixes bugs during stage3/4 but instead makes branches ready for stage1 34 [2010-05-27 16:05:24] <mark> DONE. 35 [2010-05-27 16:05:34] <stevenb> richi: that is why i said: before stage 3 36 [2010-05-27 16:05:59] <mark> OK, let's maybe ask this perennial favorite from the Wiki page: 37 [2010-05-27 16:06:05] <richi> stevenb: I think that would only be reasonabvle with a much shorter release cycle 38 [2010-05-27 16:06:06] <mark> Do you agree it is necessary, based on experience of the latest few releases, to involve more developers in bug fixing in stage 3 to reduce release cycle lengths? If so, do you have ideas about how to do this? 39 [2010-05-27 16:06:19] <mark> I will try to answer that. 40 [2010-05-27 16:06:25] <stevenb> richi: yes, and i asked for that too ;) but it's marked done, so next 41 [2010-05-27 16:06:47] <mark> First, I'm not sure that approximately annual releases are too infrequent. In other words, I'm not sure a shorter cycle would be better. It feels OK to me. 42 [2010-05-27 16:06:59] <mark> People don't want to update their compilers that often; many people wish they changed less frequently! 43 [2010-05-27 16:07:08] <mark> But, I sure wish we had more bug-fixers. 44 [2010-05-27 16:07:14] <mark> Unfortunately, I don't know how to drive that. 45 [2010-05-27 16:07:24] <mark> I've worried about that for a decade without a good answer. 46 [2010-05-27 16:07:28] <mark> DONE. 47 [2010-05-27 16:07:31] <mark> jsm28, richi: ? 48 [2010-05-27 16:07:35] <jsm28> I think having more people working on bug fixing would help, yes, and that the bug fixing stages are the ones that could most usefully be shortened. I do not have ideas on how to motivate this. 49 [2010-05-27 16:07:38] <jsm28> DONE. 50 [2010-05-27 16:07:43] <stevenb> mark: you have to look at where developers go in stage3 (branches), and try to avoid they go there 51 [2010-05-27 16:07:45] <richi> I have no idea either. DONE. 52 [2010-05-27 16:08:04] <mark> stevenb: Do you have a suggestion as to how to do that? 53 [2010-05-27 16:08:05] <stevenb> mark: the whole set of the above three questions is basically one big proposal 54 [2010-05-27 16:08:31] <mark> stevenb: OK, let me try to summarize what I think you're suggesting. 55 [2010-05-27 16:08:37] <stevenb> mark: if you require that a branch is sufficiently stable (for some measure of...) before stage 3, then folks don't have to work on that anymore in stage 3 56 [2010-05-27 16:08:47] <stevenb> mark: with shorter release cycle, it never takes long for a branch to merge 57 [2010-05-27 16:08:48] <jsm28> I'd rather represent any change positively (people bug fix *as well as* what they do now) rather than trying to replace A with B. 58 [2010-05-27 16:08:58] <mark> I think you're saying that if people have to do their big branches early, then they won't be distracted later. 59 [2010-05-27 16:09:11] <stevenb> mark: so that developers on a branch effectively still have ~1 year between start of work and seeing it in a released gcc 60 [2010-05-27 16:09:15] <stevenb> yes 61 [2010-05-27 16:09:35] <richi> stevenb: we already have eliminated the odd stage2 (unfortunatley with enlarging stage1 from 2 to effectively 6 month) 62 [2010-05-27 16:09:46] <mark> But, I think that means that people will be trying to work on 4.7 branches when we're trying to get 4.5 stabilized, instead of working on 4.6 branches when we're trying to get 4.7 stabilized. 63 [2010-05-27 16:09:54] <stevenb> richi: that's just a different label on the same basic process 64 [2010-05-27 16:09:56] <mark> DONE. 65 [2010-05-27 16:10:17] <mark> Here's something non-controversial: 66 [2010-05-27 16:10:19] <mark> Could we name differently the stages (e.g. red, orange, green, or major, minor, fixing, or anything else...) since having numbered stages 1, 2, 4 without the 3 is very confusing. 67 [2010-05-27 16:10:20] <richi> The fundamental issue is also that more frequent major releases will not get enough testing. DONE 68 [2010-05-27 16:10:39] <mark> I think we can all agree that 1,2, 4 is a weird numbering system. 69 [2010-05-27 16:10:40] <jsm28> Actually they are 1, 3, 4 rather than 1, 2, 4. And I think red, orange, green would be even less meaningful. You could name them New Features, Bug Fixing, Regression Only or similar. DONE. 70 [2010-05-27 16:10:43] <mark> The next stage would be 8. :-) 71 [2010-05-27 16:11:01] <mark> I think New Features, Bug Fixing, Regressions Only is a good call. DONE. 72 [2010-05-27 16:11:13] <stevenb> stage "New Features" :) 73 [2010-05-27 16:11:14] <richi> Agreed. DONE. 74 [2010-05-27 16:11:27] <mark> Woohoo, progress! :-) 75 [2010-05-27 16:11:34] <matz> But it's not just features in stage 1. It's also other disruptive changes. 76 [2010-05-27 16:11:35] <mark> All right, any questions from the floor? 77 [2010-05-27 16:11:38] <richi> I wanted to avoid re-using "stage 2" as it has a defined meaning to some people 78 [2010-05-27 16:11:43] <matz> So why not "Everything goes" :) 79 [2010-05-27 16:11:51] <stevenb> mark: will someone add these answers or a summary to the wiki? 80 [2010-05-27 16:11:57] <mark> matz: OK by me. :-) 81 [2010-05-27 16:11:59] <richi> "Development" "Bugfixing". Reduce it to two stages then. 82 [2010-05-27 16:12:07] <mark> stevenb: jsm28 is logging this chat, and will post it on the Wiki. 83 [2010-05-27 16:12:10] <stevenb> ok 84 [2010-05-27 16:12:10] <jsm28> The numbers are also used for bootstrap stages, though that doesn't seem to cause confusion in practice. 85 [2010-05-27 16:12:44] <mark> OK, I have a question. 86 [2010-05-27 16:13:13] <mark> How important is absolute libstdc++ ABI compatibility over time? I took the position recently that I thought it was critical, just like for GLIBC. But, what do other people think? 87 [2010-05-27 16:13:44] <sabre> Doesn't that depend on the distributors involved? 88 [2010-05-27 16:13:50] <jsm28> I think we can change the soname, but not break compatibility with old binaries unless we change the soname. 89 [2010-05-27 16:14:10] <jsm28> I think changing the soname is a matter for the libstdc++ maintainers. I would ask that when they decide to move to libstdc++.so.7 they try to make sure that no further incompatible changes will be needed for a complete C++0x implementation. 90 [2010-05-27 16:14:26] <jsm28> Furthermore, when we move to libstdc++.so.7 we should take the opportunity to change the default -fabi-version for the C++ compiler to include all the ABI bug-fixes that have accumulated since the last ABI break. Again, we should try to make sure that no more incompatible changes will be needed to the language ABI for a complete C++0x implementation. 91 [2010-05-27 16:14:27] <jsm28> DONE. 92 [2010-05-27 16:14:42] <mark> sabre: I think it's a question for us as GCC RMs; the distributors will have a hard time compensating if we make ABI changes. 93 [2010-05-27 16:14:50] <mark> jsm28: I think what you say makes a lot of sense. DONE. 94 [2010-05-27 16:14:58] <stevenb> can you use STOP instead of DONE please? makes this look more like good old telegrams 95 [2010-05-27 16:15:11] <mark> :-) 96 [2010-05-27 16:15:18] <sabre> so question for the gcc RMs: how best to coordinate gcc changes like that with releases of various linux (and other unix) distros? 97 [2010-05-27 16:15:32] <matz> libstdc++ ABI breakage is fairly terrible for distributors. 98 [2010-05-27 16:15:42] <mark> richi: You're a C++ guy in an alternate life -- any thoughts? 99 [2010-05-27 16:15:59] <mark> (And a SuSE guy so perhaps you can answer sabre's question?) 100 [2010-05-27 16:16:02] <matz> The largest point here is plugin capable systems having c++ plugins (mozilla + flash) 101 [2010-05-27 16:16:04] <richi> sabre: the vendors will fix all gcc bugs in time 102 [2010-05-27 16:16:14] <richi> mark: I prefer a stable libstdc++ ABI 103 [2010-05-27 16:16:38] <stevenb> fwiw the new Airbus structure tools use gcc for its libstdc++ stabiliy, even on proprietary unix variants 104 [2010-05-27 16:16:48] <stevenb> so it matters 105 [2010-05-27 16:16:53] <stevenb> to some 106 [2010-05-27 16:16:55] <jsm28> The soname has been fixed for a long time now. 107 [2010-05-27 16:17:15] <matz> jsm28: Yes, sorry to be unclear, I was talking about the soname. 108 [2010-05-27 16:17:31] <matz> Forward compatible changes are easy to deal with. 109 [2010-05-27 16:17:48] <mark> richi: Are you able to say whether SuSE/Red Hat/Debian/Ubuntu/etc. have any formal coordination re. GCC releases? 110 [2010-05-27 16:17:49] <jsm28> Certainly 3.4 used the same soname. 111 [2010-05-27 16:18:04] <mark> jsm28: Sorry, didn't mean to cut you off. 112 [2010-05-27 16:18:19] <richi> mark: no, we just pick what's ready. If it's not ready we have to maek it ready or backport HW enablement changes. 113 [2010-05-27 16:18:30] <matz> jsm28: I fear I don't get what you're trying to say. 114 [2010-05-27 16:19:03] <jsm28> matz: Just observing that it has indeed been stable for a long time - if we change it now, that's not as if we change it every year. 115 [2010-05-27 16:19:20] <matz> Oh agreed. But even a change every 10 years is terrible. 116 [2010-05-27 16:19:23] <richi> jsm28: libstdc++.so.5 is still used ... 117 [2010-05-27 16:19:25] <tromey> I still occasionally hear complaints about the bad old days when libstdc++ changed a lot. People hated this. So if we do change it I think the messaging is important 118 [2010-05-27 16:19:47] <mark> jsm28: The soname has been stable. Has the libstdc++ ABI been stable since GCC 3.4? Or has the ABI shifted without the soname shifting? 119 [2010-05-27 16:20:02] <dgregor> C++0x is a great excuse to change the libstdc++ ABI moving forward 120 [2010-05-27 16:20:05] <jsm28> mark: I don't know. 121 [2010-05-27 16:20:20] * mark neither 122 [2010-05-27 16:20:21] <tromey> Jakub would know the answer to that. I think there were some obscure changes 123 [2010-05-27 16:20:34] <mark> OK. 124 [2010-05-27 16:20:37] <matz> I think so too. 125 [2010-05-27 16:20:42] * jsm28 remembers the libc5-to-libc6 transition, but Linux was much less widely used then 126 [2010-05-27 16:20:54] <mark> OK, speaking of C++: 127 [2010-05-27 16:21:03] <mark> In your opinion, should GCC complete the transition to C++ as the main implementation language? 128 [2010-05-27 16:21:06] <mark> <from the Wiki> 129 [2010-05-27 16:21:12] <mark> jsm28, richi: Any thoughts? 130 [2010-05-27 16:21:16] <richi> yes. STOP. 131 [2010-05-27 16:21:23] <dnovillo> yes! STOP 132 [2010-05-27 16:21:26] <matz> But in fact to some it's better to live with obscure bugs (for not changing soname when strictly required), rather than to live with a soname change to fix those obscure bugs. 133 [2010-05-27 16:21:32] <richi> but it's a maintainers call, not RMs IMHO 134 [2010-05-27 16:21:39] <TobFZJ> stevenb/RMs/all: What is about libgfortran stability. (There is a difficult-to-avoid ABI [stable since 4.3] break planned for a new array descriptor [required for some bug fixes and some F2003 features]) STOP 135 [2010-05-27 16:21:41] <jsm28> I think the C++ transition would be appropriate to replace the various places C++ features are emulated in C (mainly using macros), such as vec.h. I don't think a wholesale coding style change, as opposed to using standard features to replace local macros, would be a productive use of time. 136 [2010-05-27 16:21:47] <jsm28> The transition needs someone to drive it forward, producing patches that demonstrate the benefits of using C++ so there is something concrete for the SC to review. (I don't think this is anything to do with the FSF, just the SC.) STOP. 137 [2010-05-27 16:22:26] <mark> jsm28: I agree with the thought that we don't need to turn the whole sourcebase upside down. But, I'd be in favor of switching to being able to use C++ features and libraries as appropriate. 138 [2010-05-27 16:22:26] <dnovillo> IMO, with the modular gcc effort we could move that question to the resulting libraries. STOP 139 [2010-05-27 16:22:28] <stevenb> jsm28: let's take a practical example, 140 [2010-05-27 16:22:33] <matz> And I'd like it very much if those patches introducing C++ prove that they don't affect performance in either way. Not for developing GCC itself, nor for developing with GCC. 141 [2010-05-27 16:22:48] <stevenb> jsm28: the 'tree' data structure. i'd like to hide it. say gcc would go c++. what changes would be acceptable? 142 [2010-05-27 16:22:51] <jsm28> TobFZJ: As with libstdc++, I'd leave that to the relevant maintainers. There are fewer users, so more freedom to make such changes. 143 [2010-05-27 16:22:59] <matz> Or wait, I'm fine if they improve performance, so make that "to the worse" :) 144 [2010-05-27 16:23:01] <mark> jsm28: Furthermore, I think this is someone that might need SC blessing, but I think we should ignore the FSF question. 145 [2010-05-27 16:23:05] <stevenb> jsm28: hide it in a name space? hide the data structure behind accessor functions/ 146 [2010-05-27 16:23:07] <stevenb> ? 147 [2010-05-27 16:23:21] <mark> In other words, the fact that RMS doesn't want us to use C++ doesn't carry any water with me. 148 [2010-05-27 16:23:33] <mark> I'd ask the SC for permission, and if that came back positive, go ahead. 149 [2010-05-27 16:23:34] <mark> STOP. 150 [2010-05-27 16:23:41] <jsm28> stevenb: Replace macros by accessors, probably. Replace unions for the different sorts of trees, likewise. STOP 151 [2010-05-27 16:23:55] <dnovillo> mark: why ask a technical decision to the SC? 152 [2010-05-27 16:23:57] <dnovillo> STOP 153 [2010-05-27 16:24:00] <stevenb> i keep forgetting the stop. STOP. 154 [2010-05-27 16:24:22] <richi> dnovillo: because of the C++ host compiler requirement only. STOP 155 [2010-05-27 16:24:32] <mark> dnovillo: Fair question. It seems overarching enough that it seems appropriate. STOP. 156 [2010-05-27 16:24:53] <richi> dnovillo: the technical side should be the maintainers calls only. 157 [2010-05-27 16:25:01] <jsm28> I think the SC gets to deal with controversial technical questions. If it's not controversial, no need to bring in the SC. STOP. 158 [2010-05-27 16:25:02] <stevenb> TobFZJ: re. libfortran, i think abi is less important. people tend to compile their own code, there are no real large apps commercially distributed 159 [2010-05-27 16:25:42] <mark> stevenb: There are some big libraries, though. I'd be worried if ATLAS ABIs were changing. 160 [2010-05-27 16:26:00] <mark> richi, dnovillo: I don't quite understand richi's last comment. 161 [2010-05-27 16:26:12] <mark> Richi, I agree -- most technical issues shouldn't require the SC at all. 162 [2010-05-27 16:26:15] <mark> Was that what you were saying? 163 [2010-05-27 16:26:31] <richi> mark: I don't want to ask the SC about switching to C++. I want to ask them if it's ok to require a C++ host compiler though. 164 [2010-05-27 16:26:50] <jsm28> If we do move to move C++-style datastructures, can someone produce a quick guide to whatever bits of the ABI are needed to tell if those structures are larger than they would be in C? I know how to tell how large a "tree" is, but not what hidden data a C++ structure might have or whether a patch is making it larger. STOP. 165 [2010-05-27 16:27:20] <mark> richi: Oh, I see. Because that has an impact on "users" (where here we mean people who build and install GCC themselves)? STOP. 166 [2010-05-27 16:27:32] <mark> (that = "require C++ host compiler") 167 [2010-05-27 16:27:33] <richi> mark: yes, exactly 168 [2010-05-27 16:27:48] <mark> richi: OK. 169 [2010-05-27 16:28:11] <mark> OK, well, hey, I can ask the SC. 170 [2010-05-27 16:28:14] <richi> jsm28: I think you can inspect dwarf 171 [2010-05-27 16:28:22] <mark> Anybody here want to pop up and say stop? 172 [2010-05-27 16:28:25] <stevenb> to add to jsm28's question about ABI/size: also code style guides before anyone starts actually using c++. STOP 173 [2010-05-27 16:28:28] <mark> (re. asking SC about C++)? 174 [2010-05-27 16:28:32] <richi> jsm28: I am mostly looking forward to stl use, namespaces and function overloading 175 [2010-05-27 16:28:57] <richi> in increasing order of importance ;) 176 [2010-05-27 16:28:57] <matz> STL use will slow down compilation of GCC pretty much. 177 [2010-05-27 16:29:00] <jsm28> richi: I'm hoping for something easier to do in patch review to tell if there's hidden overhead in a patch. I rarely compile with a patch when reviewing it. STOP. 178 [2010-05-27 16:29:31] <jsm28> richi: Where would function overloading be useful in GCC? 179 [2010-05-27 16:29:39] <richi> jsm28: we could regression test certain sizes 180 [2010-05-27 16:29:40] <mark> OK, I think we can all agree that we need C++ coding standards and that we want to transition to "fancy stuff" (e.g., virtual functions, inheritance, multilpe inheritance) slowly. STOP. 181 [2010-05-27 16:29:51] <stevenb> or not at all STOP 182 [2010-05-27 16:29:59] <stevenb> (esp. multiple inheritance) 183 [2010-05-27 16:30:04] <mark> Yes, possibly with infinite slowness. :-) 184 [2010-05-27 16:30:10] <matz> And we need such coding standards before people go wild in producing "cleanup" patches. 185 [2010-05-27 16:30:13] <richi> jsm28: different arguments to int_plus, double_ints, ints, trees, etc. w/o all different fancy names 186 [2010-05-27 16:30:26] <jsm28> vec.h is near the top of the list of things to switch to C++. 187 [2010-05-27 16:30:43] <stevenb> so is basic-block.h 188 [2010-05-27 16:30:46] <richi> mark: like that std::sort one? ;) 189 [2010-05-27 16:30:57] <mark> :-) 190 [2010-05-27 16:31:08] <richi> matz I meant - stupid autocompletion 191 [2010-05-27 16:31:29] <mark> OK, anyone else want to ask a question from the floor? 192 [2010-05-27 16:31:31] <matz> like that one, yes. 193 [2010-05-27 16:31:32] <jsm28> qsort at least people know as standard C so replacing it is less important than replacing vec.h which is GCC-specific. 194 [2010-05-27 16:31:55] <richi> indeed. 195 [2010-05-27 16:32:01] <mark> To close out the previous one, I think I'll go ahead and ask the SC about the C++ host compiler. Or do people think I should post on gcc@gcc.gnu.org before doing that? 196 [2010-05-27 16:32:12] <stevenb> mark: yes. can we assign actions to people here too? or it'll probably go nowhere from here anytime soon... stop 197 [2010-05-27 16:32:31] <mark> stevenb: Yes, I should ask the SC, or yes, I should ask on the mailing list? STOP. 198 [2010-05-27 16:32:54] <stevenb> mark: yes, questions from the floor. 199 [2010-05-27 16:32:55] <jsm28> It's not just "is it OK to require such a compiler?" but what requirements should be placed on it. GCC 4.1 or later? Require code also to be C++98 (except for long long) so it can work with other compilers? STOP. 200 [2010-05-27 16:33:02] <stevenb> mark: you're way ahead of me. STOP 201 [2010-05-27 16:33:17] <mark> stevenb: -) 202 [2010-05-27 16:33:30] <richi> jsm28: require strict C++98 203 [2010-05-27 16:33:32] <mark> jsm28: Yes, I think C++98 is the only practical choice, and, yes, we should say that. 204 [2010-05-27 16:33:45] <mark> stevenb: Let's finish this up, and then I'll take your question. 205 [2010-05-27 16:33:54] <jsm28> richi: Plus long long, as I said. GCC requires a 64-bit type. STOP. 206 [2010-05-27 16:34:13] * mark is trying to figure out if it will be considered inconsiderate if I take this to the SC without another round of mailing list discussion. 207 [2010-05-27 16:34:41] <richi> mark: the SC outcome shouldn't be the result of the question whether we want to switch 208 [2010-05-27 16:34:54] <matz> mark: Well, you can ask the SC without discussion. Then at least that part is solved when the discussion starts. 209 [2010-05-27 16:35:01] <mark> OK, fair enough. 210 [2010-05-27 16:35:06] * mark takes that action item, then 211 [2010-05-27 16:35:22] <tromey> woo hoo STOP 212 [2010-05-27 16:35:26] <jsm28> The SC question should be whether the requirement would be OK, given a patch that gives enough reason to switch. STOP. 213 [2010-05-27 16:35:35] <mark> stevenb: OK, go ahead. 214 [2010-05-27 16:37:03] <stevenb> mark: eh 215 [2010-05-27 16:37:07] <stevenb> mark: yes. can we assign actions to people here too? or it'll probably go nowhere from here anytime soon... stop 216 [2010-05-27 16:37:18] <stevenb> mark: but you were already doing that 217 [2010-05-27 16:37:25] <stevenb> mark: anyway, i do have another question 218 [2010-05-27 16:37:31] <mark> OK, go for it. 219 [2010-05-27 16:37:58] <stevenb> mark: re. technical leadership, it seems to me that there are some issues where gcc the community just doesn't move forward because thigns are controversial 220 [2010-05-27 16:38:07] <stevenb> mark: see e.g. splitting up the gcc/ directory 221 [2010-05-27 16:38:22] <jsm28> stevenb: I don't see that as controversial, but carry on with the question. 222 [2010-05-27 16:38:33] <stevenb> mark: i think that you as RMs and highly respected technical folks should the lead in this, show technical leadership 223 [2010-05-27 16:38:39] <richi> stevenb: we do not have technical leadership 224 [2010-05-27 16:38:41] <stevenb> mark: do you agree 225 [2010-05-27 16:38:49] <mark> stevenb: Great question. 226 [2010-05-27 16:38:49] <stevenb> richi: i'm arguing you should have it 227 [2010-05-27 16:39:02] <mark> I have a bit of a long answer. 228 [2010-05-27 16:39:04] <mark> Bear with me. 229 [2010-05-27 16:39:17] <stevenb> richi: there are 3, 4 folks from different background with lot of respect in the community. i think it would be accepted. stop 230 [2010-05-27 16:39:24] <mark> I do think we as RMs should lead more. I feel that we've been too passive over the past couple of cycles. 231 [2010-05-27 16:39:35] <mark> I think we can't *make* things happen, but we can try to set direction. 232 [2010-05-27 16:39:45] <mark> We can try to encourage people with spare cycles to run <this way> rather than <that way>. 233 [2010-05-27 16:39:50] <mark> And we can cheerlead. 234 [2010-05-27 16:40:08] <mark> That's part of why I'm trying to re-involve myself more in the day-to-day of GCC. I won't be doing ay coding of consequence, but I'm hoping I can help lead. 235 [2010-05-27 16:40:25] <mark> However, I think that jsm28 and richi disagree with me, based on some of our calls. 236 [2010-05-27 16:40:33] <mark> So, I want to let them speak up. 237 [2010-05-27 16:40:40] <mark> js82, richi: ? 238 [2010-05-27 16:40:42] <mark> stop 239 [2010-05-27 16:40:58] <richi> mark: that's a good suggestion though I already see this happening with directed reviews. It of course doesn't help when people come up with complete implementations that go in the wrong direction (hello google). STOP. 240 [2010-05-27 16:41:06] <iant> I think gcc has not had an overall architect since RTH dropped out 241 [2010-05-27 16:41:12] <iant> I think that has been a problem 242 [2010-05-27 16:41:18] <iant> There is no one person who can say "yes" or "no" 243 [2010-05-27 16:41:26] <iant> STOP 244 [2010-05-27 16:41:54] <richi> mark: I also have the "problem" myself. The last couple of RFCs for infrastructure changes received _zero_ comments. 245 [2010-05-27 16:41:57] <jsm28> I'm wary of saying "people should do X" except in the context of "I'm contributing this patch that does X(a), X(b) and X(c) and I think it would be great if someone added X(d) and X(e) to it.". 246 [2010-05-27 16:42:06] <iant> The Google issue is a separate one (and the fault is not only Google's, it requires work on both sides) STOP 247 [2010-05-27 16:42:27] <mark> Let's not get into Google/Apple/Microsoft/Red Hat/CodeSourcery here. 248 [2010-05-27 16:42:35] <mark> Probably a good discussion, but not this one. 249 [2010-05-27 16:42:36] <jsm28> That is, my instinct is leadership through code rather than talk, which takes time coding. 250 [2010-05-27 16:43:04] <richi> jsm28: I agree. Talk is cheap 251 [2010-05-27 16:43:08] <iant> jsm28: agreed but I think it helps a great deal if someone can say "yes" or "no" 252 [2010-05-27 16:43:23] <matz> iant: The maintainers can. 253 [2010-05-27 16:43:26] <richi> iant: I mostly see nobody saying anything 254 [2010-05-27 16:43:32] <jsm28> But if people think RMs should post visions for where GCC should go in the next five years say, I suppose we could do that. STOP. 255 [2010-05-27 16:43:35] <stevenb> i think there are people (hi!) who just won't post code because there is close to zero chance of it getting anywhere 256 [2010-05-27 16:43:39] <iant> matz: sure, but they don't; richi: right, that's the problem 257 [2010-05-27 16:43:58] <richi> iant: nobody complained about DECL_PT_UID for example, or enlarging all call stmts by two points-to sets 258 [2010-05-27 16:44:10] <iant> I'm not being clear; it's not that nobody has the power, it's that nobody takes that role 259 [2010-05-27 16:44:14] <mark> jsm28: Indeed, and you're an exceptional engineer. I'm probably compensating for my lack of engineering by hoping there's value elsewhere. But, I'm willing to be a yes/no resource, at least for big-picture strategy things. 260 [2010-05-27 16:44:14] <stevenb> richi: they were the right thing to do 261 [2010-05-27 16:44:22] <matz> iant: That's a general problem of not having very many reviewers. The non-existance of overall guidance just follows from that. 262 [2010-05-27 16:44:23] <stevenb> richi: there is usually just not much wrong with your calls 263 [2010-05-27 16:44:32] <richi> stevenb: yes, but even saying "yes" would be helpful sometimes 264 [2010-05-27 16:44:44] <stevenb> i'll remember that 265 [2010-05-27 16:44:57] <iant> matz: I'm looking at the problem at a slightly higher level, but perhaps it is just a maintainer issue 266 [2010-05-27 16:45:02] <mark> iant: You're very knowledgeable about GCC -- do you think you could be more RTH-like on technical things? 267 [2010-05-27 16:45:15] <mark> Or are you too busy? Or not confident in making those calls? 268 [2010-05-27 16:45:24] <tromey> I thought the SC stopped giving people RTH-like power STOP 269 [2010-05-27 16:45:32] <mark> It did. 270 [2010-05-27 16:45:46] <jsm28> tromey: We still have Global Reviewers, and were talking about review.... 271 [2010-05-27 16:45:47] <iant> I could perhaps do the job but I am too busy working on other things 272 [2010-05-27 16:45:58] <iant> there are other people who could do the job too 273 [2010-05-27 16:46:06] <mark> iant: OK. 274 [2010-05-27 16:46:10] <iant> the RTH power that was taken away was the power to commit anything 275 [2010-05-27 16:46:22] <stevenb> mark: note, my question is not so much about individuals giving direction, but just saying, "OK, everyone has had their say. Here's how we're going to proceed." 276 [2010-05-27 16:46:33] <iant> yes 277 [2010-05-27 16:46:37] <stevenb> mark: because too often discussions just die out with no action 278 [2010-05-27 16:46:56] <richi> stevenb: isn't this just because it just was talk and nobody wanted to do the work? 279 [2010-05-27 16:47:01] <jsm28> stevenb: You mean global discussions? Because for local ones I'd think that's for the relevant maintainer. 280 [2010-05-27 16:47:22] <matz> richi: Right. 281 [2010-05-27 16:47:25] <stevenb> jsm28: global ones, yes. the split-up of gcc/ is at the moment the most relevant one and the best example 282 [2010-05-27 16:47:32] <mark> stevenb: I understand. In corporate terms, we're lacking a CEO. We have a board of directors (the SC), but not really someone who can say "OK, I've heard the input -- here's what we're doing." Now, the question is whether we *want* a CEO. Maybe we feel that's concentrating too much power in one place. 283 [2010-05-27 16:47:48] <richi> I have many great ideas but not enough time to implement them all myself. And I don't think talking about them would help much. 284 [2010-05-27 16:47:50] <matz> It doesn't help the slightest bit if someone empowered enough says "and that's the way", if then nobody follows that way. 285 [2010-05-27 16:48:06] <stevenb> mark: i would say that the power has naturally distributed itself fairly well with this group hug approach to RM 286 [2010-05-27 16:48:38] * mark is certainly happy that he asked the SC for permission to expand RM-ness to Jakub, Joseph, and Richard. 287 [2010-05-27 16:48:56] <stevenb> mark: also the number of issues where it really matters mostly concern the architecture of the compiler as a whole, the direction. there are not that many issues of this kind. stop 288 [2010-05-27 16:48:59] <iant> mark: I think our policies prevent too much concentration of power 289 [2010-05-27 16:48:59] <jsm28> stevenb: I still don't think that's controversial. Is there actually a bikeshed where one person wants a directory "gimple" and another wants "libgimple" and another wants a toplevel directory and no-one will just review a patch to create it with one name? 290 [2010-05-27 16:49:26] <richi> stevenb: simply start with separating out the C frontend. finally. 291 [2010-05-27 16:49:30] <stevenb> jsm28: i also don't think it's controversial, but the bikeshed discussion is what i would like to end with a decision 292 [2010-05-27 16:49:40] <richi> stevenb: I don't like gimple/, rtl/ and all the fluff diego proposed though 293 [2010-05-27 16:49:47] <stevenb> richi: i have to talk to jsm28 about that, there's something with c-common but i don't remember 294 [2010-05-27 16:49:50] <jsm28> richi, stevenb: I've previously posted what I think the names should be for C front-end subdirectories. 295 [2010-05-27 16:50:02] <stevenb> richi: but it's obviously in the line of things i've tried to achieve lately 296 [2010-05-27 16:50:11] <matz> stevenb: I think, ultimately the way to stop bikeshedding is to create a patch for review. 297 [2010-05-27 16:50:12] <richi> stevenb: yep - very much appreciated. 298 [2010-05-27 16:50:13] <mark> OK, let's not get into a specific technical topic. 299 [2010-05-27 16:50:18] <stevenb> jsm28: yes you have, but i can't find it anymore! :( 300 [2010-05-27 16:50:44] <jsm28> "Re: Separate dir for the C frontend", gcc list, 12 Sep 2004, for example. 301 [2010-05-27 16:50:50] <richi> I have a question. 302 [2010-05-27 16:50:51] <matz> stevenb: I mean, instead of someone forcibly deciding (without doing the work). 303 [2010-05-27 16:50:52] <mark> stevenb: I think it's an interesting discussion. I don't know if we've gotten any sort of consensus, but I will say that I want to help break logjams, and am happy for people to CC: me if things get stuck. 304 [2010-05-27 16:51:06] <mark> richi: OK, go ahead? 305 [2010-05-27 16:51:08] <stevenb> ok 306 [2010-05-27 16:51:24] <richi> Should we close the 4.3 branch? Should we close branches at all or simply stop doing releases? STOP 307 [2010-05-27 16:51:44] <matz> The difference between "close branch" and "stop doing releases" being? 308 [2010-05-27 16:51:52] * mark would simply stop doing releases, keeping the branches open for regression fixes forever. STOP. 309 [2010-05-27 16:52:03] <richi> Make sure the branch doens't get worse (whcih it doens't when no commits are made to it) 310 [2010-05-27 16:52:05] <jsm28> Closing a branch means we no longer track bug status in Bugzilla. 311 [2010-05-27 16:52:25] <richi> Over time old branches get nearly no testing, so they I guess get worse instead of better over time 312 [2010-05-27 16:52:37] <matz> If there are commits to them, yes. 313 [2010-05-27 16:52:52] <jsm28> Maybe if there were better ways of tracking that a bug exists on old branches without showing it as "open" in a default search and without a 4.3/4.4/4.5/4.6/4.7/4.8 marker in the summary, there would be no need to close branches. 314 [2010-05-27 16:52:57] <matz> So, IMO: yes we should close branches. 315 [2010-05-27 16:53:27] <jsm28> I'm certain releases still make sense and lots of people use them, even if more people do get them from various distributors. 316 [2010-05-27 16:53:43] <jsm28> But for old branches we might stop making releases eventually. 317 [2010-05-27 16:53:44] * stevenb thinks the marker in the summary is a Bad Thing -- often hides the actual subject of the bug 318 [2010-05-27 16:54:25] <mark> OK, I want to try to answer at least one more question before the hour is up. 319 [2010-05-27 16:54:41] <mark> There are a series of questions on the Wiki page about modular GCC and plug-ins and GFDL/GPL, etc. 320 [2010-05-27 16:54:56] <richi> I like to comment on plug-ins 321 [2010-05-27 16:54:58] <mark> The general thrust of all these is "can we do more modern programming techniques in GCC"? 322 [2010-05-27 16:55:04] <mark> richi: OK, give me a minute, please? 323 [2010-05-27 16:55:07] <richi> sure 324 [2010-05-27 16:55:28] <mark> Whether that's literate programming for docs, or C++ for structuring code, or plug-ins to allow third-party use of GCC, etc. 325 [2010-05-27 16:55:41] <mark> These are all techniques that are now mainstream coding approaches -- but not in GCC. 326 [2010-05-27 16:55:59] <mark> I believe, unambiguosly, that we must move in this direction. We do not have to jump on a bandwagon, but we must move. 327 [2010-05-27 16:56:13] <mark> Furthermore, we must not let the FSF stop us from moving. 328 [2010-05-27 16:56:20] <iant> FORK! 329 [2010-05-27 16:56:20] <iant> sorry 330 [2010-05-27 16:56:32] <mark> I think we've been too timid in pressing forward. 331 [2010-05-27 16:56:35] <mark> And we includes me. 332 [2010-05-27 16:56:53] <mark> I think it's time for us to start saying "look, these things are going to happen" and do them. 333 [2010-05-27 16:56:54] <stevenb> it includes all those who talk to RMS/FSF in the name of the gcc community 334 [2010-05-27 16:57:07] <mark> I think the FSF will get on board. 335 [2010-05-27 16:57:12] <mark> OK, that's my long answer. STOP. 336 [2010-05-27 16:57:15] <matz> (I think moving "forward" (whereever that is) for the sake of moving is not very worthwhile) 337 [2010-05-27 16:57:15] <dnovillo> mark: i agree completely. 338 [2010-05-27 16:57:20] <jsm28> The FSF has responsibility for legal issues, but is bound by the Mission Statement just as much as the GCC maintainers are, in particular "Patches will be considered equally based on their technical merits.". So if something is only controversial on technical grounds and does not engage legal issues, opinions from FSF people have no special status and technical decisions are ultimately up... 339 [2010-05-27 16:57:20] <jsm28> ...to maintainers and the SC. STOP. 340 [2010-05-27 16:57:50] <stevenb> matz: do you have the feeling that gcc is moving for the sake of moving on some front? 341 [2010-05-27 16:57:55] <mark> jsm28: I agree. 342 [2010-05-27 16:58:00] <matz> stevenb: For some things, yes. 343 [2010-05-27 16:58:16] <stevenb> matz: could you give an example? 344 [2010-05-27 16:58:30] <matz> Plugins. (really, I'm sorry to say, but it is as it is to me) 345 [2010-05-27 16:58:38] <stevenb> ok, an example !plugins 346 [2010-05-27 16:58:40] <stevenb> :) 347 [2010-05-27 16:59:24] * stevenb likes plugins, for the record, but thinks that the way it's done in gcc now is too much 348 [2010-05-27 16:59:24] <iant> plugins are not there "for the sake of moving;" they have real uses cases for real people 349 [2010-05-27 16:59:25] <matz> Literate programming, when it would entail more than opening comments with '/**' 350 [2010-05-27 16:59:45] <richi> We see patches adding plugin hooks in performance sensitive areas. And 351 [2010-05-27 16:59:46] <richi> plugins wanting access to all details of GCC. I think we have to be 352 [2010-05-27 16:59:46] <richi> very careful here to not generate a maintainance nightmare. I think 353 [2010-05-27 16:59:46] <richi> plugins are very badly architected and we should severely restrict what 354 [2010-05-27 16:59:46] <richi> interfaces we expose. 355 [2010-05-27 16:59:49] <apinski> question from me: when is 4.6's stage 1 ends? 356 [2010-05-27 16:59:53] <jsm28> Moving for the sake of accessibility to new contributors trained in modern coding practices has a genuine benefit, even if not a direct technical one. 357 [2010-05-27 16:59:53] <sabre> a few vocal people on the list aside, are there any "success stories" for plugins? 358 [2010-05-27 17:00:10] <jsm28> Dehydra/Treehydra is the obvious plugins success story. 359 [2010-05-27 17:00:11] <iant> sabre: we are using them successfully internally 360 [2010-05-27 17:00:13] <stevenb> sabre: they have their uses, 361 [2010-05-27 17:00:14] * mark agrees with richi; "dlopen" is not a plugin API. :-) 362 [2010-05-27 17:00:23] <sabre> iant: ah, didn't know that, ok 363 [2010-05-27 17:00:42] <richi> modularity will help us close down some of it I guess 364 [2010-05-27 17:00:52] <mark> iant: Can you say what you're doing with them? Analysis? Or optimization? Or both? 365 [2010-05-27 17:00:54] <jsm28> I think by "literate programming" we are referring to an extremely light version. Extracting comments, full documentation for options in .opt files, for example. 366 [2010-05-27 17:01:08] <jsm28> We're not referring to Knuth-style writing something that is first a book and second a program. 367 [2010-05-27 17:01:11] <stevenb> richi: i think we should allow plugins at different levels, not one plugin taking over control over all of gcc 368 [2010-05-27 17:01:13] <iant> thread safety analysis, the work that is on the annotalysis branch or whatever it is called in the main repository 369 [2010-05-27 17:01:22] <mark> iant: Thanks. 370 [2010-05-27 17:01:44] <tromey> mozilla uses plugins for a lot of things, via treehydra STOP 371 [2010-05-27 17:01:45] <iant> we also have a plugin which disables warnings in certain cases, e.g., in code which is not currently being edited by the user 372 [2010-05-27 17:01:45] <matz> jsm28: I even have strong reservations against docbook markup in comments. 373 [2010-05-27 17:01:48] <iant> that one is not widely used, though 374 [2010-05-27 17:01:48] <mark> OK, well it looks like our hour is up. I have to get to another meeting, though of course I'm happy for people to keep discussing things. 375 [2010-05-27 17:01:57] <iant> mark: thanks for doing this 376 [2010-05-27 17:01:59] <mark> For me, this was very useful. I appreciate people participating. 377 [2010-05-27 17:02:03] <stevenb> yes, thanks mark et al. 378 [2010-05-27 17:02:05] <mark> Do we think we should do it again in a month or two? 379 [2010-05-27 17:02:12] <iant> yes 380 [2010-05-27 17:02:20] <iant> subject to your time constraints, obviously, but yes 381 [2010-05-27 17:02:29] <mark> Anyone want to vote "no"? (That's OK -- no reason to be shy.) 382 [2010-05-27 17:02:43] <jsm28> matz: I claim we want to put extracted text in our main Texinfo manuals and so would encourage that rather than docbook, but whoever writes the code has a big say.... 383 [2010-05-27 17:02:43] <dnovillo> i vote yes 384 [2010-05-27 17:03:05] <TobFZJ> No - I man yes - well. (Yes, do a RM meeting again.) STOP 385 [2010-05-27 17:03:13] <stevenb> matz: the message is: beat them to it 386 [2010-05-27 17:03:23] <matz> jsm28: Indeed :) 387 [2010-05-27 17:03:27] <matz> stevenb: yeah yeah :-) 388 [2010-05-27 17:03:41] <mark> OK, thanks a lot everyone! Joseph, Richi, thank you both especially! 389 [2010-05-27 17:03:58] <jsm28> Can someone now get the topic back to its normal gccbot-updated state? 390 [2010-05-27 17:03:59] <stevenb> jsm28: re. c front end to own dir: you also mentioned last year that there is something with c-common that has to be resolved before the C front end can be moved into its own directory 391 [2010-05-27 17:04:10] <dnovillo> mark: are you going to publish the minutes? 392 [2010-05-27 17:04:13] <stevenb> jsm28: this had something to do with things in c-common that do not belong there 393 [2010-05-27 17:04:14] <apinski> general question: with the amount of bug reports, how do we reduce the numbers? 394 [2010-05-27 17:04:17] <jsm28> stevenb: c-common.c *shouldn't* include c-tree.h, but that doesn't block a move. 395 [2010-05-27 17:04:19] <iant> regress 396 [2010-05-27 17:04:20] <stevenb> jsm28: but i forgot the details 397 [2010-05-27 17:04:21] <stevenb> ah 398 [2010-05-27 17:04:24] <iant> %regress 399 [2010-05-27 17:04:36] <iant> there is no gccbot.... 400 [2010-05-27 17:04:41] <jsm28> stevenb: It would simply be a file including "../c/c-tree.h", making it more obvious it's something it shouldn't be doing than it is at present. 401 [2010-05-27 17:04:54] <TobFZJ> Two questions: 4.6 stage 1 will end when ? (asked by apinski). And: Will ther be a GCC Summit 2010? 402 [2010-05-27 17:05:09] <richi> TobFZJ: stage 1 will end when it will end 403 [2010-05-27 17:05:15] <stevenb> jsm28: because if c-common.c needs something from c-tree, then this thing should be in c-common.h or in a hook? 404 [2010-05-27 17:05:16] <jsm28> The summit is a question for ajh. 405 [2010-05-27 17:05:17] <dnovillo> TobFZJ: yes to your 2nd question. october, most likely 406 [2010-05-27 17:05:29] <apinski> dnovillo: october now, I thought September 407 [2010-05-27 17:05:35] <TobFZJ> richi: That's a perfect timing :-) 408 [2010-05-27 17:05:45] <jsm28> stevenb: Yes. Or a function with the same name in C and C++, different implementations, although we should probably move away from that approach. 409 [2010-05-27 17:05:46] <richi> TobFZJ: yep - we'll try hard to make it 410 [2010-05-27 17:05:48] <iant> we do not have a very good summit, alas 411 [2010-05-27 17:05:48] <dnovillo> apinski: that's the latest from ajh (~2 weeks ago) 412 [2010-05-27 17:05:49] =-= mark has changed the topic to ``Trunk status -- stage 1 || Still 103 regressions in 4.3, 100 in 4.4, 104 in 4.5 and 121 in 4.6 (ssb)'' 413 [2010-05-27 17:05:52] <matz> apinski: Nope, obtober is the last info ajh sent 414 [2010-05-27 17:06:02] <apinski> I need to get on that mailing list again 415 [2010-05-27 17:06:05] <stevenb> jsm28: ok, thanks for the clarification! 416 [2010-05-27 17:06:13] <jsm28> stevenb: The real bugs are when we have a function with the same name, *different prototype*, and c-common.c calls it with the C parameters..
http://gcc.gnu.org/wiki/Release%20Manager%20Q%26A?action=AttachFile&do=view&target=rmqa-20100527.txt
CC-MAIN-2018-17
refinedweb
9,192
78.18
Getting Started With RenderScript on Android RenderScript is a scripting language on Android that allows you to write high performance graphic rendering and raw computational code. Learn more about RenderScript and write your first graphics app that leverages RenderScript in this tutorial. The RenderScript APIs were formally introduced to the Android SDK in API Level 11 (aka Android 3.0, Honeycomb). RenderScript provides a means of writing performance critical code that the system later compiles to native code for the processor it can run on. This could be the device CPU, a multi-core CPU, or even the GPU. Which it ultimately runs on depends on many factors that aren't readily available to the developer, but also depends on what architecture the internal platform compiler supports. This tutorial will get you started with a simple rendering script we're calling "Falling Snow". It's a particle system where each snowflake is represented by a point that falls, accelerating down the screen. Wind and some other randomness create a mild swirling effect. Step 0: Getting Started RenderScript is based on the C programming language. If you're not familiar with C, we recommend that you get familiar with it first before trying to use RenderScript. Although RenderScript is not OpenGL, nor does it require that you use it for graphics rendering, the concepts for using it are similar to OpenGL concepts. Therefore, familiarity with OpenGL and 3D graphics terminology will help. The open source code for this tutorial is available for download. We recommend using it to follow along. The code listings in this tutorial do not include the entire contents of each file. Step 1: Creating the Rendering Script Let's start with the most detailed step and work up to using the script from within a typical Android Activity. Create a new project file called snow.rs in your src tree, under the package you'll be working in. At the top, define the version of RenderScript you're working with: #pragma version(1) Next, set the Java package that this script belongs to, for example: #pragma rs java_package_name(com.mamlambo.fallingsnow) We'll use some functions from the RenderScript graphics API, so include that header: #include "rs_graphics.rsh" Now, define two functions, root() and init(): int root() { // TBD } void init() { // TBD } The root() function will be the entry point of this script. The return value defines whether the script runs once (return 0) or at N-millisecond intervals (return N). If the hardware can't keep up with the requested frequency, then root() runs as often as it can. The init() function is called once when the script loads and is a good place to initialize variables and other state parameters. Create a mesh variable that will be initialized on the Android side and create a simple struct to hold information about each snowflake. While you're at it, create a couple of variables to hold wind and gravity values. rs_mesh snowMesh; typedef struct __attribute__((packed, aligned(4))) Snow { float2 velocity; float2 position; uchar4 color; } Snow_t; Snow_t *snow; float2 wind; float2 grav; Initialize the wind and gravity in the init() function: grav.x = 0; grav.y = 18; wind.x = rsRand(50)+20; wind.y = rsRand(4) - 2; Initialize the snow in its own function: void initSnow() { const float w = rsgGetWidth(); const float h = rsgGetHeight(); int snowCount = rsAllocationGetDimX(rsGetAllocation(snow)); Snow_t *pSnow = snow; for (int i=0; i < snowCount; i++) { pSnow->position.x = rsRand(w); pSnow->position.y = rsRand(h); pSnow->velocity.y = rsRand(60); pSnow->velocity.x = rsRand(100); pSnow->velocity.x -= 50; uchar4 c = rsPackColorTo8888(255, 255, 255); pSnow->color = c; pSnow++; } } Before we move on, let's talk about the initSnow() function. To start, the width and height of the drawing area are retrieved. Then the script needs to know how many snowflake structures we’ll create. It does this by getting the dimensions of the allocation, which is referenced by the snow pointer. But where is the pointer being initialized and what is an allocation? The pointer is initialized from the Android code. An allocation is one of the means by which memory is managed by the Android code, but used by the script. The internal details aren't important at this time. For our purposes, we can think of it as an array of Snow_t struct objects. The loop iterates over each structure and sets some random values so the starting scene looks natural. Now, let's implement a simple root() function that draws the scene without animation. We'll use this to get the rest of the system in place: int root() { rsgClearColor(0.0f, 0.0f, 0.0f, 0.0f); rsgDrawMesh(snowMesh); return 0; } When you save the script project file in Eclipse, the builders will automatically create a file called snow.bc in the /res/raw directory. This automatically generated file should not be checked into source control, nor should it be modified. In addition, some Java files are created in the /gen folder. These are the interface files used for calling into the script from Android. Step 2: Initializing the Script Now that the script is created, we need to initialize it for use from within your Android classes. To do this, we've created a helper Java class called SnowRS. In it, we allocate the memory for the snowflakes, initialize the script, and bind the mesh and snowflake allocation to it. This class also uses a RenderScriptGL object. This object is created in the next step as part of the View class we'll make. public class SnowRS { public static final int SNOW_FLAKES = 4000; private ScriptC_snow mScript; protected int mWidth; protected int mHeight; protected boolean mPreview; protected Resources mResources; protected RenderScriptGL mRS; public SnowRS(int width, int height) { mWidth = width; mHeight = height; } public void stop() { mRS.bindRootScript(null); } public void start() { mRS.bindRootScript(mScript); } public void init(RenderScriptGL rs, Resources res, boolean isPreview) { mRS = rs; mResources = res; mPreview = isPreview; mScript = (ScriptC_snow) createScript(); } public RenderScriptGL getRS() { return mRS; } public Resources getResources() { return mResources; } public ScriptC createScript() { ScriptField_Snow snow = new ScriptField_Snow(mRS, SNOW_FLAKES); Mesh.AllocationBuilder smb = new Mesh.AllocationBuilder(mRS); smb.addVertexAllocation(snow.getAllocation()); smb.addIndexSetType(Mesh.Primitive.POINT); Mesh sm = smb.create(); ScriptC_snow script; script = new ScriptC_snow(mRS, getResources(), R.raw.snow); script.set_snowMesh(sm); script.bind_snow(snow); script.invoke_initSnow(); return script; } } In particular, let's look at the createScript() method. The first section creates the structure array with 4,000 entries (SNOW_FLAKES = 4000). It then uses this to create a mesh object, used for rendering. The rendering construct is set to POINT, so each snowflake will show up as a pixel on the screen. Next, we initialize the script itself, using the raw resource entry created by the Eclipse builder. Then we assign the mesh and the array allocation into the script via the calls set_snowMesh() and bind_snow(), respectively. Finally, we initialize the snow with a call to the initSnow() function we created earlier by calling invoke_initSnow(). The script does not start running at this point, but the init() function has been called. To get the script running, call bindRootScript() on the script object, as seen in the start() method. Step 3: Rendering to a View The Android SDK provides just the object we need for output of the RenderScript: the RSSurfaceView class. Implement a class called FallingSnowView that extends this class, like so: public class FallingSnowView extends RSSurfaceView { private RenderScriptGL mRSGL; private SnowRS mRender; public FallingSnowView(Context context) { super(context); } @Override public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { super.surfaceChanged(holder, format, w, h); if (mRSGL == null) { RenderScriptGL.SurfaceConfig sc = new RenderScriptGL.SurfaceConfig(); mRSGL = createRenderScriptGL(sc); mRSGL.setSurface(holder, w, h); mRender = new SnowRS(w, h); mRender.init(mRSGL, getResources(), false); mRender.start(); } } @Override protected void onDetachedFromWindow() { if (mRSGL != null) { mRSGL = null; destroyRenderScriptGL(); } } } The surfaceChanged() method creates a RenderScriptGL object from the SurfaceHolder passed in, as needed. Then our SnowRS object is created and rendering is started. Step 4: Completing the App Everything is in place to use the FallingSnowView class within an Activity class. The onCreate() method of your Activity class could be as simple as this: public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); snowView = new FallingSnowView(this); setContentView(snowView); } Step 5: Animating the Snow But wait! That's just a static image. Not very interesting, is it? Let's return to the snow.rs file and edit the root() function. For some simple pseudo-physics-style simulation, you'll want to iterate over each snowflake and apply its current velocity and wind to its position. Then adjust the velocity based on gravity acceleration. Finally, check to see if any snow has fallen off the bottom of the screen. The complexity level and efficiency of coding here will impact what sort of frame rate you'll ultimately get. We’ve tried to keep it really simply for this tutorial. Here's what we've done: int root() { // Clear to the background color rsgClearColor(0.0f, 0.0f, 0.0f, 0.0f); // time since last update float dt = min(rsGetDt(), 0.1f); // dimens float w = rsgGetWidth(); float h = rsgGetHeight(); int snowCount = rsAllocationGetDimX(rsGetAllocation(snow)); Snow_t *pSnow = snow; for (int i=0; i < snowCount; i++) { pSnow->position.x += ((pSnow->velocity.x +wind.x) * dt); pSnow->position.y += ((pSnow->velocity.y +wind.y) * dt); if (pSnow->position.y > h) { pSnow->position.y = 0; pSnow->position.x = rsRand(w); pSnow->velocity.y = rsRand(60); } pSnow->velocity.x += (grav.x)*dt; pSnow->velocity.y += (grav.y)*dt; pSnow++; } rsgDrawMesh(snowMesh); if (rsRand(32) == 1) { wind.x = 0-wind.x; } return 30; } And here it is in motion: Step 5: Advanced Topics This tutorial has just scratched the surface of what RenderScript can do (Haha, get it? Surface?). You can use a RenderScript compute script to apply graphical effects to bitmaps. You can add shaders to leverage device graphics hardware to draw the scene differently. You can set up transformations to draw in a 3D space. You can configure textures to draw. There’s a lot more you can do with RenderScript. While RenderScript is more limiting than using OpenGL ES in the 3D rendering area, the addition of compute-only RenderScript adds some welcome capabilities. Drawing a quick 3D scene using RenderScript may be more efficient, coding-wise, than using OpenGL. Using RenderScript for heavy computation or image manipulation may be faster to develop, and perform better than similar NDK solutions (due to automatic distribution across hardware cores). Unlike when developing with the Android NDK, you don't have to worry about the underlying hardware architecture. The main downside of RenderScript is the lack of portability of existing code. If you already have OpenGL code or computational functions in C that you want to leverage in your Android apps, you may want to just stick with the Android NDK. Conclusion This tutorial has given you a taste of using RenderScript with your Android applications. You learned the basics of writing and initializing a script, and rendering to the screen. All of this was done in the context of a simple particle system simulating pixel-sized snowflakes. Let us know what cool RenderScript apps you build<<
http://code.tutsplus.com/tutorials/getting-started-with-renderscript-on-android--mobile-9154
CC-MAIN-2015-14
refinedweb
1,859
57.27
WiringPi supports a devLib extension to allow you to use the PiGlow add on board from Pimoroni. ThePiGlow board has an SN3218 I2C LED controller and 18 LEDs arranged in 3 “legs” of 6 LEDs. (or 6 “rings” of 3 LEDs) The LED colours in each leg match and are in the order Red (at the outside), Yellow, Orange, Green, Blue and White (in the center) The devLib driver allows you to select the brightness of an individual LED, a “leg” or a “ring”. Include #include <wiringPi.h> #include <piGlow.h> Initialise piGlowSetup (int clear) ; This initialises the PiGlow devLib software. You need to make sure the I2C kernel module is pre-loaded and if you have not used the gpio program to load it, then you may have to run your program as root (ie. with sudo) The clear parameter is TRUE or FALSE. If TRUE, then all the LEDs will be turned off to start with. Use void piGlowRing (const int ring, const int intensity) ; This will light up all 3 LEDs on the given ring at the given intensity – 0 (off) to 255 (really bright!) The ring number is 0 from the outside to 5 for the inside. You can use the constants: PIGLOW_RED, PIGLOW_YELLOW, PIGLOW_ORANGE, PIGLOW_GREEN, PIGLOW_BLUE or PIGLOW_WHITE. piglowRing (PIGLOW_ORANGE, 60) ; will light up the 3 orange LEDs with an intensity of 60. void piGlowLeg (const int leg, const int intensity) ; This will light up all 6 LEDs on the given led (0, 1 or 2) to the supplied intensity. The leg number will depend on which way up you have the Pi, but leg 0 is normally the one that points to the same edge the composite video connector in on, 1 is to the right (clockwise) and 2 is to the left (anticlockwise) void piGlow1 (const int leg, const int ring, const int intensity) ; This lights up an individual LED to the intensity given. The leg and ring parameters specify the LED to set. Examples Look in the wiringPi/examples/PiGlow directory for some example programs including a simple piglow utility. Compile these by typing make as usual. the piGlow1 program is the ones used in the video below. The piglow utility allows for simple command-line control: piglow off # All off piglow red 50 # Light the 3 red LEDs to 50% piglow all 75 # Light all to 75% piglow leg 0 25 # Light leg 0 to 25% piglow ring 3 100 # Light ring 3 to 100% piglow led 2 5 100 # Light the single LED on Leg 2, ring 5 to 100% You could install the piglow command in /usr/local/bin/ so you could use it at any time. (sudo make install will do this for you) Notes - You need to load the I2C kernel modules before you can use I2C devices. Use the gpio command: gpio load i2c - If this is the only I2C device on your Pi (and it almost certianly will be unless you’re using some sort of break-out connector!), then it will run at 400KHz, so try: gpio load i2c 400 - Use the i2cdetect program to scan your I2C bus to make sure the Pi can see the SN3218 which will show up as 0x54. - If you have a Rev 1 Pi, then the i2cdetect command is: i2cdetect -q -y 0 if you have a Rev. 2 Pi, then use i2cdetect -q -y 1 - The gpio command supports the i2cdetect command and automatically caters for board revision. Simply type: gpio i2cd - The wiringPi SN3218 driver knows which revision Pi you have, so you know need to take any special precautions – your code will work on either a Revision 1 or 2 Pi. - Internally the PiGlow devLib extension adds 18 more pins to wiringPi’s pin map. These pin are normally at location 577. This should not be an issue as the PiGlow is designed to be the only peripheral on the Pi, but if you have used a breakout board to add other devices to it, then you should pick a pinBase that’s outside the range 577 through 595. Video demonstration:
http://wiringpi.com/dev-lib/piglow/
CC-MAIN-2018-17
refinedweb
687
73.21
ERSEK Laszlo <address@hidden> ha escrit: > I kindly request you to review the patch below. Have you tried the patch I sent you? > The patch introduces a level of indirection between the dedicated compressor > selector options and the corresponding executable names. The parametrized > executable names default to the previous fixed values. Each one can be > changed via a specific long option before a compressor is selected with a > dedicated named option. Thus they are suitable for adding to TAR_OPTIONS. > They generally look like --COMPRESSOR-filter, as in --bzip2-filter. I prefer a single option instead. Tar is already overloaded with command option names. Two option names per each compressor program is too much. > +GLOBAL const char > + *compress_filter_option, > + *gzip_filter_option, > + *bzip2_filter_option, > + *lzma_filter_option, > + *lzop_filter_option, > + *xz_filter_option; The same here. I'd like to avoid polluting the global namespace. Apart from that, there remains my remark from the previous posting. I'm not sure the game is worth the candles. It seems much simpler to have an option/variable that would allow to redefine the compressor name at compile time instead. Regards, Sergey
http://lists.gnu.org/archive/html/help-tar/2009-10/msg00006.html
CC-MAIN-2014-42
refinedweb
178
51.34
ZF Home Page Issue Tracker Code Browser Wiki Dashboard Contributors Wiki Developers Wiki Proposers Wiki Most Wanted Contributor License Agreement Mailing Lists Code Contributor Guide Documentation Contributor Guide Developer Notes Zend_Tool_Project is a component that facilitates Project based development through extending Zend_Tool_Framework. The goals of Zend_Tool_Project is two fold:: Specifics: General: Doesn't address how the project profile would be updated well enough. The project profile file is updated from within the provider after any object graph interaction has been completed (See use case 1) I don't see why we need a CommandSystem package. Artifacts, they were removed and renamed With a context node registry, I've now counted 3 separate registries including those defined in the Zend_Tool_Rpc proposal. I can see justifications for this one and a manifest registry. The number of registries may indicate an overly complex design.. Both requirements and dependencies need to be filled out. I have no idea what happened here, copy and paste must have gone awry. I don't get a clear picture of how context nodes and providers work together from the description. How are they instantiated and managed, for example? Updated in the "The Providers" section. (and moved first.) We need some use cases to help understand what we're trying to accomplish here. see above I think the namespaces could be reorganized to better reflect responsibilities of the separate components. What suggestions do you. One thing that I don't see from UC-01 (and I might be missing it) is the creation of the controller directory if it's not there. It seems to me that any provider should recursive find or create its parents. It's also not clear to me how nodes and contexts are different. What are the responsibilities of each? Powered by a free Atlassian Confluence Open Source Project License granted to Zend Framework. Evaluate Confluence today.
http://framework.zend.com/wiki/display/ZFPROP/Zend_Tool_Project+-+Ralph+Schindler
crawl-002
refinedweb
313
56.76
#include <sortedIds.h> Manages a container of Hydra Ids in a sorted order. For performance reasons, sorting of the list is deferred due to inserting a large number of items at once. The class chooses the type of sort based on how many unsorted items there are in the list. Definition at line 43 of file sortedIds.h. Removes all ids from the collection. Sorts the ids if needed and returns the sorted list of ids. Add a new id to the collection. Remove an id from the collection. Remove a range of id from the collection. Range defined by position index in sorted list. end is inclusive.
https://www.sidefx.com/docs/hdk/class_hd___sorted_ids.html
CC-MAIN-2021-17
refinedweb
108
78.65