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
.-::Analysis of brute force & dictionary attacks.::-. by Zapotek zapotek[at]segfault.gr Website: [ 0x00 ] Chapters ================================================ [ 0x01 ] Prologue [ 0x02 ] Terms & Conventions [ 0x03 ] Tools, Environment & Prerequisites [ 0x04 ] Basic Theory [ 0x05 ] ASCII Codes [ 0x06 ] Hashes [ 0x07 ] Brute Force Attack [ 0x08 ] Theory [ 0x09 ] Source Code Analysis [ 0x0a ] Dictionary Attack [ 0x08 ] Theory [ 0x09 ] Source Code Analysis [ 0x0d ] Famous Crackers [ 0x0e ] Pros and Cons of the 2 attacks [ 0x0f ] Epilogue ================================================ [ 0x01 ] Prologue =============================================== A lot of discussion has taken place for a long time in password cracking techniques. In this paper we will analyze the two most commonly used techniques. The first one being "Brute Force Attacks" and the second "Dictionary Attacks". We will start from the hardest and most effective one, brute force. After that, dictionary attacks will look like a piece of cake. I hope that you will find the paper interesting and enlightening. [ 0x02 ] Terms & Conventions ============================================ Blocks between: "*********************************************************************************************" contain code. Blocks between: "---------------------------------------------------------------------------------------------" contain preformatted or special text. Cryptography: ============= Cryptography (or cryptology; derived from Greek ....... kryptós "hidden," and ....... gráfein "to write") is a discipline of mathematics concerned with information security and related issues, particularly encryption, authentication, and access control. Its purpose is to hide the meaning of a message rather than its existence. [ ] Encryption: =========== In cryptography, encryption is the process of obscuring information to make it unreadable without special knowledge. [ ] [ 0x03 ] Tools, Environment & Prerequisites ============================================ In oder for the examples presented here to be functional your system must comply with the following: Operating System: ================= Linux with a 2.6.x kernel. Other versions might work, I can't guarantee anything though. Get it from: Compiler: ========= gcc 4.1.0 and higher I'm pretty sure any other version will work, it's just that v.4.1.0 is what I used to develop the examples. Get it from: PHP: ==== PHP 5.1.2 will be used for some examples. I'm pretty sure any other version will work. Get it from: Chances are you already have all that software installed, but better make sure. [ 0x04 ] Basic Theory ============================================ Ok, that's fairly easy to grasp, even though I'm a lousy teacher. :P Let's move on. [ 0x05 ] ASCII Codes ============================================ You probably already know this but it doesn't hurt to review it. Computers don't know characters, they only understand binary, "0"s & "1"s. For our comfort, though, we have fashioned other systems too, Hexadecimal, Decimal, Octal etc. It would be pretty hard for a human to read binary, even decimal, that's when ASCII comes into play. ASCII, American Standard for Information Interchange, codes represent characters and are expressed in Decimal, Hexadecimal etc. We will work with decimal codes here. An example follows: "A"=65, "B"=66 ... "Z"=90 So "ZAPOTEK" = 90 65 80 79 84 69 75 . That's very useful when it comes to generating passwords, you'll see why in later chapters. [ 0x06 ] Hashes ============================================ That's significantly harder than the ASCII codes. Long story short, a hash is a "fingerprint" of some piece of data. In general, a lot of hash functions exist, the most popular are MD5, SHA1, CRC. What makes hashes so important is that they are one-way, at least they are supposed to be. For example, the word "hash" has an MD5 hash of "0800fc577294c34e0b28ad2839435945". And the fact that it is one-way means that we cannot figure out what the encrypted data was from it's hash. Hashes are also used as checksums, meaning that we can use them to check if transported data is not corrupted in some way. Even if a byte is missing from the data the hash will differ from the original one. That comes in handy in password validation too, you'll see. [ 0x07 ] Brute Force Attack ============================================ Remember when I said that we cannot recompute the data from the hash? That's was true, the only thing we can try is bruteforcing. Say, we have the password "hash", which converts to "0800fc577294c34e0b28ad2839435945". The only way we can figure out the password from the hash is to brute force it. [ 0x08 ] Theory ============================================ Brute forcing is the method of testing random strings against a given hash until we find a match. The way string generation works is that we generate a random number between the ASCII codes "65" to "90", that's for capital, English, characters, and then convert it to it's ASCII equivalent character By adding up characters we generate our random string. Looping through random strings until we exhaust the keyspace is the hard part because the keyspace increases dramatically depending on the characters in the string, it's length, and the HASH function used. Generally the following keyspace formula applies: --------------------------------------------------------------------------------------------- keyspace = characters_used ^ string_length --------------------------------------------------------------------------------------------- characters_used = the number of different characters used in the string string_length = the amount of characters in a string Worst case scenario is: --------------------------------------------------------------------------------------------- keyspace = 94 ^ a_very_big_number --------------------------------------------------------------------------------------------- 94 ensues from the number of printable ASCII characters. In case you didn't notice, keyspace is equal to the number of possible generated strings for the given character set and string length. So, looping until we exhaust the keyspace ensures that we will find a match. If however the keyspace is exhausted and we have no match, either the string length is wrong, or the character set is different from what was expected. That's pretty much the gist. [ 0x09 ] Source Code Analysis ============================================ This is a John the Ripper kind of bruteforcer in PHP: bruteforcer.php: ********************************************************************************************* <?php /* * @author: zapotek <zapotek[at]segfault.gr> * @version: 0.1 * @name: MD5/SHA1 BruteForcer * @description: A sample MD5/SHA1 bruteforcer in PHP, inspired from JTR. */ error_reporting(0); echo "MD5/SHA1 Bruteforcer\n". "by Zapotek <zapotek [at] segfault.gr\n\n"; // is we have insuficient parameters return usage if ($argc!=3){ echo "Usage: ".$argv[0]." <hash> <lenght> <hash> The MD5/SHA1 hash <lenght> The estimated length of the encrypted string\n"; exit(1); } array_shift($argv); $hash = array_shift($argv); // get the hash $len = (int) array_shift($argv); // get the hash length $start = strtotime ("now"); $start2 = strtotime ("now"); $keyspace = pow(75,$len); // compute keyspace // decide the encryption algorithm switch (strlen($hash)) { //If the Hash is 32 chars long it's a MD5 Hash //(Only for HEX encoded hashes) case 32; $algo="MD5"; break; //If the Hash is 40 chars long it's a SHA1 Hash //(Only for HEX encoded hashes) case 40; $algo="SHA1"; break; //Else print error msg default; echo "Could not determine the encryption algorithm.\n"; echo "Ensure that the Hash is correct and try again.\n"; exit(); } // generate initial key $key = ""; for ($y=0;$y<$len;$y++){ $key .= "0"; } // return some info to the user echo "Specified string length: $len characters\n".str_repeat("-",65). "\n$algo hash: $hash\n".str_repeat("-",65). "\nKeySpace: $keyspace characters\n".str_repeat("-",65)."\n"; // loop through the keyspace for ($x=0;$x<$keyspace;$x++){ // generate random string for ($y=0;$y<$len;$y++){ // if we haven't reached "z" yet, move on to the next character if ($key[$y] != "z"){ // create character from number $key[$y] = chr(ord($key[$y])+1); // zero the rest of the string out if ($y > 0){ for ($z = 0; $z < $y; $z++){ $key[$z] = "0"; } } break; } } // create hash from random string $gen_hash = ($algo=="MD5")? md5($key):sha1($key); // if the hashes match we have a winner! if($hash==$gen_hash){ // inform the user we cracked the hash echo "\nDecrypted string: $key\n". str_repeat("-",65). "\nOperation took: ". date("H:i:s",mktime(0,0,strtotime("now")-$start2)). "\n".str_repeat("-",65)."\n"; // and exit exit(0); } // print out some statistics if ($x % 24000 == 0){ $x2++; if ($x2 == 4){ $x2 =0; $time = strtotime ("now") - $start; $start = strtotime("now"); if ($time==0) $time=1; $rate = (24000 *4) / $time; echo " $x/$keyspace ($key) [$rate Keys/sec]". " [".round(100-(($keyspace-$x)/$keyspace)*100,3)."%]". " [".gmdate("H:i:s", round((($keyspace-$x)/$rate),3))." left]\n"; } } } // if the keyspace loop is finished with no match inform the user we failed echo "\nKeyspace exhausted.\n". "Please check the provided lentgh and try again.\n" ?> ********************************************************************************************* Lets give this baby a trial run. For an MD5 hash: --------------------------------------------------------------------------------------------- zapotek@lil-z:~/Documents> php bruteforcer.php 900150983cd24fb0d6963f7d28e17f72 3 MD5/SHA1 Bruteforcer by Zapotek <zapotek [at] segfault.gr Specified string length: 3 characters ----------------------------------------------------------------- MD5 hash: 900150983cd24fb0d6963f7d28e17f72 ----------------------------------------------------------------- ----------------------------------------------------------------- --------------------------------------------------------------------------------------------- For a SHA1 hash: --------------------------------------------------------------------------------------------- zapotek@lil-z:~/Documents> php bruteforcer.php a9993e364706816aba3e25717850c26c9cd0d89d 3 MD5/SHA1 Bruteforcer by Zapotek <zapotek [at] segfault.gr Specified string length: 3 characters ----------------------------------------------------------------- SHA1 hash: a9993e364706816aba3e25717850c26c9cd0d89d ----------------------------------------------------------------- ----------------------------------------------------------------- --------------------------------------------------------------------------------------------- Well, that's easy, lets give it a bit of a challenge. Let's see what happens with "fb50df9b6b86db51569f2bab6457a24e" (= "zapo") (I'd give it "zapotek" but the keyspace would get exhausted at around 6hours, so...) --------------------------------------------------------------------------------------------- zapotek@lil-z:~/Documents> php bruteforcer.php fb50df9b6b86db51569f2bab6457a24e 4 MD5/SHA1 Bruteforcer by Zapotek <zapotek [at] segfault.gr Specified string length: 4 characters ----------------------------------------------------------------- MD5 hash: fb50df9b6b86db51569f2bab6457a24e ----------------------------------------------------------------- KeySpace: 31640625 characters ----------------------------------------------------------------- 72000/31640625 (1l<0) [96000 Keys/sec] [0.228%] [00:05:28 left] 168000/31640625 (1qM0) [96000 Keys/sec] [0.531%] [00:05:27 left] 264000/31640625 (1v^0) [96000 Keys/sec] [0.834%] [00:05:26 left] ............. 26664000/31640625 (1D?o) [96000 Keys/sec] [84.271%] [00:00:51 left] 26760000/31640625 (1IPo) [48000 Keys/sec] [84.575%] [00:01:41 left] 26856000/31640625 (1Nao) [96000 Keys/sec] [84.878%] [00:00:49 left] Decrypted string: zapo ----------------------------------------------------------------- Operation took: 00:03:57 ----------------------------------------------------------------- --------------------------------------------------------------------------------------------- Pretty cool huh? By the way, the time reported at the right is how much it will take for the script to try all the possible combinations and not necessarily the exact time it'll take to crack a given hash. The comments in code make it easy to grasp so I won't explain it line-to-line, so I'll just paint you the big picture in steps. 1) Read the hash & estimated string length from user input 2) Decide hash type depending on it's length (given that the hash is hexadecimal) 3) Compute the keyspace (75^estimated string length) 4) Create an initial key containing only "0"s 5) Loop until we have reached the end of the keyspace 6) Loop until we have crated a random string 7) Compare the random string's hash with the one provided by the user 8) If we have a match inform the user and exit, else keep looping 9) If we have exhausted the keyspace tell the user we were unable to find a matching hash That's pretty much it... [ 0x0a ] Dictionary Attack ============================================ If you understood the previous chapter this will be a walk in the park. [ 0x08 ] Theory ============================================ Dictionary attacks are like brute force attacks, but significantly easier. Instead of creating our own random strings we read them from a dictionary and then test them against a given hash. And, instead of looping until the end of the keyspace, we loop until the end of file. That's all there is to it. Now, to some code. [ 0x09 ] Source Code Analysis ============================================ dicattack.php: ********************************************************************************************* #!/usr/bin/php <?php /* * @author: zapotek <zapotek[at]segfault.gr> * @version: 0.1 * @name: DicAttack * @description: A sample dictionary attacker in PHP. */ $supported= "MD5/SHA1"; $name= array_shift($argv); $wordlst= array_shift($argv); $hash= array_shift($argv); // timer function getmicrotime() { list ($usec, $sec)= explode(" ", microtime()); return ((float) $usec + (float) $sec); } // the function that does the cracking function crack($algo) { global $wordlst, $hash; // start the timer $time_start= getmicrotime(); // read the dictionary $wordlist= file_get_contents($wordlst); // do some error checking if (!$wordlist) { echo "Cannot access $wordlst.\n"; echo "Ensure that the file exists and try again.\n"; }else{ // put the words in an array $words=explode("\n",$wordlist); // create each word's hash foreach ($words as $word) { // create the word's hash switch ($algo) { case "md5"; $word_hash= md5($word); break; case "sha1"; $word_hash= sha1($word); break; } // compare the hashes if ($word_hash == $hash) { // stop the timer $time_stop= getmicrotime(); echo "Crack Successful!\n"."-----------------\n"; echo "$hash = $word\n"."-----------------\n"; $time= $time_stop - $time_start; echo "[ Operation took $time seconds ]\n\n"; exit(); } } } } // in case of insuficient arguments return usage info if ($argc != 3) { stamp(); exit(); } // decide the hash type // given that the hash is in hexadecimal format switch (strlen($hash)) { // if the hash is 32 bytes it must be a MD5 Hash case 32; echo "\nGuessing MD5...\n\n"; crack("md5"); break; // if the hash is 40 bytes it must be a MD5 Hash case 40; echo "\nGuessing SHA1...\n\n"; crack("sha1"); break; // else return an error msg default; echo "Could not determine the encryption algorithm.\n"; echo "Ensure that the Hash is correct and try again.\n"; break; } // the usage stamp function stamp() { global $supported, $name; echo "\nDicAttack\n-------\n"; echo "Simple Wordlist Based Password Cracker\n"; echo "Currently supporting $supported\n"; echo "Syntax: $name <wordlist file> <hash>\n\n"; } echo "Couldn't find a match check your dictionary or hash and retry.\n"; ?> ********************************************************************************************* The code is fairly simple and usage examples follow. We will be using this file as a wordlist. list.txt: --------------------------------------------------------------------------------------------- a b c ab bc abc --------------------------------------------------------------------------------------------- For an MD5 hash: --------------------------------------------------------------------------------------------- zapotek@lil-z:~/Documents> php dicattack.php list.txt 900150983cd24fb0d6963f7d28e17f72 Guessing MD5... Crack Successful! ----------------- 900150983cd24fb0d6963f7d28e17f72 = abc ----------------- [ Operation took 0.028094053268433 seconds ] --------------------------------------------------------------------------------------------- For a SHA1 hash: --------------------------------------------------------------------------------------------- zapotek@lil-z:~/Documents> php dicattack.php list.txt a9993e364706816aba3e25717850c26c9cd0d89d Guessing SHA1... Crack Successful! ----------------- a9993e364706816aba3e25717850c26c9cd0d89d = abc ----------------- [ Operation took 0.00048303604125977 seconds ] --------------------------------------------------------------------------------------------- Once again, these are the steps: 1) Read the hash from user input 2) Decide hash type depending on it's length (given that the hash is hexadecimal) 3) Read the dictionary 4) Put every word in an array 5) Loop through the array of words 6) Create each words hash and compare it with the user given hash 7) If we have a match inform the user and exit, else keep looping 8) If we have exhausted the array tell the user we were unable to find a matching hash [ 0x0d ] Famous Crackers ============================================ Ok, these scripts are far from optimized and not suited for serious cracking. Fortunately, a lot of advanced, high-end, applications exist, a list follows: John The Ripper =============== Ok, who hasn't heard of that before huh? Very fast hash cracker supporting a lot of algorithms. Website: Cain & Abel =============== That's more of a security suite than just a cracker. Sniffer, cracker, decrypter, encrypter you name it, it's got it. It's only for windows and it can extract VERY interesting information from a system. Website: RainbowCrack =============== Now that's a big boy toy! The difference of RainbowCrack from other crackers is that it reads precomputed hashes which make password cracking faster. Considering that the precomputed hash tables can reach terrabytes in size you can imagine how many hashes you have before you even know it. Problem is though, unless you have a cluster it is better to get the hash tables from somewhere else than generate them yourself. Website: L0phtCrack5 =============== That's the Cadillac of password recovery tools for Windows. It's a sad thing that @stake got bought from Symantec and stopped supporting LC. Search for LC5, though, chances are someone has a copy buried somewhere. LCP =============== That's a freeware L0phtCrack clone. Unfortunately, it runs only on Windows boxes Website: These are the most widely used applications, give them a shot, you'll love them. [ 0x0e ] Pros and Cons of the 2 attacks ============================================ Brute Force ================= Pros Cons ----- ----- It is guaranteed that the hash will get cracked It might even take years for the crack to complete It requires a lot of computation power Dictionary Attack ================= Pros Cons ----- ----- Faster than bruteforcing Significantly less chances to crack a hash than bruteforce A lot of big dictionaries are freely available If the encrypted string is random no "valid" wordlist will crack it [ 0x0f ] Epilogue ============================================ Ok, this paper got to an end. It wasn't a big, in depth, analysis of the 2 techniques but I hope that it served as a good starting point. Thanks for baring through it, Zapotek. # milw0rm.com [2006-09-17]
https://www.exploit-db.com/papers/13161/
CC-MAIN-2018-09
refinedweb
2,623
63.39
As April 15 approaches, small business owners become keenly aware of every penny that goes out the door. After all, the taxman cometh, and he wants his pound of flesh. To make this time of year easier, weve gathered half a dozen online resources that can help you with your taxing IRS questionsand none of them will cost you a dime. Start Behind Enemy Lines It might be hard to believe, but the IRS might be your best friend this time of year. Some of your hard-earned tax dollars go toward funding the agencys isnt evil incarnate after all. Then again Free Advice from the Pros Intuitsre not in the market for tax-prep software, Intuits cant. Itsve given Microsoft plenty of money in the past, so now its time to get something for free. The companys isnt the slickest looking site on the Web, but Small Business Taxes & Management is a clearinghouse for all things tax related. Here youll. Theres also help with doing your own tax return (or hiring a professional, business use of automobiles, last-minute tax tips and getting a jump on next years taxes. This article was first published.
http://www.datamation.com/cnews/article.php/3736081/Online-Free-Tax-Advice-Top-Sources.htm
crawl-003
refinedweb
195
68.91
Important: Please read the Qt Code of Conduct - how to compare QStringList to std::string vector - Qt Enthusiast last edited by how to compare a std::vector<string> to a QStringList Checkout the different conversion routines for QList and QVector There are a couple of options for conversions. - Flotisable last edited by Though you can convert the QStringListto std::vector<QString>by using QStringList::toVector()and QVector::toStdVector. But there seems to be no single function to compare a std::stringto a QString. So you need to write one such function. - SGaist Lifetime Qt Champion last edited by Hi, What exact comparison do you have in mind ? That they have the same content in the same order ? Or that they have all values in common ? - Qt Enthusiast last edited by - aha_1980 Lifetime Qt Champion last edited by You cannot directly compare QStringand std::stringas the former is Unicode UTF-16 and the latter may have one of the 8 bit encodings. So you need to convert one of them anyway. - J.Hilk Moderators last edited by from what the others already said, you could do something like this: bool compareQStdString(const QString &str1, const std::string &str2){ return (str1 == QString::fromStdString(str2)); } int main(int argc, char *argv[]) { QApplication a(argc, argv); QList<QString> qstrings({"a","b","c","d","e","f","g"}); std::vector<std::string>strings({"a","b","b","d","d","f","f"}); for(int i(0); i < qstrings.size() && i < strings.size(); i++){ qDebug() << "Strings are at index"<< i << "are equal:" << compareQStdString(qstrings.at(i), strings.at(i)); } return a.exec(); } /*Result: Strings are at index 0 are equal: true Strings are at index 1 are equal: true Strings are at index 2 are equal: false Strings are at index 3 are equal: true Strings are at index 4 are equal: false Strings are at index 5 are equal: true Strings are at index 6 are equal: false */ It's probably not the fastest or most elegant way to do it, but it works at least.
https://forum.qt.io/topic/94647/how-to-compare-qstringlist-to-std-string-vector
CC-MAIN-2021-10
refinedweb
338
67.49
Important: Please read the Qt Code of Conduct - Compilation error - 'QFuture' is not declared in this scope - Qt Hello there, I am trying to use QFuture and QtConcurrent classes in my application. I # included <QFuture> like this: <QtCore/QFuture> but when i compiled, got a compilation error. I could not event # include QtConcurrent. Do I need to include something else in my .pro file to use both of these? thanks It should work. Did you use some special custom configure flags (if you have compiled Qt yourself)? No nothing of that sort. Yeah, its strange. I am using Qt version 4.7.3 on QtCreator. I just want to try something like void myclass::init() { QFuture<void> future = QtConcurrent::run(fun); future.waitForFinished(); }@ therefore i want to include QFuture which documentation says should be found in @QtCore@ . Even after including QFuture, I am getting compilation error. QtConcurrent is not even getting included. Please let me know if there is some issue with this. I've never used that class. Here is what stackoverflow has to say on this: "link":. So: @ #include <QFuture> #include <QtConcurrent/QtConcurrentRun> @ Thanks for putting a search but doesn't work for me. Can you please try creating a hello world app and use these? [quote author="raj.qtdev" date="1382959691"]Thanks for putting a search but doesn't work for me. [/quote] What exactly didn't work for you ? The compiler don't find the QFuture header or other linker error ? What sierdzio said is correct, so you should be fine including QFuture in that way. From what I see you try to run a class member function, in this case you need something like this: @ QFuture<void> future = QtConcurrent::run(this, &myclass::run) @ That is okay @cincirin. The compiler didn't find the QFuture header and the QtConcurrent header that is the main issue. Should be simple thing but don't know what is missing apart from #including the two headers Perhaps you forgot to include this in your .pro file, but that is unlikely: @ QT += core @ Since you have posted it in Mobile and Embedded, let me ask you this: even though you have not compiled Qt yourself, maybe you are aware of some special conditions your platform may be forcing? Maybe threading support is somehow throttled on that hardware? Ok, I simply included the two files in this way: @ #include <QFuture> #include <QtConcurrentRun> @ The project is successfully compiled even with Qt 4.5.3 on both Mac and Windows.
https://forum.qt.io/topic/33612/compilation-error-qfuture-is-not-declared-in-this-scope-qt
CC-MAIN-2020-40
refinedweb
416
67.15
If: Faster calibration with Maximo Anywhere - Calibration on Work Execution enables you to complete your calibration work orders in the field, in disconnected and connected environments. With it's simplified UI, you can quickly capture the calibration data that you need and receive immediate tolerance validation. If: Maximo supported versions and fix information March 2016 - Get to know Eleri Gregory and Navin Desai as they discuss information surrounding Supported Versions and IFIX availability / testing Moving a linkset from a link module to another link module in DOORS 9. The DOORS 9 client does not provide such a feature. However, it is possible to perform this task by running a DXL script. Disclaimer: THE SAMPLE SCRIPT SCRIPT, WILL MEET YOUR REQUIREMENTS OR BE ERROR-FREE. The entire risk related to the quality and performance of the script SCRIPT, EVEN IF THE AUTHOR OR IBM HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. Some jurisdictions do not allow the exclusion of implied warranties or the limitation or exclusion of liability for incidental or consequential damages, so some of the above may not apply to you." Getting) You are glad that after connecting your Eclipse BIRT environment to your TRIRIGA Database, and using a SQL Query you build your own very first report. You preview it in BIRT and the report runs just fine, pulling data from the database and displaying within the format you set. It is a good looking report you think and my users will love it! Now it is time to see it running in TRIRIGA, so you read the instructions that say you need to import it to Document Manager as a ZIP file to be used in a System Report running an External Query, and you think: Easy! You get back to Eclipse and export the report. There are a lot of options to export it and you go for the "Archive File" one, that gives you the option to select as a zip what is the exact file you need to upload to TRIRIGA Document Manager, how convenient. You import it to TRIRIGA, create a System Report, point to the zip file you imported to Document Manager and the report does not run, throwing an error in the front-end. Depending on the browser it could be an HTTP 500 error or a MID-xxxxxxxxx error. What could be wrong? Well, although BIRT Eclipse gives you the convenient option to export the report as a zip file, that zip file will preserve the folder structure from your Workspace panel (usually on bottom left of Eclipse Report Designer view). TRIRIGA needs that the .rptdesign file inside the zip is located on the zip file root. If not, the report will not run. See the Bad and Good examples below: No Soup for you! Yeah, that will work! In case you set the BIRT Flags in the Admin Console - Platform Logging and reproduce the issue you will see an error in server.log like this: 2016-04-18 13:11:04,682 ERROR [com.tririga.platform.error.ErrorHandler](http-0.0.0.0-12001-14) Report handled exception: com.tririga.platform.error.PlatformRuntimeException: java.lang.RuntimeException: com.tririga.platform.birt.runtime.BirtRuntimeException: Unable to process BIRT viewer request.[MID-3396119991] (....) Caused by: com.tririga.platform.birt.runtime.resource.BirtResourceException: No .rptdesign file was found the report design zip. The "main" .rptdesign file must be in the root of the zip file. A very amicable message in the logs! Well, you get TRIRIGA 3.4.2 or later to install and see how cool to use the Liberty Profile for WebSphere Application Server (WAS). This lets you install both the web server and TRIRIGA at one strike and self deploys itself from TRIRIGA installer. What an easy deal! After installing TRIRIGA and the WAS Liberty profile, the user logged into the service and running it cannot log out or the service will be stopped. Many businesses do not allow an Admin user to be logged in indefinitely. Now you're thinking you have to install all over again in a WAS deployed first. You double check and see WAS Liberty cannot run as a service as a product limitation. What a drag... Well, there is one workaround you can try. Using the Apache's daemon you can create a Windows service. The following instructions are an idea for how you can implement it, but it depends on your architecture and installation: Note: If you run into any issues, check the logs in the LogPath directory location for any errors - the errors as listed in the event viewer logs from Windows do not give meaningful errors. References: There is an RFE to implement this and I encourage you to vote for it: You can also check if that has been implemented already in the above page. developerWorks Forum:. Maximo 7.6 JSON API - Getting Started: Session 1 covering an introduction to the Maximo JSON API In DOORS 9, it is not possible via the user interface to manage the "baseline power" for users. But it is possible to modify the original behavior of DOORS by editing a DXL file and by creating a "special" group for those users. User currUser = find() Group baselineallow = find("baseline-allow") string currUserName = currUser.name if(member((baselineallow, currUser)) || currUserName == "Administrator") { #include <standard/baseline/createBaseline.inc> } else { ack("you are not allowed to create baseline") } When a user attempts to create a baseline from the UI, this code will be executed and only users in the group will be able to create baseline... A tag is a defined value that you can add to configurations to filter the artifacts. Use content assist to conveniently tag work items in the Eclipse client or Web UI work item editor. For a particular Project Area, you can identify a list of tags available in work-item in IBM Rational Team Concert (RTC) and export them. Steps: References With the new CLM 6.0.1 and upcoming IBM Rational Collaborative Lifecycle Management (CLM) releases, IBM WAS Liberty has replaced the Apache Tomcat application server. The current documentation will not assist you to configure the WAS Liberty to run as a Windows service. There is an existing Enhancement Request for the same: Document that running Liberty as a service is not supported (382091) As a workaround, you can use the Apache Commons Daemon as an option. Steps to create the service using Apache Commons Daemon to run CLM 6.0.1 in IBM WAS Liberty: Run the following script to create a Manual service. You need to change the values in the variables, and you might need to change other values too (e.g. --Startup if you want this service to be automatic): Eclipse Memory Analyzer Tool (MAT) for analyzing heap dumps and identifying memory leaks from JVMs and reduce memory consumption. This supports the IBM system dumps, heap-dumps and Sun HPROF binary dumps. Provides memory leak detection and footprint analysis, shows areas of memory wastage. Displays Stack trace with object references. Overview of the dump including Java heap size and total number of objects Provides links to continued analysis: Path to GC Roots Provides the reference chain that prevents an object being garbage collection. Displays Stack trace with object references. Dominator Tree grouped by Class Loader Lists the biggest objects using a “keep alive tree”. Grouping by Class Loader limits the analysis to a single application in a JEE environment. Provides memory leak detection and footprint analysis Objects by Class, Dominator Tree Analysis, Path to GC Roots, Dominator Tree by Class Loader. As a use-case to troubleshoot or identify the problem, MAT has been used to analyze the memory leak: -XX:+HeapDumpOnOutOfMemoryError References.
https://www.ibm.com/developerworks/community/blogs/iotsupport?tags=ibm-iot&sortby=0&page=13&maxresults=30&order=desc&lang=en
CC-MAIN-2020-10
refinedweb
1,287
53.51
In order to show you the Mobile MVC framework I came up with, let me walk you through the same excersise we did when I showed you the MVC pattern. Let's create a simple application with the same login form. Let's create a Smart Devices project and rename the Form1.cs to LoginForm.cs and add a few controls to the form: We will add the reference to the System.Mobile.Mvc assembly and start with the Controller. Login Controller Let's add the LoginController class and derive it from the Controller which is defined in the System.Mobile.Mvc. We will also define the constructor that excepts IView as a parameter and overrige OnViewStateChange method: public class LoginController : Controller { public LoginController(IView view) : base(view) { } /// <summary> /// This method indicates that something has been changed in the view. /// </summary> /// <param name="key">The string key to identify what has been changed.</param> protected override void OnViewStateChanged(string key) base.OnViewStateChanged(key); } Next, let's modify the OnViewStateChanged to handle the Login event from the view: protected override void OnViewStateChanged(string key) { // Check what's changed if (key == "Login") { // The values are in the ViewData. Let's validate them and return the status to the view if (view.ViewData["UserId"].ToString() == "Alex" && view.ViewData["Password"].ToString() == "password") { // Pass the status to the view this.view.ViewData["Status"] = "Login succedded."; } else this.view.ViewData["Status"] = "Login failed."; // Notify the view of the changes to the status this.view.UpdateView("Status"); } if (key == "Exit") { Application.Exit(); } } Switch to the code view of your LoginView form and change it to derive from ViewForm. Let's also implement some logic for the menuLogin_Click and menuExit_Click event handlers: public partial class LoginForm : ViewForm public LoginForm() InitializeComponent(); private void menuLogin_Click(object sender, EventArgs e) // Assign the values this.ViewData["UserId"] = txtUser.Text; this.ViewData["Password"] = txtPassword.Text; // Notify the Controller this.OnViewStateChanged("Login"); private void menuExit_Click(object sender, EventArgs e) this.OnViewStateChanged("Exit"); In the code for menuLogin_Click method we assign the values from the text boxes to the ViewData and make a call to the OnViewStateChanged to notify the controller of the event. Don't forget to pass the key which is used to recoginize what kind of event has happenned in the view. All what is left here is to add an override for the OnUpdateView method to the LoginView which will be called when controller wants us to update the view: protected override void OnUpdateView(string key) // Controller requested to update the view if (key == "Status") { // Update status label this.lblStatus.Text = this.ViewData["Status"].ToString(); } The last step is to wire up the controller and view together. You can do it by modifying the Main in the Program.cs: [MTAThread] static void Main() LoginForm form = new LoginForm(); LoginController controller = new LoginController(form); Application.Run(form); That is all to the code sample for now. I think the adavantages over the previous implementation are obvious - a lot less of the code to write. Plus we get a certain structure in the way the data is being passed between the view and controller. You can download the demo project from here. I am looking forward to any feedback on the approach I've taken. In the next posts I am going to show you how to pass strongly typed data between the layers (although, you should be able to guess it by looking at the MVC for ASP.NET). Alex everything works fine but when the LoginForm (design) is openned, we cannot actually see the form because of the abstract class ViewForm. Is there a way to overcome through this? Thanks, Fergara I understand that there's a lot less code to write (mainly the concrete IView interfaces), but I really don't like the string-based key approach. It's vulnerable to typos and can't be checked during compile time. I'd prefer to write rather more code than to use this string-based approach. But that's only my opinion :) BTW I wrote you an email few weeks ago about implementing some mean of navigation among controllers/views. Would you cover this topic in this new MVC series too, please? 2Fergara: try to comment out the Form class declaration like "public partial class LoginForm : /*View*/Form" when you need to use the designer. I agree about string based approach, but as you said it's a choice between writing a lot more code or this approach. IMO, this can be mitigated by the ability to easilty write Unit Test against all layers. To Fergara: I've removed the abstract from ViewForm to allow to design the form in the later build. Last time I showed you how to create a simple Login Form and pass the data between the View and Controller 2 FilipK: Thanks but yes, that´s what I´ve been doing to make the form appears to me. 2 priozersk: Thanks! It´s more productive being able to see the form right away! AlexYakhnin在他的blog上发布了一系列关于WindowsMobileMVCFramework的文章. Nestas coisas das teorias sobre a melhor forma de separar as diferentes camadas de uma aplicação, há Trademarks | Privacy Statement
http://blogs.msdn.com/priozersk/archive/2008/10/10/mobile-mvc-framework-part-1.aspx
crawl-002
refinedweb
857
63.8
Parses an input file and extracts parameters. More... #include <inputOutput.hh> Parses an input file and extracts parameters. The parameters are stored in a separate object in hashes and arrays. Another instance of the same class can be used to store output information. The output operator writes the date and time in a comment and then content of the input parameters, then "end" and then the content of the output parameters (eg. convergence data). This can be used to generate "unfified" result files where the input data is also present. Advice: put the name of the executable and the command line options in a comment on the first line of the output file. The format of the input file is the following. Comments are C/C++ style. In an input line, only C-style comments are allowed, the // form is only allowed in otherwise empty lines. An example of an input file: // Here, it begins string title "Title of the problem" double eps 1e-16 bool debug true array string bc { 0 "(0)" 1 "(x)" 2 "(y)" } int iter 10 array string bc { 3 "(x*y)" } end This is ignored "end" marks the end of the input file, everything after it will be ignored. The possible types are string, double, int and bool (also as arrays -- arrays are not allowed to be mixed). An array may be continued (like shown in the example). The parser is written using a combination of bison(1) and flex(1) hpFEM2d.cc, hpFEM3d-EV.cc, inputoutput.cc, linearDG1d.cc, and linearFEM1d.cc. Definition at line 436 of file inputOutput.hh. The buffer representing the input file (for the parser) Definition at line 460 of file inputOutput.hh. Default constructor. Enters the string parameters title, author and comment into the input field with value "(empty)". These may be overriden by the input file. Returns information in an output stream. Reimplemented from concepts::OutputOperator. Returns the input data. Definition at line 454 of file inputOutput.hh. Returns the output data. Definition at line 457 of file inputOutput.hh. Parses the input file. Parses the input file. The current input buffer (for the parser) Definition at line 465 of file inputOutput.hh. Input data. Definition at line 468 of file inputOutput.hh. Output data. Definition at line 471 of file inputOutput.hh. Suppress output of current time, machine name etc. in the output. Definition at line 474 of file inputOutput.hh.
http://www.math.ethz.ch/~concepts/doxygen/html/classconcepts_1_1InputParser.html
crawl-003
refinedweb
404
59.7
Important: Please read the Qt Code of Conduct - QCA-GnuGP tutorials, samples I have compiled qca-gnupg-2.0.0-beta3 and copied the dll's in QTDIR\plugins\crypto and this is my code to test the library. @ // QtCrypto has the declarations for all of QCA #include <QtCrypto> #include <QCoreApplication> #include <QDebug> int main(int argc, char **argv) { QCoreApplication app(argc, argv); // the Initializer object sets things up, and // also does cleanup when it goes out of scope QCA::Initializer init; qDebug() << "after here, fails"; // must always check that an algorithm is supported before using it if( !QCA::isSupported("openpgp") ) { qDebug() << "openpgp not supported!\n"; } else { qDebug() << "openpgp supported!\n"; } return 0; } @ When I compiled my code, all it's fine, but at runtime, fails. There are anybody that had used successfully this library and want to share a "howto"? Thanks
https://forum.qt.io/topic/28018/qca-gnugp-tutorials-samples/?
CC-MAIN-2021-39
refinedweb
142
53.31
curs_bkgd(3) UNIX Programmer's Manual curs_bkgd(3) bkgdset, wbkgdset, bkgd, wbkgd, getbkgd - curses window background manipulation routines #include <curses.h> void bkgdset(chtype ch); void wbkgdset(WINDOW *win, chtype ch); int bkgd(chtype ch); int wbkgd(WINDOW *win, chtype ch); chtype getbkgd(WINDOW *win); The bkgdset and wbkgdset routines manipulate the background of the named window. The window background is a chtype con- sisting. The routines bkgd and wbkgd return the integer OK. The SVr4.0 manual says "or a non-negative integer if immedok is set", but this appears to be an error. Note that bkgdset and bkgd may be macros. These functions are described in the XSI Curses standard, MirOS BSD #10-current Printed 19.2.2012 1 curs_bkgd(3) UNIX Programmer's Manual curs_bkgd(3) Issue 4. It specifies that bkgd and wbkgd return ERR on failure. but gives no failure conditions. curses(3), curs_addch(3), curs_attr.
http://mirbsd.mirsolutions.de/htman/sparc/man3/getbkgd.htm
crawl-003
refinedweb
151
67.76
How to Build Your Own Visual Similarity App How to Build Your Own Visual Similarity App I'll be showing Clarifai's Face Embedding model three different photos: one of me, one of my mom, and one of my dad. It will tell me which parent I look most similar to. Join the DZone community and get the full member experience.Join For Free Insight for I&O leaders on deploying AIOps platforms to enhance performance monitoring today. Read the Guide. We recently released a new public model called Face Embedding, which was developed from our Face Detection model. If you’re not familiar with the term embedding, you can think of it as the numerical representation of a model’s input in 1024 dimensional space. Don’t worry if it’s your first time hearing this terminology — we’ll dive a little deeper in this tutorial. For now, just know we’ll be using embeddings to create a simple program that will let you compare how visually similar two people’s faces are! More specifically, this program will use the embedding model to see which one of my parents I look more visually similar to. Dataset Here are the photos I will be using for this tutorial. Feel free to replace my photos with those of your own! You can also make your guess now on which parent I look more similar to. The bottom of this post will have Clarifai’s result for you to compare against. - You need a Clarifai account and can sign up for free here. - We'll be using our Python Client. The installation instructions are here. Make sure to click Py to see the Python instructions. - Install Numpy with the instructions for your environment here. Deeper Dive Into Embeddings You can think of an embedding as a low-dimensional representation of a model’s input that has rich semantic information. That means the Face Embedding model will receive an image as an input, detect all faces in the image, and output a vector of length 1024 for each detected face. The response returned from the API will contain all the vectors generated from the image. These vectors can be thought of as coordinates in a 1024 dimensional space. Images that are visually similar will have embeddings that are “closer” to each other in that dimensional space. We can find how visually similar two faces are by calculating the distance between their corresponding embeddings. In this example, we will be using the Numpy library. Let's Write Some Code! Start by setting an environment variable for your API Key so our Python module can use it to authenticate export CLARIFAI_API_KEY=your_API_key. Paste the following into a file named faceEmbed.py. import json from clarifai.rest import ClarifaiApp from math import sqrt from numpy import linalg from numpy import array # Initalize Clarifai and get the Face Embedding model app = ClarifaiApp() model = app.models.get("d02b4508df58432fbb84e800597b8959") # Dataset kunalPhoto = "" momPhoto = "" dadPhoto = "" # Function to get embedding from image def getEmbedding(image_url): # Call the Face Embedding Model jsonTags = model.predict_by_url(url=image_url) # Storage for all the vectors in a given photo faceEmbed = [] # Iterate through every person and store each face embedding in an array for faces in jsonTags['outputs'][0]['data']['regions']: for face in faces['data']['embeddings']: embeddingVector = face['vector'] faceEmbed.append(embeddingVector) return faceEmbed[0] # Get embeddings and put them in an array format that Numpy can use kunalEmbedding = array(getEmbedding(kunalPhoto)) momEmbedding = array(getEmbedding(momPhoto)) dadEmbedding = array(getEmbedding(dadPhoto)) # Get Distances useing Numpy momDistance = linalg.norm(kunalEmbedding-momEmbedding) print "Mom Distance: "+str(momDistance) dadDistance = linalg.norm(kunalEmbedding-dadEmbedding) print "Dad Distance: "+str(dadDistance) # Print results print "" print "**************** Results are In: ******************" if momDistance < dadDistance: print "Kunal looks more similar to his Mom" elif momDistance > dadDistance: print "Kunal looks more similar to his Dad" else: print "Kunal looks equally similar to both his mom and dad" print "" Run the file with python faceEmbed.py. How Does This Work? The simple program above calls our Face Embedding model and gets the vectors for the three photos in our dataset. It then calculates the distance between vectors for myself and each of my parents. It then prints out the results on who I look more visually similar to. The smaller the distance, the more visually similar our faces are, according to the Face Embedding Model. Moment of truth... The results are in, and my mom is the winner! To recap, we walked through embeddings and the use case for finding visual similarity. Try out the code above with your own images and let us know the results! You can also try out some other interesting use cases, such as: Creating your own search based on facial recognition. Authenticating using the face embeddings. Deduplicating similar photos in a large dataset. ...and much more! If you have any questions from this post or Clarifai in general, please let me know in the comments section below! TrueSight is an AIOps platform, powered by machine learning and analytics, that elevates IT operations to address multi-cloud complexity and the speed of digital transformation. Published at DZone with permission of Kunal Batra , 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/build-your-own-visual-similarity-app-with-clarifai
CC-MAIN-2018-34
refinedweb
884
55.95
09 October 2008 07:58 [Source: ICIS news] SINGAPORE (ICIS news) -- Spot prices of purified terephthalic acid (PTA) in Asia have firmed towards $860-865/tonne CFR China in the past three days, following news of the sudden shutdown of a major plant in China and intensified enquiries after the week-long Chinese National Day holidays, buyers and sellers said on Thursday. ?xml:namespace> But the uptick seemed to be losing steam, as market fundamentals remained simply too weak to support much higher PTA numbers. The sudden stoppage of Hualian Sunshine Petrochemical’s three units in China last week meant that some 1.8m tonnes/year of capacity disappeared from the market, and that had caused some buyers to be concerned that they might not get their supplies from the producer, said market watchers. “We’ve confirmed delivery of 14,000 tonnes of PTA from [Hualian Sunshine] this week, I suppose they would not come, at least for the short term,” said the procurement manager of Zhejiang Lianda Polyester, a mid-sized filament yarn maker in Xiaoshan in eastern China. “Our situation is also bad, we have regular supplies of 40,000-50,000 tonnes every month from [Hualian Sunshine], so when they stopped, we started buying aggressively from other sources so as to keep our operations going,” said the deputy general manager of Shaoxing Cifu, a major producer of polyester filament yarn, fibre chips and film-grade chips in eastern China. According to several of Hualian Sunshine’s customers, some of them had paid up in cash first, and would get their cargoes about a few days later. “We can get much cheaper PTA that way, since [Hualian Sunshine] wanted to keep their cash flow going and was in need for cash, and they’re selling cheap,” said an official from Zhejiang Jinxing, a mid-sized polyester filament yarn maker based in Shaoxing in eastern China. In the past three days, PTA deals were reported as high as $875/tonne CFR China, with traders and end-users alike snapping up cargoes at $855-860/tonne CFR China. Similarly, domestic prices in China had also risen towards yuan (CNY) 7,100-7,200/tonne ex-warehouse (EXWH), about CNY50-150/tonne higher than the levels seen before the National Day holidays in end-September. “The production cutbacks among some Korean and Taiwanese PTA producers in the past few months also helped to maintain supply snug,” said a trader with Sinocoast, based in Shanghai. “The current seasonal peak for the polyester and textile industries, even though they may be weaker than in previous years, is also a factor in boosting PTA values,” said an official from China Textile City in Shaoxing, the largest dedicated mercantile exchange in China for textiles and textile-related products. Nevertheless, it seemed by Thursday that the three-day-old uptick seemed to be slowing and prices could reverse trend soon, said market observers. The original belief that Hualian Sunshine could take up to six months to resume production seemed misplaced, said these observers, referring to earlier talk among some Taiwanese and South Korean industry veterans. Rumours were abound that the Hua Xi group of companies, one of the shareholders of Hualian Sunshine, could pump in more cash into the ailing PTA producer and partial production could at least resume next week. “We knew that it’s impossible that [Hualian Sunshine] would stop for a long time,” said an official with Xiang Sheng Polyester, a leading polyester filament yarn and chip maker in eastern China. “In our local culture, we’ve a saying: if you owe just a few millions, you’re dead for sure; but if you owe tens or hundreds of millions, then you’ll definitely survive but you need to keep earning money back to repay your creditors,” said the Xiang Sheng official. “Even if the [Hualian Sunshine] name is gone, I believe that production at the PTA lines would come in one form or another, for the simple reason that so many polyester producers had paid up for the PTA and they could easily force the PX idling in the tanks to be made into the PTA they need so much,” said a trader with Ningbo Cixi Import and Export. Against such a backdrop, it would be naive to believe that PTA pricing could leap into new heights and shrug off the sluggishness which had plagued it for the most of the past three years. “First, there are inadequate bankruptcy laws in China, and so far, you notice no one government body or bank had said anything about the [Hualian Sunshine episode], so we can conclude that the issue is not as serious as perceived,” said a veteran market watcher in Taiwan. “The fundamentals in the market were also still bearish,” added this market watcher, referring to the overcapacity of PTA in Asia and the sharp decline in feedstock paraxylene (PX) costs in the past few weeks. To some extent, the Hualian Sunshine episode had depressed demand for spot PX, as the idled PTA producer was one of the largest spot PX consumers. But also due to tumbling crude and naphtha futures, PX prices had fallen to $970-980/tonne CFR (cost and freight) Taiwan this week, and looked set to slip further. “The global economic climate is so bad, with stocks crashing, with banks closing, and the worst recession in a century coming, tell me, how can PTA prices rise and why would PX and oil prices rise?,” said the procurement manager of a leading PTA producer in Taiwan. In fact, maybe because of the relative firmness in PTA prices these past few days, those producers which had idled their lines or trimmed their operations could be encouraged to rev up their production again soon, given that margins were no longer squeezed as before. “If that happens, then I can say we’re back to square one, because PTA was, is and would still be in oversupply,” said an official from Sam Nam Petrochemical. And given that new capacities in Taiwan’s Loong-der and China’s Dalian could seize on the slightly more bullish picture to start up in the next few weeks, the outlook could quickly turn into a bearish one in no time and PTA prices could dip towards $800/tonne CFR China once again, said market participants. ($ 1 = CNY 6.81)
http://www.icis.com/Articles/2008/10/09/9162473/Asia-PTA-uptick-fizzles-out-on-weak-fundamentals.html
CC-MAIN-2014-52
refinedweb
1,063
52.77
Express ES5 to Koa ES7 Express ES5 to Koa ES7 At Bandwidth we recently created a new node server for serving up our UI. Being the coding hipsters that we are, of course we looked into the latest tech stack. In this post, I am going to specifically talk about Koa, the web application framework, and how it compares to Express, the current dominator in the space. Koa was designed by the same team that originally designed Express. Koa aims to be much lighter weight than Express by keeping the Koa core small and pushing more functionality to modules. This ideology might sound familiar—it’s how Node as a whole has been orchestrated. One of the great advantages of Koa is that it uses generator syntax, and their 2.0 version (which I will be discussing in this post) uses async/await. Koa and Express have a lot of similarities but there are also some key differences and some gotchas which you’ll have to watch out for. I’ve created some basic github samples that you can follow along with as we walk through the differences; see if you can figure out what the results will be without reading the answer. The apps can be found at: ES5 Express Sample, ES7 Koa Sample. Routing Routing is a core component in Express, while it has been moved to a module in Koa. The koa-router module has been made to mimic the Express syntax, so you’ll notice that it’s very similar. Most Koa modules have a @next version which are the ones that use the new async/await syntax. For any modules that don’t, you can wrap them in koa-convert for compatibility. In Express all you needed was an Express application object. You could use the http methods directly on that: var express = require('express'); var app = express(); app.get('/', function (req, res) { console.log('success!'); res.send({ success: true }); }); In Koa, you must first include the router middleware and then create a new instance of a router object. The router object has access to the HTTP methods. Once you’ve created your route you call the routes() function, which will return a middleware you can add to your Koa app. import Koa from 'koa'; import Router from 'koa-router'; const app = new Koa(); const sampleRouter = new Router(); sampleRouter.get('/', async ctx => { console.log('success!'); ctx.body = { success: true }; }); app.use(sampleRouter.routes()); As you can see, the Koa routing is very similar to how it worked in Express, except that now the routing has been turned into middleware. To dive into some more of the options checkout koa-router on github . Control Flow You might have noticed in the previous example that the control flow was slightly different between Express and Koa. Both of the GET examples above return the same value to the user but the code flow is slightly different. In Express a response isn’t returned to the client until a piece of middleware explicitly tells it so (via something like res.send). Let’s go through some flows using the following code below: var express = require('express'); var app = express(); var PORT = 8432; app.use(function(req, res, next) { console.log('before next'); next(); console.log('after next'); }); app.get('/', function (req, res) { console.log('success!'); res.send({ success: true }); }); app.listen(PORT, function () { console.log('Server started on port: ' + PORT); }); Let’s start with the simple stuff: given the code above, what do you think the order of the log statements will look like when the server starts up and a user makes a get request to the url:? If you thought something like this… before next success! after next Then you are almost correct! Just missing the Server started on port: 8432 log which should happen first. The app.listen happens right when the server starts up. The flow goes through our first piece of middleware, logs out “before next” then when next it called it moves onto the next piece of middleware, which in this case is the route handler. The route handler logs out “success!” and then calls res.send which triggers Express to start executing back up the stack. Express then goes back to our previous piece of middleware and executes everything AFTER our next() call, which in this case will log out “after next”. An example of where you might want to take advantage of this flow is timing how long it takes to process an incoming request. You could add the following piece of middleware before any other to get the total time its taking to process a user’s request on the server. app.use(function(req, res, next) { var startTime = Date.now(); next(); var timeToProcess = Date.now() - startTime; var fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl; console.log(req.method + ' ' + fullUrl + ' - ' + timeToProcess + ' ms'); }); That covers the basics of the control flow in Express. Now let’s take a look at Koa’s control flow and how that compares. Here is a sample piece of code that does something identical to what we did with Express. import Koa from 'koa'; import Router from 'koa-router'; const app = new Koa(); const sampleRouter = new Router(); const PORT = 8431; app.use(async (ctx, next) => { console.log('before next'); await next(); console.log('after next'); }); sampleRouter.get('/', async ctx => { console.log('success!'); ctx.body = { success: true }; }); app.use(sampleRouter.routes()); app.listen(PORT, () => { console.log('Server started on port: ' + PORT); }); This code’s output will be identical to Express output from earlier. One of the key differences is how you continue down the stack. The next() function now returns a promise that you are able to await. I think this more cleanly shows that you want to execute the next piece of middleware, wait until that is done, then come back and execute the rest of this function. Let’s take a closer look at this piece of middleware app.use(async (ctx, next) => { console.log('before next'); await next(); console.log('after next'); }); What do you think would happen if we removed await next()? We get a 404 Not Found. Essentially what is happening is this piece of middleware gets executed and since next() is never called, it ends at this piece of middleware and goes back up the stack. Since neither a ctx.status nor a ctx.body is ever set the default of ctx.status = 404 is returned instead. Let’s compare that to how Express works so we can really see the difference. app.use(function(req, res, next) { console.log('before next'); next(); console.log('after next'); }); Remember this piece of middleware from earlier? What do you think will happen there if we remove the next() line? The correct answer is: nothing! Since we never sent a response via res.send() the process just hangs until eventually the client times out the request. With Express you must explicitly attach middleware to handle the 404 case whereas Koa comes with that by default. You’ll notice that previously we only set the ctx.body, we never set the ctx.status. By default the status will be set to 200, assuming no errors. Let’s play around with this some more and see what happens when we ONLY set a status but don’t set a body. sampleRouter.get('/created', async ctx => { console.log('statusOnly'); ctx.status = 201; }); sampleRouter.get('/noContent', async ctx => { console.log('statusOnly'); ctx.status = 204; }); sampleRouter.get('/tooManyRequests', async ctx => { console.log('statusOnly'); ctx.status = 429; }); Here are a few different status-only examples, so we can really see what is going on. If you hit those endpoints you’ll notice that if the ctx.body isn’t set, then Koa will default it to the normal http status message. For example the /created endpoint will set the body to Created. The only notable exception to this is a status of 204 which will appropriately leave the body empty, since 204 means No Content. Those were most of the interesting control flow differences that we experienced when switching from Express to Koa. Feel free to experiment on your own and discover the rest of the subtle differences! If you are having trouble figuring out Koa, check out the source code, there isn’t much of it. Final Thoughts We have been working with Koa for about 6 months now and have been appreciating the differences. It definitely takes some getting used to when you first make the switch, but after working with it a while we have adapted and believe that it is a bit more intuitive. We also approve of how Koa is trying to keep the core library small. In general, we take that approach to most things, do one thing and do it well. It allows the library to really focus instead of being spread too thin. Being able to code using async/await syntax has been awesome. It is the most intuitive way to do synchronous coding in an asynchronous environment. Koa’s middleware ecosystem isn’t as big as Express’s but it is still sizable and you are able to build a production ready server with what is out there. You can certainly use ES7 features with Express but since Koa 2.0 includes async/await by default it requires using Babel which means we get all of the other juicy features that come along with it. Our code organization has greatly improved since switching to ES7 syntax. If you are considering spinning up a new node server consider looking into Koa, I think once you make the switch you won’t want to go back. TLDR; - Async/await syntax is great - Koa has a more intuitive control flow - ES7 features have greatly improved code quality - Koa core is smaller than Express, 3rd party middleware fills in the gaps - Koa 2.0 is still in the early phases but the conversion library will bridge the gap - Routing is not part of Koa core
https://www.bandwidth.com/blog/express-es5-to-koa-es7/
CC-MAIN-2020-16
refinedweb
1,671
66.23
package require Tcl 8.5 set license { /* Copyright . */ } set gl_license { /* ** License Applicability. Except to the extent portions of this file are ** made subject to an alternative license as permitted in the SGI Free ** Software License B, Version 1.1 (the "License"), the contents of this ** file are subject only to the provisions of the License. You may not use ** this file except in compliance with the License. You may obtain a copy ** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600 ** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at: ** ** ** ** Note that, as provided in the License, the Software is distributed on an ** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS ** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND ** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A ** PARTICULAR PURPOSE, AND NON-INFRINGEMENT. ** ** Original Code. The Original Code is: OpenGL Sample Implementation, ** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics, ** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc. ** Copyright in any portions created by third parties is as indicated ** elsewhere herein. All Rights Reserved. ** ** Additional Notice Provisions: This software was created using the ** OpenGL(R) version 1.2.1 Sample Implementation published by SGI, but has ** not been independently verified as being compliant with the OpenGL(R) ** version 1.2.1 Specification. */ } set init_code { static void *glsym(void *handle, const char *name) { void *sym = dlsym(handle, name); if(NULL == sym) { fprintf(stderr, "Error: symbol not found: '%s'. " "Error information: %s\n", name, dlerror()); abort(); } return sym; } } set dlopen_code { #ifndef LIBGLNAME #define LIBGLNAME "/System/Library/Frameworks/OpenGL.framework/Libraries/libGL.dylib" #endif LIBGLNAME (void)dlerror(); /*drain dlerror()*/ handle = dlopen(LIBGLNAME, RTLD_LAZY); if(NULL == handle) { fprintf(stderr, "error: unable to dlopen " LIBGLNAME " :" "%s\n", dlerror()); abort(); } } set this_script [info script] proc main {argc argv} { if {2 != $argc} { puts stderr "syntax is: [set ::this_script] serialized-array-file output.c" return 1 } set fd [open [lindex $argv 0] r] array set api [read $fd] close $fd set fd [open [lindex $argv 1] w] puts $fd "/* This file was automatically generated by [set ::this_script]. */" puts $fd $::license puts $fd { #define GL_GLEXT_PROTOTYPES #include <GL/gl.h> #include <dlfcn.h> #include "glxclient.h" #include "apple_xgl_api.h" #include "apple_glx_context.h" } puts $fd "struct apple_xgl_api __gl_api;" set sorted [lsort -dictionary [array names api]] set exclude [list DrawBuffer DrawBuffers DrawBuffersARB] #These are special to glXMakeContextCurrent. #See also: apple_xgl_api_read.c. lappend exclude ReadPixels CopyPixels CopyColorTable #This is excluded to work with surface updates. lappend exclude Viewport foreach f $sorted { if {$f in $exclude} { continue } set attr $api($f) set pstr "" foreach p [dict get $attr parameters] { append pstr "[lindex $p 0] [lindex $p 1], " } set pstr [string trimright $pstr ", "] if {;" } else { set body "[set return]__gl_api.[set f]([set callvars]);" } puts $fd "GLAPI [dict get $attr return] APIENTRY gl[set f]([set pstr]) \{\n\t$body\n\}" } puts $fd $::init_code puts $fd "void apple_xgl_init_direct(void) \{" puts $fd "\tvoid *handle;" puts $fd $::dlopen_code foreach f $sorted { set attr $api($f) puts $attr puts $f if {[dict exists $attr alias_for] || [dict exists $attr noop]} { #Function f is an alias_for another, so we shouldn't try #to load it. continue } puts $fd "\t__gl_api.$f = glsym(handle, \"gl$f\");" } puts $fd "\}\n" close $fd return 0 } exit [main $::argc $::argv]
http://opensource.apple.com/source/X11server/X11server-85.3/libGL/AppleSGLX-60/gen_api_library.tcl
CC-MAIN-2016-44
refinedweb
547
55.84
This section demonstrates you how to delete a non empty directory. It is easy to delete a directory if it is empty by simply calling the built in function delete(). But if the directory is not empty then this method will not delete subdirectories and files of that directory. So it is necessary to recursively delete all the files and subdirectories that are available in the directory. You can see in the given example, we have created a recursive function deleteDir() that will remove all the files and subdirectories of the given directory. We have called this method in the main function. Here is the code: import java.io.*; public class DeleteNonEmptyDirectory { public static void main(String[] argv) throws Exception { deleteDir(new File("c:/Hello")); } public static boolean deleteDir(File dir) { if (dir.isDirectory()) { String[] children = dir.list(); for (int i = 0; i < children.length; i++) { boolean success = deleteDir(new File(dir, children[i])); if (!success) { return false; } } } return dir.delete(); } } Through the above code, you can delete any non empty directory.
http://www.roseindia.net/tutorial/java/core/files/deletenonemptydirectory.html
CC-MAIN-2013-48
refinedweb
172
59.09
Hi, I was trying to set up my raspberry pi 3b to communicate to a device via pyuavcan. Is there any tutorial on how to set it up and smoke testing? Best regards, Malis Hi, I was trying to set up my raspberry pi 3b to communicate to a device via pyuavcan. Is there any tutorial on how to set it up and smoke testing? Best regards, Malis This should be good to start with: Hi Pavel, Thanks a lot for your reply. Here is the error I get when I try to run the create node basic usage script. (I apologize in advance, I m a beginner) Traceback (most recent call last): File “create_no.py”, line 8, in node_info.hardware_version.unique_id = b’12345’ # Setting first 5 bytes; rest will be kept zero File “/home/pi/.local/lib/python2.7/site-packages/uavcan/transport.py”, line 589, in setattr raise AttributeError(‘Array field could not be constructed from the provided value’, ex) AttributeError: (u’Array field could not be constructed from the provided value’, ValueError(u’encode() can be used only with string-like arrays’,)) Any idea? Side question, I’m trying to close and retrieve an exiting node, but cannot find a way to do it because I get: closing(uavcan.driver.make_node('can0', bitrate=500000)) NameError: name ‘uavcan’ is not defined if I run import uavcan from contextlib import closing closing(uavcan.driver.make_node(‘can0’, bitrate=500000)) Best regards, Malis Wrong version of Python. The tutorial says: This tutorial will walk you through the basic usage of Pyuavcan. It is intended for execution in an interactive shell of Python 3.4 or newer. While Pyuavcan supports Python 2.7, its use is strongly discouraged. You shouldn’t see the error if you use Python 3. You should also beware that Python 2.7 will reach its end-of-life in 4 months so writing any new software in it is probably not a good idea. you should check python3 apt-cache policy python3 python3-pip python3-numpy and install sudo apt-get install python3-pip python3-numpy pip3 install pyuavcan[transport_can_pythoncan,transport_serial,cli] OP seems to be using UAVCAN v0. The instructions you posted are for UAVCAN v1. I would recommend OP to consider switching to v1 though; for that, one should refer to pyuavcan.readthedocs.io. pip is for python 2.7. or need to set alias python=’/usr/bin/python3.7’ ~/.bashrc I have a pyuavcan installed. I am running the script ./show_data_type_info.py I get. PyUAVCAN is not installed. Please install from PIP: sudo pip3 install uavcan library is not V1.0? There are two Python packages related to PyUAVCAN, they cannot be used simultaneously: uavcan that implements v0, and pyuavcan that implements v1. From our earlier conversation I deduce that you need v0, so you should do pip uninstall pyuavcan -y && pip install uavcan. Support for v1 is implemented in Libcanard in a separate branch, it is very experimental still. I should finalize it soon. I do not want to use V0. V0 is leaving and will not be supported anymore. or? Where to discuss about new data types(DSDL). I am interested in the parameters for motors, RPM, etc. This is not standard V1. We don’t yet have a well-defined date for its EOL, but you are correct in your view that new applications should be using v1. The first stage of the v0-v1 transition will begin in 2020Q1, as explained in UAVCAN 2019 roadmap. This is when we are going to update the website and all GitHub repositories to point to v1 by default. For the benefit of existing deployments, v0 will still be available and maintained for a few more years at least. This forum is the right place for such discussions. If you have a piece of feedback or a proposal, please start a new topic in. V1 does not and will not include any application-specific data types. Instead, they are relegated to the regulated namespace, which is outside of the scope of the Specification. Eventually, we will use that to define a set of application-specific profiles, but they are not going to be part of the core specification (think of it like USB device classes or CANopen profiles). You can learn more about this decision here: From the other thread: All regulated data types will use SI, hence radian/second instead of RPM. We are unlikely to accept a data type using RPM because it does not follow the application recommendations outlined in the Specification and in the public regulated data types repository. We can certainly add a new namespace for your company if it does not replicate the functionality available under existing namespaces and it follows the data type design recommendations. If you would like to go ahead, I recommend you to start a new thread in /c/dev with your proposal. RPM is not in the si system? I think this is a dead end. Almost all motor manufacturers use RMP. You do not plan to enter the market of industrial applications? Standards are made for relief, not inconvenience. Do you think that the company is Simems or Bosch, NXP and etc. will someone use a UVACAN with a type zubax? It would be more logical if the type of zubax or another manufacturer was on the Git of the manufacturer, and in the Git UAVCAN there were abstract types. as it is not logical for an advanced abstract protocol. As explained in Data type regulation policy and membership fees, the idea is to enable vendors to collaborate on abstract, reusable interfaces in a well-regulated fashion. In the longer term, we will use regulated vendor namespaces (such as regulated.zubax) as a base to define standard vendor-agnostic profiles. Keeping such generic namespaces in one repository is necessary to reduce the risk of fragmentation and to simplify their maintenance. I don’t think the name of a namespace could prevent other companies from using it in their systems or products.
https://forum.uavcan.org/t/uavcan-and-raspberry-pi/592/11
CC-MAIN-2020-10
refinedweb
1,009
65.62
Opened 7 years ago Closed 7 years ago Last modified 3 years ago #9878 closed Uncategorized (invalid) Database backend leaves idling connections when used in multiple threads Description When creating and saving model instances in multiple threads, the database backend leaves idling connections. This will finally cause a "Too many connections"-exception. I'm using Django 1.0 with a MySQL database This script will leave ~10-20 open connections def createArticle(): a = Article(title = '...', text = '...') a.save() threads = [] for i in xrange(200): t = threading.Thread(target = createArticle) t.start() threads.append(t) for t in threads: t.join() To see the active connections in the mysql client mysql> show full processlist; +--------+------+-----------+------+---------+------+-------+-----------------------+ | Id | User | Host | db | Command | Time | State | Info | +--------+------+-----------+------+---------+------+-------+-----------------------+ | 463987 | ---- | localhost | NULL | Query | 0 | NULL | show full processlist | | 463994 | ---- | localhost | ---- | Sleep | 44 | | NULL | | 464020 | ---- | localhost | ---- | Sleep | 85 | | NULL | | 464042 | ---- | localhost | ---- | Sleep | 85 | | NULL | | 464045 | ---- | localhost | ---- | Sleep | 85 | | NULL | | 464048 | ---- | localhost | ---- | Sleep | 85 | | NULL | | 464067 | ---- | localhost | ---- | Sleep | 85 | | NULL | | 464093 | ---- | localhost | ---- | Sleep | 85 | | NULL | | 464105 | ---- | localhost | ---- | Sleep | 85 | | NULL | | 464136 | ---- | localhost | ---- | Sleep | 85 | | NULL | | 464139 | ---- | localhost | ---- | Sleep | 85 | | NULL | | 464165 | ---- | localhost | ---- | Sleep | 85 | | NULL | | 464166 | ---- | localhost | ---- | Sleep | 85 | | NULL | | 464183 | ---- | localhost | ---- | Sleep | 85 | | NULL | +--------+------+-----------+------+---------+------+-------+-----------------------+ 14 rows in set (0.00 sec) Change History (7) comment:1 follow-up: ↓ 3 Changed 7 years ago by mtredinnick - Needs documentation unset - Needs tests unset - Patch needs improvement unset - Resolution set to invalid - Status changed from new to closed comment:2 Changed 7 years ago by norvegh Hi, You are correct in that we are not using the HTTP layer. We have a back-end application and it was very convenient to reuse Django's model API that we use for the front-end Webapp. However there is clearly a bug in Django, as the connections are not closed even when the threads using those connections are terminated. Those DB connections are just hanging there for a long time (or forever, don't really know that). We know that this is not exactly the way Django is supposed to be used, but Django has grown too powerful and useful to limit it only to the front-end. norvegh comment:3 in reply to: ↑ 1 Changed 7 years ago by anonymous - Resolution invalid deleted - Status changed from closed to reopened Replying to mtredinnick: However, Django closes its connection to the database at the end of each request/response cycle This is not true even when using the HTTP layer (only tested with the development server). After all the threads have joined, there is still idling connections left behind. Try the code I posted erlier and you will see. comment:4 Changed 7 years ago by ubernostrum - Resolution set to invalid - Status changed from reopened to closed What Malcolm means is that the database connection Django itself created automatically for the ORM in the current request/thread will be closed. Additional connections that you yourself cause to be opened are your responsibility to clean up (just as files you open are your responsibility to close, mail-server connections you open are your responsibility to close, etc., etc.). comment:5 Changed 7 years ago by ubernostrum (and to see why this is so for the case of DB connections, note that Django's automatic connection-closing happens on the request_finished signal, which fires only in a thread that's processing an HTTP request, not in any other threads you may have spawned on your own. Django takes care of its thread, and you should take care of yours) comment:6 Changed 7 years ago by Fredde So at the end of each thread django.db.connection.close() should be called? But still, not every thread leaves an open connection. Only about 10% of them, so it looks like a race condition to me. comment:7 Changed 3 years ago by cameel2+django@… - Easy pickings unset - Severity set to Normal - Type set to Uncategorized - UI/UX unset I just got bitten by this after migration from Django 1.3.4 to 1.4.2. Test runner started to hang during cleanup (on an instruction that issues 'drop database test_<appname>' query). Turns out that's because the threads one of the methods under test is spawning were not closing the database connection (even though they themselves seem exit correctly) and server was waiting for them to do so. show full processlist; in mysql client was showing the threads as sleeping with no command to execute. I understand that this is a bug in my code, but if the connections need to be closed explicitly, wouldn't it be better if I was also required to open them explicitly? I wasn't even aware that I'm using the database in those threads. They don't explicitly import any models or database-related code from Django. The fact that they're using it is the actual bug and it would be better if it caused an error instead of failing silently. Another thing is that the test runner should be prepared to handle misbehaving code. Wouldn't it make sense for it check if there are connections from other threads still open (is it possible if the threads have already exited and the runner did not have any references to them?) and if so, print an error and forcefully close them? Letting it just hang like that makes debugging harder. The particular example you give is not the way Django is used, however. So, yes, if you do something to deliberately create lots of connections, lot of connections will be created. However, Django closes its connection to the database at the end of each request/response cycle, so there is only one connection in operation per thread or process handling requests and responses. If you're not using the HTTP layer, it's still only one connection per thread of execution and you are in complete control of the number of threads you create. So there's not really any Django bug here. The connection usage is predictable and controlled.
https://code.djangoproject.com/ticket/9878
CC-MAIN-2015-35
refinedweb
1,002
57.1
15 June 2011 12:00 [Source: ICIS news] LONDON (ICIS)--Here is Wednesday’s midday European oil and chemical market summary from ICIS. CRUDE: July WTI: $98.61/bbl, down $0.76/bbl. July BRENT: $119/bbl, down $1.16/bbl Prices weakened after eurozone finance ministers failed to reach an agreement on a second bailout plan for ?xml:namespace> NAPHTHA: $950-958/tonne, down $6/tonne The cargo range slipped from Tuesday afternoon due to lower crude oil prices. July swaps were assessed at $962–965/tonne. BENZENE: $1,140-1,160/tonne, widened The range widened in an uncertain market. July is flat with June. STYRENE: $1,390-1,410/tonne up $30/tonne Bids and offers climbed after two deals late on Tuesday at $1,385/tonne and $1,390/tonne. July is flat
http://www.icis.com/Articles/2011/06/15/9469578/noon-snapshot-europe-markets-summary.html
CC-MAIN-2014-35
refinedweb
137
69.99
Lifting From HaskellWiki (Difference between revisions) Latest revision as of 22:41, 12 August 2013 Lifting is a concept which allows you to transform a function into a corresponding function within another (usually more general) setting. [edit] 1 Lifting in generalWe usually start with a (covariant) functor, for simplicity we will consider the Pair functor first. Haskell doesn't allow a to be a functor instance, so we define our own Pair type instead. type Pair a = (a, a) If you look at the type of data Pair a = Pair a a deriving Show instance Functor Pair where fmap f (Pair x y) = Pair (f x) (f y) ( fmap ), you will notice that Functor f => (a -> b) -> (f a -> f b) already is a lifting operation: It transforms a function between simple types fmap and a into a function between pairs of these types. b Note, however, that not all functions between lift :: (a -> b) -> Pair a -> Pair b lift = fmap plus2 :: Pair Int -> Pair Int plus2 = lift (+2) -- plus2 (Pair 2 3) ---> Pair 4 5 and Pair a can constructed as a lifted function (e.g. Pair b can't). \(x, _) -> (x, 0) A functor can only lift functions of exactly one variable, but we want to lift other functions, too: In a similar way, we can define lifting operations for all containers that have "a fixed size", for example for the functions from to any value Double , which might be thought of as values that are varying over time (given as ((->) Double) ). The function Double would then represent a value which switches at time 2.0 from 0 to 2. Using lifting, such functions can be manipulated in a very high-level way. In fact, this kind of lifting operation is already defined. \t -> if t < 2.0 then 0 else 2 (see MonadReader) provides a Control.Monad.Reader , Functor , Applicative , Monad and MonadFix instance for the type MonadReader . The (->) r (see below) functions of this monad are precisely the lifting operations we are searching for. If the containers don't have fixed size, it's not always clear how to make lifting operations for them. The liftM - type could be lifted using the [] -family of functions or using zipWith from the list monad, for example. liftM [edit] 2 Applicative liftingThis should only provide a definition what lifting means (in the usual cases, not in the arrow case). It's not a suggestion for an implementation. I start with the (simplest?) basic operations , which combines to containers into a single one and zipL , which gives a standard container for (). zer?) Today we have the -} class that provides Applicative functors. It is equivalent to the Applicative class. Liftable In principle, pure = liftL0 (<*>) = appL zeroL = pure () zipL = liftA2 (,) should be a superclass of Applicative , but chronologically Monad and Functor were before Monad . Unfortunately, inserting Applicative between Applicative and Functor in the subclass hierarchy would break a lot of existing code and thus has not been done as of today (2011). This is still true as of Jan 2013. Monad [edit] 3 Monad liftingLifting is often used together with monads. The members of the -family take a function and perform the corresponding computation within the monad. liftM Consider for example the list monad (MonadList). It performs a nondeterministic calculation, returning all possible results. return :: (Monad m) => a -> m a liftM :: (Monad m) => (a1 -> r) -> m a1 -> m r liftM2 :: (Monad m) => (a1 -> a2 -> r) -> m a1 -> m a2 -> m r just turns a deterministic function into a nondeterministic one: liftM2 Every plus :: [Int] -> [Int] -> [Int] plus = liftM2 (+) -- plus [1,2,3] [3,6,9] ---> [4,7,10, 5,8,11, 6,9,12] -- plus [1..] [] ---> _|_ (i.e., keeps on calculating forever) -- plus [] [1..] ---> [] can be made an instance of Monad using the following implementations: Liftable Lifting becomes especially interesting when there are more levels you can lift between. {-# OPTIONS -fglasgow-exts #-} {-# LANGUAGE AllowUndecidableInstances #-} import Control.Monad instance (Functor m, Monad m) => Liftable m where zipL = liftM2 (\x y -> (x,y)) zeroL = return () (see Monad transformers) defines a class Control.Monad.Trans lift takes the side effects of a monadic computation within the inner monad class MonadTrans t where lift :: Monad m => m a -> t m a -- lifts a value from the inner monad m to the transformed monad t m -- could be called lift0 and lifts them into the transformed monad m . We can easily define functions which lift functions between inner monads to functions between transformed monads. Then we can perform three different lifting operations: t m". liftM [edit] 4 Arrow liftingUntil now, we have only considered lifting from functions to other functions. John Hughes' arrows (see Understanding arrows) are a generalization of computation that aren't functions anymore. An arrow stands for a computation which transforms values of type a b c to values of type b . The basic primitive c , aka arr , pure arr :: (Arrow a) => (b -> c) -> a b c is also a lifting operation.
https://wiki.haskell.org/index.php?title=Lifting&diff=56580&oldid=41050
CC-MAIN-2016-44
refinedweb
831
60.55
Building Reactive Applications With Combine Pure Functions and Higher-Order Functions The Missing Manual for Swift Development The Guide I Wish I Had When I Started Out Join 20,000+ Developers Learning About Swift DevelopmentDownload Your Free Copy In the previous episode, you learned about function types and what it means for Swift to have first-class functions. With these concepts in mind, we continue exploring the functional features of the Swift programming language. In this episode, we explore pure functions and higher-order functions. We start with pure functions. What Is a Pure Function? Pure functions are a key concept in functional programming. The idea is surprisingly simple. A pure function is a function that has no side effects. To understand this definition, you need to know what is meant by side effects. We explore side effects in a moment. We can rephrase the definition of a pure function by stating that a pure function only depends on or operates on what it is given. Let me illustrate this with an example. We define a variable with name a and value 1. The increment(by:) function accepts an argument of type Int and increments the value of a. We print the initial value of a, invoke increment(by:) once, and print the new value of a. var a = 1 func increment(by value: Int) { a += value } print(a) increment(by: 2) print(a) The output isn't surprising. The initial value of a is 1 and the new value of a is 3. 1 3 The increment(by:) function is an impure function because it has side effects. What is a side effect? Every time the increment(by:) function is invoked, it modifies the value of a. It modifies state outside its local environment. Remember the definition of a pure function. A pure function only depends on or operates on what it is given. That is not true for the increment(by:) function because it depends on the value of a. Let's revise the example and convert increment(by:) from an impure function to a pure function. We can accomplish this by passing the value of a to increment(by:) and returning the result of the addition from the function. var a = 1 func increment(_ initialValue: Int, by value: Int) -> Int { initialValue + value } print(a) a = increment(a, by: 2) print(a) Even though the output in the console hasn't changed, we improved the implementation in several respects. The most obvious improvement is that the increment(_:by:) function is reusable because it no longer depends on the value of a. Another significant benefit is that increment(_:by:) no longer has side effects. It operates exclusively on what it is given, the parameters it defines. This has another important benefit. The testability of increment(_:by:) has improved significantly. For a given input, the output is always the same. This is a key feature of pure functions. A pure function always returns the same result for a given set of arguments. In other words, a pure function is predictable and that is a good thing. Because a pure function doesn't depend on anything but the arguments it is given, a pure function has two interesting characteristics. It always accepts one or more arguments and it always returns a value. If you come across a function that doesn't take any arguments or returns nothing, then you can be sure it is an impure function (or a function that does nothing). A pure function is predictable and that means it is easy to understand what it does. You don't need to take other variables into account to understand the effect of a pure function. This is a powerful concept and a cornerstone of functional programming. Are Side Effects Bad? You may think that pure functions are preferred over impure functions. This isn't accurate. Side effects are necessary if your goal is building software people can use. How would you update the user interface of your application if you could only use pure functions, that is, functions that don't have side effects? It is more accurate to say that you should only use an impure function if you can't accomplish the same result with a pure function. What Is a Higher-Order Function? Let's take it one step further and talk about higher-order functions. Don't let yourself be thrown off by the term higher-order function. Like the term pure function, the idea is simple. A higher-order function accepts one or more functions as arguments or it returns a function. It can also do both. Let me show you an example to make sure you understand the concept. I bet you are familiar with Swift's map(_:) function. Take a look at this example. We define a variable, fruits, of type [String]. The array of strings contains three elements. I would like to make each string in the array uppercase. The map(_:) function is perfect to carry out this task. We call map(_:) on fruits, passing in a closure. The map(_:) function invokes the closure for each element in the array, passing the element to the closure as an argument. We invoke uppercased() on the String object and implicitly return it from the closure. import Foundation let fruits = [ "apple", "orange", "cherry" ] fruits.map { (string) -> String in string.uppercased() } The result of the map(_:) function is an array of strings. The array of strings that is stored in fruits is not modified. We can simplify the implementation by using shorthand argument syntax and by leveraging type inference. import Foundation let fruits = [ "apple", "orange", "cherry" ] fruits.map { $0.uppercased() } The map(_:) function is a higher-order function because it accepts a function as an argument. In the example, we pass a closure to the map(_:) function, but it can be a function with a name. Take a look at this example. import Foundation let fruits = [ "apple", "orange", "cherry" ] func uppercase(_ string: String) -> String { string.uppercased() } fruits.map(uppercase) We define a function, uppercase(_:), that accepts an argument of type String and returns a String object. The uppercase(_:) function is a pure function. The signature of the uppercase(_:) function matches what the map(_:) function expects. We can pass the uppercase(_:) function as an argument to the map(_:) function. The result is identical. What's Next? Working with functions can be confusing at times. Before you continue, you need to understand what it means for Swift to have first-class functions. We explored the concepts pure, impure, and higher-order functions. We use these concepts when we explore the Combine framework so it is important that you take the time to learn about them. The Missing Manual for Swift Development The Guide I Wish I Had When I Started Out Join 20,000+ Developers Learning About Swift DevelopmentDownload Your Free Copy
https://cocoacasts.com/building-reactive-applications-with-combine-pure-functions-and-higher-order-functions
CC-MAIN-2020-45
refinedweb
1,163
66.74
Create a snapshot policy You can use Cloudera Manager to create snapshot policies for a directory. - Select in the left navigation bar.Existing snapshot policies are shown in a table on the Snapshot Policies page. - Click Create Snapshot Policy.The Create Snapshot Policy window displays. - From the drop-down list, select the service (HDFS or HBase) and cluster for which you want to create a policy. - Provide a name for the policy and, optionally, a description. - Specify the directories, namespaces or tables to include in the snapshot. - For an HDFS service, select the paths of the directories to include in the snapshot. The drop-down list allows you to select only directories that are enabled for snapshot creation. If no directories are enabled for snapshot creation, a warning displays. Click to add a path and to remove a path. - For an HBase service, list the tables to include in your snapshot. You can use a Java regular expression to specify a set of tables. For example, finance.*match. - Specify whether Alerts should be generated for various state changes in the snapshot workflow.You can alert on failure, on start, on success, or when the snapshot workflow is aborted. - Click Save Policy.The new Policy displays on the Snapshot Policies page.
https://docs.cloudera.com/runtime/7.2.12/data-protection/topics/hdfs-create-snapshot-policy.html
CC-MAIN-2021-49
refinedweb
210
60.61
lp:charms/trusty/apache-hadoop-client Created by Kevin W Monroe on 2015-06-01 and last modified on 2015-10-07 - Get this branch: - bzr branch lp:charms/trusty/apache-hadoop-client Members of Big Data Charmers can upload to this branch. Log in for directions. Branch merges Related bugs Related blueprints Branch information - Owner: - Big Data Charmers - Status: - Mature Recent revisions - 102. By Cory Johns on 2015-10-07 Test cleanups to favor and improve bundle tests - 101. By Kevin W Monroe on 2015-09-15 [merge] merge bigdata-dev r100 into bigdata-charmers - 100. By Kevin W Monroe on 2015-08-24 [merge] merge bigdata-dev r98..r99 into bigdata-charmers - 99. By Kevin W Monroe on 2015-06-18 remove namespace refs from readmes now that we are promulgated - 98. By Kevin W Monroe on 2015-06-01 remove dev references for production - - 94. By Kevin W Monroe on 2015-05-13 update terasort.sh script here. this charm wont have this much longer (once the minimal MP is accepted), but it will be useful until that merge is complete. - 93. By Cory Johns on 2015-05-12 Converted to use jujubigdata library Branch metadata - Branch format: - Branch format 7 - Repository format: - Bazaar repository format 2a (needs bzr 1.16 or later)
https://code.launchpad.net/~bigdata-charmers/charms/trusty/apache-hadoop-client/trunk
CC-MAIN-2017-13
refinedweb
216
66.84
call: () => { const x = 1 + 2; assertEquals(x, 3); }, }); AssertionsAssertions There are some useful assertion utilities at to make testing easier: import { assertArrayIncludes, assertEquals, } from ""; Deno.test("hello world", () => { const x = 1 + 2; assertEquals(x, 3); assertArrayIncludes([1, 2, 3, 4, 5, 6], [3], "Expected 3 to be in the array"); }); Async functionsAsync functions You can also test asynchronous code by passing a test function that returns a promise. For this you can use the async keyword when defining a function: import { delay } from ""; Deno.test("async hello world", async () => { const x = 1 + 2; // await some async task await delay(100); if (x !== 3) { throw Error("x should be equal to 3"); } }); Resource and async op sanitizersResource and async op sanitiz test", fn() { Deno.open("hello.txt"); }, sanitizeResources: false,test definition. Deno.test({ name: "false success", fn() { Deno.exit(0); }, sanitizeExit: false, }); Deno.test({ name: "failing test", fn() { throw new Error("this test fails"); }, }); deno test uses the same permission model as deno run and therefore will require, for example, --allow-write to write to the file system during testing. To see all runtime options with deno test, you can reference the command line deno help test FilteringFiltering There are a number of options to filter the tests you are running. Command line filteringCommand line filtering Tests can be run individually or in groups using the command line --filter option. The filter flags accept a string or a pattern as value. Assuming the following tests: Deno.test({ name: "my-test", fn: myTest }); Deno.test({ name: "test-1", fn: test1 }); Deno.test({ name: "test2", fn: test2 }); This command will run all of these tests because they all contain the word "test". deno test --filter "test" tests/ On the flip side, the following command uses a pattern and will run the second and third tests. deno test --filter "/test-*\d/" tests/ To let Deno know that you want to use a pattern, wrap your filter with forward-slashes like the JavaScript syntactic sugar for a REGEX. Test definition filteringTest definition filtering Within the tests themselves, you have two options for filtering. Filtering out (Ignoring these tests)Filtering out (Ignoring these tests) Sometimes you want to ignore tests based on some sort of condition (for example you only want a test to run on Windows). For this you can use the ignore boolean in the test definition. If it is set to true the test will be skipped. Deno.test({ name: "do macOS feature", ignore: Deno.build.os !== "darwin", fn() { doMacOSFeature(); }, }); Filtering in (Only run these tests)Filtering in (Only run these tests) Sometimes you may be in the middle of a problem within a large test class and you would like to focus on just that test and ignore the rest for now. For this you can use the only option to tell the test framework to only run tests with this set to true. Multiple tests can set this option. While the test run will report on the success or failure of each test, the overall test run will always fail if any test is flagged with only, as this is a temporary measure only which disables nearly all of your tests. Deno.test({ name: "Focus on this test only", only: true, fn() { testComplicatedStuff(); }, }); Failing fastFailing fast If you have a long running test suite and wish for it to stop on the first failure, you can specify the --fail-fast flag when running the suite. deno test --fail-fast Test --unstable # From this you can get a pretty printed diff of uncovered lines deno coverage --unstable cov_profile # Or generate an lcov report deno coverage --unstable files matching the regular expression ^file:. These filters can be overriden using the --exclude and --include flags. A source file's url must match both regular expressions for it to be a part of the
https://deno.land/manual@v1.9.2/testing
CC-MAIN-2022-40
refinedweb
639
60.14
In this article, I will show you how to apply XP-styles to a RichTextBox. The only thing I do here is to derive from the RichTextBox and add support for XP-themed border style. The control is able to run on .NET 1.1 and .NET 2.0. Visual Styles are not fully supported in NET 1.1. There is a bug in the Application.EnableVisualStyles method, and some controls do not render the XP-styles correctly. Here is a good overview about what is going wrong in NET 1.1: VisualStyles. But now we have NET 2.0 and all these bugs are fixed, and nearly all controls render with XP-styles. The only exception is the RichTextBox control. So I decided to write this article. Normally, in NET, all paintings are done in the OnPaint or OnPaintBackground methods of a control. The problem is, inside these methods, you always draw to the client area ( ClientRectangle) of a control. However, the borders are drawn outside this area in the window frame that should be drawn during the WM_NCPAINT message. For a better understanding, look at this illustration... When we customize the window frame, we must filter some messages and process them. WM_NCPAINTmessage tells us that the border should be redrawn. WM_NCCALCSIZEmessage tells us that the client area should be calculated. /// <summary> /// Filter some message we need to draw the border. /// </summary> protected override void WndProc(ref Message m) { switch(m.Msg) { case NativeMethods.WM_NCPAINT: // the border painting is done here. WmNcpaint(ref m); break; case NativeMethods.WM_NCCALCSIZE: // the size of the client area is calcuated here. WmNccalcsize(ref m); break; default: base.WndProc (ref m); break; } } To find out if we should render an application with visual styles, is not an easy task. There are three things to consider. After Googling around in the web, I found a method that does the job: IsVisualStylesEnabled Revisited. To draw in the window frame, we need some Win32-APIs to get the corresponding device context (DC). GetWindowDCto get the device context of the window frame. GetWindowRectto get the rectangle of the window frame. ExcludeClipRectto exclude the client area of the window frame. ReleaseDCto release the DC. Here are the declarations in C#: [DllImport("user32.dll")] public static extern IntPtr GetWindowDC(IntPtr hWnd); [DllImport("user32.dll")] public static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC); [DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect); [DllImport("gdi32.dll")] public static extern int ExcludeClipRect(IntPtr hdc, int nLeftRect, int nTopRect, int nRightRect, int nBottomRect); Drawing visual styles is provided through the uxTheme.dll. We only need a few functions to draw the border. OpenThemeDatato get a theme handle. GetThemeBackgroundContentRectto retrieve the size of the border. DrawThemeBackgrounddraws the border. CloseThemeDatareleases the theme handle. Here are the declarations in C#. [DllImport("uxtheme.dll", ExactSpelling=true, CharSet=CharSet.Unicode)] public static extern IntPtr OpenThemeData(IntPtr hWnd, String classList); [DllImport("uxtheme", ExactSpelling=true)] public extern static Int32 GetThemeBackgroundContentRect(IntPtr hTheme, IntPtr hdc, int iPartId, int iStateId, ref RECT pBoundingRect, out RECT pContentRect); [DllImport("uxtheme", ExactSpelling=true)] public extern static Int32 DrawThemeBackground(IntPtr hTheme, IntPtr hdc, int iPartId, int iStateId, ref RECT pRect, IntPtr pClipRect); [DllImport("uxtheme.dll", ExactSpelling=true)] public extern static Int32 CloseThemeData(IntPtr hTheme); The .NET Framework 2.0 contains new classes for drawing visual styles. You can find them in the System.Windows.Forms.VisualStyles namespace. Also a method to check, if visual styles are enabled, is available in the new framework. Look for the Application.RenderWithVisualStyles property. However, I had not made two versions, because I think having one version for both is less to do on modifications and thus the better solution. MultiLineis set to false. General News Question Answer Joke Rant Admin
http://www.codeproject.com/KB/edit/RichTextBoxEx.aspx
crawl-002
refinedweb
624
60.92
font used by the Text component. Use it to alter or return the font from the Text. There are many free fonts available online. See more information on fonts and importing your own in the Fonts section. no example available in JavaScript //Create a new Text GameObject by going to Create>UI>Text in the Editor. Attach this script to the Text GameObject. Then, choose or click and drag your own font into the Font section in the Inspector window. using UnityEngine; using UnityEngine.UI; public class TextFontExample : MonoBehaviour { Text m_Text; //Attach your own Font in the Inspector public Font m_Font; void Start() { //Fetch the Text component from the GameObject m_Text = GetComponent<Text>(); } void Update() { if (Input.GetKey(KeyCode.Space)) { //Change the Text Font to the Font attached in the Inspector m_Text.font = m_Font; //Change the Text to the message below m_Text.text = "My Font Changed!"; } } }
https://docs.unity3d.com/2017.4/Documentation/ScriptReference/UI.Text-font.html
CC-MAIN-2021-04
refinedweb
146
68.36
China's reaction to demonstrations is being watched closely Trend could be bad news for major banks Join the NASDAQ Community today and get free, instant access to portfolios, stock ratings, real-time alerts, and more! Keith Schaefer: Stick with Wet Gas, Heavy Oil Plays Source: Brian Sylvester of The Energy Report 08/03/2010 Oil and Gas Investments Bulletin Editor and Publisher Keith Schaefer specializes in Canadian oil and gas plays. Despite the languishing gas price, he sees opportunities in some hedged Canadian gas companies and unhedged "wet-gas" producers. If you're not into gas, Keith is big on oil. In this exclusive interview with The Energy Report, Keith will tell you how radial drilling is creating opportunities in heavy oil, too. The Energy Report: Keith, when The Energy Report talked with you in December , you said that a gas price below $5 would be "hell." Well, welcome to hell. Gas is hovering around $4.50 right now. Where's the bottom? Keith Schaefer: It has been a very tough year for gas producers. Since January, the gas price has been on a straight downhill slide, with very few bumps up along the way. It has been hell, particularly for the juniors that are unhedged. These companies are creating no value for their shareholders. Their cash flow is anemic. Where is the bottom? I think there's a good chance we're going to find that out in the next month or so, because gas traditionally bottoms in August. Last year, it bottomed around $2.50, $2.75 per MCF. Then in September, it started to take a big jump back up to $5. These stocks had a huge run along with that. It's almost funny, because none of these companies were really making money at $5, but the fact that they were losing a little bit less made the market very happy, and that took the stocks for a big run. TER: At the same time, a lot of producers are hedged. Most of them are right around the $6 mark. KS: Many of the seniors are hedged at $6. The forward curve has allowed them to do that. Good for them and their shareholders, because it looks like we could be in for a multi-year low gas price if these U.S. shale plays hold up. TER: What's your view on the gas price through the end of this year and the end of 2011? KS: I think this year we're going to get a little bit higher, but not much. Right now gas in the States is running around $4.50. In Canada, it's running at about a dollar less. These shale gas plays in the U.S. are doing a superb job at increasing production. Unless there's a dramatic increase in demand or a significant falloff from production, we're going to be staying right around here; maybe a little bit higher, but not much. TER: And that's through the end of 2011 as well? KS: The end of 2011 could be very interesting, just because many of these shale gas plays are relatively new. Right now companies stake a bunch of land and they have to drill the land to hold it. Once they've drilled a certain amount of holes, that land is theirs. When that happens, I expect these companies to stop drilling. That should actually be quite positive for the gas price. Companies are being forced to drill to keep their land when the market says they shouldn't. TER: Are there companies that, despite the low gas prices, continue to perform? KS: Oh, yes. You're seeing several companies do better than expected, for a couple of reasons. Some have been smart enough to hedge, which has benefited their balance sheet and their cash flow. Bellatrix Exploration Ltd. ( BXE ) is at the top of that list, and it's in our Oil and Gas Investment Bulletin Portfolio. They've hedged 50% of their gas at close to $7, so their cash flow has been fantastic this year. A second reason Bellatrix is doing better than expected is that they have a large land position in a burgeoning oil play in Alberta known as the Cardium. That stock has outperformed its peers this year, and in my mind, it will continue to. Another company that's done really well is Angle Energy Inc. ( NGL ) , a wet-gas producer. Wet gas gets about twice the amount of money as dry gas. TER: Is this what's known as natural gas liquids in the U.S.? KS: Yes, liquid-rich gas. Angle has a huge growth curve in front of them. They're not hedged. If you're looking to play gas, that's a good one, because from their wet gas, they have downside protection with good cash flow, at current gas prices. They also have huge exposure to the upside if gas moves. TER: Are we seeing companies with assets that have a high percentage of natural gas liquids getting higher valuations? KS: Absolutely. Companies are getting higher valuations because of their higher wet gas percentages. Not across the board, but most of them are, companies like Angle and some of the other high wet-gas producers, which are mostly in the Deep Basin area of Alberta, right outside the foothills. And up in the Montney shale play, as well, they're getting higher liquids contents. They're getting 10, 20, 30, 40 barrels of wet gas per million cubic feet of dry gas, which could basically double the economics. TER: Wow. Do you have some specific names with exposure to those plays besides Angle? KS: Orleans Energy Ltd. ( OEX ) has a good wet gas count. Cinch Energy Corp. ( CNH ) has a wet gas count. Vero Energy Inc. ( VRO ) . . . TER: All right, what about Vero? KS: I love Vero. I think it's a great company. The stock trades very, very well for how few shares-only 30 million-are out. Vero has one of the top management teams in the business, Doug Bartole and his vice president of exploration, Kevin Yakiwchuk. They have a great property in the Edson area of Alberta. They've shown great discipline in producing when the gas price is good and shutting down production when it's not. They've managed their finances very well. Vero keeps a high debt ratio, which means they don't have to issue many shares because they're generating most of their growth by using debt. They've got this new Cardium oil play, which has over 90 net sections. That's a lot of oil that they can bring onstream, very profitable oil. TER: Are they in production right now? KS: They're producing 8,000-8,500 barrels a day. TER: Are there any other gas companies that you're excited about? You cover Peyto Energy Trust (TSX:PEY-U; OTC:PEYUF) . Tell us about that one. KS: Peyto is the lowest-cost producer in Canada. Their suite of properties is best of breed. Management has done a fantastic job. Over the last 10 years, that stock went from $1 to $45. I actually owned that stock when it was $1 a share, back in 1998. Now, of course, after the crash, everything's changed; but they continue to have the lowest- cost production, and a great growth profile. If you were only going to buy one gas company to get some exposure to a potentially rising gas price, Peyto-being the lowest-cost producer-would be it. TER: A recent report on the U.S. shale plays by Credit Suisse talked about some of the gas shale plays with the best internal rates of return ( IRR ). The Marcellus was ranked second, with a 42% IRR. What are some companies with significant exposure to the Marcellus? KS: One of the best companies that I like for exposure to the Marcellus shale play is actually an energy services company that does a lot of the drilling work and mud work for the producers in that area. It's called Canadian Energy Services and Technology Corp. ( CEU ) . They've been able to make huge inroads into the Marcellus by selling their products to the drillers and producers there. Their mud allows drillers to complete a well in the Marcellus about 10 days sooner than normal. That dramatically reduces costs, which is one of the reasons the Marcellus is turning into a much more profitable play. On the producer's side, I think one of the safest plays in the Marcellus is a company called Epsilon Energy Ltd. ( EPS ) . They have a deal with Chesapeake Energy Corp. ( CHK ) , the second largest gas producer in the United States. Between cash payments and work commitments, they've paid Epsilon about $200 million to get access to Epsilon's Marcellus ground in Pennsylvania. Epsilon basically has a free ride. In one sense it doesn't really matter what gas prices do, because Chesapeake is paying the freight. I love companies like that. TER: I think we'll switch over to oil. Oil remains just below $80 a barrel. Do you think that's a psychological barrier?. TER: It's more expensive to process, but are there still some companies that you like that are big into heavy oil and are profitable. Could you tell us about some of those? KS: Yes. That's a great point. What's happening here is that many of the U.S. refineries, particularly those down in the Gulf of Mexico, are geared toward heavy oil. You just can't change your refinery at the flick of a switch and say, "Alright, today we're going to do light oil. Tomorrow we're going to do heavy oil." When you're a heavy oil refinery, that's the type of feedstock you need. The two biggest sources of heavy oil, Mexico and Venezuela, are in steep decline-Mexico for geological reasons, Venezuela for political reasons. That means that the heavy oil from Canada is in hot demand in U.S. refineries. There's a new pipeline being proposed to take oil from Canada down to the U.S. refineries. Many heavy oil producers that are used to getting only 50%-60% of the regular oil price for their products, because it costs so much more to process them, are now getting 85%-90% of the regular oil price. Over the last two or three years, there has been a huge increase in the heavy oil price. What they called a "heavy oil discount" has gotten much smaller. And the heavy oil in Canada is very shallow, so it does not cost much to produce. Wells only cost $300,000-$700,000, versus $3 million-$5 million for a deep light oil well. So when your costs are low and the price of your product has gone up a great deal, that's a recipe for profits. TER: Tell us about some of those companies that are profiting from this trend in heavy oil. KS: Well, one of my favorites is a company called Emerge Oil and Gas Inc. ( EME ) , which has lots of heavy oil in Alberta and in Saskatchewan. They have done a great job securing large land packages that have highly prospective oil leases. Emerge has been able to deliver good production growth and will continue to do so over at least the next two years. TER: Any others? KS: Another one that I like is a company called Rock Energy Inc. ( RE ) . CEO Al Bey knows how to secure land positions, and he has a very good cost-control system in place. Some of their properties are able to deliver profits of three to seven times the money that Rock puts into them. For every dollar that they put into the search for the oil, they're able to return $3-$7 to the shareholders. That's a fantastic "recycle ratio." TER: What other things has management done? KS: They just brought on John Van De Pol as President and CFO. John's been involved in a couple of winners in the past, has a lot of experience and does it right. He's very methodical. For a shareholder, he's exactly the type of guy who gives you a lot of confidence. TER: What are Rock's prospects for growth? KS: They still have a large undeveloped land package, with a drilling inventory of at least two to three years ahead of them. They'll be able to continue to grow production quite strongly. Rock is also one of the pioneers in using this new radial drilling technology. They're finding that the amount of oil they can get out of each of their land sections is increasing quite dramatically, and that's been a big, big bonus. TER: Are there any other companies you like in the heavy oil space? KS: Not too many. Rock and Emerge are two of the best. Another one is BlackPearl Resources Inc. ( PXX ) , which has a strong growth profile. Their growth is actually going to come in chunks. Unlike Emerge and Rock, which are able to drill a lot of small wells, BlackPearl has slightly larger assets that take more time and more capital to develop. Their growth is going to come more in steps and stages, as opposed to the steady growth that Rock and Emerge will have. But it's a well-respected team, and the market loves BlackPearl. TER: How so? KS: They trade at a much higher valuation, for example, than Emerge does. Its market cap relative to its production is very high. With almost 300 million shares issued, the company is worth almost $1 billion. For the level of production that it has right now, BlackPearl is a relatively expensive stock. TER: Yesterday, BP (NYSE:BP; LSE:BP) sold most of its Canadian assets to Apache Corp. ( APA ) . Will that create any opportunities in Canada? KS: I think it's too early to say. But let's consider Apache the general contractor in a construction job. They are going to cherry-pick the assets that they really want and sell off the smaller assets that they don't want. You're going to see a filtering-down of these assets to smaller companies over the next year. That should create a pretty big opportunity for the right team that's able to get a good land position. TER: What could it do for Apache? KS: Apache has been spending a lot of money up here, which is interesting. They're one of the largest gas producers in Canada. They bought the controlling interest in the LNG (Liquefied Natural Gas) terminal being built at Kitimat, British Columbia. That gas will go to Asia, where the price is much better. This is one of the strategic things Apache has been able to do: basically, set themselves up as huge land and major infrastructure owners to send gas overseas, where it gets a much better price. If Apache had to send this gas down to the U.S., it would not be very profitable, because it's way up near the Yukon border. And with Marcellus production coming on-stream, that's really cutting out a lot of Canadian gas into the States. But if they can keep that gas producing and send it over to Asia, via the LNG terminal on Canada's west coast, that could be a huge profit center for Apache. TER: Are there parting thoughts you want to leave us with? KS: Many natural gas companies are trying to rebrand themselves now as wet-gas companies, to try to get higher valuations. We're going to see a lot of that type of talk over the next six months. But I don't see any sustained pick-up in the gas price for a year. Having said that, as soon as we get a sign that some of these U.S. shale plays are going to fizzle quicker than expected, that situation could change very, very quickly. Also, we have a special offer exclusively for Energy Report readers-we're offering a free Oil & Gas Investments Bulletin report, which includes an exclusive stock pick, one which I believe has lots of room for growth-despite it having already doubled for my subscribers. As well, we're offering your readers a 30% discount on current subscription rates for a limited time only. For more information on this special offer, please visit our website at: . Our returns have done very, very well this year and with the annual subscription there is a 60-day money back guarantee. Keith Schaefer of the Oil & Gas Investments Bulletin writes on oil and natural gas markets. His newsletter outlines which TSX-listed energy companies have the ability to grow, and bring shareholders prosperity. He has a degree in journalism and has worked for several dailies in Canada, but has spent the last 15 years assisting public resource companies in raising exploration and expansion capital. none of the companies mentioned in this interview. 2) The following companies mentioned in the interview are sponsors of The Energy Report: Rock Energy. 3) Keith Schaefer-I personally and/or my family own the following companies mentioned in this interview: Rock Energy, Angle Energy, Bellatrix Energy, Vero Energy, Orleans Energy, Cinch Energy, Canadian Energy Services, Emerge Energy, BlackPearl Resources.?
http://www.nasdaq.com/article/keith-schaefer-stick-with-wet-gas-heavy-oil-plays-cm31077
CC-MAIN-2014-42
refinedweb
2,916
74.08
...one of the most highly regarded and expertly designed C++ library projects in the world. — Herb Sutter and Andrei Alexandrescu, C++ Coding Standards template <std::size_t Size, std::size_t Align> struct aligned_storage { typedef see-belowtype; }; type: a built-in or POD type with size Size and an alignment that is a multiple of Align. Header: #include <boost/type_traits/aligned_storage.hpp> or #include <boost/type_traits.hpp> On the GCC and Visual C++ compilers (or compilers that are compatible with them), we support requests for types with alignments greater than any built in type (up to 128-bit alignment). Visual C++ users should note that such "extended" types can not be passed down the stack as by-value function arguments.
http://www.boost.org/doc/libs/1_60_0/libs/type_traits/doc/html/boost_typetraits/reference/aligned_storage.html
CC-MAIN-2016-07
refinedweb
118
53.41
I copied and pasted the code, so I know there aren't any typos. I made sure the file name was correct, but the program just spits random, unreadable characters at me. Any ideas? Code: #include <fstream> #include <iostream> using namespace std; int main() { char str[10]; //Creates an instance of ofstream, and opens example.txt ofstream a_file ( "F:\test.txt" ); // Outputs to example.txt through a_file a_file<<"This text will now be inside of example.txt"; // Close the file stream explicitly a_file.close(); //Opens for reading the file ifstream b_file ( "F:\test.txt" ); //Reads one string from the file b_file>> str; //Should output 'this' cout<< str <<"\n"; cin.get(); // wait for a keypress // b_file is closed implicitly here }
http://cboard.cprogramming.com/cplusplus-programming/103586-trouble-lesson-10-file-i-o-printable-thread.html
CC-MAIN-2015-35
refinedweb
119
77.53
This is a small project for Windows applications. It creates a control which simulates a LED light. The LED is round and colorful and it draws itself from the overridden OnPaint method. In addition to its On/Off functionality, it uses a timer to rotate a finite number of colors with individually set intervals. Used with imagination, it will add fancy effects to your application. Create a new project as C# Window Control Library. Before anything else, change the inheritance from UserControl to just Control, rename everywhere UserControl with Led, and delete everything related to InitialiseComponent - Led won't have sub controls. Continue by changing the namespace from whatever to something suitable for your control collection, as TH.WinControls (where TH stands for my initials - but it could be yours). Right click on the Led project in Solution Explorer, select Properties from the pop up menu, and change Default Namespace to the above name. Then add a bitmap to your project, name it like the project as Led.bmp, and before editing its content, select another item in Solution Explorer and then select back Led.bmp. In the Properties pane, change Build Action to Embedded Resource. Only then enter the bitmap editor and start designing a nice bitmap, 16 X 16 with 16 colors, like: Now, you may build the project and add the control in the Toolbox. At this stage, the control just comes on the palette with no functionality. Add in its constructor the following lines: private Timer tick; public Led():base() { SetStyle(ControlStyles.AllPaintingInWmPaint, true); SetStyle(ControlStyles.DoubleBuffer, true); SetStyle(ControlStyles.UserPaint, true); SetStyle(ControlStyles.ResizeRedraw, true); Width = 17; Height = 17; Paint += new System.Windows.Forms.PaintEventHandler(this._Paint); tick = new Timer(); tick.Enabled = false; tick.Tick += new System.EventHandler(this._Tick); } Create also the SetStyle statements are self explanatory. I'm setting the Width and Height to an odd number for the convenience of having a pixel in the centre of the control. 17 came as the best size for a perfect circle, as our LED will be circular. Timerat this moment, but keep it disabled for the moment. Now, we have to add the two referred handlers - _Pant, which will draw the control, and _Tick, which will handle the change of color in the Flashmode. Trick: to be able to build each phase, just add empty handlers for _Timer and _Paint. To know what the method signature looks like, create the handler of Paint in the main form, also place there a Timer and create its handler. Then copy the related code in the control's file and adapt the corresponding names: private void _Paint(object sender, System.Windows.Forms.PaintEventArgs e) { } private void _Tick(object sender, System.EventArgs e) { } Add a new property to be able to activate the LED, and two more to be able to specify the colors of the two - active/inactive - states: private bool _Active = true; [Category("Behavior"), DefaultValue(true)] public bool Active { get { return _Active; } set { _Active = value; Invalidate(); } } private Color _ColorOn = Color.Red; [Category("Appearance")] public Color ColorOn { get { return _ColorOn; } set { _ColorOn = value; Invalidate(); } } private Color _ColorOff = SystemColors.Control; [Category("Appearance")] public Color ColorOff { get { return _ColorOff; } set { _ColorOff = value; Invalidate(); } } Note the Invalidate call that will make sure that Paint will redraw the component as soon as a time slice will be available for this task. The _Paint handler is responsible for interpreting the Enable and Active states. Here is its code: private void _Paint(object sender, System.Windows.Forms.PaintEventArgs e) { e.Graphics.Clear(BackColor); if (Enabled) { if (Active) { e.Graphics.FillEllipse(new SolidBrush(ColorOn),1,1,Width-3,Height-3); e.Graphics.DrawArc(new Pen(FadeColor(ColorOn, Color.White,1,2),2),3,3,Width-7, Height-7,-90.0F,-90.0F); e.Graphics.DrawEllipse(new Pen(FadeColor(ColorOn, Color.Black),1),1,1,Width-3,Height-3); } else { e.Graphics.FillEllipse(new SolidBrush(ColorOff),1,1,Width-3,Height-3); e.Graphics.DrawArc(new Pen(FadeColor(ColorOff, Color.Black,2,1),2),3,3,Width-7,Height-7,0.0F,90.0F); e.Graphics.DrawEllipse(new Pen(FadeColor(ColorOff, Color.Black),1),1,1,Width-3,Height-3); } } else e.Graphics.DrawEllipse(new Pen(System.Drawing.SystemColors.ControlDark,1), 1,1,Width-3,Height-3); } To better manipulate colors, I have introduced a helper function - FadeColor - which will blend the color given in the first parameter over the second one with a given ratio. I'll give a default for the ratio as 1 to 1. I'll make the function public and static for being able to use it from outside the component source code and without the need to create a LED; in fact, it has nothing to do with the shape and behavior of it: #region helper color functions public static Color FadeColor(Color c1, Color c2, int i1, int i2) { int r=(i1*c1.R+i2*c2.R)/(i1+i2); int g=(i1*c1.G+i2*c2.G)/(i1+i2); int b=(i1*c1.B+i2*c2.B)/(i1+i2); return Color.FromArgb(r,g,b); } public static Color FadeColor(Color c1, Color c2) { return FadeColor(c1,c2,1,1); } #endregion The function works by splitting the two colors in R, G and B components, applying the ratio, and returning the recomposed color. I use this function to blend the LED color in the margin of the bubble, as well as for adding the sparkle that will give the bubble's volume. When the LED is On, the margin is enlightened with White, while - when Off is darkened with Black. The same for the sparkle, but with different ratios. You may now compile the solution, drag a LED on the test form, change its colors and switch it On/Off directly there in the design mode! Now here is the deal: I want to be able to add more that one flash interval, and - why not - more than a set of two On/Off colors. In fact, I want to be able to add as many colors as I want and fire them in sequence like a smooth gradient or an invasive Red-Yellow-Magenta warning. The way to preset this behavior through properties should be easy and error free, while being able to program lengthy sequences by code. To achieve this, I'll add two properties: private string _FlashIntervals="250"; public int [] flashIntervals = new int[1] {250}; [Category("Appearance"), DefaultValue("250")] public string FlashIntervals { get { return _FlashIntervals; } set { _FlashIntervals = value; string [] fi = _FlashIntervals.Split(new char[] {',','/','|',' ','\n'}); flashIntervals = new int[fi.Length]; for (int i=0; i<fi.Length; i++) try { flashIntervals[i] = int.Parse(fi[i]); } catch { flashIntervals[i] = 25; } } } private string _FlashColors=string.Empty; public Color [] flashColors; [Category("Appearance"), DefaultValue("")] public string FlashColors { get { return _FlashColors; } set { _FlashColors = value; if (_FlashColors==string.Empty) { flashColors=null; } else { string [] fc = _FlashColors.Split(new char[] {',','/','|',' ','\n'}); flashColors = new Color[fc.Length]; for (int i=0; i<fc.Length; i++) try { flashColors[i] = (fc[i]!="")?Color.FromName(fc[i]):Color.Empty; } catch { flashColors[i] = Color.Empty; } } } } FlashIntervals and FlashColors will accept delimited strings, which will be converted to public arrays accessible to the internal code as as well as to external procedures. Any reasonable delimiter will break the input string, and error items will default to Color.Empty for colors that will switch the LED Off, and 25 ms for the interval - small enough not to be troublemaker. There is no need to have the two arrays with the same length: when the colors table is bigger, the extra items will be ignored, while if there are fewer colors than intervals, extra intervals will switch the LED On and Off. The same for empty colors. public int tickIndex; private void _Tick(object sender, System.EventArgs e) { tickIndex=(++tickIndex)%(flashIntervals.Length); tick.Interval=flashIntervals[tickIndex]; try { if ((flashColors==null) ||(flashColors.Length<tickIndex) ||(flashColors[tickIndex]==Color.Empty)) Active = !Active; else { ColorOn = flashColors[tickIndex]; Active=true; } } catch { Active = !Active; } } This would conclude our flash feature if we had a Flash property to switch this mode: private bool _Flash = false; [Category("Behavior"), DefaultValue(false)] public bool Flash { get { return _Flash; } set { _Flash = value && (flashIntervals.Length>0); tickIndex = 0; tick.Interval = flashIntervals[tickIndex]; tick.Enabled = _Flash; Active = true; } } FlashIntervalsand nothing in FlashColors. FlashColors- RED,Greenand for FlashIntervals- 500,500. Red,Off,Yellow,Off,Blue. You may enter exactly this string as Offis not a valid color, or - shorter: Red,,Yellow,,Blue(don't enter space in-between commas - space is also a separator!). For FlashIntervals, enter 500,250,500,250,500,250. Note the extra 250 value for having an Off interval between Blue and Red. FlashIntervalsas 250,250,250,1000. Will do: quarter sec On, quarter Off, again quarter On, and finally one second Off; then will repeat. You may also program double-pulse of dark with 1000,250,250,250. FadeColormethod. So, just add the following code somewhere in the test-form's code-behind, as in the form's constructor (or add a button): Color c; led5.flashColors = new Color[40]; led5.flashIntervals = new int[40]; for (int i= 0; i<20; i++) { c= TH.WinComponents.Led.FadeColor(Color.Yellow,Color.Red, (i<=20)?i:20,(i>20)?20:20-i); led5.flashColors[ i]=c; led5.flashIntervals[ i]=50; led5.flashColors[39-i]=c; led5.flashIntervals[39-i]=50; } led5.Flash=!led5.Flash; I would have finished here, but a couple of details forced me to continue, in fact with a lot more. Is our control really transparent outside the babble? Let's find out! Let's go in the test form and draw a line from corner to corner: private void Form1_Paint(object sender, System.Windows.Forms.PaintEventArgs e) { e.Graphics.DrawLine(new Pen(Color.White,2),0,0, ClientRectangle.Width,ClientRectangle.Height); } private void Form1_SizeChanged(object sender, System.EventArgs e) { Invalidate(); } (First of all, we learn how to address the coordinates inside the form area using the ClientRectangle. Then we are forced to invalidate the form each time the form resizes. Else, this is what happens: What? - Windows has invalidated only areas that have been added to the original form, and through where the mouse has moved. So, put back the Invalidate call, and make the line wider. Now, what do we learn? Surprise: the control is not transparent at all! Let's add the following lines to the LED's constructor. (Disable also the big one, just to see how Enable works): SetStyle(ControlStyles.SupportsTransparentBackColor, true); BackColor = Color.Transparent; More likely... At this point, our control is quite done. However, let's see what else we could achieve from outside the control code. To do that we have to connect some code to the LED events, and the first event we need to attach code to is Paint. Unfortunately, we have already consumed the Paint event inside the control's code. Well, Paint is kind of delegate - we attach code on with the += operator, so we assume that we can attach other handlers as well. However, in the internal handler, the area of the LED was already rendered - we can only add graphical elements over the bubble. That means we have to change things. Let's delete the reference to the _Paint handler from the LED's constructor and let's change this method's declaration with the following lines: protected override void OnPaint(PaintEventArgs e) { if (Paint!=null) Paint(this,e); else { base.OnPaint(e); // ... the same as above _Paint method Trying to compile this, we find out that the original Paint event cannot be used on the left part of expressions; neither can we call it. Fortunately, we can replace it with a new one: public new event PaintEventHandler Paint; And now, we can replace the internal rendering of the control with a completely new one. Let's start drawing an exclamation point inside a triangle - the universal sign of "Attention!". We'll use led5 which we have already programmed to rotate colors through a gradient from Red to Yellow. I'll attempt to change not only the shape, but also make the sign pulsating: private void led5_Paint(object sender, System.Windows.Forms.PaintEventArgs e) { TH.WinComponents.Led l = sender as TH.WinComponents.Led; if (l.Enabled && l.Active) { int cx,cy,w,h,d; d = (l.tickIndex<20)?l.tickIndex:39-l.tickIndex; cx = l.Width/2; cy = l.Height/2; w = 2*d+8; h = 2*d+8; try { // Triangle Point startPoint = new Point(cx,cy-h/2); e.Graphics.FillPolygon(new SolidBrush(l.ColorOn), new Point[] {startPoint, new Point(cx-w/2,cy+h/2), new Point(cx+w/2,cy+h/2), startPoint }); // Exclamation mark e.Graphics.DrawLine(new Pen(Color.Red,4),cx,cy-h/2+9,cx,cy+h/2-11); e.Graphics.DrawLine(new Pen(Color.Red,6),cx,cy-h/2+11,cx,cy); e.Graphics.DrawLine(new Pen(Color.Red,4),cx,cy+h/2-7,cx,cy+h/2-3); } catch {} } } This exclamation point is not very nice especially when it is small, but at that time, I'll dissolve it in the triangle becoming Red. Also, some error may occur when the shape goes too small, but the empty catch block will take care. Another challenge: using external bitmap: create a small bitmap file by right-clicking the LED project and adding a new item as a bitmap file. Let's draw a heart and name it that way. I want this heart to beat with double pulses like a real heart. To do that, prepare the Flash mode, assigning 100,250,100,750 to its FlashIntervals property. Now, put the following code on the Paint handler of led1: Bitmap hart; private void led6_Paint(object sender, System.Windows.Forms.PaintEventArgs e) { TH.WinComponents.Led l = sender as TH.WinComponents.Led; Rectangle r = new Rectangle(0,0,40,40); switch (l.tickIndex) { case 0 : r = new Rectangle(0,0,47,47); hart.RotateFlip(RotateFlipType.Rotate90FlipNone); break; case 1 : r = new Rectangle(3,3,40,40); break; case 2 : r = new Rectangle(1,1,46,46); break; case 3 : r = new Rectangle(3,3,40,40); break; } e.Graphics.DrawImage(hart,r); } To make this code work, we have to load and prepare the heart bitmap somewhere. Let's do that in the constructor of the form: hart = new Bitmap(@"C:\CS\WinComponents\Led\Hart.bmp"); hart.MakeTransparent(Color.White); Is it not nice to refer and deliver a file with an executable file, so let's include it in the resources of the assembly. Click on the Hart.bmp file from the test program and, in the Properties panel, change the Build Action to Embedded Resource. Now modify the initialization code: //hart = new Bitmap(@"C:\CS\WinComponents\Led\Hart.bmp"); Stream s = Assembly.GetCallingAssembly().GetManifestResourceStream("Led.Hart.bmp"); hart = new Bitmap(s); Note: Led from the resource name Led.Hart.bmp stands for the assembly name of the test program. I have presented a small project which creates a control simulating a LED light. The LED control draws itself from its OnPaint method. In addition to its On/Off functionality, it flashes rotating a set of colors with preset intervals. In the end, I have added as a bonus, external events to modify the embedded functionality with drawing bitmap stored in the assembly resources. Used with imagination, it can add fancy effects to any application. General News Question Answer Joke Rant Admin
http://www.codeproject.com/KB/miscctrl/FlashLED.aspx
crawl-002
refinedweb
2,575
58.58
On 24 October 2000, Barry A. Warsaw said: > All well and good and doable in Python today, except getting the > current frame with the exception raising trick is slooow. A simple > proposed addition to the sys module can improve the performance by > about 8x: > > def _(s): > frame = sys.getcaller(1) > d = frame.f_globals.copy() > d.update(frame.f_locals()) > return the_translation_of(s) % d > > The implementation of sys.getcaller() is given in the below patch. > Comments? I think this particular addition is too small for a PEP, > although ?!ng still owns PEP 215 (which needs filling in). +1. Not sure if I would call that function 'getcaller()' or 'getframe()'; could go either way. In my implementation of this (I guess everyone has one!), I also have a couple of convenience functions: def get_caller_env (level=1): """get_caller_env(level : int = 1) -> (globals : dict, locals : dict) Return the environment of a caller: its dictionaries of global and local variables. 'level' has same meaning as for 'caller()'. """ def get_frame_info (frame): """get_frame_info(frame) -> (filename : string, lineno : int, function_name : string, code_line : string) Extracts and returns a tuple of handy information from an execution frame. """ def get_caller_info (level=1): """get_caller_info(level : int = 1) -> (filename : string, lineno : int, function_name : string, code_line : string) Extracts and returns a tuple of handy information from some caller's execution frame. 'level' is the same as for 'caller()', i.e. if level is 1 (the default), gets this information about the caller of the function that is calling 'get_caller_info()'. """ These are mainly used by my unit-testing framework (which you'll no doubt remember, Barry) to report where test failures originate. Very handy! Looks like Ping's inspect.py has something like my 'get_frame_info()', only it's called 'getframe()'. Obviously this is the wrong name if Barry's new function gets added as 'sys.getframe()'. How 'bout this: sys.getframe(n) - return stack frame for depth 'n' inspect.getframeinfo(frame) - return (filename, line number, function name, lines-of-code) Although I haven't grokked Ping's module enough to know if that rename really fits his scheme. Greg -- Greg Ward - software developer gward@mems-exchange.org MEMS Exchange / CNRI voice: +1-703-262-5376 Reston, Virginia, USA fax: +1-703-262-5367
https://mail.python.org/pipermail/python-dev/2000-October/010182.html
CC-MAIN-2016-50
refinedweb
368
58.18
This post is part of an ongoing series that I am writing with @jesseliberty .The original post is on his site and the spanish version on mine. In this series, we will explore a number of topics on Advanced Xamarin.Forms that have arisen in our work for clients, or at my job as Principal Mobile Developer for IFS Core. Before we can start, however, we need to build an API that we can program against. Ideally, this API will support all CRUD operations and will reside on Azure. Building the API Begin in Visual Studio, creating an API Core application, which we’ll call BookStore. Change the name of the values controller to BookController. Create a new project named Bookstore.Dal (Data access layer), within which you will create two folders: Domain and Repository. Install the Nuget package LiteDB a NoSql database. In the BookRepository folder, create a file BookRepository.cs. In that file you will initialize LiteDB and create a collection to hold our books. public class BookRepository { private readonly LiteDatabase _db; public BookRepository() { _db = new LiteDatabase("bookstore.db"); Books.EnsureIndex(x => x.BookId); } If bookstore.db does not exist, it will be created. Similarly if the index doesn’t exist, it too will be created. Go up to the API project and right-click on Dependencies to add a reference to our Bookstore.dal project. Open the BookstoreController file. Add using statements for Bookstore.Dal.Domain and Bookstore.Dal.Repository. Create an instance of the BookRepository in the controller, and initialize it. public class BooksController : ControllerBase { private BookRepository _bookRepository; public BooksController() { _bookRepository = new BookRepository(); } Creating the Book Object We will need a simple book object (for now) to send and retrieve from our repository and database. Start by creating the book object (feel free to add more fields) public class Book { public Book() { BookId = Guid.NewGuid().ToString(); } public string BookId { get; set; } public string ISBN { get; set; } public string Title { get; set; } public List<Author> Authors { get; set; } public double ListPrice { get; set; } } Notice that the Book has a List of Author objects. Let’s create that class now, again keeping it very simple, public class Author { public string AuthorId { get; set; } public string Name { get; set; } public string Notes { get; set; } } The Repository Let’s return to the repository. Earlier we initialized the database. Now all we need is to create the methods. We begin by creating the connection of our local List of Book to the db table: public LiteCollection<Book> Books => _db.GetCollection<Book>(); Next comes our basic methods: get, insert, update, delete: public IEnumerable<Book> GetBooks() { return Books.FindAll(); } public void Insert(Book book) { Books.Insert(book); } public void Update(Book book) { Books.Update(book); } public void Delete(Book book) { Books.Delete(book.BookId); } Connecting to the API We are ready to create the CRUD methods in the API and connect them to the methods in the repo. [HttpGet] public ActionResult<IEnumerable<Book>> Get() { var books = _bookRepository.GetBooks(); return new ActionResult<IEnumerable<Book>>(books); } This will return the retrieved data to the calling method. Note that this will retrieve all the books. Following along with using the HTTP syntax, let’s create the Post method: [HttpPost] public void Post([FromBody] Book book) { _bookRepository.Insert(book); } Testing To check that we can now add and retrieve data, we’ll create a Postman collection. Bring up the Postman Desktop App (the Chrome extension has been deprecated), and see or create a Bookstore collection. In that collection will be your post and get methods. To keep this simple let’s add a book using JSON. Click on Headers and set authorization to applicatoin/json. Then click on body and enter the Json statement: {"Title":"Ulyses"} Press send to send this to our local database. To ensure it got there, switch Postman to Get, Enter the url and press send. You should get back your book object. [ { "bookId": "d4f8fa63-1418-4e06-8c64-e8408c365b13", "isbn": null, "title": "Ulyses", "authors": null, "listPrice": 0 } ] The next step is to move this to Azure. That is easier than it sounds. First, go to the Azure site.Select the Start Free button. Create an account with your email address and after you confirm your email address you are ready to use the account form in Visual Studio. Our next step is to publish the API. Select the publish option and select the following steps: When you are creating the App Service to be used in the hosting plan, you can select the free tier. After publishing is complete, you will have access to your API in the endpoint you just created. In our example, the endpoint is You can test your new endpoint in Postman and then use it in your project. By Jesse Liberty (Massachusetts US) and Rodrigo Juarez (Mendoza, Argentina) About Jesse Liberty Jesse Liberty is the Principal Mobile Developer with IFS Core. He has three decades of experience writing and delivering software projects. He is the author of 2 dozen books and a couple dozen Pluralsight & LinkedIn Learning courses, and has been. Posted on by: Rodrigo Juarez Just a programmer using Microsoft tools to create awesome apps! Discussion
https://dev.to/codingcoach/advanced-xamarin-forms-part-1-the-api-3k6p
CC-MAIN-2020-40
refinedweb
859
66.13
On Mon, Jan 26, 2009 at 11:11:35AM +0900, Kenji Kaneshige wrote:...> Thanks to you, I found the root cause of the> problem. The acpi_pci_get_bridge_handle() function assumes> pci_bus->self is NULL on the root bus.Mea culpa: I contributed this mess too. This worked for PA-RISCand lacking better guidance, is what I used in 1/2 the places.> But it is not true> and pci_bus->self can have a non-NULL value on some> platfroms (like yours). So it must check pci_bus->parent> instead.It is true for PA-RISC and some other architectures.These architectures don't provide fake PCI devices(emulated PCI config space) for Host-PCI Bus controllers.> I found some other code that has the same wrong assumption.> I'll make a fix for them and send it soon.I would like to keep the code consistent. Attached is a patchfor drivers/parisc. Please include with my Signed-off-by: Grant Grundler <grundler@parisc-linux.org>Or if you prefer, I can repost as a separate patch.I've compiled the iosapic/lba changes and will test those shortly.I have no HW (by choice) to test the dino code change.thanks,grantdiff --git a/drivers/parisc/dino.c b/drivers/parisc/dino.cindex d539d9d..f79266c 100644--- a/drivers/parisc/dino.c+++ b/drivers/parisc/dino.c@@ -587,7 +587,7 @@ dino_fixup_bus(struct pci_bus *bus) bus->resource[i+1] = &res[i]; } - } else if(bus->self) {+ } else if (bus->parent) { int i; pci_read_bridge_bases(bus);diff --git a/drivers/parisc/iosapic.c b/drivers/parisc/iosapic.cindex 0797659..1cdfdea 100644--- a/drivers/parisc/iosapic.c+++ b/drivers/parisc/iosapic.c@@ -487,7 +487,7 @@ iosapic_xlate_pin(struct iosapic_info *isi, struct pci_dev *pcidev) } /* Check if pcidev behind a PPB */- if (NULL != pcidev->bus->self) {+ if (pcidev->bus->parent) { /* Convert pcidev INTR_PIN into something we ** can lookup in the IRT. */@@ -523,10 +523,9 @@ iosapic_xlate_pin(struct iosapic_info *isi, struct pci_dev *pcidev) #endif /* PCI_BRIDGE_FUNCS */ /*- ** Locate the host slot the PPB nearest the Host bus- ** adapter.- */- while (NULL != p->parent->self)+ * Locate the host slot of the PPB.+ */+ while (p->parent->parent) p = p->parent; intr_slot = PCI_SLOT(p->self->devfn);diff --git a/drivers/parisc/lba_pci.c b/drivers/parisc/lba_pci.cindex d8233de..59fbbf1 100644--- a/drivers/parisc/lba_pci.c+++ b/drivers/parisc/lba_pci.c@@ -644,7 +644,7 @@ lba_fixup_bus(struct pci_bus *bus) ** Properly Setup MMIO resources for this bus. ** pci_alloc_primary_bus() mangles this. */- if (bus->self) {+ if (bus->parent) { int i; /* PCI-PCI Bridge */ pci_read_bridge_bases(bus);@@ -802,7 +802,7 @@ lba_fixup_bus(struct pci_bus *bus) ** Can't fixup here anyway....garr... */ if (fbb_enable) {- if (bus->self) {+ if (bus->parent) { u8 control; /* enable on PPB */ (void) pci_read_config_byte(bus->self, PCI_BRIDGE_CONTROL, &control);
http://lkml.org/lkml/2009/1/26/20
CC-MAIN-2014-41
refinedweb
448
69.48
How would I make lines etc in console mode (I'm using Microsoft VC++) How would I make lines etc in console mode (I'm using Microsoft VC++) This should work for horizontal lines. Where \xCD is the hex value for = in the ascii table. You would need to watch for overflow though. #include <iostream.h> int main() { int line; for(line = 1; line <= 10; line++) cout << "\xCD"; return 0; } hey thanks! NP :) I've been working on that very thing myself. I've got a crude method of drawing lines as well, but it needs work in 32 bit compilers like VC 6. It causes the blue screen of death... likely cause is the regs or data type for the pointer, but I'm working on it. It *works* ok in 16 bit compilers though. #include <iostream.h> int main() { int line; char *xrow, *ycol; xrow = 0; ycol = 0; for(line = 1; line <=20; line++) { _asm { xor bh,bh mov dh,BYTE PTR xrow mov dl,BYTE PTR ycol mov ah,2 int 10h mov dl,'.' // or \xXX hex code for ascii mov ah,02 int 21h } xrow = xrow + 1; // adjust increment of row ycol = ycol + 1; // adjust increment of col } return 0; }
https://cboard.cprogramming.com/cplusplus-programming/3877-line-printable-thread.html
CC-MAIN-2017-51
refinedweb
204
87.76
# External Interrupts in the x86 system. Part 2. Linux kernel boot options In the [last part](https://habr.com/ru/post/446312/) we discussed evolution of the interrupt delivery process from the devices in the x86 system (PIC → APIC → MSI), general theory, and all the necessary terminology. In this practical part we will look at how to roll back to the use of obsolete methods of interrupt delivery in Linux, and in particular we will look at Linux kernel boot options: * pci=nomsi * noapic * nolapic Also we will look at the order in which the OS looks for interrupt routing tables (ACPI/MPtable/$PIR) and what the impact is from the following boot options: * pci=noacpi * acpi=noirq * acpi=off You've probably used some combination of these options when one of the devices in your system hasn't worked correctly because of an interrupt problem. We'll go through these options and find out what they do and how they change the kernel '/proc/interrupts' interface output. ### Boot without any extra options In this article for our interrupt investigation we will be using custom board with the Intel Haswell i7 CPU with the LynxPoint-LP chipset which runs [coreboot](https://www.coreboot.org/). We will be getting information about interrupts in the Linux system through the command: ``` cat /proc/interrupts ``` Here is the output when the kernel was booted without any external options: ``` CPU0 CPU1 CPU2 CPU3 0: 15 0 0 0 IO-APIC-edge timer 1: 0 1 0 1 IO-APIC-edge i8042 8: 0 0 0 1 IO-APIC-edge rtc0 9: 0 0 0 0 IO-APIC-fasteoi acpi 12: 0 0 0 1 IO-APIC-edge 23: 16 247 7 10 IO-APIC-fasteoi ehci_hcd:usb1 56: 0 0 0 0 PCI-MSI-edge aerdrv,PCIe PME 57: 0 0 0 0 PCI-MSI-edge aerdrv,PCIe PME 58: 0 0 0 0 PCI-MSI-edge aerdrv,PCIe PME 59: 0 0 0 0 PCI-MSI-edge aerdrv,PCIe PME 60: 0 0 0 0 PCI-MSI-edge aerdrv,PCIe PME 61: 0 0 0 0 PCI-MSI-edge aerdrv,PCIe PME 62: 3118 1984 972 3454 PCI-MSI-edge ahci 63: 1 0 0 0 PCI-MSI-edge eth59 64: 2095 57 4 832 PCI-MSI-edge eth59-rx-0 65: 6 18 1 1309 PCI-MSI-edge eth59-rx-1 66: 13 512 2 1 PCI-MSI-edge eth59-rx-2 67: 10 61 232 2 PCI-MSI-edge eth59-rx-3 68: 169 0 0 0 PCI-MSI-edge eth59-tx-0 69: 14 14 4 205 PCI-MSI-edge eth59-tx-1 70: 11 491 3 0 PCI-MSI-edge eth59-tx-2 71: 20 19 134 50 PCI-MSI-edge eth59-tx-3 72: 0 0 0 0 PCI-MSI-edge eth58 73: 2 1 0 152 PCI-MSI-edge eth58-rx-0 74: 3 150 2 0 PCI-MSI-edge eth58-rx-1 75: 2 34 117 2 PCI-MSI-edge eth58-rx-2 76: 153 0 2 0 PCI-MSI-edge eth58-rx-3 77: 4 0 2 149 PCI-MSI-edge eth58-tx-0 78: 4 149 2 0 PCI-MSI-edge eth58-tx-1 79: 4 0 117 34 PCI-MSI-edge eth58-tx-2 80: 153 0 2 0 PCI-MSI-edge eth58-tx-3 81: 66 106 2 101 PCI-MSI-edge snd_hda_intel 82: 928 5657 262 224 PCI-MSI-edge i915 83: 545 56 32 15 PCI-MSI-edge snd_hda_intel NMI: 0 0 0 0 Non-maskable interrupts LOC: 4193 3644 3326 3499 Local timer interrupts SPU: 0 0 0 0 Spurious interrupts PMI: 0 0 0 0 Performance monitoring interrupts IWI: 290 233 590 111 IRQ work interrupts RTR: 3 0 0 0 APIC ICR read retries RES: 1339 2163 2404 1946 Rescheduling interrupts CAL: 607 537 475 559 Function call interrupts TLB: 163 202 164 251 TLB shootdowns TRM: 48 48 48 48 Thermal event interrupts THR: 0 0 0 0 Threshold APIC interrupts MCE: 0 0 0 0 Machine check exceptions MCP: 3 3 3 3 Machine check polls ERR: 0 MIS: 0 ``` File '/proc/interrupts' is the procfs Linux interface to the interrupt subsystem, and it presents a table about the number of interrupts on every CPU core in the system in the following form: * First column: interrupt number * CPUx columns: interrupt counters for every CPU core in the system * Next column: interrupt type: + IO-APIC-edge — edge-triggered interrupt for the I/O APIC controller + IO-APIC-fasteoi — level-triggered interrupt for the I/O APIC controller + PCI-MSI-edge — MSI interrupt + XT-PIC-XT-PIC — interrupt for the PIC controller (we will see it later) * Last column: device (driver) associated with this interrupt Everything here is like it is supposed to be in the modern system. For the devices and drivers which support MSI/MSI-X, this is the type of interrupt that they use. The rest of the interrupt routing is done through the APIC controller. Simplistically, the interrupt routing schematics can be drawn like this: (red lines are active routing paths and black lines are unused routing paths) ![](https://habrastorage.org/r/w1560/webt/pb/ej/7c/pbej7cfkiyscux6fzyttfbi99my.png) A device that supports MSI/MSI-X interrupts should have that particular capability listed in its [PCI configuration space](https://en.wikipedia.org/wiki/PCI_configuration_space). As an example of that let's look at a little fragment of the lspci output for the devices that declare they use MSI/MSI-X. In our case it is a SATA controller (interrupt 'ahci'), two ethernet controllers (interrupts 'eth58\*' and 'eth59\*'), graphical controller ('i915'), and two HD Audio controllers ('snd\_hda\_intel'). ``` lspci -v ``` ``` 00:02.0 VGA compatible controller: Intel Corporation Haswell-ULT Integrated Graphics Controller (rev 09) (prog-if 00 [VGA controller]) ... Capabilities: [90] MSI: Enable+ Count=1/1 Maskable- 64bit- Capabilities: [d0] Power Management version 2 Capabilities: [a4] PCI Advanced Features Kernel driver in use: i915 00:03.0 Audio device: Intel Corporation Haswell-ULT HD Audio Controller (rev 09 ... Capabilities: [60] MSI: Enable+ Count=1/1 Maskable- 64bit- Capabilities: [70] Express Root Complex Integrated Endpoint, MSI 00 Kernel driver in use: snd_hda_intel 00:1b.0 Audio device: Intel Corporation 8 Series HD Audio Controller (rev 04) ... Capabilities: [60] MSI: Enable+ Count=1/1 Maskable- 64bit+ Capabilities: [70] Express Root Complex Integrated Endpoint, MSI 00 Capabilities: [100] Virtual Channel Kernel driver in use: snd_hda_intel 00:1f.2 SATA controller: Intel Corporation 8 Series SATA Controller 1 [AHCI mode] (rev 04) (prog-if 01 [AHCI 1.0]) ... Capabilities: [80] MSI: Enable+ Count=1/1 Maskable- 64bit- Capabilities: [70] Power Management version 3 Capabilities: [a8] SATA HBA v1.0 Kernel driver in use: ahci 05:00.0 Ethernet controller: Intel Corporation I350 Gigabit Network Connection (rev 01) ... Capabilities: [50] MSI: Enable- Count=1/1 Maskable+ 64bit+ Capabilities: [70] MSI-X: Enable+ Count=10 Masked- Capabilities: [a0] Express Endpoint, MSI 00 Kernel driver in use: igb 05:00.1 Ethernet controller: Intel Corporation I350 Gigabit Network Connection (rev 01) ... Capabilities: [50] MSI: Enable- Count=1/1 Maskable+ 64bit+ Capabilities: [70] MSI-X: Enable+ Count=10 Masked- Capabilities: [a0] Express Endpoint, MSI 00 Kernel driver in use: igb ``` As we see, all of these devices either have a string «MSI: Enable+» or «MSI-X: Enable+». Let's downgrade our system! For a start let's boot with the kernel option 'pci=nomsi'. ### pci=nomsi Because of this option MSI interrupts become IO-APIC/XT-PIC depending on the interrupt controller in use. In this case the priority choice is still modern APIC controller, so the interrupt picture will be: ![](https://habrastorage.org/r/w1560/webt/er/ft/jy/erftjybrd7rm61bmmmhcs3qfzni.png) Output of /proc/interrupts: ``` CPU0 CPU1 CPU2 CPU3 0: 15 0 0 0 IO-APIC-edge timer 1: 0 1 0 1 IO-APIC-edge i8042 8: 0 0 1 0 IO-APIC-edge rtc0 9: 0 0 0 0 IO-APIC-fasteoi acpi 12: 0 0 0 1 IO-APIC-edge 16: 1314 5625 342 555 IO-APIC-fasteoi i915, snd_hda_intel, eth59 17: 5 0 1 34 IO-APIC-fasteoi eth58 21: 2882 2558 963 2088 IO-APIC-fasteoi ahci 22: 26 81 2 170 IO-APIC-fasteoi snd_hda_intel 23: 23 369 8 8 IO-APIC-fasteoi ehci_hcd:usb1 NMI: 0 0 0 0 Non-maskable interrupts LOC: 3011 3331 2435 2617 Local timer interrupts SPU: 0 0 0 0 Spurious interrupts PMI: 0 0 0 0 Performance monitoring interrupts IWI: 197 228 544 85 IRQ work interrupts RTR: 3 0 0 0 APIC ICR read retries RES: 1708 2349 1821 1569 Rescheduling interrupts CAL: 520 554 509 555 Function call interrupts TLB: 187 181 205 179 TLB shootdowns TRM: 102 102 102 102 Thermal event interrupts THR: 0 0 0 0 Threshold APIC interrupts MCE: 0 0 0 0 Machine check exceptions MCP: 2 2 2 2 Machine check polls ERR: 0 MIS: 0 ``` As expected, all MSI/MSI-X interrupts have disappeared. Instead of them devices now use interrupts of 'IO-APIC-fasteoi' type. Let us draw our attention to the fact that earlier, before enabling this kernel boot option, each of the 'eth58' and 'eth59' had nine interrupts! But now each of them has only one interrupt. Recall that without the MSI, one function in the PCI device can have only one interrupt! Here is a little info from the 'dmesg' command about the ethernet controllers' initialization: — boot without the 'pci=nomsi' option: ``` igb: Intel(R) Gigabit Ethernet Network Driver - version 5.0.5-k igb: Copyright (c) 2007-2013 Intel Corporation. acpi:acpi_pci_irq_enable: igb 0000:05:00.0: PCI INT A -> GSI 16 (level, low) -> IRQ 16 igb 0000:05:00.0: irq 63 for MSI/MSI-X igb 0000:05:00.0: irq 64 for MSI/MSI-X igb 0000:05:00.0: irq 65 for MSI/MSI-X igb 0000:05:00.0: irq 66 for MSI/MSI-X igb 0000:05:00.0: irq 67 for MSI/MSI-X igb 0000:05:00.0: irq 68 for MSI/MSI-X igb 0000:05:00.0: irq 69 for MSI/MSI-X igb 0000:05:00.0: irq 70 for MSI/MSI-X igb 0000:05:00.0: irq 71 for MSI/MSI-X igb 0000:05:00.0: irq 63 for MSI/MSI-X igb 0000:05:00.0: irq 64 for MSI/MSI-X igb 0000:05:00.0: irq 65 for MSI/MSI-X igb 0000:05:00.0: irq 66 for MSI/MSI-X igb 0000:05:00.0: irq 67 for MSI/MSI-X igb 0000:05:00.0: irq 68 for MSI/MSI-X igb 0000:05:00.0: irq 69 for MSI/MSI-X igb 0000:05:00.0: irq 70 for MSI/MSI-X igb 0000:05:00.0: irq 71 for MSI/MSI-X igb 0000:05:00.0: added PHC on eth0 igb 0000:05:00.0: Intel(R) Gigabit Ethernet Network Connection igb 0000:05:00.0: eth0: (PCIe:5.0Gb/s:Width x1) 00:15:d5:03:00:2a igb 0000:05:00.0: eth0: PBA No: 106300-000 igb 0000:05:00.0: Using MSI-X interrupts. 4 rx queue(s), 4 tx queue(s) acpi:acpi_pci_irq_enable: igb 0000:05:00.1: PCI INT B -> GSI 17 (level, low) -> IRQ 17 igb 0000:05:00.1: irq 72 for MSI/MSI-X igb 0000:05:00.1: irq 73 for MSI/MSI-X igb 0000:05:00.1: irq 74 for MSI/MSI-X igb 0000:05:00.1: irq 75 for MSI/MSI-X igb 0000:05:00.1: irq 76 for MSI/MSI-X igb 0000:05:00.1: irq 77 for MSI/MSI-X igb 0000:05:00.1: irq 78 for MSI/MSI-X igb 0000:05:00.1: irq 79 for MSI/MSI-X igb 0000:05:00.1: irq 80 for MSI/MSI-X igb 0000:05:00.1: irq 72 for MSI/MSI-X igb 0000:05:00.1: irq 73 for MSI/MSI-X igb 0000:05:00.1: irq 74 for MSI/MSI-X igb 0000:05:00.1: irq 75 for MSI/MSI-X igb 0000:05:00.1: irq 76 for MSI/MSI-X igb 0000:05:00.1: irq 77 for MSI/MSI-X igb 0000:05:00.1: irq 78 for MSI/MSI-X igb 0000:05:00.1: irq 79 for MSI/MSI-X igb 0000:05:00.1: irq 80 for MSI/MSI-X igb 0000:05:00.1: added PHC on eth1 igb 0000:05:00.1: Intel(R) Gigabit Ethernet Network Connection igb 0000:05:00.1: eth1: (PCIe:5.0Gb/s:Width x1) 00:15:d5:03:00:2b igb 0000:05:00.1: eth1: PBA No: 106300-000 igb 0000:05:00.1: Using MSI-X interrupts. 4 rx queue(s), 4 tx queue(s) ``` — boot with the 'pci=nomsi' option: ``` igb: Intel(R) Gigabit Ethernet Network Driver - version 5.0.5-k igb: Copyright (c) 2007-2013 Intel Corporation. acpi:acpi_pci_irq_enable: igb 0000:05:00.0: PCI INT A -> GSI 16 (level, low) -> IRQ 16 igb 0000:05:00.0: added PHC on eth0 igb 0000:05:00.0: Intel(R) Gigabit Ethernet Network Connection igb 0000:05:00.0: eth0: (PCIe:5.0Gb/s:Width x1) 00:15:d5:03:00:2a igb 0000:05:00.0: eth0: PBA No: 106300-000 igb 0000:05:00.0: Using legacy interrupts. 1 rx queue(s), 1 tx queue(s) acpi:acpi_pci_irq_enable: igb 0000:05:00.1: PCI INT B -> GSI 17 (level, low) -> IRQ 17 igb 0000:05:00.1: added PHC on eth1 igb 0000:05:00.1: Intel(R) Gigabit Ethernet Network Connection igb 0000:05:00.1: eth1: (PCIe:5.0Gb/s:Width x1) 00:15:d5:03:00:2b igb 0000:05:00.1: eth1: PBA No: 106300-000 igb 0000:05:00.1: Using legacy interrupts. 1 rx queue(s), 1 tx queue(s) ``` Because of the decreased number of interrupts per device, enabling this option can lead to a significant performance limitation of the device driver, and that is not even counting that according to the Intel research ['Reducing Interrupt Latency Through the Use of Message Signaled Interrupts'](https://www.intel.com/content/dam/www/public/us/en/documents/white-papers/msg-signaled-interrupts-paper.pdf), MSI interrupts 3 times faster than the IO-APIC interrupts and 5 times faster than the PIC interrupts. ### noapic This option disables I/O APIC. MSI interrupts can still find their way to all of the CPUs, but the rest of interrupts from the devices can go only to CPU0, because PIC is only connected to CPU0. However, LAPIC is working and all other CPUs can still work and handle interrupts. ![](https://habrastorage.org/r/w1560/webt/uw/tf/rt/uwtfrt5lgbpfenyjwb3u_fc4yvq.png) ``` CPU0 CPU1 CPU2 CPU3 0: 5 0 0 0 XT-PIC-XT-PIC timer 1: 2 0 0 0 XT-PIC-XT-PIC i8042 2: 0 0 0 0 XT-PIC-XT-PIC cascade 8: 1 0 0 0 XT-PIC-XT-PIC rtc0 9: 0 0 0 0 XT-PIC-XT-PIC acpi 12: 172 0 0 0 XT-PIC-XT-PIC ehci_hcd:usb1 56: 0 0 0 0 PCI-MSI-edge aerdrv, PCIe PME 57: 0 0 0 0 PCI-MSI-edge aerdrv, PCIe PME 58: 0 0 0 0 PCI-MSI-edge aerdrv, PCIe PME 59: 0 0 0 0 PCI-MSI-edge aerdrv, PCIe PME 60: 0 0 0 0 PCI-MSI-edge aerdrv, PCIe PME 61: 0 0 0 0 PCI-MSI-edge aerdrv, PCIe PME 62: 2833 2989 1021 811 PCI-MSI-edge ahci 63: 0 1 0 0 PCI-MSI-edge eth59 64: 301 52 9 3 PCI-MSI-edge eth59-rx-0 65: 12 24 3 178 PCI-MSI-edge eth59-rx-1 66: 14 85 6 2 PCI-MSI-edge eth59-rx-2 67: 17 24 307 1 PCI-MSI-edge eth59-rx-3 68: 70 18 8 10 PCI-MSI-edge eth59-tx-0 69: 7 0 0 23 PCI-MSI-edge eth59-tx-1 70: 15 227 2 2 PCI-MSI-edge eth59-tx-2 71: 18 6 27 2 PCI-MSI-edge eth59-tx-3 72: 0 0 0 0 PCI-MSI-edge eth58 73: 1 0 0 27 PCI-MSI-edge eth58-rx-0 74: 1 22 0 5 PCI-MSI-edge eth58-rx-1 75: 1 0 22 5 PCI-MSI-edge eth58-rx-2 76: 23 0 0 5 PCI-MSI-edge eth58-rx-3 77: 1 0 0 27 PCI-MSI-edge eth58-tx-0 78: 1 22 0 5 PCI-MSI-edge eth58-tx-1 79: 1 0 22 5 PCI-MSI-edge eth58-tx-2 80: 23 0 0 5 PCI-MSI-edge eth58-tx-3 81: 187 17 70 7 PCI-MSI-edge snd_hda_intel 82: 698 1647 247 129 PCI-MSI-edge i915 83: 438 135 16 59 PCI-MSI-edge snd_hda_intel NMI: 0 0 0 0 Non-maskable interrupts LOC: 1975 2499 2245 1474 Local timer interrupts SPU: 0 0 0 0 Spurious interrupts PMI: 0 0 0 0 Performance monitoring interrupts IWI: 132 67 429 91 IRQ work interrupts RTR: 3 0 0 0 APIC ICR read retries RES: 1697 2178 1903 1541 Rescheduling interrupts CAL: 561 496 534 567 Function call interrupts TLB: 229 254 170 137 TLB shootdowns TRM: 78 78 78 78 Thermal event interrupts THR: 0 0 0 0 Threshold APIC interrupts MCE: 0 0 0 0 Machine check exceptions MCP: 2 2 2 2 Machine check polls ERR: 0 MIS: 0 ``` As we see, all IO-APIC-\* interrupts have turned into XT-PIC-XT-PIC, and all of these interrupts have been routed to CPU0 only. MSI interrupts on the other hand have remained unchanged and go to all of the CPUs. ### nolapic This kernel boot option disables LAPIC. MSI interrupts can't work without LAPIC, and I/O APIC can't work without LAPIC either. All of the device interrupts can only go to the PIC, and it works with the CPU0 only. And without LAPIC the rest of the CPUs besides CPU0 won't work. ![](https://habrastorage.org/r/w1560/webt/rm/jd/4t/rmjd4tr9wxvkghj5hzb5wu7fswi.png) Output of /proc/interrupts: ``` CPU0 0: 6416 XT-PIC-XT-PIC timer 1: 2 XT-PIC-XT-PIC i8042 2: 0 XT-PIC-XT-PIC cascade 3: 5067 XT-PIC-XT-PIC aerdrv, aerdrv, PCIe PME, PCIe PME, i915, snd_hda_intel, eth59 4: 32 XT-PIC-XT-PIC aerdrv, aerdrv, PCIe PME, PCIe PME, eth58 5: 0 XT-PIC-XT-PIC aerdrv, PCIe PME 6: 0 XT-PIC-XT-PIC aerdrv, PCIe PME 8: 1 XT-PIC-XT-PIC rtc0 9: 0 XT-PIC-XT-PIC acpi 11: 274 XT-PIC-XT-PIC snd_hda_intel 12: 202 XT-PIC-XT-PIC ehci_hcd:usb1 15: 7903 XT-PIC-XT-PIC ahci NMI: 0 Non-maskable interrupts LOC: 0 Local timer interrupts SPU: 0 Spurious interrupts PMI: 0 Performance monitoring interrupts IWI: 0 IRQ work interrupts RTR: 0 APIC ICR read retries RES: 0 Rescheduling interrupts CAL: 0 Function call interrupts TLB: 0 TLB shootdowns TRM: 0 Thermal event interrupts THR: 0 Threshold APIC interrupts MCE: 0 Machine check exceptions MCP: 1 Machine check polls ERR: 0 MIS: 0 ``` ### Combinations of options: Actually there is only one combination for the new variant of routing: «noapic pci=nomsi». In this case all interrupts from the devices only go to the CPU0 through the PIC controller. But the LAPIC system is still working, so all the other CPUs can work and handle interrupts. You cannot combine any other options with «nolapic» since it makes I/O APIC and MSI unaccessible. Therefore, if you've ever added Linux kernel boot options like «noapic nolapic» (or the most common case «acpi=off noapic nolapic») it seems like you've written some extra letters. Finally, here is the result of the options «noapic pci=nomsi» to our interrupt routing picture: ![](https://habrastorage.org/r/w1560/webt/jx/bu/is/jxbuissu4c453b_5g-4pcs6_d-w.png) And the output of /proc/interrupts is: ``` CPU0 CPU1 CPU2 CPU3 0: 5 0 0 0 XT-PIC-XT-PIC timer 1: 2 0 0 0 XT-PIC-XT-PIC i8042 2: 0 0 0 0 XT-PIC-XT-PIC cascade 3: 5072 0 0 0 XT-PIC-XT-PIC i915, snd_hda_intel, eth59 4: 32 0 0 0 XT-PIC-XT-PIC eth58 8: 1 0 0 0 XT-PIC-XT-PIC rtc0 9: 0 0 0 0 XT-PIC-XT-PIC acpi 11: 281 0 0 0 XT-PIC-XT-PIC snd_hda_intel 12: 200 0 0 0 XT-PIC-XT-PIC ehci_hcd:usb1 15: 7930 0 0 0 XT-PIC-XT-PIC ahci NMI: 0 0 0 0 Non-maskable interrupts LOC: 2595 2387 2129 1697 Local timer interrupts SPU: 0 0 0 0 Spurious interrupts PMI: 0 0 0 0 Performance monitoring interrupts IWI: 159 90 482 135 IRQ work interrupts RTR: 3 0 0 0 APIC ICR read retries RES: 1568 1666 1810 1833 Rescheduling interrupts CAL: 431 556 549 558 Function call interrupts TLB: 124 184 156 274 TLB shootdowns TRM: 116 116 116 116 Thermal event interrupts THR: 0 0 0 0 Threshold APIC interrupts MCE: 0 0 0 0 Machine check exceptions MCP: 2 2 2 2 Machine check polls ERR: 0 MIS: 0 ``` ### Interrupt routing tables and the options «acpi=noirq», «pci=noacpi», «acpi=off» How does the operating system get information about the device interrupt routing? The BIOS prepares such info for the OS in the form of: * ACPI tables (\_PIC/\_PRT functions) * \_MP\_ table (MPtable) * $PIR table * Registers 0x3C/0x3D of the device's PCI configuration space It is worth to note for the MSI interrupts declaration that the BIOS doesn't need to do anything extra (beside declaring the use of the LAPIC): all the aforementioned routing information is needed only for the APIC/PIC interrupt lines. Tables in the list above are presented in the order of priority. Let's examine it in detail. Let's assume the BIOS has presented all this data and we boot our OS without any extra boot options: * OS finds ACPI tables. * ОS executes ACPI function "\_PIC", passing it the argument stating that the boot should happen in APIC mode. Here there is function code that usually saves the chosen mode in a variable (for example, PICM=1). * To access interrupt routing info the OS calls ACPI function "\_PRT". This checks the PICM variable and returns routing for the APIC mode case. In the case when we boot with the option **noapic**: * OS finds ACPI tables * ОS executes ACPI function "\_PIC", passing it the argument stating that the boot should happen in PIC mode. Here there is function code that usually saves the chosen mode in a variable (for example, PICM=0) * To access interrupt routing info the OS calls ACPI function "\_PRT". This checks the PICM variable and returns routing for the PIC mode case. If ACPI tables aren't present or interrupt routing with ACPI is disabled through the option **acpi=noirq** or **pci=noacpi** (or ACPI subsystem is completely disabled with the **acpi=off** option), then the OS looks for the MPtable (\_MP\_) to get all the interrupt routing information: * OS can't find/doesn't look at the ACPI tables * OS finds MPtable (\_MP\_) If ACPI tables aren't present or interrupt routing with ACPI is disabled through the option **acpi=noirq** or **pci=noacpi** (or ACPI subsystem is completely disabled with the **acpi=off** option), and if the MPtable (\_MP\_) is not present either (or there is a boot option **noapic** or **nolapic**): * OS can't find/doesn't look at the ACPI tables * OS can't find/doesn't look at the MPtable (\_MP\_) * OS finds $PIR table If there is no $PIR table or it is not full, then the OS will look at the registers 0x3C/0x3D of the device's PCI configuration space to guess interrupt routing. Here is a picture summarizing all of this: ![](https://habrastorage.org/r/w1560/webt/rj/9s/mk/rj9smkhk7c_ou_fzskxasgeriw8.png) One should remember that not every BIOS provides all of these three tables (ACPI/MPtable/$PIR), so if you've passed an option to your bootloader (e.g. GRUB) that disables the use of ACPI or ACPI and MPtable for the interrupt routing, it is possible that your system won't boot. **Note 1**: In the case when we try to boot in APIC mode with the option 'acpi=noirq' and without MPtable present, the picture of interrupts will be like in the case of normal booting with only the 'noapic' option. The operating system will go to PIC mode by itself. In the case when you try to boot without any ACPI tables at all ('acpi=off') and without MPtable present, then the picture will be like this: ``` CPU0 0: 6 XT-PIC-XT-PIC timer 1: 2 XT-PIC-XT-PIC i8042 2: 0 XT-PIC-XT-PIC cascade 8: 0 XT-PIC-XT-PIC rtc0 12: 373 XT-PIC-XT-PIC ehci_hcd:usb1 16: 0 PCI-MSI-edge PCIe PME 17: 0 PCI-MSI-edge PCIe PME 18: 0 PCI-MSI-edge PCIe PME 19: 0 PCI-MSI-edge PCIe PME 20: 0 PCI-MSI-edge PCIe PME 21: 0 PCI-MSI-edge PCIe PME 22: 8728 PCI-MSI-edge ahci 23: 1 PCI-MSI-edge eth59 24: 1301 PCI-MSI-edge eth59-rx-0 25: 113 PCI-MSI-edge eth59-tx-0 26: 0 PCI-MSI-edge eth58 27: 45 PCI-MSI-edge eth58-rx-0 28: 45 PCI-MSI-edge eth58-tx-0 29: 1280 PCI-MSI-edge snd_hda_intel NMI: 2 Non-maskable interrupts LOC: 24076 Local timer interrupts SPU: 0 Spurious interrupts PMI: 2 Performance monitoring interrupts IWI: 2856 IRQ work interrupts RTR: 0 APIC ICR read retries RES: 0 Rescheduling interrupts CAL: 0 Function call interrupts TLB: 0 TLB shootdowns TRM: 34 Thermal event interrupts THR: 0 Threshold APIC interrupts MCE: 0 Machine check exceptions MCP: 2 Machine check polls ERR: 0 MIS: 0 ``` This happens because without the ACPI MADT table ([Multiple APIC Description Table](https://wiki.osdev.org/MADT)) and the necessary info from the MPtable, the operating system doesn't know APIC identifiers (APIC IDs) for the other CPUs and can't work with them. But the LAPIC of the main CPU0 works because we haven't disabled it, and MSI interrupts can still go to it. So the interrupt picture would be: ![](https://habrastorage.org/r/w1560/webt/b-/pz/hx/b-pzhxxyugr5iv203wysxfs7-mo.png) **Note 2**: In general, interrupt routing with the use of ACPI in an APIC case should match the interrupt routing with the MPtable. Also, the interrupt routing with the use of ACPI in a PIC case should match the interrupt routing with the $PIR table. Therefore the '/proc/interrupts' output should not differ. But in my investigation I've noticed one strange fact. For some reason in the case of interrupt routing through the MPtable there is a cascade interrupt «XT-PIC-XT-PIC cascade» in the output: ``` CPU0 CPU1 CPU2 CPU3 0: 15 0 0 0 IO-APIC-edge timer 1: 2 0 0 0 IO-APIC-edge i8042 2: 0 0 0 0 XT-PIC-XT-PIC cascade 8: 0 1 0 0 IO-APIC-edge rtc0 9: 0 0 0 0 IO-APIC-edge acpi ... ``` It is a little bit strange that it happens like that, but it seems like [the kernel source documentation](https://elixir.bootlin.com/linux/latest/source/Documentation/x86/i386/IO-APIC.txt) says that it is OK. ### Сonclusion In conclusion we review for one more time the discussed options. Interrupt controller choice options: * **pci=nomsi** — MSI interrupts become IO-APIC/XT-PIC depending on the interrupt controller in use. * **noapic** — Disables I/O APIC. MSI interrupts can still go to all the other CPUs, the rest of the device interrupts can only go to the PIC, and it works with the CPU0 only. But LAPIC still works and other CPUs can work and handle interrupts. * **noapic pci=nomsi** — All of the device interrupts can only go to the PIC, and it works with the CPU0 only. But LAPIC works and other CPUs can work and handle interrupts. * **nolapic** — Disables LAPIC. MSI interrupts can't work without LAPIC, and I/O APIC can't work without LAPIC. All of the device interrupts can only go to the PIC, and it works with the CPU0 only. And without LAPIC the rest of the CPUs besides CPU0 won't work. Interrupt tables priority options: * **no options** — routing through the APIC with the help of ACPI tables * **noapic** — routing through the PIC with the help of ACPI tables * **acpi=noirq** (**pci=noacpi**/**acpi=off**) — routing through the APIC with the help of MPtable * **acpi=noirq** (**pci=noacpi**/**acpi=off**) **noapic** (**nolapic**) — routing through the PIC with the help of $PIR In the next part we will look at how coreboot configures the chipset for the interrupt routing. #### Acknowledgments Special thanks to Jacob Garber from the coreboot community for helping me with this article translation
https://habr.com/ru/post/501660/
null
null
4,904
64.64
Sandbox:TechDraw template creation tutorial Introduction This tutorial shows you how to create an SVG file that can be used as the background template for the TechDraw Workbench pages. This is intended to be a parallel version for wandererfan's template tutorial because I personally found the guide to be a bit too hard to follow from a beginner standpoint. Here so my aim is to make a version intended for beginners that includes more information and guidance. This tutorial assumes you have relatively little experience with Inkscape and SVG, as well as FreeCAD and the TechDraw Workbench. In this tutorial we're going to make a simple template for US Letter or ISO 216 A4 size paper in landscape orientation. The process is the same for any paper size and once you've finished your first template, it's relatively easy to create templates for other page sizes and orientations. A copy of the result of this tutorial is not available in $INSTALL_DIR/Mod/TechDraw/Templates/HowToExample.svg Where $INSTALL_DIR is the directory where FreeCAD was installed, for example /usr/share/freecad/Mod/TechDraw/Templates/HowToExample.svg Create the base document 1. Open a new document in Inkscape. All of the following steps will be carried out within Inkscape. During this tutorial, FreeCAD and TechDraw are only useful for inspecting the state of your template by opening the TechDraw workbench, clicking TechDraw PageTemplate and selecting the template you are working on. 2. Use the built-in XML Editor Edit → XML Editor... or Shift+Ctrl+X) to add a "freecad" namespace clause to the <svg> item. - Select the topmost <svg> item and press the + located on the top left of the contents window to create a new entry - In the Name field of the new item, paste xmlns:freecad - In the Attribute field, paste " Press Enter to confirm the edit to the namespace; if you just click away, the edit will revert. Note that your editable texts will not work if you use " even though the wiki is reached via these days. Since SVG is a human readable format you could also enter the line above into the file with a text editor. Inkscape: XML Editor adding the "freecad" namespace clause to the <svg> item 3. Set up some references The finished template is likely to turn out irregular and messy if made without any references for the placement of lines, text and other items. - Open File → Document Properties → Grids and click New to create a new grid. - A set of grid properties will shown, adjust these to your liking. For example, to get a 1 by 1 mm grid, set Grid units: to mm and both Spacing X: and Spacing Y: to 1.0 - Also, you can set the interval of major grid lines for easier readability by changing the Major grid line every: parameter. 4. Set page size In Document Properties (File → Document Properties or Shift+Ctrl+D) - Select page size "US Letter" or "A4" and orientation "landscape". - Set default units to "mm". For US Letter, set the page size to width "279.4" and height "215.9". For A4 you would use "210" and "297". Inkscape: document with page size and orientation Create the template drawing 5. Draw the template geometry The draft needs some base geometry to frame all the written information you wish to convey. If your draft needs to follow a standard, consult the standard on what exactly you need to draw. Otherwise, it is up to you what you decide to add to your template. If you don't know where to start, consider the following list of elements that are almost universally found on technical drawings: - Page frame lines - a rectangular frame offset from the page edges by a certain distance - Information box - a well-organized set of boxes for containing written information related to the drawing, usually located in the bottom-right corner Different fields of design and engineering have different requirements for the information required to be shown in the drawing. For example, a drawing of an individual part (metal, plastic, wood) needs to be accompanied by the material that it's made of. 7. Add and position text Not everything about an object can be efficiently conveyed with views and dimensions, so usually it is necessary to add some kind of written information to the drawing. Before adding any text, you should decide which font you want/need to use throughout your draft. If you need to follow a standard, it likely includes one or multiple accepted fonts. Otherwise, you are free to choose any font you like, though it should be kept in mind that some are easier to read than others and thus your choice of font directly affects the quality of your draft and its ability to convey information. Try osifont if you want to have a font that's both available for free, available in multiple languages and also compliant with ISO 3098 specification. Here is some information that is almost universally written on drafts: - Part/assembly/drawing designation - Name of depicted object/assembly or general drawing title - Names of people directly involved in the design and engineering of the object - Name of organization where the drawing is produced - Intended paper size and main drawing view scale (a good idea for electronically stored drawings) 8. The finished template should look something like this: Inkscape: tentative template layout Create editable fields 9. Add tags to each text element - Use the XML Editor to add a freecad:editabletag to each editable <text>item. The process is similar to adding the freecad namespace clause as described in section 2. Select the <svg:text> item that you want to make editable and add a new attribute. For 'name,' write freecad:editable and for 'value,' assign a meaningful name. Caution: if two or more text items share the same name, they will also display the same (Ctrl+c). 17. Then delete the current layer, Layer → Delete Current Layer. - Note: if you deleted the layer already (in your layer panel is no layer listed) this step is not required. In that case you should select all (Ctrl+a), cut the selection (Ctrl+x) and paste it with the command in the next step. 18. Then paste, Edit → Paste in Place. - Note: This command prevents that the text positions are stored in transform tags. It's important that you do not use the normal paste command! 19. Your template should now look right and shouldn't have any unwanted transforms. 20. Save your template. 21. Try it in FreeCAD and TechDraw Workbench with TechDraw PageTemplate.. If you do not see the green boxes for your editable texts, there might be something wrong with your document scale. Open your file in Inkscape again and confirm the values of the viewBox and the sizes are matching. -, -
https://wiki.freecadweb.org/Sandbox:TechDraw_template_creation_tutorial/en
CC-MAIN-2022-21
refinedweb
1,142
60.35
Module::Require use Module::Require qw: require_regex require_glob :; require_regex q[DBD::.*]; require_regex qw[DBD::.* Foo::Bar_.*]; require_glob qw[DBD::* Foo::Bar_*]; walk_inc sub { m{(/|^)Bar_.*$} and return $_ }, undef, q"DBD";. This function will walk through @INC and pass each filename under "path::" to &filter. If &filter returns a defined value, the returned value is then passed to the &todo function. and directories otherwise. This allows for an easy way to keep walk_inc from descending directories. The filter function may also be used to transform module names. If the module is already in %INC it will be passed over. This function takes a list of files and searches @INC trying to find all possible modules. Only the last part of the module name should be the regex expression ( Foo::Bar_.* is allowed, but F.*::Bar is not). Each file found and successfully loaded is added to %INC. Any file already in %INC is not loaded. No import functions are called. The function will return a list of files found but not loaded or, in a scalar context, the number of such files. This is the opposite of the sense of require, with true meaning at least one file failed to load. This function behaves the same as the require_regex function except it uses the glob operator (<>) instead of regular expressions. perldoc -f require. James G. Smith <jsmith@cpan.org> This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
http://search.cpan.org/~jsmith/Module-Require-0.05/lib/Module/Require.pm
CC-MAIN-2016-50
refinedweb
249
77.03
Net someone jobs Hello, I need someone who is expertise in, .net developer needed the rotation up (farm bids automated) - self restart Questions) 03. C# Language (15 Questions) ...have a desktop application build in .NET using SQL server as database. It is basically a restaurant billing software so we would like to develop an order taking process through tablets. Idea is app would be hybird connected with local database (sql server) through a network router and waiter could take order. If someone has made somthing similar then that Lütfen detayları görmek için Kaydolun ya da Giriş Yapın.. ...fintech which offers to its clients the best investment profitabilities of the market, comparing our plans with the most known fixed and variable incomes. We are looking for someone, or a team, who can develop for us our new Landing Page, the design of this website is already done, and we have a team who will manage and will give maintenance to this application need someone to give my ikm assessment .net 4.5 framework using c# on my system using team viewer. need to score 70-80 percentage. 51 questions in around 65 mins. .. he/she's doing. Code requirements: * Java 8; * spring-boot only We need someone DEDICATED, who will work until this is completed, we promise to be generous and ensure you're paid more than what you deserve, we don't expect these problems to take more than 2-4 days. Need to finish neural net puzzle solver which includes browser scrapping and AI. Most parts are done just needs to debug and assemble. This neural Hi, I am looking for someone from India who have prior experience in preparing Bank Loan Proposal document with Required loan estimation, Future Estimates for 7 years in term Sales, Net Profit Cross user messaging (chat) File upload, Gallery c# console application. The code needs to be cleaned up a bit, i.e. make it more re-useable across different methods. reduce redundancy. Need someone to work with me on this remotely. Should be a relatively quick job. .. I see it. I would like someone who cares about their work Hello, I want to someone to build .net HTTP automation software that can automate irctc website and payment .to book irctc ticket faster than ever. We have a .net backend that was done by a dev and needed an api added so we had another dev do it but he doesn't seem to be able to get it setup on our server properly so we need someone who can do it. Should be a quick job for someone who knows .net We need someone to convert the following application from Ruby to C# More details on the application will be provided in message: All the fields / overall application need to be converted as per requirement. We also want it to work with SQL Server / .NET This should not be an issue or an extensive project someone who already knows Ruby and C# ...familiar with this so would like advice and am willing to pay someone to make it work fast - like yesterday... Items: Unit 1: Pi Zero W E-Ink 4.2" Raw Display - 3 Color with driver board Unit 2: Raspberry pi 3b GSM SIM868 hat Functions: Unit 2 needs to fetch data from the net to display on Unit 1. This needs to be refreshed periodically I need someone who is familiar with web-scrapping! I need someone with experience! You will have to build the scrappers using WinForm C# (.net framework). If you did not work with WebClient and WebBrowser, please don't bid. Thanks. .. which is part of an ongoing R&D project Hi I would like to put a short video together for a future charity event. I have all the material. I need someone efficient and easy going to work with. I need the video to be net and nicely done to look professionally. This is an urgent deadline Hi, I cannot call the namespace, and any code from added Web Reference to my project in VS2008 for smart devices (windows mobile 5.0). I have the...always have the same error: "The type or namespace name 'WS' does not exist in the namespace 'xxx' (are you missing an assembly reference?)" I am looking someone, who works with Dynamics NAV and .NET. We have 2 high end beauty salons and we have some staf...any longer but we would like to contact the clientele who are no longer are coming back to us as a result of their departure. We need someone with great communication skills and who is very experienced handling high net worth clients and get them to come back to our salon with our amazing offer.).
https://www.tr.freelancer.com/job-search/net-someone/
CC-MAIN-2018-39
refinedweb
793
72.36
In this shot, we will learn how to extract a float number’s fractional part. %) operator The % operator is an arithmetic operator that calculates and returns the remainder after the division of two numbers. If a number is divided by 1, the remainder will be the fractional part. So, using the modulo operator will give the fractional part of a float. decNum = 3.14159265359 frac = decNum % 1 print(frac) round() round(float[, decimals]) The in-built function round() takes two parameters: float: The float number that needs to be rounded decimals: This is an optional argument that specifies the decimal place to which the function should round the float. If this argument is unspecified, the float will be rounded to the nearest integer. The function will round off the float to the nearest integer value when the second argument is not given, which is equivalent to using int(). After rounding the float, we can take the difference between the original float and the rounded-off number to find the fractional part. decNum = 3.14159265359 frac = decNum - round(decNum) print(frac) math.modf() To access the function math.modf(), we must first import the math module. math.modf(float) This function takes one parameter: It returns the integer and fractional parts of float as a tuple, in that order. If some data type other than float or int is passed, the function returns a TypeError. import math decNum = 3.14159265359 frac, intNum = math.modf(decNum) print(frac) print("TypeError raised: ") math.modf("5") RELATED TAGS CONTRIBUTOR View all Courses
https://www.educative.io/answers/how-to-extract-the-fractional-part-of-a-float-number-in-python
CC-MAIN-2022-33
refinedweb
258
57.27
The array as a whole can be referenced by the array name without the brackets, for example, as a parameter to or return value from a function public class Arrays2 { public static void main(String[] args) { String[] names = new String[3]; names[0] = "Joe"; names[1] = "Jane"; names[2] = "Herkimer"; printArray(names); } public static void printArray(String[] data) { for (int i = 0; i < data.length; i++) { System.out.println(data[i].toUpperCase()); } } } The array names is passed to printArray, where it is received as data. Note also the syntax to access a method directly for an array element: data[i].toUpperCase() Since an array reference is a variable, it can be made to refer to a different array at some point in time String[] names = new String[3]; names[0] = "Joe"; names[1] = "Jane"; names[2] = "Herkimer"; printArray(names); names = new String[2]; names[0] = "Rudolf"; names[1] = "Ingrid"; printArray(names);
https://www.webucator.com/tutorial/learn-java/arrays/array-variables-reading.cfm
CC-MAIN-2017-17
refinedweb
151
54.15
i need to make a program that finds all primes between some numbers the biggest number is 1000000000. the code that i have works fine, the only problem is that what i thought that would solve this, is too slow #include <stdio.h> int main(){ FILE *fin=fopen("in.txt","r"); int t,n1[10],n2[10],i,j,ex,k; fscanf(fin,"%d\n",&t); for (i=1;i<=t;i++){ fscanf(fin,"%d %d\n",&n1[i],&n2[i]); } fclose(fin); FILE *fout=fopen("out.txt","w"); for (k=1;k<=t;k++){ for (i=n1[k];i<=n2[k];i++){ ex=0; for (j=1;j<=i;j++){ if (i%j==0){ ex=ex+1; } } if (ex==2){ fprintf(fout,"%d\n",i); } } fprintf(fout,"\n"); } fclose(fout); return 0; } i want to make it faster, like, 5 secs to find all primes until number 1000000000. cant think anything right now, well imean a better algorithm, so would appreciate any help provided. thanks
https://www.daniweb.com/programming/software-development/threads/194780/find-primes-help
CC-MAIN-2018-47
refinedweb
166
70.43
The Hello World program is the most common first example of how to write programs in a new language, even when they don't say Hello World. Five different ways to say hello in Ruby offer a gentle introduction to the language. Examples of how to write many simple programs that are of little practical use litter the Internet for anyone to find. Among the most common are: - a Fibonacci number calculator, because it is the canonical example for recursion. - a FizzBuzz solver, because it has become a canonical example of a simple job interview coding question. - a Hello World greeter, because it is the canonical example used to introduce a language. While teaching someone a new programming language in any depth requires a lot of discussion of syntactic forms, semantic design, and "best practices," it usually does not make much sense to the student until he or she gets to see a few examples of source code. This is where the Hello World program comes in: It is usually the first code example presented to a complete beginner, to give the simplest possible example of how the language looks in actual use. More complex examples follow, often involving the addition of more complexity and functionality to the Hello World program until it is nearly unrecognizable as a descendant of that first program. It is easy to dismiss the Hello World as a meaningless toy, but it serves an important purpose that more experienced developers may forget later in their careers: With a little creativity, such programs can even demonstrate the flexibility and unique qualities of the language to some small extent. For those of you who have never used Ruby, the following Hello World examples in the Ruby programming language may serve that purpose. Each example includes a standard shebang line that tells the OS where to find the Ruby interpreter on a Unix system. 1. The simple example #!/usr/bin/env ruby puts 'Hello, world!' There is not much to this. It consists of a grand total of two tokens -- the puts method and a string datum. Similar languages such as Perl and Python would use #!/usr/bin/env perl print "Hello, world!\n"; The double quotes and \n newline character are necessary here if you want a newline at the end of the program's output. Ruby has a puts, which conveniently adds the newline character at the end of its output without having to be asked. 2. The input example #!/usr/bin/env ruby puts "Hello, #{ARGV[0]}!" In this case, we are using double quotes for an interpolated string -- that is, a string that is actually parsed for executable code and special characters that should not be taken literally by the Ruby interpreter. Code that you want evaluated before passing the double-quoted string to the puts method can be wrapped in #{ }. In this case, we want the ARGV array -- where Ruby stores input from the command line -- to give us its first element. Because Ruby starts counting array elements at zero, that means we need ARGV[0] evaluated. If you name this program hello.rb and feed it world as a command line argument when you execute the program, the output will say Hello, world!: > ./hello.rb world Hello, world! 3. The array example #!/usr/bin/env ruby greeting = ['Hello', ARGV[0]] puts greeting.join(', ') + '!' Here, we first create a two-element array and give its second element the value of the first element of the ARGV array so that the user, as in the previous example, can specify the target of a greeting. Next, the join method is passed to the greeting array object, telling it to join its elements together with a comma followed by a single space between any two elements. Finally, it adds (concatenates, in this context) an exclamation point to the end of the string, before the puts method finally attaches a newline to the end and sends the whole string to standard output. If we run this program on a Monday, with a long, frustrating workweek ahead of us, we might be feeling less charitable than in the previous examples, and call the world something a bit less friendly: > ./hello.rb 'cruel world' Hello, cruel world! This version uses a little unnecessary complexity to achieve the exact same effects as the previous example, but that complexity does demonstrate for us a couple of things: - It displays some of the convenient text-processing capabilities of Ruby, including two ways to connect separate strings together into a larger string. - It begins to show the object-oriented design of Ruby. People who know object oriented programming from working with other languages might look at a lot of the code from before this example and wonder why everything in Ruby looks procedural, when it has a reputation as an object-oriented language. Prior to this, one could not tell just by looking at it that objects and methods infested the Ruby source code for a Hello World program. It turns out that puts is a method of the Kernel class, and strings are object instances of the String class. Array objects come with a join method, and while it looks like a procedural infix operator, + is actually being used here as a String object's method. In fact, the last line of this version of the Hello World program can be written like this, more explicitly revealing these methods for what they are: Kernel.puts( greeting.join(', ').+('!') ) Thank goodness for syntactic sugar; the version that does not use as many parentheses, does not explicitly name the Kernel class, and does not use as much dot-notation for methods was a bit easier on the eyes. 4. The custom method example #!/usr/bin/env ruby def greet(target) return "Hello, #{target}!" end puts greet(ARGV[0]) With another bit of unnecessary complexity, this time we have separated the string-building process from the output process by constructing a method called greet. By creating the greet method without explicitly including it in any class definition, we have added it to the Kernel class. As with puts, we do not need to specify the class to which the method belongs. In fact, because greet is a private method of Kernel, it cannot be called like this: Kernel.puts Kernel.greet(ARGV[0]) Actually, it can in irb (the interactive Ruby interpreter), but with standard executable files, this will not work. Once again, even when we create a method, we are doing something that could easily be mistaken for using a programming paradigm other than object-oriented programming. In this case, it looks like functional programming, where we have defined a "function" that takes exactly one input, produces exactly one output, and has no side effects. That "function" is then used to provide its output as input for another "function", the puts method. It is only because we know that both of these supposed functions are in fact methods of the Kernel class that we know this is a purely object-oriented exercise. If you want to develop code in a functional style, you may simply ignore what is going on behind the scenes and write your code in a manner calculated to give the impression it is purely functional, and not object oriented at all. 5. The custom class example #!/usr/bin/env ruby class Greeter def initialize(greeting) @greeting = greeting end def greet(subject) puts "#{@greeting}, #{subject}!" end end hail = Greeter.new('Well met') hail.greet(ARGV[0]) farewell = Greeter.new('Goodbye') farewell.greet(ARGV[1]) Finally, we are getting into the thick of object-oriented programming a little bit. A Greeter class is defined, and its initialize method (which automatically aliases to new) takes an argument for the type of greeting you want an instance of that class to use. Another method, greet, takes a single argument as well -- the subject, or target, of your greeting. Two separate objects of this class are instantiated with the new method, each of them being assigned to a separate label at the time they are created: hail and farewell. Each object is then sent the greet message with the first and second elements of the ARGV array, respectively, so that the person running the program from the command line can specify who will receive each greeting. Let us assume that the person running the program gets up happy and optimistic on a Friday morning, looking forward to a quick and painless day of work, followed by a long weekend (Monday will be a holiday for this user). As such, when the user says hello, it is with a smile and a friendly outlook for the world. By the end of the day, however, this user's entire department has been laid off. To top it off, our hapless user has just bought a new, expensive house that he simply cannot afford without that job, and the economy is in the toilet. As such, he has a very emo moment when it comes time to say goodnight. Given such a turnaround in his day, the program is run thus, complete with a teenage angst filled spelling error: > ./hello.rb 'fine world' 'crule world' Well met, fine world! Goodbye, crule world! If you become an expert Rubyist, you will hopefully never have the problem of being laid off so suddenly. I also hope that this quick introduction to Ruby gives you an idea of the language's clarity and flexibility.
https://www.techrepublic.com/blog/software-engineer/five-ruby-hello-world-greetings/
CC-MAIN-2020-16
refinedweb
1,582
59.53
Uncategorized Range comprehensions with C++ lazy generators++. Stackless coroutines with Visual Studio 2015 Let). Je suis Charlie Generator functions in C++. Async-Await in C++ Concurrency in C++11 C++11 is a much better language than its previous versions, with features like lambda expressions, initializer lists, rvalue references, automatic type deduction. The C++11 standard library now provides regular expressions, revamped smart pointers and a multi-threading library. But modern C++ is still limited in its support of parallel and asynchronous computations, especially when compared to languages like C#. The need for asynchrony But why do we need support for asynchrony? Computer architectures are becoming more and more parallel and distributed, with multi-core processors nearly ubiquitous and with cores distributed in the cloud. And software applications are more and more often composed by multiple components distributed across many cores located in a single machine or across a network. Modern programming languages need to offer support to manage this parallelism. At the same time, responsiveness has become a more and more indispensable quality of software (This is one of the tenets of “Reactive Programming”, an emerging programming paradigm). Responsiveness means that we don’t want to block waiting for the I/O operation to complete. In the server-side we don’t want to block a worker thread while it could be used to do some other work and be alerted when an operation completes. And in the client-side we really don’t want to block in the main/GUI thread of our process, making the application sluggish and non-responsive. Being able to write asynchronous code is therefore more and more important to manage the latency of I/O operations without blocking and losing responsiveness. For example, as a rule, in WinRT all I/O-bound APIs that could take more than 50ms only provide asynchronous interfaces, and cannot even be invoked with a “classical” blocking call. In this and in the next few posts we will have a look at what C++ currently provides to support concurrency, and what new features are on their way. We’ll see what is in the standard but also at the Windows-specific PPL framework provided by Microsoft. A simple example To understand how we can write asynchronous code in C++ let’s play with a very simple example. Let’s imagine that we want to write a function to read a file and copy its content into another file. To do this we could write functions like the following: #include <string> #include <vector> #include <fstream> #include <iostream> using namespace std; vector<char> readFile(const string& inPath) { ifstream file(inPath, ios::binary | ios::ate); size_t length = (size_t)file.tellg(); vector<char> buffer(length); file.seekg(0, std::ios::beg); file.read(&buffer[0], length); return buffer; } size_t writeFile(const vector<char>& buffer, const string& outPath) { ofstream file(outPath, ios::binary); file.write(&buffer[0], buffer.size()); return (size_t)file.tellp(); } With these, we can easily write a simple function to copy a file into another and return the number of characters written: size_t sync_copyFile(const string& inFile, const string& outFile) { return writeFile(readFile(inFile), outFile); } Evidently we want to execute readFile and writeFile in sequence, one after the other. But should we block while waiting for them to complete? Well, this is evidently a contrived example, if the file is not very big it probably does not matter much, and if the file is very large we would rather use buffering and copy it in chunks rather than returning all its content in a big vector. But both readFile and writeFile are I/O bound and represent here just a model for more complex I/O operations; in real applications it is common to have to read some data from a network, transform it in some way and return a response or write it somewhere. So, let’s say that we want to execute the copyFile operation asynchronously. How can we manage to do this in standard C++? Task-based parallelism: futures and promises The C++11 standard library provides a few mechanisms to support concurrency. The first is std::thread, which together with synchronization objects (std::mutex, std::lock_guards, std::condition_variables and so on) finally offer a portable way to write “classic” multithread-based concurrent code in C++. We could modify copyFile to instantiate a new thread to execute the copy, and use a condition_variable to be notified when the thread completes. But working at the level of threads and locks can be quite tricky. Modern frameworks (like the TPL in .NET) provides offer a higher level of abstraction, in the form of task-based concurrency. There, a task represents an asynchronous operation that can run in parallel with other operations, and the system hides the details of how this parallelism is implemented. The C++11 library, in its new <future> header, also provides a (somehow limited) support for task-based parallelism, in the form of promises and futures. The classes std::promise<T> and std::future<T> are roughly the C++ equivalent of a .NET Task<T>, or of a Future<T> of Java 8. They work in pairs to separate the act of calling a function from the act of waiting for the call results. At the caller-side when we call the asynchronous function we do not receive a result of type T. What is returned instead is a std::future<T>, a placeholder for the result, which will be delivered at some point in time, later. Once we get our future we can move on doing other work, while the task executes on a separate thread. A std::promise<T> object represents a result in the callee-side of the asynchronous call, and it is the channel for passing the result asynchronously to the caller. When the task completes, it puts its result into a promise object calling promise::set_value. When the caller finally needs to access the result it will call the blocking future::get() to retrieve it. If the task has already completed the result will be immediately available, otherwise, the caller thread will suspend until the result value becomes available. In our example, this is a version of copyFile written to use futures and promises: #include <future> size_t future_copyFile(const string& inFile, const string& outFile) { std::promise<vector<char>> prom1; std::future<vector<char>> fut1 = prom1.get_future(); std::thread th1([&prom1, inFile](){ prom1.set_value(readFile(inFile)); }); std::promise<int> prom2; std::future<int> fut2 = prom2.get_future(); std::thread th2([&fut1, &prom2, outFile](){ prom2.set_value(writeFile(fut1.get(), outFile)); }); size_t result = fut2.get(); th1.join(); th2.join(); return result; } Note that here we have moved the execution of the readFile and writeFile into separate tasks but we also have to configure and start threads to run them. Also, we capture references to the promise and future objects to make them available to the task functions. The first thread implements the read, and moves its result into a promise when it completes, in the form of a big vector. The second thread waits (blocking) on a corresponding future and when the read completes, get the read vector and pass it to the write function. Finally, when the writes complete, the number of chars written is put in the second future. In the main function we could take advantage of this parallelism and do some lengthy operation before the call to future::get(). But when we call get() the main thread will still block if the read and write tasks have not completed yet. Packaged tasks We can slightly simplify the previous code with packaged_tasks. Class std::packaged_task<T> is a container for a task and its promise. Its template type is the type of the task function (for example, vector<char>(const string&) for our read function. It is a callable type (defines the operator()) and automatically creates and manage a std::promise<T> for us. size_t packagedtask_copyFile(const string& inFile, const string& outFile) { using Task_Type_Read = vector<char>(const string&); packaged_task<Task_Type_Read> pt1(readFile); future<vector<char>> fut1{ pt1.get_future() }; thread th1{ move(pt1), inFile }; using Task_Type_Write = size_t(const string&); packaged_task<Task_Type_Write> pt2([&fut1](const string& path){ return writeFile(fut1.get(), path); }); future<size_t> fut2{ pt2.get_future() }; thread th2{ move(pt2), outFile }; size_t result = fut2.get(); th1.join(); th2.join(); return result; } Note that we need to use move() to pass the packaged_task to thread because a packaged_task cannot be copied. std::async With packaged_tasks the logic of the function does not change much, the code becomes slightly more readable, but we still have to manually create the threads to run the tasks, and decide on which thread the task will run. Things become much simpler if we use the std::async() function, also provided by the library. It takes as input a lambda or functor and it returns a future that will contain the return value. This is the version of copyFile modified to use std::async(): size_t async_copyFile(const string& inFile, const string& outFile) { auto fut1 = async(readFile, inFile); auto fut2 = async([&fut1](const string& path){ return writeFile(fut1.get(), path); }, outFile); return fut2.get(); } In a way std::async() is the equivalent of TPL task schedulers. It decides where to run the task, if a new thread needs to be created or if an old (or even the current) thread can be reused. It is also possible to specify a launch policy, which can be either “async” (which requires to execute the task asynchronously, possibly in a different thread) or “deferred” (which asks to execute the task only at the moment when get() is called). The nice thing is that std::async hides all the implementation, platform specific details for us. Examining the <future> header file that comes with VS2013 we can see that the Windows implementation of std::async internally uses the Parallel Patterns Library (PPL), the native equivalent of .NET TPL. PPL What we have seen so far is what has been standardized in C++11. It is fair to say that the design of futures and promises is still quite limited, especially if compared with what is provided by C# and .NET. The main limitation is that in C++11 futures are not composable. If we start several tasks to execute computations in parallel, we cannot block on all the futures, waiting for any of them to complete, but only on one future at a time. Also, there is no easy way to combine a set of tasks into a sequence, which each task that consumes as input the result of the previous task. Composable tasks allow to make the whole architecture non-blocking and event-driven. We really would like to have also in C++ something like task continuations or the async/await pattern. With the PPL (aka Concurrency Runtime) Microsoft had the possibility of overcoming the constraints of the standards and to experiment with a more sophisticated implementation of a task library. In the PPL, class Concurrency::task<T> (defined in the <ppltasks.h> header) represents a task. A task is the equivalent of a future; it also provides the same blocking method get() to retrieve the result. The type parameter T is the return type, and the task is initialized passing a work function (either a lambda or a function pointer or a function object). So, let’s abandon all concerns of portability for a moment and let’s re-implement our copyFile function, this time with tasks: size_t ppl_copyFile(const string& inFile, const string& outFile) { Concurrency::task<vector<char>> tsk1 = Concurrency::create_task([inFile]() { return readFile(inFile); }); Concurrency::task<size_t> tsk2 = Concurrency::create_task([&tsk1, outFile]() { return writeFile(tsk1.get(), outFile); }); return tsk2.get(); } Here we have created two task objects, initialized with two lambda expressions, for the read and write operations. Now we really don’t have to worry about threads anymore; it’s up to the PPL schedule to decide where to run the tasks and to manage a thread pool. Note however that we are still manually coordinating the interaction of our two tasks: task2 keeps a reference to the first task, and explicitly waits for task1 to terminate before using its result. This is acceptable in a very simple example like this, but it could become quite cumbersome when we deal with more tasks and with more complicated code. Task continuations Unlike futures, PPL tasks support composition through continuations. The task::next method allows to add a continuation task to a task; the continuation will be invoked when its antecedent task completes and will receive the value returned by the antecedent task. So, let’s rewrite the copyFile function again, but this time using a continuation: size_t ppl_then_copyFile(const string& inFile, const string& outFile) { Concurrency::task<size_t> result = Concurrency::create_task([inFile]() { return readFile(inFile); }).then([outFile](const vector<char>& buffer) { return writeFile(buffer, outFile); }); return result.get(); } Now the code is really clean. We have split the logic of a copy function into two separate components (tasks) that can run in any thread and will be run by a task scheduler. And we have declared the logic of our function as the dependency graph of the tasks. In this implementation the copyFile function still blocks, at the end, to get the final value, but in a real program it could just return a task that we would insert in the logic of our application, attaching to it a continuation to asynchronously handle its value. We would have code like this: Concurrency::task<size_t> ppl_create_copyFile_task(const string& inFile, const string& outFile) { return Concurrency::create_task([inFile]() { return readFile(inFile); }).then([outFile](const vector<char>& buffer) { return writeFile(buffer, outFile); }); } ... auto tCopy = ppl_create_copyFile_task(inFile, outFile).then([](size_t written) { cout << written << endl; }); ... tCopy.wait(); Finally, PPL tasks also provide other ways to compose tasks with the methods task::wait_all and task::wait_any, useful to manage a set of tasks that run in parallel. Given a set of tasks, when_all creates another task that completes when all the tasks complete (so, it implements a join). Instead when_any creates a task that completes when one of the tasks in the set completes; this can be useful for example to limit the number of concurrent tasks, and start a new one only when another completes. But this is just the tip of the PPL iceberg… the PPL offers a rich set of functionalities, almost equivalent to what is available in its managed version. It also provides scheduler classes that perform the important duty of managing a pool of worker threads and allocating tasks to threads. More details can be found here. Towards C++17 Hopefully we could soon see some of the improvements introduced by PPL in the C++ standard. There is already a document (N3857) written by Niklas Gustaffson et al. that proposes a few changes to the library. In particular, the idea is to enable the composability of future with future::then, future::when_any and future::when_all, with the same semantic seen in the PPL. The previous example, with the new futures, would be rewritten in a portable-way like this: future<size_t> future_then_copyFile(const string& inFile, const string& outFile) { return async([inFile]() { return readFile(inFile); }).then([outFile](const vector<char>& buffer) { return writeFile(buffer, outFile); }); } There would also be a method future::is_ready to test the future for completion before calling the blocking get(), and future::unwrap to manage nested futures (futures that returns future); of course all the details of this proposal can be found in the document above. Would this be the perfect solution? Not quite. Out experience with .NET teaches us that task-based asynchronous code is still hard to write, debug, and maintain. Sometimes very hard. This is the reason why new keywords were added to the C# language itself, in the version 5.0, to more easily manage asynchrony through the Async/Await pattern. Is there anything similar brewing even for the unmanaged world of C++?
https://paoloseverini.wordpress.com/category/uncategorized/
CC-MAIN-2017-04
refinedweb
2,655
52.29
Ruby March 1st, 2002 by Thomas Østerlie in. Once the invocation parameters have been processed, it is time to call delete_older: delete_older(path, age_in_seconds) rescue puts "Error: #$!" Errors may occur during execution. If the script is invoked with the path to a nonexistent directory, for instance, an error will occur the first time Ruby invokes a method on the Dir class. The code above not only invokes delete_older, it also handles possible errors that occur during execution. The key here is the rescue expression. When an error occurs, the Ruby interpreter packages the error in an exception object. This object propagates back up the call stack until it reaches some code that explicitly declares it knows how to handle this particular type of exception. Exceptions that are never caught propagate through the call stack, ending up with an abnormal program termination; the stack trace is printed to stderr. This is opposed to returning error codes like shell scripts and C do, leading to less-nested statements, less spaghetti logic and simply better error handling. Including an ensure statement in connection with the rescue expression ensures that a code block is run no matter what else happens. Combine this with the possibility of writing your own exceptions, making your own code throw exceptions (with the raise expression as shown in the program listing in Containers), and the ability to actually recover from an exception by running some code and retrying the code that caused the failure, and you have one of the neatest error-handling mechanisms I've ever used. Let's return to delete_older to look at some of Ruby's more advanced features (see Listing 2 [available at]). Line two sees “foreach” being invoked on the Dir class; foreach is an implementation of the iterator design pattern. If you are doing object-oriented programming, but have not read the Gang of Four's groundbreaking book Design Patterns, you'd better run out and buy a copy. Iterator is not the only pattern implemented in core Ruby. Singleton, publisher/subscriber, visitor and delegation patterns also are implemented. Other patterns also can be implemented simply if required, but the listed patterns are shipped with Ruby. foreach iterates over the files in a directory. Following the call to Dir's foreach is a block of code with a start and end very much resembling that of a regular Java or C++ code block. The code contained within the curly braces is called a block, which is like a method within a method. A block is never executed at the time it is encountered. Whenever the foreach method has read a single file from the directory, it yields control to the block. The code within the block is executed, and control returns to foreach, which reads a new file from the directory repeating the procedure over again until no more files are left to iterate over. Instead of having to write helper classes to make iterators work, as you have to in Java or C++, Ruby includes the yield expression that makes it possible to implement iterators as methods. This is a prime example of the language's expressiveness and flexibility. Instead of writing the scaffolding to make it happen, Ruby lets you concentrate on doing the job. As mentioned earlier, a method is invoked by sending a message to the target object on the target.message form. Only methods local to the class may be called without specifying a target. My script calls “puts”, which is a method belonging to the kernel, without specifying any target. How does the interpreter know which method I'm calling when puts is not local to the object and no target is specified? It is the magic of mix-ins. Mix-ins basically allow you to mix methods implemented elsewhere into a class without the use of inheritance (for more on mix-ins, please refer to the article “Using Mix-ins with Python”, Linux Journal, April 2001). Mix-ins aren't a new idea, nor is Ruby the only language to support it. But it is most definitely one of the features that gives Ruby that nice and clean syntax. I could never hope to deal with all of Ruby's features in this article. Instead I'll refer you to David Thomas and Andrew Hunt's book Programming Ruby for more details on issues like modules, aliasing, namespaces, reflection, dynamical method calls, system hooks, program distribution and networking. It is worth mentioning that Ruby also supports regular expressions that are just as good as Perl's and supports CGI, in addition to having its own Apache module, mod_ruby. Is Ruby yet another scripting language? No, it is not. It is something more, something new and exciting coming out of the Japanese open-source scene. Ruby is the programmer's best friend. While Ruby is presented as a scripting language, it has proven equally suited for large projects. It includes some exciting features that other alternative languages are only beginning to implement. Ruby is therefore well worth checking out. A special thanks goes out to my technical reviewers: Armin Roehrl, of approximity.com, for reviewing the draft manuscript and guidance in editing the final version. David Thomas, of pragmaticprogrammer.com, for massively improving the original sample script and reviewing the draft manuscript. Kent Dahl and Sean Chittenden for reviewing the draft manuscript. Last, but not least, Magnus Lie Hetland, Python guru, for invaluable works On February 3rd, 2009 Anonymous (not verified) says: It works This example doesn't work, On December 22nd, 2008 Anonymous (not verified) says: This example doesn't work, it is missing something so has an extra ) Dir.entries(full_name) - ['.', '..']).empty? Post new comment
http://www.linuxjournal.com/article/4834
crawl-002
refinedweb
951
53.51
Writing a Control and Measurement Device Interface (COMEDI) driver Writing a Control and Measurement Device Interface (COMEDI) driver 2005-09-04T07:30:00 The Phoenix mailing list (phoenix-project@freelists.org) is becoming active. Georges Khaznadar had this interesting suggestion that if we wrap the COMEDI framework over the Phoenix driver, it would be easy to use programs like QtScope which don't care what the underlying DAQ hardware is as long as it is COMEDI-compliant. I spent an hour today exploring this idea [Note that Ajith's Phoenix library also does much the same stuff; but in a less `generic' way. COMEDI will be useful only if there are sufficient number of applications which use it's interface specification; make the Phoenix driver COMEDI-compliant and presto, these data acquisition applications suddenly become Phoenix-friendly] What does COMEDI doAll data acquisition boards act the same conceptually - there will atleast be a few analog input channels and facility to: - Select the channel - Trigger start-of-conversion - Know when the conversion has ended (polling or interrupts) Installing COMEDII downloaded comedi-0.7.70 and comedilib-0.7.22 from the project home page; installation was simple - the usual ./configure;make;make installdance. COMEDI requires a few device files, so you have to do a `make dev' also. comedi-0.7.70 implements the kernel space layer including drivers for plenty of boards. comedilib is the user space library - you need it to invoke the kernel space routines. Configuring COMEDIOn my machine, the COMEDI kernel space drivers get installed into: /lib/modules/2.6.7/comedi/You will find a module called `comedi.ko'; this is the `master' module which implements lots of `generic' stuff. Then you have plenty of .ko files like usbdux.ko, ni_labpc.ko etc - these are the board specific drivers. You should start off by reading the file `skel.c', a `dummy' driver which shows you how to code COMEDI-based drivers. The documentation which comes with comedilib (under doc/doc_html) is also very useful. To get started, lets try to make the dummy driver work. First, it will be nice if `modprobe' is able to load skel.ko and the file on which it depends, comedi.ko, automagically. Make sure that /lib/modules/2.6.7/modules.dep contains the line: /lib/modules/2.6.7/comedi/skel.ko: /lib/modules/2.6.7/comedi/comedi.koNow, you can do a `modprobe skel' and both `skel.ko' and `comedi.ko' will be loaded. Just loading the required modules is not enough. You now have to associate a COMEDI device file with one specific driver, in this case, `skel': This is done using the comedi_config command: comedi_config /dev/comedi0 skel-100Run `dmesg' and make sure that you are getting some meaningful message from the kernel. Run the `info' command (under `demo' folder in `comedilib') and you will get plenty of information regarding the dummy driver. Writing your own COMEDI driverHere is a simple driver program (just skel.c minus lots of stuff). #include <linux/comedidev.h> // Not really required. typedef struct { char *name; int ai_chans; int ai_bits; int have_dio; }phoenix_board; static phoenix_board phb = {"phoenix", 8, 8, 0}; static int phoenix_attach(comedi_device *dev, comedi_devconfig *it); static int phoenix_detach(comedi_device *dev); static int phoenix_ai_rinsn(comedi_device*, comedi_subdevice*, comedi_insn*, lsampl_t*); static comedi_driver driver_phoenix = { driver_name: "phoenix", module: THIS_MODULE, attach: phoenix_attach, detach: phoenix_detach }; static int phoenix_attach(comedi_device *dev, comedi_devconfig *it) { comedi_subdevice *s; printk("Attach called: dev = %x\n", dev); dev->board_name = "Phoenix, NSC India"; if(alloc_subdevices(dev, 1) < 0) return -ENOMEM; s = dev->subdevices+0; s->type = COMEDI_SUBD_AI; s->subdev_flags = SDF_READABLE | SDF_GROUND; s->n_chan = phb.ai_chans; s->maxdata = (1 << phb.ai_bits) - 1; s->range_table = &range_unipolar5; s->insn_read = phoenix_ai_rinsn; return 1; } static int phoenix_ai_rinsn(comedi_device *dev, comedi_subdevice *s, comedi_insn *insn, lsampl_t *data) { int i, n; printk("rinsn called: channel = %d\n", CR_CHAN(insn->chanspec)); printk("samples to read = %d\n", insn->n); n = insn->n; for(i = 0; i < n; i++) data[i] = 1234; return insn->n; } static int phoenix_detach(comedi_device *dev) { printk("detach called: dev = %x\n", dev); return 0; } COMEDI_INITCLEANUP(driver_phoenix);Before we understand how it works, let's try to compile and install it. The driver source, `phoenix.c' should be placed under the comedi/drivers directory. Then, Makefile.am should be changed in two places: - `phoenix.ko' should be added to module_PROGRAMS - phoenix_ko_SOURCES should be set to `phoenix.c' comedi_config /dev/comedi0 phoenixThis will `attach' the phoenix driver to /dev/comedi0. How does the code work?Fairly simple. The structure `phoenix_driver' is the key; it contains address of two routines - one of which is called during driver attach (`attach' takes place when you run `comedi_config'). The macro COMEDI_INITCLEANUP does the job of doing whatever initialization is required to `register' this structure with the COMEDI generic layer. The generic layer builds up a structure of type `comedi_device' and passes it's address to `phoenix_attach' which does the job of filling up certain important fields with device specific info. The Phoenix box can be thought of as a data acquisition device with multiple subdevices, each subdevice having multiple channels. Thus, we have an analog input subdevice with 8 channels each of resolution 8 bits and 5V unipolar range. We also have an analog output subdevice with just one channel, 8 bits resolution and 5V bipolar range ... and so on. In the code above, I am setting up the number of subdevices to 1 (just the analog inputs). The line: s->insn_read = phoenix_ai_rinsn;is crucial. It set's up a function which will respond to various read operations from user space. Here is a user space test program: #include <stdio.h> #include <comedilib.h> #define N 100 main() { comedi_t *fd; //lsampl_t is a 32 bit object. lsampl_t data[N]; int i, r = 33; int subdev = 0, channel = 0, range = 0; fd = comedi_open("/dev/comedi0"); printf("%x\n", fd); //printf("%d\n", sizeof(lsampl_t)); r = comedi_data_read_n(fd,subdev,channel,range,AREF_GROUND, data, N); printf("r = %d\n", r); for(i = 0; i < N; i++) printf("%d\n", data[i]); }To wind up, here is the output shown on my machine when I run the `info' program (present under the `demo' directory of comedilib source distro). overall info: version code: 0x000746 driver name: phoenix board name: Phoenix, NSC India number of subdevices: 1 subdevice 0: type: 1 (analog input) number of channels: 8 max data value: 255 ranges: all chans: [0,5] command: not supported huseyinkozan Thu Nov 20 20:08:24 2008 Thanks for your article. Lincoln Tue Oct 27 17:22:12 2009 Thank you for this dummy explaination
https://pramode.net/2005/09/04/writing-a-control-and-measurement-device-interface-comedi-driver/
CC-MAIN-2022-33
refinedweb
1,096
54.83
After entering the price as 90 and the pricing code as H the sum that is being calculated is 0.00 and after changing it around a little it comes out as 1.Ef#, the compiler being used is codeblocks 10.05. #include <stdio.h> int main() { float price,sum,discount_rate; char pricing_code; printf("Enter the price for the article:\n"); scanf("%f", &price); printf("Enter the pricing code for the article:\n"); scanf("%o", &pricing_code); if (pricing_code == 'H') { sum = (discount_rate = 0.5); } else if (pricing_code == 'F') { (discount_rate = 0.6); } else if (pricing_code == 'T') { (discount_rate = 0.77); } else if (pricing_code == 'Q') { (discount_rate = 75/100); } else if (pricing_code == 'Z') { printf("No discount /n"); } sum = price * discount_rate; printf("The sum is %.2f\n", sum); return 0; }
http://www.dreamincode.net/forums/topic/263861-why-is-the-sum-is-not-being-calculated-correctly/
CC-MAIN-2016-07
refinedweb
124
66.64
Today, We want to share with you matrix multiplication in python user input.In this post we will show you matrix in python example, hear for matrix multiplication in python using function we will give you demo and example for implement.In this post, we will learn about How To Take Two Inputs In One Line In Python? with an example. Matrix addition in python user input Below is python program to multiply two matrices. Example 1: def print_design(design): for i in range(len(design)): for j in range(len(design[0])): print("\t",design[i][j],end=" ") print("\n") def main(): m = int( input("enter single design rows")); n = int( input("enter single design columns")); p = int( input("enter second design rows")); q = int( input("enter second design columns")); if( n != p): print ("matrice multipilication not possible..."); exit(); #declaration of arrays items1=[[0 for j in range (0 , n)] for i in range (0 , m)] items2=[[0 for j in range (0 , q)] for i in range (0 , p)] response=[[0 for j in range (0 , q)] for i in range (0 , m)] #taking input from user print ("enter single design data values:" ) for i in range(0 , m): for j in range(0 , n): items1[i][j]=int (input("enter data value")) print ("enter second design data values:") for i in range(0 , p): for j in range(0 , q): items2[i][j]=int(input("enter data value")) print ("single design") print_design(items1) print ("second design") print_design(items2) #for multiplication # i will run throgh each row of design1 for i in range(0 , m): # j will run through each column of design 2 for j in range(0 , q): # k will run throguh each row of design 2 for k in range(0 , n): response[i][j] += items1[i][k] * items2[k][j] #printing response print ( "multiplication of two matrices:" ) print_design(response) main() Program to multiply two matrices in Python Example 2: import random jds=input("Give Any No. of rows in the single design: ") fl1=input("Give Any No. of columns in the single design: ") a = [[random.random() for col in range(fl1)] for row in range(jds)] for i in range(jds): for j in range(fl1): a[i][j]=input() lks=input ("Give Any No. of rows in the second design: ") secPar=input ("Give Any No. of columns in the second design: ") b = [[random.random() for col in range(secPar)] for row in range(lks)] for i in range(lks): for j in range(secPar): b[i][j]=input() c=[[random.random()for col in range(secPar)]for row in range(jds)] if (fl1==lks): for i in range(jds): for j in range(secPar): c[i][j]=0 for k in range(fl1): c[i][j]+=a[i][k]*b[k][j] print c[i][j],'\t', print else: print "Multiplication not possible" Results: Give Any No. of rows in the single design: 3 Give Any No. of columns in the single design: 2 1 2 3 4 5 6 Give Any No. of rows in the second design: 2 Give Any No. of columns in the second design: 3 1 2 3 4 5 6 Output: 9 12 15 19 26 33 29 40 51 I hope you get an idea about python program to generate n*n matrix from user input. I would like to have feedback on my infinityknow.com blog. Your valuable feedback, question, or comments about this article are always welcome. If you enjoyed and liked this post, don’t forget to share.
https://www.pakainfo.com/python-program-multiplication-of-two-matrix-from-user-input/
CC-MAIN-2022-21
refinedweb
595
56.89
Replace the current raster operation #include <gf/gf.h> uint8_t gf_context_set_rop( gf_context_t context, unsigned short rop ); gf This function sets the raster operation (ROP) for subsequent draw operations for a draw context. ROPs give you extended control over how pixels are plotted in the form of bitwise operations considering source and desination values, as well as patterns. You can set the pattern using gf_context_set_pattern(). The QNX Graphics Framework supports a total of 256 ROPs. The table below lists the defined ROPs for GF. For additional macros, see public/gf/gf_rop.h in the GF source directory. In the ROP names, these letters have the following meanings: The previous ROP code. QNX Graphics Framework
https://www.qnx.com/developers/docs/6.5.0SP1.update/com.qnx.doc.gf_dev_guide/api/gf_context_set_rop.html
CC-MAIN-2021-31
refinedweb
113
60.51
Pretty easy task from pwnable.kr but took me waaay too long. #include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct tagOBJ{ struct tagOBJ* fd; struct tagOBJ* bk; char buf[8]; }OBJ; void shell(){ system("/bin/sh"); } void unlink(OBJ* P){ OBJ* BK; OBJ* FD; BK=P->bk; FD=P->fd; FD->bk=BK; BK->fd=FD; } int main(int argc, char* argv[]){ malloc(1024); OBJ* A = (OBJ*)malloc(sizeof(OBJ)); OBJ* B = (OBJ*)malloc(sizeof(OBJ)); OBJ* C = (OBJ*)malloc(sizeof(OBJ)); // double linked list: A <-> B <-> C A->fd = B; B->bk = A; B->fd = C; C->bk = B; printf("here is stack address leak: %p\n", &A); printf("here is heap address leak: %p\n", A); printf("now that you have leaks, get shell!\n"); // heap overflow! gets(A->buf); // exploit this unlink! unlink(B); return 0; } We’ve got here three structures allocated on the heap, which are doubly-linked in a ptalloc fashion where a chunk’s header contains a pointer to the previous chunk and to the next one. There is also an obvious overflow which presumably would allow us to corrupt these structures. At the start of the program an address from the heap and one from the stack are leaked which is quite handy since the binary has got ASLR enabled. After launching the program in gdb with a 100 byte buffer we see that we control $eax and $edx, and mov dword ptr [eax + 4], edx fails since $eax+4 is an invalid address. It basically means that this mov operation provides us with a generic “write-what-where” condition. Just two instructions below there is another mov which does a vice versa thing: it writes from $edx to a location pointed by $eax. The first idea is of course to overwrite the return pointer when ret is performed at 0x804852e with a pointer to shell() function from the original task code. However, this attempt will fail since the second mov will try to write our $esp pointer from $edx to a dereferenced pointer in $eax, i.e. overwrite the shell() function. This is where I stuck for a while until I noticed pretty interesting operations at the end of program execution: 0x080485ff <+208>: mov ecx,DWORD PTR [ebp-0x4] 0x08048602 <+211>: leave 0x08048603 <+212>: lea esp,[ecx-0x4] 0x08048606 <+215>: ret We see that we’ve got an additional dereference at $ecx-0x4 which may point to our controlled data in the heap if we use the “write-what-where” condition to overwrite $ebp-0x4. We don’t care about unwanted write done by the second mov any more as it will be done in the heap, and not in the code section. So we overwrite $ebp-4 with a pointer to the heap, where we will store a pointer (with an -0x4 offset) to the shell() function. pwndbg> r <<< `python -c 'from struct import pack; print(pack("<I", 0x80484eb) + "A" * 20 + pack("<I", 0xffffd2b4 - 4) + pack("<I", 0x804b578 + 4))'` Starting program: /home/raz0r/pwn/unlink <<< `python -c 'from struct import pack; print(pack("<I", 0x80484eb) + "A" * 20 + pack("<I", 0xffffd2b4 - 4) + pack("<I", 0x804b578 + 4))'` here is stack address leak: 0xffffd2a4 here is heap address leak: 0x804b570 now that you have leaks, get shell! [New process 21976] process 21976 is executing new program: /bin/dash [New process 21977] process 21977 is executing new program: /bin/dash [Inferior 3 (process 21977) exited normally] Nice! /bin/dash is executed which means that we successfully overwritten return address with shell() pointer. However, we have to get rid of static addresses because of ASLR. And we can do so by using leaks from the stdout. The addresses will change to the following: 0x80484ebpoints to shell()and is static; 0xffffd2b4is retaddress, offset is stack leak + 16; 0x804b578is a pointer to the heap where we store a pointer to shell(), offset is heap leak + 8. I also had to adjust the distance between the first two pointers (20 “A”s – on my machine, 12 “A”s – on pwnable.kr server). Final PoC: import re from pwn import * from struct import pack p = process("./unlink") stack_leak = int(re.search('0x[^\n]+', p.recvline()).group(0),16) print(hex(stack_leak)) heap_leak = int(re.search('0x[^\n]+', p.recvline()).group(0),16) print(hex(heap_leak)) ret = stack_leak + 16 shell = 0x80484eb heap = heap_leak + 8 p.sendline(pack('<I', shell) + "A" * 12 + pack('<I', ret - 4) + pack('<I', heap + 4)) p.interactive() And the flag:
https://raz0r.name/writeups/writeup-pwnable-kr-unlink/
CC-MAIN-2019-43
refinedweb
747
67.99
Red Hat Bugzilla – Bug 64746 AM_PATH_XML2 always fails Last modified: 2008-05-01 11:38:02 EDT Because /usr/bin/xml2-config --cflags no longer includes -I/usr/include/libxml2/libxml (which is good, I don't want to solve conflicts between header files named tree.h), the AM_PATH_XML2 macro in /usr/share/aclocal/libxml.m4 always fails, because it tries to #include <xmlversion.h> instead of <libxml/xmlversion.h>. The attached patch fixes it. Version-Release number of selected component: libxml2-devel-2.4.19-4 Created attachment 56964 [details] Patch fixing this Okay this should be fixed in recent releases, the libxml.m4 now always do properly namespaced includes by doing #include <libxml/xxx.h> thanks for the report, Daniel
https://bugzilla.redhat.com/show_bug.cgi?id=64746
CC-MAIN-2017-17
refinedweb
122
52.56
AWS S3 Overview This week I’m recapping what I’ve learned about data storage in AWS with a heavy focus on S3. If you want to see what else I’ve learned about AWS over the recent weeks then check out my AWS Overview, EC2 Intro and Amazon Redshift at a Glance posts. Amazon S3 101 S3 stands for Simple Storage Service. It is Amazon’s object based storage service for uploading data files. It is not suitable for installing an OS for example. It’s used for applications like Dropbox that allows users to store files of all different types in a Cloud based filesystem. Files can be any size from 0 Bytes up to 5 Terabytes in size and the storage capacity is effectively unlimited. Amazon will continually increase their storage capacity at the back end. When a file is uploaded to S3, it will be stored in a Bucket. A Bucket is just like a folder or repository and will be the holding pen for all your sub folders and files. S3 is a universal namespace, meaning each S3 bucket you create must have a unique name that is not being used by anyone else in the world. This is because your bucket name makes up part of your S3 url, which must be unique. Url Format:-<region>.amazonaws.com/<bucketname> e.g.: Reading and Writing Data to and from S3 When you upload a new file to S3, it has Read after Write consistency. What this means is that once your file is successfully written to S3 it is immediately available for reading anywhere in the world. However, if you are updating or deleting a file, S3 has Eventual consistency. This means that it can take some time for the update or delete to appear, so depending on the region you may or may not see the changes instantly. This is because if you’re S3 file is cached on an edge location for example, then it may take time for the update or delete to propagate through to each of these locations. Data stored in S3 can be held in one of 4 Storage Classes. - Standard S3 — This is the most durable storage class and should be used for frequently accessed files that require quick access. - S3 Infrequently Accessed — As the name suggests, this is for files that are accessed less frequently but you still need available to you. - S3 Redundancy Storage — should be used for data that can be reproduced (no big issue if it is lost) such as thumbnails or auto generated docs. - Glacier — This is the data archive capability. You can hold your data here super cheaply, however can wait up to 3–5 hours for data access. Files are stored with the following attributes: - Key — the filename - Value — the file data - Version ID — if versioning is turned on, you can keep track of the current version. Versioning will store all versions of an object (even if you delete) so can be useful for backups and can be used in conjunction with MFA. - Metadata — data about upload times, last accessed etc. Data Lifecycle Management As your data ages within S3, you can set it up to flow through each of the Storage Classes in order to reduce your costs. So that data that is old and never accessed can be put into Glacier for example. Lifecycle management can be applied to current or previous versions of files. You can move files into S3 IA after at least 30 days and then into Glacier another 30 days after being in IA. These numbers are all user configurable but can’t be below the minimum of 30 days. Meaning at a minimum your file has to be within S3 + IA for 60 days before making its way to Glacier.
https://medium.com/@lewisdgavin/aws-s3-overview-6fe9ca2a1e0a
CC-MAIN-2017-39
refinedweb
636
68.6
AMQ Streams With Kafka Connect on Openshift AMQ Streams With Kafka Connect on Openshift Receiving messages from Telegram with Kafka Connect Join the DZone community and get the full member experience.Join For Free Have you ever heard about AMQ Streams? It is a Kafka Platform based on Apache Kafka and powered by Red Hat. A big advantage of AMQ Streams is that as all Red Hat tools, it is open source. This article's about a common feature of Apache Kafka, called Kafka Connect. I'll explain how it works with OpenShift. What Is Kafka Connect? Kafka Connect is an open-source component of Apache Kafka®. It is a framework for connecting Kafka with external systems, such as databases, key-value stores, search indexes, and file systems. The Telegram platform is one of these systems and in this article, I will demonstrate how to use Kafka Connect deployed on OpenShift to get data from Telegram. Kafka Connect API Architecture Basically there are 2 types of Kafka Connectors: Sources: A source connector collects data from a system and sends it to a Kafka topic, for example, we can get messages from Telegram and put it in a Kafka topic. Synk: A sink connector delivers data from Kafka topics into other systems, which might be indexed such as Elasticsearch, batch systems such as Hadoop, or any kind of database. There are two ways to execute Kafka Connect: Standalone and Distributed. However, the operator supports only Distributed mode in OpenShift. That's not a restriction, because none Kafka distribution in production environments is recommended set standalone mode. The Kafka Connector uses an environment independent of Kafka Broker, on OpenShift Kafka Connect API runs in a separated pod. In this example, we will use a source connector. Before We Start Firstly will be necessary to create a bot in the Telegram platform and generate an access token to him. We need this token to generate a secret on OpenShift to Kafka Connect can receive messages from Telegram. To create this bot, see the article — Bots: An introduction for developers. The necessary files to execute this demonstration is on GitHub. Click here to start the download. The files have a number that identifies the sequence of use of them in this article. Any person can download and reproduce this demonstration. Let's Start The first step is to deploy AMQ Streams on OpenShit. For this, use the Strimzi operator provided on the Red Hat Web Site. The link of the file to download is "Red Hat AMQ Streams 1.4.1 OpenShift Installation and Example Files". If you prefer, I generated a package with the operator also available on GitHub. Use the commands below to install AMQ Stream (Kafka) on OpenShift. $ oc new-project kafkaproject $ oc apply -f ./operator/ $ oc apply -f ./kafka.yaml What have we done? Firstly, we have created a project named 'kafkaproject' and deploy the Strimzi operator. When the operator was finished we deploy AMQ Streams through the kafka.yaml template. The result of these commands is bellow, The next step is to generate the Openshift secret using Telegram access token. Create the property file, see the example below. I chose 'telegram-credentials.properties' filename. Feel free to choose your filename. xxxxxxxxxx token=1011765240:AAG-PdMojD1pZWUpNySa8rHDjxym3CVyqTxd Create the file telegram-credentials.yaml and put the base64 representation of file telegram-credentials.properties. xxxxxxxxxx apiVersion: v1 data: telegram-credentials.properties: ##BASE64 telegram-credentials.properties## kind: Secret metadata: name: telegram-credentials namespace: kafkaproject type: Opaque Use the below commands to create the secret and deploy the Kafka Connect. Making a reference with RHEL version, the kafka-connect.yaml is similar to execute connect-distributed.sh xxxxxxxxxx $ oc apply -f ./4-telegram-credentials.yaml $ oc apply -f ./5-kafka-connect.yaml Notice that a new pod was created on OpenShift. After deploying Kafka Connect, we need to inform the parameters to connect to the Telegram. For this, we use the file 6-telegram-connector.yaml. See below: x apiVersion: kafka.strimzi.io/v1alpha1 kind: KafkaConnector metadata: name: telegram-connector labels: strimzi.io/cluster: my-connect-cluster spec: class: org.apache.camel.kafkaconnector.CamelSourceConnector tasksMax: 1 config: key.converter: org.apache.kafka.connect.storage.StringConverter value.converter: org.apache.kafka.connect.storage.StringConverter camel.source.kafka.topic: telegram-topic camel.source.url: telegram:bots camel.component.telegram.authorizationToken: ${file:/opt/kafka/external-configuration/telegram-credentials/telegram-credentials.properties:token} Execute the command below: xxxxxxxxxx oc apply -f 6-telegram-connector.yaml After completion, and if the credentials are correct, any message sent to your bot will be received by Kafka Connect and saved in a topic called telegram-topic, which was defined in property camel.source.kafka.topic in the file 6-telegram-connector.yaml. Notice how the API token is mounted from a secret in the property camel.component.telegram.authorizationToken. You can go to the Telegram app and talk with the bot, in this example I create a bot called @amqstreams. Run the receiver on a Kafka topic telegram-topic to see the messages sent to the bot. To consume the messages on the topic, we can use the command below: xxxxxxxxxx kubectl run kafka-consumer -ti --image=strimzi/kafka:0.16.0-kafka-2.4.0 \ --rm=true --restart=Never \ -- bin/kafka-console-consumer.sh \ --bootstrap-server my-cluster-kafka-bootstrap:9092 \ --topic telegram-topic \ --from-beginning A good point to notice here is the property camel.source.url. Internally, when we provide the value , telegram-bots, to property, the connector created a camel route using a Camel Telegram component. There are a lot of connectors available for Kafka Connet, in our hands-on, we used a Camel Connector, this one allows us to use all power of Apache Camel together Kafka Connect. In this example, we didn't write any code. However, if necessary, we can create customized routes to connect to anything and use the same steps used here to put dada on the Apache Kafka. Final Considerations The Kafka Connect is a powerful member of the Kafka Ecosystem. In this article I showed a simple integration, however, Kafka Connect allows us to interact with a lot of systems or even other message brokers. Guard this advice: “If there is data, we can connect and get it.“ Opinions expressed by DZone contributors are their own. {{ parent.title || parent.header.title}} {{ parent.tldr }} {{ parent.linkDescription }}{{ parent.urlSource.name }}
https://dzone.com/articles/kafka-connect-openshift
CC-MAIN-2020-29
refinedweb
1,068
50.23
14 May 2013 23:37 [Source: ICIS news] TEHRAN (ICIS)--?xml:namespace> Behruz Alishiri, the vice minister of economic policy and finance for He highlighted Suggested projects in Mahshahr include a methanol plant of 1.65m tonne/year, a 120,000 tonne/year propylene plant, a 150,000 tonne/year 2-ethylhexanol (2EH) plant, a 300,000 tonne/year acetic acid plant, a 160,000 tonne/year vinyl acetate monomer facility, a 800,000 tonne/year dimethyl ether (DME) plant, a 27,000 tonne/year cyclohexane plant, a 70,000 tonne/year caprolactum plant and a 70,000 tonne/year adipic acid plant. The projects are expected to cost around $1.86bn (€1.43bn), much of which will need to be financed with foreign funds,
http://www.icis.com/Articles/2013/05/14/9668504/iran-planning-more-petrochemical-projects-in-mahshahr.html
CC-MAIN-2014-35
refinedweb
125
67.89
Add the Navigation Welcome to the fifth article in the getting started with Prismic and Gatsby tutorial series. We'll be walking through the steps required to convert the top navigation. There's a navigation bar at the top of the page that we'll keep as a static top-level component. Let's review the fields used to build it: Navigation API ID: top_navigation A Group field to handle our links since we don't know how many we might need in the future. Link API ID: link A Link field for internal content. Text API ID: link_label A Rich Text field to add the link's labels. The model for this banner is already in your Prismic repository. Click on Custom Types, and see the content modeling of the Navigation type. Then, click the Documents button and select the Navigation document to view the live version. It should look something like this: For more complex use cases where you need to add sub-navigation within the main navigation, you could use Slices. Add links in both the repeatable and non-repeatable zone to make nested links.. Click on Add a new element in top_navigation to add a new link to the navbar. Now that we know how to create new links, let's add them to our Gatsby project. Run the project with npm start. Next, open the GraphQL Playground at and paste this GraphQL query: query Navigation { prismicNavigation { data { top_navigation { link { url } link_label { text } } } } } Run the query by pressing the "play" button ▷ at the top to see the query results on the right. We're going to query data with useStaticQuery in the header component to get the document for the single document of the type Navigation. Since this component is in the Layout that wraps all the page files, it will appear on all our pages. Open your Header.js component found in the 〜/src/components folder replace the existing code of your files in your project with the following: // Header.js file import * as React from 'react' import { graphql, useStaticQuery } from 'gatsby' import { PrismicLink } from '@prismicio/react' export const Header = ({ isHomepage }) => { const queryData = useStaticQuery(graphql` { prismicNavigation { data { top_navigation { link { url link_type } link_label { text } } } } } `) const navigation = queryData.prismicNavigation const topNav = navigation.data.top_navigation const homepageClass = isHomepage ? 'homepage-header' : '' return ( <header className={`site-header ${homepageClass}`}> <a href="/"> <div className="logo">Example Site</div> </a> <nav> <ul> {topNav.map((navItem, index) => { return ( <li key={`link-${index}`}> <PrismicLink field={navItem.link}> {navItem.link_label.text} </PrismicLink> </li> ) })} </ul> </nav> </header> ) } Now when you refresh your site, your top navigation will be pulling its content from Prismic! Link Resolving You may or may not remember that we added this to our project back in the second article in the series. If it didn't make any sense, then, hopefully, it is more clear now. The Link Resolver is what populates the url field. Was this article helpful? Can't find what you're looking for? Get in touch with us on our Community Forum.
https://prismic.io/docs/technologies/tutorial-5-add-navigation-gatsby
CC-MAIN-2022-05
refinedweb
503
56.15
What type of errors do have? Compiler erros? Linker errors? Run-time errors? Victor Nijegorodov error C3861: "dwt_sym": identifier not found. Best regards, Nikolas Originally Posted by Physikant error C3861: "dwt_sym": identifier not found. What is "dwt_sym"? Where is it declared? If it is the wavelet2d.h then you had to Code: #include "wavelet2d.h" in the file rhat uses this identifier. #include "wavelet2d)". Thanks for the reply. Best regards, Nikolas Good! Now you have to add some libs containing these "unresolved external symbols". I presume there should be wavelet2d.lib library! Try inserting #pragma comment( lib, "wavelet2d") at the top of the program. This will instruct the linker to load the wavelet2d.lib (looks first in the current working directory and then in the path specified in the LIB environment variable.) All advice is offered in good faith only. You are ultimately responsible for effects of your programs and the integrity of the machines they run on. I inserted the line at the beginnig of my code and I added wavelet2d.lib in the project-explorer as a ressource-file and in the main root of the project. Still the external symbol can't be resolved. Best regards, Nikolas Originally Posted by Physikant I inserted the line at the beginnig of my code and I added wavelet2d.lib in the project-explorer as a ressource-file and in the main root of the project. You should not do it. This .lib file has nothing to do with the resources. You have to insert the file into project folder (note that I mean Windows Explorer folder, not a VS "project-explorer"!) I removed the lib from the ressources folder again, but its still in the list of the project. The lib-file is in the folder of my source on the hdd. Any more ideas? Best regards, Nikolas Becker Originally Posted by Physikant I removed the lib from the ressources folder again, but its still in the list of the project. The lib-file is in the folder of my source on the hdd. Any more ideas? Perhaps "the folder of your source on the hdd" is not "the current working directory"? I've checked wavelet2d.lib and dwt_sym is defined there as an export. So there must be somethig wrong with how you are telling the linker to find/use wavelet2d.lib. Try putting the full path name to wavelet2d.lib in the #pragma statement - or add it to the linker additional dependencies property field for the project in MSVS. Ok, I came back to this project and it's still not working. I made a test project from scratch to make sure there is no problem with what ive done so far. My project has this structure: [1]wavelet2test [2]wavelet2test\Debug [3]wavelet2test\Release [4]wavelet2test\wavelet2test [5]wavelet2test\wavelet2test\Debug [6]wavelet2test\wavelet2test\Release What ive done: In the download, there are two folders, Release and Debug. I copied the wavelet2d.dll and wavelet2d.lib from Debug to [2] and [5], and from the Release folder to [3] and [6]. Then I copied the libfftw3-3.dll from another directory of the download to [2],[5],[3] and [6]. Then I copied wavelet2d.h from the src-folder of the download to [1] and [4]. In the project-explorer, I added the wavelet2d.lib I copied to [2] as an element to the wavelet2test-project. I added #include "wavelt2d.h" as the first line to my program. I added [2],[3],[5],[6] to the directories for the linker. In the program, I call dwt_sym (I think it has no namespace). If I do that, I get the two previously discussed linker errors LNK2028 and LNK2019. If I add #pragma comment( lib, "wavelet2d") to the first lines of my code, I get many warnings in addition to the two linker errors (here is one of them, they are all similar): warning C4272: "dwt_sym": is marked __declspec(dllimport); must specify native calling convention when importing a function. Any ideas what i could try? Thanks so far! Best regards, Nikolas 1. You did not mention "linker errors LNK2028 and LNK2019". 2. You neither added the wavelet2d.lib in the linker additional dependencies property field nor did you set the full path name to wavelet2d.lib in the #pragma statement. So you have just ignored what 2kaud suggested you in his latest post. Originally Posted by Physik)". Where to start... First, I can't fathom why anyone would create a library that passes STL and/or C++ classes between DLL and application like this. You now have to verify that you're using the same compiler, compiler version (right down to the same service pack), compiler options, etc. to ensure that the link will work. This has been discussed on many threads here, with the bottom line being that a library shouldn't pass STL or any C++ objects across DLL/exe boundaries like this. Unless you have complete documentation on the exact build options for your application (and you're using the same compiler), then you're going to get into more trouble trying to use this library. I looked at the dll file using dependency walker. That function that is attempting to be resolved does not exist in that DLL. What exists in that DLL is exactly why my first point is relevant: Code: ?dwt_sym@@YAPAXAAV... See the difference? What you compiled and linked doesn't match the name that's in the DLL. The name is mangled differently in the DLL, meaning that the DLL was built differently. Add to that, the author may have used the _SECURE_SCL=0 macro (which optimizes the STL iterator logic in release versions). If they did and you didn't use that macro (or vice-versa), then at runtime, things will come crashing down. This is the price that is paid when C++ objects and types are passed as parameters instead of standard types such as LONG, LPCTSTR, etc. You now have to basically have the entire set of the compile options you need to set before building your application. Regards, Paul McKenzie ?dwt_sym@@YAPAXAAV... Last edited by Paul McKenzie; July 26th, 2013 at 11:49 AM. Forum Rules
http://forums.codeguru.com/showthread.php?537513-Problems-with-implementing-dlls&p=2119755
CC-MAIN-2015-40
refinedweb
1,039
76.32
PythonCard, Python, and opinions on whatever technology I'm dabbling in these days like XML-RPC and SOAP. It is difficult to manually read a WSDL description of a SOAP web service and figure out which parts you need for your programming language and SOAP library of choice. I was looking for something to take the URL of a WSDL description and produce human readable output that simply says this is the URL for the service, the namespace (if any) that needs to be used, the soap action (if any) that needs to be used, and the list of methods and their arguments. Obviously, this is the WSDL in a different form, but the problem with WSDL is that trying to read WSDL files by hand and actually understanding what the service expects as input is a pain. Simon Fell sent me email with a link to WSDL display tool on GotDotNet. Unfortunately, the script has been down most of the time since I started trying to reach it, it is slow to time out on WSDL that it can't interpret, and so far I haven't had much luck getting it to work with WSDL that wasn't generated from .NET. Then after a bit of searching I found a WSDL verifier, again on GotDotNet. This page gives a clue as to why most of the WSDL I tried to get info on probably failed. For example, try this verification request for the delayed stock quote service on xmethods.net. I've been using this service and others without problems, but the MS .NET tool doesn't like them. So much for interop. [Tony Hong sent me a note that the above WSDL file for the delayed stock quote service is no longer valid and should be: If you try the URL above with the WSDL verifier you'll get a valid result.] My enthusiam for SOAP and WSDL is greatly diminished. Unless you want to use a single vendor, it looks like we don't really have interop yet, the tools need to improve, and quite frankly, using SOAP and WSDL feels like work. This stuff is not ready for prime-time. I would appreciate links to other online validators or WSDL interpreters that do work. The helpful emails I received today give me hope that things will get easier. Mike Stone recommends the Generic SOAP Client that "not only parses the WSDL file, but also generates forms for you to access the defined web service directly."
http://radio.weblogs.com/0102677/2002/02/11.html
crawl-002
refinedweb
420
66.57
How prior versions by eliminating a useless text file describing tests and a useless Manual Test file that I never once used. It still includes a unit test file, which I think is fine, with the name that will never be correct, UnitTest1.cs (though I understand it would be a tough problem to guess a name that might be correct). Let’s look at the default file created: I do appreciate that there is a file created here for me, and that it has the requisite attributes on the class and method, and even uses my project’s namespace. However, I’ve circled all of the bits that are useless and are immediately deleted by me the first time I open this file. Resharper does a good job of highlighting unused code by making it light grey (lines 1-4 and line 15 for instance). The TestContext I never use. And the region full of additional test attributes falls into the category of “good to know if this was my first time” but really a comment listing the 4 attributes I need would be more useful to me. Here’s what that section looks like expanded: Since regions are pretty much evil because they provide places for bad code to hide, I delete this as a matter of course as well. If I were in charge of this template, I would probably replace this whole section with a comment like this one: That cuts the number of lines of code used by these comments in half. And honestly I’m not sure I’d include it at all, but I do occasionally find it useful and I’m sure it’s helpful to users new to testing with MS Test. Once I’m ready to actually start writing a test, though, my file looks like this (from 71 lines of code to 14): Honestly, if this is what I had to start with, it would save me a non-insignificant amount of time and frustration whenever I create a new test. So, rather than complaining about it to Microsoft (who does listen sometimes – note the existence now of an Empty option when creating new ASP.NET MVC web applications), I can make this change myself – and so can you. Here’s what you need to do to customize your Visual Studio project templates. Customizing Visual Studio Project Templates – Create Your Own The simplest way to achieve this is to simply create a new project template and then use that in the future. You can do this by following the instructions on Creating a Template which are (after you have the project how you want it): 1. Go to File – Export Template 2. Choose a template type (I’m doing Project but you could also do this for individual file items) 3. Provide a Name and Description and any icons or preview images you’d like to use. By default the project will automatically be imported for you (but only on this machine, of course). 4. Click Finish. You can most easily locate your new template when you select New Project by using the search box. In my case it was listed under Installed Templates – C# but not within any of the sub-areas under this heading: If you look at what was actually installed into your folder, you’ll find this: Ok, so what if you really do want to change the actual C# Test Project template (specifically, the UnitTest1.cs file within it)? That’s a bit trickier, and unfortunately I’m out of time for this post and it’s gotten long so I’ll see if I can add that as a future article.
http://ardalis.com/how-to-fix-visual-studio-file-templates
CC-MAIN-2014-41
refinedweb
618
64.24
#include "l_bitmap.h" L_INT pEXT_CALLBACK YourFunction(lpFileData, nTotalPercent, nFilePercent, lpUserData) Lets you update a status bar or interrupt the L_DlgOpen function operation. Pointer to an OPENDLGFILEDATA structure that contains loading data for the file currently being loaded. The data in this structure is read only information. An integer that indicates the completion percentage for loading all selected files in the Open dialog. This value will be updated every time a file finishes loading. Valid values range from 0 to 100. An integer that indicates the completion percentage for loading a single file from the selected files. Valid values range from 0 to 100. A void pointer that you can use to access a variable or structure containing data that your callback function needs. This gives you a way to receive data indirectly from the function that uses this callback function. (This is the same pointer that you pass in the lpUserData parameter of the calling function.). Keep in mind that this is a void pointer, which must be cast to the appropriate data type within your callback function. Required DLLs and Libraries For an example, refer to L_DlgOpen. Direct Show .NET | C API | Filters Media Foundation .NET | C API | Transforms Media Streaming .NET | C API
https://www.leadtools.com/help/sdk/v20/commondialog/api/opendlgfileloadcallback.html
CC-MAIN-2020-29
refinedweb
205
58.58
P. What (most) users want What do you want from your computer? This is quite an open question, with a large number of possible answers. Computer users can generally be categorised between two extremes. There are those who just want to type documents, write email, play games and look at porn—all the wonderful things modern PCs make possible. They want their computer to work like their TV/DVD/Hi-Fi, turn it on, use it for purpose, and then turn it off. If something goes wrong they’re not interested in the why or how, they just want the problem resolved. At the other end of the scale there are those who love to tinker, to dig into the bowels of their machine for kicks, to eke out every last ounce of performance, or to learn. If something goes wrong they’ll read the documentation, roll up their sleeves and plunge back in. Where do you as a user belong on this scale? As a Free Software Magazine reader you’re probably nearer the tinkerer end of the spectrum (and you’re also probably asking, what does any of this have to do with free software. Well, bear with me). The majority of users, however, are nearer the indifferent end of the scale, they neither know nor care how a PC works. If their PC works for the tasks they perform and runs smoothly, all is well—if it doesn’t, they can either call up an IT helpline or twiddle their thumbs (usually both). It’s easy to dismiss such users, many problems that occur on any system are usually well documented or have solutions easily found with a bit of googling. Is it fair to dismiss such users? Sometimes it is, but, more often than not, you just can’t expect an average user to solve software or hardware problems themselves. The users in question are the silent majority, they have their own jobs to do and are unlikely to have the time, requisite knowledge or patience to troubleshoot; to them documentation, no matter how well indexed or prepared, is tedious and confusing. They don’t often change their settings and their desktops are crammed with icons. They are the target demographic of desktop operating systems. Ensnared by Windows, afraid of GNU/Linux, they were promised easy computing but have never quite seen it. Can an operating system appeal to these users without forcing everyone into the shackles of the lowest common denominator? Can developers make life easier for the less technically oriented, as well as themselves, without sacrificing freedom or power? Can we finally turn PCs into true consumer devices while retaining their awesome flexibility? I believe we can, and the answer lies (mostly) with GNU/Linux. This article loosely describes an idealised PC, realised through changes in how the underlying hardware is organised, along with the consequences, both good and bad, of such a reorganisation. It is NOT a HOW-TO guide, you will not be able to build such a PC after reading this article (sorry to disappoint). The goal is to try and encourage some alternate thinking, and explore whether we truly are being held back by the hardware. The goal is to try and encourage some alternate thinking, and explore whether we truly are being held back by the hardware The problem with PCs and operating system evolution So what are the problems with PCs that make them fundamentally difficult to use for the average person. The obvious answer would probably be the quality of software, including the operating system that is running on the PC. Quality of software covers many areas, from installation through everyday use to removal and upgrading, as well as the ability to modify the software and re-distribute it. A lot of software development also necessitates the re-use of software (shared libraries, DLLs, classes and whatnot) so the ability to re-use software is also an important measure of quality, albeit for a smaller number of users. Despite their different approaches, the major operating systems in use on the desktop today have both reached a similar level of usability for most tasks, they have the same features (at least from the users point of view), similar GUIs, even the underlying features of the operating system work in a similar manner. Some reasons for this apparent “convergence” are user demand, the programs people want to run, the GUI that works for most needs and the devices that users want to attach to their PC to unlock more performance or features. While this is evidently true for the “visible” portions of a PC (i.e. the applications) it doesn’t explain why there are so many underlying similarities at the core of the operating systems themselves. The answer to this, and by extension, the usability problem, lies in the hardware that the operating systems run on. Am I saying the hardware is flawed? Absolutely not! I’m constantly amazed at the innovations being made in the speed, size and features of new hardware, and in the capability of the underlying architecture to accommodate these features. What I am saying is there is a fundamental problem in how hardware is organised within a PC, and that this problem leads to many, if not all, of the issues that prevent computers from being totally user friendly. There is a fundamental problem in how hardware is organised within a PC, which leads to many, if not all, of the issues that prevent computers from being totally user friendly The archetypal PC consists of a case and power supply. Within the case you have the parent board which forms the basis of the hardware and defines the overall capabilities of the machine. Added to this you have the CPU, memory, storage devices and expansion cards (sound/graphics etc.). Outside of the case you’ve got a screen and a keyboard/mouse so the user can interact with the system. Cosmetic features aside, all desktop machines are fundamentally like this. The job of the operating system is to “move” data between all these various components in a meaningful and predictable way, while hiding the underlying complexity of the hardware. This forms the basis for all the software that will run on that operating system. The dominant desktop operating systems have all achieved this goal to a large extent. After all, you can run software on Windows, GNU/Linux or Mac OS without worrying too much about the hardware—they all do it differently, but the results are essentially the same. What am I complaining about then? Unfortunately, hiding the underlying complexity of the hardware is, in itself, a complex task: data whizzes around within a PC at unimaginable speed; new hardware standards are constantly evolving; and the demands of users (and their software) constantly necessitate the need for new features within the operating system. The fact that an operating system is constantly “under attack” from both the underlying hardware and the demands of the software mean these systems are never “finished” but are in a constant state of evolution. On the one hand this is a good thing, evolution prevents stagnation and has got us to where we are today (in computing terms, things have improved immeasurably over the 15 years or so that I’ve been using PCs). On the other hand, it does mean that writing operating systems and the software that runs on them will not get any easier. Until developers have the ability to write reliable software that interact predictably with both the operating system/hardware and the other software on the system, PCs will remain an obtuse technology from the viewpoint of most users, regardless of which operating system they use. How do operating systems even manage to keep up at all? The answer is they grow bigger. More code is added to accommodate features or fix problems (originating from either hardware, other operating system code or applications). Since their inception, all the major operating systems have grown considerably in the number of lines of source code. That they are progressively more stable is a testament to the skill and thoughtfulness of the many people that work on them. At the same time, they are now so complex, with so many interdependencies, that writing software for them isn’t really getting any easier, despite improvements in both coding techniques and the tools available. Device drivers are a particularly problematic area within PCs. Drivers are software, usually written for a particular operating system, which directly control the various pieces of hardware on the PC. The operating system, in turn, controls access to the driver, allowing other software on the system to make use of the features provided by the hardware. Drivers are difficult to write and complicated, mainly because the hardware they drive is complicated but also because you can’t account for all the interactions with all the other drivers in a system. To this day most stability problems in a PC derive from driver issues. The devices themselves are also problematic from a usability standpoint. Despite advances, making any changes to your hardware is still a daunting prospect, even for those that love to tinker. Powering off, opening your case, replacing components, powering back on, detecting the device and installing drivers if necessary can turn into a nightmare, especially when compared to the ease of plugging in and using say, a new DVD player (though some people find this tough also). Even if things go smoothly there’s still the problem of unanticipated interactions down the line. If something goes wrong the original parts/drivers must be reinstated, and even this can lead to problems. In the worst case, the user may be left with an unbootable machine. The way PCs are organised, with a parent board and loads of devices crammed into a single case, makes them not only difficult to understand and control physically, but has the knock on effect of making the software that runs on them overly complex and difficult to maintain. More external devices are emerging and these help a bit (particularly routers) but don’t alleviate the main problem. An operating system will never make it physically easier to upgrade your PC, while the driver interaction issues and the fact that the operating systems are always chasing the hardware (or that new hardware must be made to work with existing operating systems) means that software will always be buggy. Powering off, opening your case, replacing components, powering back on, detecting the device and installing drivers if necessary can turn into a nightmare If we continue down the same road, will these problems eventually be resolved? Maybe, the people working on these systems, both hard and soft, are exceptionally clever and resourceful. Fairly recent introductions such as USB do solve some of the problems, making a subset of devices trivial to install and easy to use. Unfortunately, the internal devices of a PC continue to be developed along the same lines, with all the inherent problems that entails. We could build new kinds of computer from scratch, fully specified with a concrete programming model that takes into account all we’ve learned from hardware and software (and usability) over the past half century. This, of course, wouldn’t work at all, with so much invested in current PCs both financially and intellectually we’d just end up with chaos, and no guarantee that we wouldn’t be in the same place 20 years down the line. We could lock down our hardware, ensuring a fully understandable environment from the devices up through the OS to the applications. This would work in theory, but apart from limiting user choice it would completely strangle innovation. More realistically, we can re-organise what we have, and this is the subject of the next section. Abstracted OS(es) and consumer devices What would I propose in terms of reorganisation that would make PCs easier to use? Perhaps counter intuitively, my solution would be to dismantle your PC. Take each device from your machine, stick them in their own box with a cheap CPU, some memory and a bit of storage (flash or disk based as you prefer). Add a high-speed/low latency connection to each box and get your devices talking to each other over the “network” in a well defined way. Note that network in this context refers to high-performance serial bus technology such as PCI Express and HyperTransport, or switched fabric networking I/O such as Infiniband, possibly even SpaceWire. Add another box, again with a CPU, RAM and storage, and have this act as the kernel, co-ordinating access and authentication between the boxes. Finally, add one or more boxes containing some beefy processing power and lots of RAM to run your applications. Effectively what I’m attempting to do here is turn each component into a smart consumer appliance. Each device is controlled by its own CPU, has access to its own private memory and storage, and doesn’t have to worry about software or hardware conflicts with other devices in the system, immediately reducing stability issues. The creator of each device is free to implement whatever is needed internally to make it run, from hardware to operating system to software; it doesn’t matter, because the devices would all communicate over a well-defined interface. Linux would obviously be a great choice in many cases; I imagine you could run the kernel unmodified for many hardware configurations. What are the advantages of this approach? Surely replacing one PC with multiple machines will make things more difficult. That is true to some extent, but handled correctly this step can remove many headaches that occur with the current organisation. Here are just some of the advantages I can think of from this approach (I’ll get to the disadvantages in the next section). Testing a device is simpler, no need to worry about possible hardware or software conflicts, as long as the device can talk over the interconnect, things should be cool Device isolation Each device is isolated from all the others in the system, they can only interact over a well defined network interface. Each device advertises its services/API manufacturer (or the tinkering user) needs to do the job, as well as whatever internal hardware they need (though of course all devices would need to implement the networking protocol). Consequently, integrating new hardware ideas becomes somewhat less painful too. Additional benefits of isolation include individual cooling solutions on a per device basis and better per device power management. On the subject of cooling the individual devices should run cool through the use of low frequency CPUs and the fact that there isn’t a lot of hardware in the box. As well as consuming less power this is also great for the device in terms of stability. Other advantages include complete autonomy of the device when it comes to configuration (all info can be stored on the device), update information (again, relevant info can be stored on the device), documentation, including the API/capabilities of the device (guess where this is kept!) and simplified troubleshooting (a problem with a device can immediately be narrowed down, excluding much of the rest of the system, this isn’t the case in conventional PCs). Another upside is that if the device is removed it would not leave orphaned driver files on the host system. Snazzy features such as self-healing drivers are also more easily achieved when they don’t have to interfere with the rest of the system (the device “knows” where all its files are, without the need to store such information). Many architectures Device isolation means the creator can use whatever hardware they desire to implement the device (aside from the “networking” component, which would have to be standardised, scalable and easily upgraded). RISC, CISC, 32 bit, 64 bit, intelligent yoghurt, whatever is needed to drive the device. All these architectures could co-exist peacefully as long as they’re isolated with a well defined communication protocol between them. No driver deprecation As long as the network protocol connecting the boxes does not change the drivers for the device should never become obsolete due to OS changes. If the network protocol does change, more than likely only the networking portion of the device “driver” will need an update. Worst case scenario is if the network “interface” (i.e. connector) changes. This would necessitate a new device with the appropriate connection or modification to the current device. Old devices can be kept on the system to share workload with newer devices, or the box can be unplugged and given to someone who needs it. Isolated devices remove this problem. When a device is no longer used in a PC it is generally the case that it is sold, discarded or just left to rot somewhere. Obtaining needs plugged in and are less likely to be damaged in transit. One of the great features of GNU/Linux is its ability to run on old hardware; this would be complimented greatly by the ability to include old hardware along with new in a running desktop system, something that would normally be very difficult to achieve. Security Security is a big issue and one which all operating systems struggle to fulfil for various reasons. While most operating systems are now reasonably secure keeping intruders out and user data safe is a constant battle. This system would potentially have several advantages in the area of security; the fact that the Kernel is a self-contained solution, probably running in firmware, meaning overwriting the operating system code, either accidentally or maliciously, care must be taken not to compromise the user’s control of their own system. There are several areas of security (denial of service attacks for example) where this system would be no better off than conventional systems, though it may suffer less as the network device under attack could be more easily isolated from the rest of the system. In fact it would be easier to isolate points of entry into the system (i.e. external network interfaces and removable media); this could be used to force all network traffic from points of entry through a “security box” with anti-virus and other malware tools, allowing for the benefits of on-demand scanning without placing a burden on the main system. It is likely that a new range of attacks specific to this system would appear, so security will be as much a concern as it is on other systems and should be incorporated tightly from the start. Despite the introduction of screw-less cases, jumper-less configuration and matching plug colours, installing hardware remains a headache on most systems Device installation Despite the introduction of screw-less cases, jumper-less configuration and matching plug appliance, this system would allow for hot swapping of any device. Once power and networking are plugged into the device the device would automatically boot and be. Increased performance This is admittedly a grey area, true performance changes could only be checked by building one of these things. Latency over the network between the devices will be a bottleneck for performance, the degree of which is determined by the latency of whatever bus technology is used. Where performance will definitely increase though, is through the greater parallelism of devices. With each device having its own dedicated processor and memory there will be no load on the kernel or application boxes when the device is in use (except for message passing between the boxes, which will cause some overhead). It should also be easier to co-ordinate groups of similar devices, if present, for even greater performance. In the standard PC architecture, device activity generates interrupts, sometimes lots of them, which result in process switching, blocking, bus locking and several other performance draining phenomenon. With the interrupt generating hardware locked inside a box the software on the device can make intelligent decisions about data moving into and out of the device, as well as handling contention for the device. More performance tweaks can be made at the kernel level; per device paging and scheduling algorithms become a realistic prospect, instead of the one size fits all algorithms necessarily present in the standard kernel. Device driver development It’s easier to specify a kernel, list of modules and other software in a single place (on the device), along with update information and configuration for the device, than it is to merge the device driver either statically or dynamically into an existing kernel running on a system with several other devices and an unknown list of applications. With device isolation it should be a lot simpler to build features that rely on that device, without forcing too much overhead on the rest of the system Features With device isolation it should be a lot simpler to build features that rely on that device, without forcing too much overhead on the rest of the system. For example, a box dedicated to storage could simply consist of an ext3 file system that could be mounted by other boxes in the system. On the other hand, you could build in an indexing service or a full database file system. These wouldn’t hog resources from the rest of the system as they do in a conventional PC, and would be easier to develop and test. Experimentation with new technologies would benefit due to the only constraint for interoperability with the system being the device interconnect (which would be specified simply as a way of moving data between devices), developers could experiment with new hardware and see the results in-situ on a running system (as opposed to having to connect potentially unstable hardware directly to a parent board with other devices). Users could pick and choose from a limitless array of specialised appliances, easily slotted together, which expose their capabilities to the kernel and applications. Without a parent board to limit such capabilities the possibilities literally are endless. Accessibility This is still a difficult area in all major operating systems, mainly because they are not designed from the ground up to be accessible. Most accessibility “features” in current operating systems seem like tacked on afterthoughts. I’m not sure if this is to do with the difficulty in incorporating features for vision or mobility impaired users or just whether a lot of developers think it’s not worth the hassle accounting for “minorities”, or maybe they don’t think about it at all. The fact that the population as a whole is getting older means that over the next few decades there are going to be many more “impaired” users and we should really be making sure they have full access to computing, as things stand now it is still too difficult for these users to perform general computing, never mind such things as changing hardware or programming. I see a distributed device architecture as being somewhat beneficial in this regard, apart from making hardware easier to put together for general and impaired users, the system is also conducive to device development, with the possible emergence of more devices adapted for those who need them. The many and varied software changes such a system would require would also offer a good opportunity to build accessibility into the operating system from the start, which certainly doesn’t seem to be the case with current systems. The ability to upgrade the processing power of a machine in this way is just not possible with a conventional PC organisation Applications The actual programs, such as email, word-processing and web browsers would run on the application boxes described earlier. To re-iterate, these boxes would generally consist solely of processors, memory and storage to hold the paging file and possibly applications depending on overall system organisation. More hardware could be included for specialised systems. All hardware and kernel interactions take place over the device interconnect, so applications running on one of these boxes can do so in relative peace. Because devices in the system can be packaged with their own drivers and a list of capabilities it should be fairly easy to detect and make use of desired functionality, both from the kernel and other devices. Another advantage would be the ability to keep adding application boxes (i.e. more CPU and RAM) ad-infinitum; the kernel box would detect the extra boxes and automatically make use of them. The ability to upgrade the processing power of a machine in this way is just not possible with a conventional PC organisation. Figures 1 and 2 show front and back views of a mock-up of a distributed PC, mimicking somewhat the layout of a stacked hi-fi system. While this is a workable and pleasing configuration in itself there are literally endless permutations in size and stacking of the components. The figures also illustrate the potential problems with cabling. Only one power cable is shown in the diagram, but there could be one for every box in the system unless some “pass-through” mechanism is employed for the power (again employed in many hi-fi systems). The data cables (shown as ribbon cables in the diagram) would also need to be more flexible and thinner to allow for stacking of components in other orientations. Could the power and networking cables be combined without interference? The boxes shown are also much larger than they’d need to be, for many components it would be possible to achieve box sizes of 1-3 inches with SBC or the PC/104 modules available today. The front view also shows an LCD display listing an audio track playing on the box; this highlights another advantage in that certain parts of the system could be started up (i.e. just audio and storage) while the rest of the system is offline, allowing the user for example to play music or watch DVDs without starting the rest of the system. So, we have a distributed PC consisting of several “simplified” PCs, each of them running on different hardware with different “conventional” operating systems running on each. Upgrading or modifying the machine is greatly simplified, device driver issues are less problematic and the user has more freedom in the “layout” of the hardware in that it is easier to separate out the parts they need near (removable drives, input device handlers) from the parts they can stick in a cupboard somewhere (application boxes, storage boxes). What about the software? How can such a system run current applications? Would we need a new programming model for such a system? There are many possibilities for the software organisation on such a system. One obvious possibility is running a single Linux file system on the kernel box, with the devices mapped into the tree through the Virtual File System (VFS). The /dev portion of the tree would behave somewhat like NFS, with file operations being translated across the interconnect in the background. Handled correctly, this step alone would allow a lot of current software to work. An application requesting access to a file would do so via the kernel box, which could translate the filename into the correct location on another device, a bit of overhead but authentication and file system path walking would be occurring at this point anyway. Through the mapping process it would be possible to make different parts of a “single” file appear like different files spread throughout the file system. Virtual block devices are a good way to implement this, with a single file appearing as a full file system when mounted. This feature could be utilised to improve packaging of applications which are generally spread throughout the file system, I’ve always been of the belief that an application should consist of a single file or package (not the source, just the program). Things are just so much simpler that way (while I’m grumbling about that, I also think Unicode should contain some programmer specific characters; escaping quotes, brackets and other characters used in conventional English is both tedious, error prone and an overhead, wouldn’t it be great if programmers had their own delimiters which weren’t a subset of the textual data they usually manipulate?). There is no shortage of research into multicomputer and distributed systems in general, again all very relevant Software would also need to access the features of a device through function calls, both as part of the VFS and also for specific capabilities not covered by the common file model of the VFS. Because the API of each device, along with documentation, could easily be included as part of the devices “image” linking to and making use of a device’s API should be relatively simple, with stubs both in the application and the device shuttling data between them. A programming model eminently suitable for a distributed system like this is that of tuple spaces, I won’t go into detail here, you can find many resources on Google under “tuple spaces”, “Linda” and “JavaSpaces”). Tuple spaces allow easy and safe exchange of data between parallel processes, and have been used already in JINI, a system for networking devices and services in a distributed manner pretty similar to what I’m proposing, and both Sun (who developed JINI) and Apache River (though they’ve just started) have covered much ground with the problems of distributed systems; most of their ideas and implementation would be directly relevant to this “project”. The client/server model, as used by web servers could also serve as a good basis for computing on this platform; Amoeba is an example of a current distributed OS which employs this methodology. There is no shortage of research into multicomputer and distributed systems in general, again all very relevant. I’m being pretty terse on the subject of running software, partly because the final result would be achieved through a lot of research, planning and testing; mainly because I haven’t thought of specifics yet (important as they are!). The main issue is that applications (running on application boxes) have a nicer environment within which to run, free from device interruptions and the general instability that occurs when lots of high speed devices are active on a single parent board. I’m also confident that Linux can be made to run on anything, and this system is no exception. I’m currently writing more on the specific hardware and software organisation of a distributed PC, based on current research as well as my own thoughts; if I’m not battered too much for what I’m writing now I could maybe include this in a future article. Of course, if anyone wants to build one of these systems I’m happy to share all my thoughts! None of this is really new anyway; there’s been a lot of research and development in the area of distributed computing and networked devices, especially in recent years. Looking at sites such as linuxdevices.com shows there is a keen interest among many users to build their own devices, extending this idea into the bowels of a PC, and allowing efficient interoperation between such devices, seems quite natural. With the stability of the Linux kernel (as opposed to the chaos of distros and packaging), advances in networking and the desire for portable, easy to use devices from consumers I believe this is an idea whose time has come. The platinum bullet At this stage you may or may not be convinced of how this organisation will make computing easier. What you are more likely aware of is the disadvantages and obstacles faced by such a system. In my eyes, the three most difficult problems to overcome are cost, latency and cabling. There are, of course, many sticky issues revolving around distributed software, particularly timing and co-ordination; but I’ll gloss over those for the purposes of this article and discuss them in the follow-up. The three most difficult problems to overcome are cost, latency and cabling Obviously giving each device its own dedicated processor, ram and storage, as well as a nice box; is going to add quite a bit to the price of the device. Even if you only need a weak CPU and a small amount of RAM to drive the device (which is the case for most devices) there will still be a significant overhead, even before you consider that each device will need some kind of connectivity. For the device interconnect to work well we’re talking serious bandwidth and latency constraints, and these aren’t cheap by today’s standards (Infiniband switches can be very expensive!). Though this seems cataclysmic I really don’t think it’s a problem in the long term. There are already plenty of external devices around which work in a similar way and these are getting cheaper all the time. There are also the factors that it should be cheaper and simpler to develop hardware and drivers, which should help reduce costs, particularly if the system works well and a lot of users take it on. Tied in with cost are the issues of redevelopment. While I don’t think it would take too much effort to get a smooth running prototype up, there may have to be changes in current packages or some form of emulation layer to allow current software to run. The second issue, latency, is also tied up quite strongly with cost. There are a few candidates around with low enough latency (microsecond latency is a must) and high enough bandwidth to move even large amounts of graphical data around fairly easily. The problem is that all of these technologies are currently only seen in High Performance Computing clusters (which this system “sort of” emulates, indeed, a lot of HPC would be relevant to this system) and cost a helluva lot. Again this is a matter of getting the technology into the mainstream to reduce costs. Maybe in ten years time it’ll be cheap enough! By then Windows will probably be installed in the brains of most of the population and it’ll be too late to save them. Interconnecting several devices in a distributed system will involve a non-trivial amount of cabling, with each box requiring both power and networking cables as well as any device specific connectors. Reducing and/or hiding this, and making the boxes look pretty individually as well as when “combined” will be a major design challenge. Another possible problem is resistance, people really don’t like change. The current hardware organisation has been around a long time and continues to serve us well, why should we rock the boat and gamble on an untested way of using our computers? Integration of devices on a parent board was a practical decision at the time it was made, reducing the cost and size of PCs as well as allowing for good performance. With SBC (Single Board Computers), tiny embedded devices and cheap commodity hardware, none of the factors which forced us down this route still apply. Linux doesn’t dictate hardware and even though this system would give more freedom with regards to hardware it does require a change in thinking. A lot of work would also be needed to build this system (initially) and the benefits wouldn’t be immediately realisable in comparison to the cost. My main point though is that, once the basics are nailed down, what we’d have is an easy to use and flexible platform inclusive to all hardware (even more so than Linux is already). Interoperability would exist from the outset at the hardware level, making it much easier to build interoperability at the software level. With such a solid basis, usability and ease of development should not be far behind. The way things are going now it seems that current systems are evolving toward this idea anyway (though slowly and with a lot of accumulated baggage en-route). One of the first articles I read on FSM was how to build a DVD player using Linux; this is the kind of hacking I want this system to encourage. Imagine a PC where all the hardware is hot-swappable, with drivers that are easily specified, modified and updated, even for the average user Welcome to the world of tomorrow With Linux we have an extremely stable and flexible kernel. It can run on most hardware already and can generally incorporate new hardware easily. The organisation of the hardware that it (and other operating systems) runs on however, forces a cascade effect, multiplying dependencies and complexities between device drivers and hence the software that uses those devices. The underlying file paradigm of Linux is a paragon of beauty and simplicity that is unfortunately being lost, with many distros now seemingly on a full-time mission of maintaining software packages and the dependencies between them. Imagine a PC where all the hardware is hot-swappable, with drivers that are easily specified, modified and updated, even for the average user; a system where the underlying hardware organisation, rather than forcing everything into a tight web of easily broken dependencies, promotes modularity and interoperability from the ground-up. A system that can be upgraded infinitely and at will, as opposed to one which forces a cycle of both software and hardware updates on the user. A system truly owned by the user. The Linux community is in a fantastic position to implement such a system, there isn’t any other single company or organisation in the world that has the collective knowledge, will or courage to embrace and develop such an idea. With the Kernel acting as a solid basis for many devices, along with the huge amount of community software (and experience) that can be leveraged in the building of devices, all the components needed for a fully distributed, Linux based PC are just “a change in thinking” away. What would be the consequences if distributed PCs were to enter the mainstream? Who would benefit and who would suffer? Device manufacturers would definitely benefit from greatly reduced constraints as opposed to those currently encountered by internal PC devices. Users would have a lot more freedom with regards to their hardware and in many cases could build/modify their own devices if needs be, extending the idea of open source to the hardware level. Large computer manufacturers (such as Dell) could stop releasing prebuilt systems with pre-installed operating systems and instead focus on selling devices with pre-installed drivers. This is a subtle but important distinction. One piece of broken hardware (or software) in a pre-built desktop system usually means a lot of talking with tech-support or the return of the complete system to the manufacturer to be tested and rebuilt. A single broken device can be diagnosed quickly for problems and is much less of a hassle to ship. What would be the impact on the environment? Tough to say directly, but I suspect there would be far fewer “obsolete” PCs going into landfill. With per device cooling and power saving becoming more manageable in simplified devices things could be good (though not great, even the most energy efficient devices still damage the environment, especially when you multiply the number of users by their ever-growing range of power-consuming gadgets). A single broken device can be diagnosed quickly for problems and is much less of a hassle to ship Big operating system vendors could lose out big-time in a distributed Linux world. In some ways this is unfortunate, whether you like them or not those companies have made a huge contribution to computing in the last couple of decades, keeping pace with user demand while innovating along the way. On the other hand, such companies could start channelling their not inconsiderable resources into being a part of the solution rather than part of the problem. It might just be part of the Jerry Maguire-esque hallucination that inspired me to write this article, but I’d really love to see a standardised basis for networked devices that everyone would want to use. I think everyone wants that, it’s just a shame no-one can agree on how. Brilliant Idea! With this Brilliant Idea! With this you could re-arrange a computer into a media player, then arrange it back again. You've stumbled onto something big. I hope the hardware makers are reading this. I imagine them looking like CD racks Great idea Matthew and well thought out. I can picture these PCs looking like CD/DVD racks - each component slotting into the rack and taking up one or more slots. No need for cables. How easy would the hot-swapping of components be if you just have to push-and-pop each one in/out? If you run out of room you buy a bigger rack. I'm sure I've seen some sort of prototype or mock-up of this idea somewhere but they used books on a shelf rather than CDs in a rack. Asus Modular PC Found this link regarding the Asus Modular PC, possibly the mock-up you were thinking of? *Very* similar to what I've described in the article (and nice to find something backing up what I've written, I'm getting kinda excited now :)). Though still in the concept stage the idea of powering the devices by induction from the shelf is brilliant, though I have to admit I personally don't like the bookshelf layout (but admit again I can't think of anything better atm). Pure wireless connectivity (as opposed to a combination of wired and wireless which I assumed), though very conducive to usability, was something I discounted for the immediate future due to latency and bandwidth (I wanna play games on one of these things!), but is something I'd love to see just to get rid of those damn cables :) I'm currently writing a follow-up on exactly how the components of a modular system could work together with a heavy slant on simplicity (and using open source components). That's the one That's definitely where I saw it. The CD rack picture I have in my mind is prettier than their shelf design. I can also imagine people providing skins for the individual units so you can "theme" your machine. hypertransport I'd wonder a while ago why no one has done this. Especially as home media systems started to emerge My solution to those ungainly wires at the back is simple to have a protrusion from the top that slots into the bottom basically being a bus. Probably using removable cartridge style items that can also be pulled out to push in a nice top/bottom plate. A stack of interlocking bricks. My plan was to make use of the AMD hyper transport intended to provide high communications between servers or extended the PCI bus up. Comment removed by user. Comment removed by user. That is a really great idea, That is a really great idea, but I think that there are some problems. The idea, that indexing service could be integrated into the storage box, seems to be a good one at first. At closer examination it revealed a weak point. I imagine there would be a communication protocol that regulates how to talk to storage devices. At first it probably wouldn't include indexing services specific commands, but when a storage box integrates such a service it would still need drivers to provide new commands over the old standard. Finally the protocol probably would be updated to facilitate those kinds of commands, but every time something new is implemented drivers would still be needed. So it is kind of the same as at the moment. What do you think, is there a way to relieve that problem? Another thing: i have nothing against Linux, but reading the article this Linux evangelism was just a bit annoying. This kind of articles should be written without preferring any present operating systems as this system would probably need a new kind of software anyway. Not a problem While this is a very important question that needs to be answered early in the design of such a system, I believe it is a non-issue. Think of the way the HTTP protocol works in conjunction with a browser and a server. This protocol, while it's been extended a bit over the years has remained pretty stable. All the user does (via the browser, or even the command line) is request a resource with a unique id (it's Uniform Resource Name, which covers the protocol used, http or ftp for example, as well as it's location, the host, and finally the requested resource). When you make such a request, your browser identifies the host for the resource (through DNS) then makes a connection to the host (through whatever protocol identified in the URN) requesting the resource. From the point of view of the browser it doesn't matter *how* the server provides that resource, it will either get the data in the expected format (e.g. HTML) or it will get an HTTP error code. From the point of view of the server; it gets requests for resources which it either honors or returns an error for (or is timed out on the browser or server side). Now the server is a black box, the resource requested could be a static file, a virtual file or even a proxy request to another server. That image your browser requested could just be a static .png or generated from a script, it doesn't matter to the browser, all it gets is what it asked for. Well run web servers update their internal configuration all the time, particularly as their userbase increases, updating their version of apache (or IIS), changing from sqllite to mysql (or from Access to SQLServer), adding an indexing daemon, even splitting into a cluster; the list of things that can be done internally to a webserver are endless, and the point is (aside from downtime and potential bugs) these changes have no impact on the end user (browser). Things may be going on differently behind the scene but the browser makes requests in the same way and gets what it asks for. And note specifically that NO change to the HTTP protocol is required, even though the services and data offered by the webserver may have changed. Extending the web analogy to the distributed system; i imagine all the devices in the system acting as servers (and clients) with the 'kernel box' in my article acting in a way similar to a dns server (in that it routes requests for a resource to the proper device or application; but looking like a file system, in that instead of domain names you'd have a (virtual) file (e.g. /dev/storagebox), all requests for files to /dev/storagebox (e.g. /dev/storagebox/myfile) would be processed by the relevant device (or application), in the case the storage box would receive a request for /myfile which it can process internally any way it wants. A shorter way of saying this is it would probably work in a manner similar to NFS, but with optimisations for the fact the the network is very fast and very local. Management and configuration on the device (such as an indexing service) can be handled in the same way (continuing the web analogy you have things like webmin which serve exactly this kind of function). On the issue of updating the drivers for the device. Of course there will be software updates required for the devices. Security fixes, performance updates, feature changes are all facts of life in the software world and they won't disappear whatever system you're using. Where this kind of system really scores though is that updates to the device do not impact or interact with the rest of the system. The updates are internal to the device and cannot affect the rest of the system (except indirectly in what the device offers to the system) in the same way a driver update might (like say, clobbering a file; or a buggy interaction with the kernel). Fundamentally a storage box on this system would work like any NAS (network attached storage) device available today, even in the home market (see). Updating these devices is a doddle as the update consists of a single image file (containing whatever is going to be running on the device, including operating system and software) that is flashed straight onto the device. So the device can be suspended from the system (not serve any requests temporarily), flashed then reinstated without having to power down or reboot the entire system. Backup up images also mean a rollback in case of problems is trivial, these backup images could be stored elsewhere on the system and/or in a hidden partition of the device (the way many hardware providers provide rescue solutions for home systems now). The real software issues to solve on such a system boil down to parallelism, such as co-ordinating timing of audio output (on an audio device) with video output (to the screen) when playing say, a video stream. This of course would be a nightmare if the data were moving over a network with high variable latency (such as the internet), but the fact that much of the work is local on a high-speed, low-latency network (essential for such a system) means in my mind that they are solvable in software. Deadlock and general contention issues must also be resolved, though the theory and implementation of those doesn't really differ that much from current multi-threaded/multi-processor/multi-core systems. On the issue of Linux evangelism. I'm sorry if my article came across this way, I'm pretty adamant that device manufacturers (including users who build their own devices) should have free choice in what they use to implement the device, whether they choose free software or proprietary should be irrelevant to the system, and will really only affect how they build their device and the costing of their device. This system would never work if vendors were forced down a particular route in their implementation. I'd love to see XBox 360s, washing machines, *any* kind of device working in this system, and the only requirement on those system to participate should be the ability to talk over the protocol (and appropriate connectivity, either directly or through an adapter). This doesn't exclude other systems, in fact it welcomes them. The reason my article states 'the answer lies (mostly) with GNU/Linux' boils down to the following facts. -- Linux runs on more architectures than any other operating system. This greatly opens up the implementation choices for vendors, and is the reason why so many consumer devices run Linux internally. -- The Linux kernel is free as in beer. Many manufacturers already exploit this fact to build cheaper devices. I don't personally have much in the way of cash so if I was knocking something together I'd pretty much *have* to use Linux. -- The Linux kernel is free as in speech. Source code is available and can be modified for purpose. Essential when building specialised devices, you can take the source code and start from there. Also essential for home hackers building their own devices, if you can't get working source code for your device you aren't gonna get past the first bend. -- The Linux Kernel marches on. The kernel is constantly being improved with newer versions, but the older version continue to have patches supplied for fixes and improvements, thanks to the open-source community. Proprietary systems generally don't offer this level of support for 'obsolete' versions of their software (as is now happening with Windows XP). This is necessary for a distributed system because a device manufacturer may incorporate a particular kernel version into their device. This version of the kernel may never need to be updated for the device as it may not need the features offered by newer versions (which would simply add bloat and work for the device manufacturer); however, bugs can and do appear and they will need to be fixed, it's a hell of a lot easier to achieve this if you're running a Linux kernel on the device. These factors would simply make Linux a great choice for many device makers (as it is now) but it does not in any way prevent the use of other operating systems (as my article says) and would likely result in most of the devices in the system running Linux (hence, mostly linux) but wouldn't exclude any architecture or device operating system from the party. In fact there's no reason at all why the kernel box of a user's system couldn't run embedded windows; as long as the 'implementors' don't make subtle changes to how the overall system works to ensure broken interoperability (ok, i'm being a bit bitchy there). Take a look at to see that windows does just fine in the area of devices, also check to see the Linux powered counterparts. More important than any of those factors above is the absolute necessity that this system is completely open and not controlled in a proprietary way by a single company; it should be a free and easy standard to implement by anyone. The 'system' wouldn't really be Linux (or any other os for that matter), it's really no more than a software layer for connecting devices (with their own internal operating systems) in a well-defined way and possibly over well-defined transport mechanism(s). You've sort of made me jump the gun a bit, I am currently writing a followup that goes into more detail on this; but that could be a good thing in a way. What I'm essentially hoping for by writing this stuff is that enthusiasts and the big brains out there will embrace this idea (at least in principle) and come up with a cracking protocol that works and works well. In terms of Linux the kernel and current software are there to be used, and i'm sure at least a proof of concept prototype could be cobbled together with a bit of work. I have my own ideas and a relatively broad knowledge base (bit shallow in places :o) but I'm just one guy and there are many ways this system could be built; and as you say with the possible requirement of a new programming model a definite possibility it's best to get a lot of input on how willing people are to work on this. Phew, quite a long post, hope it actually answers your questions! Thanks for your input and congratulations, you're one of the first contributors to the cause! Brilliant What a fantastic idea, the modules could be designed by different artists to make an artistic display, either just nicely colour or with different images/patterns to make your PC a work of art as well as one of genius. This idea should definitely be invested in by a major player. Lets hope the developer gets his fair share. :o) Hehe, turns out this is one of my friends. The point is a great one though, for many people the visual look of the system will be very important, and would give manufacturers the opportunity to produce a 'suite' of devices unified in aesthetic, while allowing the pragmatists to stick with a bunch of grey bricks. Optical network It would be nice if the component computers could communicate optically. It avoids a lot of EMI problems, and the bandwidth ought to be sufficient for almost anything. Agree Yeah this is something definitely worth considering. I'm not absolutely certain at this point whether it would be best to just define a protocol and let market forces (and performance requirements) determine the best connectivity options; or set a connectivity standard from the start (which would make things a lot easier *if* device manufacturers could be convinced). Though I'm a bit wary of telling people what to use (the whole point of this system is that people can use the hardware and software they want) I sort of lean toward the latter. The interoperability of the devices over the 'network' is so important that perhaps it should be set 'in stone'. Optical would be right up there in a list of candidates for this, but there also definitely a need for wireless connectivity there too. Bandwidth is a very important consideration (particularly for the way I anticipate graphical data moving around the system) but there's also the issues of cabling, latency (I'm not sure about the numbers for optical networks, but I imagine they're pretty good) and also aesthetic appeal. Parts already exist (sort of) I was thinking about this and couldn't get past the problem of cost and explaining the concept to your average Joe: "So I have to buy a new computer if I want to open my email?" But then I realised that parts for this system already exist, namely the iPod. It works by its self and I'm sure it would only take a firmware update to make it in to soundcard with usb(or what ever protocol takes your fancy) connectivity. There must be simmilar consumer devices. I think a good analogy for the system is the Power Ranger (bare with me). Seperatly they all have their own skills, but put them together and they make a giant that's greater than the sum of its parts. Absolutely but... The parts do already exist, you're absolutely right. And putting them together does result in a gestalt system. But this is no different from a current PC. All the same parts will need to be bought (optical drives, graphics cards, sound card, network card (for interfacing to any networks 'external' to the system network) as they are in a current PC, and they all add capability to the system (again, as with a current PC), where this system improves on the first is they should be a lot easier to manage and a lot more stable because of their isolation (interaction over a unified well defined 'network') and their 'intelligence' (because they'll generally have their own processing and storage resources making them more adaptable than a 'standard' device. The other advantages are you can keep on adding devices, certainly far more than achievable on a standard PC, and having a standard communication protocol means integrating new kinds of devices should be easier as the main compatibility target to aim for is support for whatever network standard is decided upon (theoretically you could add a quantum processing box transparently to this system when the technology becomes a reality, upgrading a PC of today would involve scrapping much of your current system). These advantages do come at a price though, because of the price overhead for having processing and storage resources in the device. I think I say in the article this could be offset somewhat by a cheaper development process for the device, if not I've just said it now. The Power Ranger analogy is a good one, you could probably even build one of these systems to look like one (storage devices for arms, the kernel and application boxes as the body and a webcam for a head :o) Thanks for the comments so far Thanks to everyone who've posted (and those who may post). Gonna get back to work and will continue writing the followup for anyone who is interested. I'll check back on any comments and incorporate them into my article if possible, but won't be replying to anymore unless they're really pertinent (or a follow up to any questions I've answered above). As you may notice I have a tendency for long expanses of text and I don't want to spend the next three years writing replies :o) Forgive me if I'm wrong, and I think I speak for everyone here in saying that I don't see how having a dishwasher plugged in to my xbox 390 or whatever it is in the future is going to help anyone at all. It's science fact turned in to science fiction!!!! John Sargeant we meet again! Get back to trolling on the flash and knight-rider forums my friend, this is not the place for your hi-jinks :o) I am already doing this, in I am already doing this, in a much more inelegant way, with a handful of old conventional PC's. The boxes are, for the most part, hidden away, the central heating control box is hidden in the heating cupboard and linked with CAT5 cable, the printer and scanner box is also in that cupboard while the scanner and printer usb cables pass through ducts to the office above. I have 6 other old boxes doing specialist jobs but all out of sight, and 2 main new boxes as workstations for doing 'stuff' and where I can check/alter the other 8 systems from. As I have not used winblows for years I am not sure if the system would work in an M$ enviroment, especially the older and smaller boxes. Linux is, in my case, the most obvious choice currently though I will admit that something new, not yet thought of perhaps, may be even better at integrating such a system. Ideally all these boxes would become like the small modules you talk about and actually be part of the fabric of the house with a plasma display in each room and voice control replacing keyboard and mouse. If I live long enough to see it I will be surprised. First steps This post really got my juices flowing, learning of someone who's 'rolled their own' system in this way gives me great hope that a workable distributed PC could be achieved for the masses. I imagine you had some difficulties and a lot of learning to get through to get this stuff working; and I would really love to hear more about it, such as how your boxes are setup to talk to each other and what each box does, even pics, perhaps posted onto your blog and linked back here. Would be great for me to have a look through, but only if you can be bothered :o). As I may have mentioned I'm writing a follow up detailing how I think the system should work from a user point of view, stuffed with a bit more technical detail, and it would be great to have the benefit of your experiences to refer to. You are a pioneer sir and I salute you! Novel? Not hardly.... First as a concept, yes its ok. But I have to tell you -- you ain't the first. The very idea you are promoting is Commodore64 write large for todays market. If you will recall, if you are old enough, is that you bought a component CPU/keyboard module from Commodore. The Commodore had IO code written to understand device level components. Add a hard drive, all the logic and the processing power for the drive was in the drive module. Want to dial out? You could buy a Modem and its supporting terminal software all built into the unit. You could string all these modules together with what would look like a SATA cable today. The idea has been around since the 1980's. Finally, up to a point I think this idea is heading in a direction opposite that of the market. I can for $200 buy a small sealed terminal like device with all the IO (parallel, serial, usb, etc) I could want. It boots a remote linux distro. All my apps reside external -- out on the network. The other trend that will help you though is the idea of virtualization. Soon when most PC's have 4-8 uC's in them, multiple virutal OS's will be the norm. At that point the view from the end user is that any OS they use is nothing more than a file instance on a drive or network somewhere. When the Host layer is very thin indeed then you will have achieved the file centric OS model to some degree. Heh, yeah the good old Heh, yeah the good old Commodore64, what a joy. Being quite young and totally skint at the time, I never had the joy of attaching any peripherals to my base unit (aside from the included tape player and a joystick) so I've never experienced this particular facet, but it's great to know it worked like that! On the subject of being first I'm sure you're quite right about that, Asus posted a mock-up of a similar system a few months before my article, Sun's JINI has been around a while, also taking a device-centric approach; going back even further to the 60s and 70s you've got the Modular One system (), a mini-computer built up from smaller modules. The idea certainly isn't new, and not particularly feasible for desktop systems up until recently. What makes the idea important now (at least in my opinion) is the huge tide of connectible devices already available, along with the predicted surge of new devices in the near future; if like today they all go their own way with their own protocol and hardware interconnect things are gonna get incredibly messy. Couple this with the already massive interoperability problems that exist today, particular for software running on 'standard' desktops (WinLinMac) all cramped in a single box and interfering with one another in largely unpredictable ways; and the dozens of different ways software and hardware can talk to each other (again, causing unpredictable interference with other hardware and software), and the need for a simple, clean, STANDARD way of connecting our hardware and software becomes clear. On your comment regarding thin-terminals, with apps out on the network; there's nothing in this design (distributed hardware) that precludes such a setup. Remember the idea is that a user can build (or buy) the computer they want; if you're blind you probably won't want a graphics device, if you prefer to work from a thin-terminal over the wire you can do that too. All 'my design' is stipulating is that the devices and software involved should speak to each other in a 'common tongue', what those particular devices and software actually do, and how they work internally, is up to the device vendor. I wrote a bit about using a modified version of HTTP for inter-device/application communication at ()that discusses this particular topic. I've also been having words at (), if you can make it through this epic thread (long posts, bit of trolling, bit of arguing) there's more detail as well as some arguments about specific issues. The fact that apps are external, out on the network, in this model works well with the idea of distributed hardware, and the idea of being able to reference anything (hardware features, applications, files) using the URI mechanism (or any mechanism that could be agreed upon) would be a major and compelling step in interoperability. Virtualisation (also discussed on the thread at linuxsucks.org) could be a useful tool for device vendors, one of the issues discussed involves reconfiguring your machine on the fly, for instance only running your audio and storage device for playing music without having the rest of the PC running. Virtualisation would allow device vendors an easy way to switch configurations of a device to provide this kind of functionality. Whether a particular device vendor used this approach or not would of course be up to them, for some devices it may be better to switch configurations for whatever OS is running inside the device, rather than switch to another Virtual OS within the device. one question? Laptops? All this works great for desktops, but how do you combine this effort with the needs of having small mobile and power efficient devices? As far as I'm concerned a As far as I'm concerned a laptop is just a PC with tighter integration and a different shape. Everything I've said in the article regarding desktops is equally applicable to laptops. Remember that it's now possible to buy a complete PC that's only a couple of inches square, so building a series of devices to fit within a laptop isn't much of a stretch, in fact a lot of laptops are now built out of 'modular' components (each in their own box) already. Two main concerns with laptops are of course energy efficiency and weight. In terms of energy efficiency the arguments I applied in the article still stand for laptops; the fact that each device has its own CPU and 'network' connect do mean that individually they will consume more power than a 'naked' device, but remember in the modular system the devices could be powered down more intelligently and independently, and there isn't a single large parentboard/CPU in this design, another factor that may reduce overall power consumption. Hard to tell one way or the other whether *overall* power efficiency would be better or worse, experimentation would be needed to verify that, but personally I'd favour the ability to power down the majority of my machine if those parts weren't in use. Weight is a sticky issue, I certainly imagine a laptop built from distributed devices would weigh in much heavier than the equivalent integrated ones we get now; aside from filling the modules with helium this may be a tricky one to fix, though given current rates of miniaturisation (the 2inch square PC I mentioned above) I'm sure a solution could be found. If laptops did follow a similar pattern to the desktop in this case it would be great if the components were shareable between them, such as unplugging a storage unit from your desktop and sticking it into your laptop, and also for the laptop (and all its devices) to integrate with the desktop when docked or in range. This is part of the 'lonely device' problem that I think a standardised distributed system would help with; I've got a PC, DVD player, PS2 and TV, some connect to each other in a standard way, others have to be co-erced; if they all used the same interconnect and the same protocol to talk there'd be no reason why your PS 2 couldn't make use of processing cycles on your PC and vice-versa (or DVD or any other suitable device). There are several connectors on the back of a TV, SCART, VGA, HDMI; personally I'd much prefer it if my TV plugged directly into a 'network' of my other devices, so that apps and other devices could just stream data over one interconnect/protocol, I'd like my DVD player, laptop, any device I purchase to work this way, things would just be so much easier if the big players worked on such a standard. Linuxsucks.org For anyone who's interested, I've been discussing the article at Some trolling, arguing and a few VERY long posts (my fault, sorry). Novatium India is a paradox. You have a fast growing technology sector with a vast majority of the population still wallowing in poverty. They can build nuclear bombs but millions are still unable to feed themselves regularly and have to resort to selling their organs in Europe and America. As part of the effort to bridge the digital divide, Novatium, working parallel with John Negroponte's $100 PC initiative has developed their own NetPC appliance at $70 without the monitor. The thin client type apparatus requires a fairly fast Internet connection to fully optimize its use. An alternative product they manufacture--NetTV--can receive cable signals and will provide PVR functions together with desktop computing. In essence you'd need a central server to use the NetPC or a software service provided through the user's Internet service provider. Device expansion is provided via USB 2.0 ports. The appliance itself consists of components normally used in cellular telephones. The system has been used in depressed areas where access to PCs has been difficult because of the cost of the standard desktop. It has also been deployed as a smart home solution with emphasis on home entertainment. Aside from high-end, processor intensive apps, the system will allow you to do anything a normal desktop can. For a lot of people, this is enough. I imagine this type of paradigm--along with your component-based PC idea--would make up the next generation of computer systems. NetTV is one of those ideas NetTV is one of those ideas that fits in nicely with what I'm proposing, with a user's computer consisting solely of the devices and software needed to do its job. As you say a device providing for standard home use and entertainment would be enough for many users, in effect meaning they'd only need one device, but in a distributed system more hardware can be added according to the needs of the individual user, so a distributed, standardly (couldn't think of a better word there :) connected paradigm can serve an entire spectrum of users with entirely different computing needs, while still retaining the very important characteristics of simplicity in terms of connecting devices/software and having them talk to each other in a standard way. The idea of using components from mobiles is particularly interesting; I discuss in my article the ability to switch configurations so that if you're for example just playing music you can reconfigure your machine on the fly so only the audio and storage (where your music resides, either on an optical drive or storage device) are powered up and active. Having a small display on such devices would be extremely useful, and the low power screens used on mobiles are ideal for this kind of function. Thinking of the millions of discarded mobiles every year it would be fantastic if at least part of those devices could be recycled for use this way, and devices having their own mini display like this would make them more portable and viable as standalone appliances, increasing the flexibility of the overall system into which they're connected. This brings me to another point I mentioned in the article, because the devices are in effect appliances in their own box (as opposed to naked expansion cards) a device one user considers 'obsolete' in the richer western countries would still be of enormous value to those in poorer or deprived areas, and the fact that such devices would have a standardised connector means such discarded devices could still be useful to say, a user in India, and could be attached to his/her system without difficulty. In the normal course of things an obsolete naked expansion device would probably end up in the bin, but a boxed connectible device could be shipped off to someone who can make use of it. Plan-9 from Bell Labs a distributed OS Hi there, I believe the system design is not new from a software/OS standpoint.Bell Labs, the cradle of Unix (and in extension Linux) has developed Plan-9 a distributed OS (). K<0> Hi Conficio+ A few different Hi Conficio+ A few different topics here so I'll reply to each separately... I believe the system design is not new from a software/OS standpoint.Bell Labs, the cradle of Unix (and in extension Linux) has developed Plan-9 a distributed OS () It's quite funny, about 3 years ago I downloaded Plan9 and had a play with it, long before I even had the idea of writing this article. I didn't read any of the documentation and had no idea it was a distributed OS until your comment, guess this aspect isn't readily seen if you're running it on a single PC as I was. Didn't consider it a viable OS alternative at the time so ended up removing it, but after reading your comment I may give it another try just to see how closely it matches what I've been writing about. Based on Plan9's documentation I can see a number of similarities. The basic design principles; consistent naming of resources, as well as a standardised protocol for their access, are strikingly similar, but then, they should be, these two steps are pretty much mandatory if you want a simple distributed system. How these principles are implemented however, differs to a large extent between what I'm proposing and what Bell Labs have achieved with Plan9. Firstly, while Plan9 has a standard messaging protocol (9P) there is no assumption about the underlying network (other than it will be unreliable). To this end, a reliable transport protocol needs to be added (in the case of Plan9 they use IL, again, a protocol designed by the Plan9 people, designed to serve a similar purpose to TCP but without the overhead). The upshot of this is that Plan9's networking protocol can work over any transport (Ether, USB etc) and so the 'devices' in Plan9 can be connected together by a variety of cables while still ensuring reliable transport. In contrast, what I'm proposing is not only a standard networking protocol (like 9P) but also a standard network connection and transport. The main reason for this is simplicity, rather than having a multitude of connectors, and the necessity of having the correct ports on the machines to be networked (and that means extra software inside the boxes to account for all possible 'network' hardware, ethernet drivers, TCP, Plan9's IL, USB etc), there should be a single (read idiot proof) way to connect devices together, ideally with as little impact on the host systems as possible in terms of required 'drivers'. One example I cite is Infiniband, this technology has high enough bandwidth that even uncompressed video could be shunted about with relative ease, low enough latency to be usable, and with reliable transport provided at the hardware level rather than through the addition of a transport protocol. If USB could somehow achieve the same performance as Infiniband it would be an even better choice, as USB incorporates power transfer too. A second important difference is in the definition of distributed for these two systems. I may be wrong about this but the impression I get from the Plan9 docs is that it is more a centralised time-sharing system, users have a terminal or workstation through which they interact, but all the work takes place on those centralised CPUs, in a way similar to the standard Unix setups you tend to see in research institutes and academia. To this end all machines (devices) in a Plan9 distributed computer all need to be running the Plan9 kernel. Contrasting with what I've written, machines (devices) in the network can run any operating system internally, with the requirements being instead that the device must implement the network protocol AND the network hardware, but apart from that can run any software it wants internally that helps it do its job. For the actual protocol I also consider something such as HTTP more viable than a new protocol, see (), for more details, quite a bit of preamble in this post, but about halfway down there's a more comprehensive description of how I see the system working. HTTP may seem like an odd choice for the transport protocol, but in combination with the right networking (i.e. something like Infiniband) I believe it would expose great power between devices while still being relatively simple both to implement and use, HTTP also gives the advantage of combining resource location and namespacing (through URLs) with the networking protocol as well as being already familiar to a large number of developers and users. Also note in that post the simplicity of the file system, this is another necessary step I consider important, and is something that in my opinion all current systems have a problem with. Plan9 solves this by using namespaces to restrict a users view of resources to only those that are currently relevant, in contrast with what I'm proposing where resources are hidden in the devices and the URLs exposed by the device signify resources available to users (if you can't see the difference here bear in mind that manipulating the users namespaced resources requires work on the part of the kernel, whereas using URLs to access internal device functions does not). Also note in the file tree I describe how each device has management and configuration URLs; apart from providing simple, likely HTML based configuration screens for the device these URLs would also allow for direct access to the underlying device in a similar way to telnet or SSH, for if the user does need to get at the underlying operating system.. Yes, this is potentially a major stumbling block as mentioned in the article, and is a problem with any distributed system (Plan9 included), in fact, cabling is a big problem in current PC system, there are far too many plugs and cables even now (though of course a distributed system would definitely be worse in this respect). Ideally power should be transferred through devices using the same cable as networking (a la USB) though it may prove more difficult to incorporate this into a standard such as Infiniband. Pass through power is also another option, though of course this doesn't alleviate the cables. Wireless is yet another option for both networking and power (there have been recent demonstrations of wireless power transfer). I would see such a system using both wired and wireless transfer, which possibly further exacerbates the cabling and power problems, and wireless has a long way to go before it could fulfill the latency/bandwidth requirements of a distributed system as I describe. This is another reason (apart from greater simplicity for the user) why we absolutely need to standardise a networking/power interconnect for devices, both wired and wireless, not only to clean up the cables, but to make it trivial for users to plug things into each other (by far the most important factor in my opinion). On the matter of power, remember that these devices will generally have low power requirements individually, as well as being more cleanly detachable from the system, it may be possible that overall power usage is reduced on such systems, we'll never know until one is built.. Yep, there is in my view too definitely a need for simpler and easier ways to connect devices, apart from external devices that all have differing connectors the internal devices such as graphics cards have all the problems I describe in the article. Not sure about a combination cable, while it could be useful for a conventional PC it would introduce great inflexibility into a distributed system as I describe it, what if the user is blind for intstance and doesn't have a mouse, graphics device or monitor, that combination cable is gonna start looking pretty messy.. This is one of those grey areas. While having a graphics card in the monitor is ostensibly a logical and good idea, and provides several advantages as you describe, there are several disadvantages. Firstly, what happens when the graphics card is no longer powerful enough for the latest games, a complete monitor replacement is necessary, which sort of eliminates the cost savings for the user. Another option I'd like available for a distributed system is also multiple graphics devices, allowing for redundancy and concurrent (and hence faster) usage. If the graphics devices are in the monitor this obviously becomes problematic. One possible solution I discuss at linuxsucks.org, which matches what you say but in a slightly different way, is to have a 'screen manager' within the monitor. Really this is what you describe, a graphics device in the monitor, matched to the capabilities of the monitor. However, this graphics device does not do general graphical operations in the same way a conventional graphics card does, and instead focuses on composition. Applications on the system send their bitmaps to the monitor, where the internal graphics card composites them for display. The applications themselves could work directly with bitmaps, or use other parts of the system (such as an accelerated graphics device providing vector and font functionality) to generate bitmaps on their behalf. This would allow for additional 3d graphics devices to be added to the system, they simply send frames as they are created to the monitor, which composites them into an overall display, you could have several 3d devices generating bitmap data for a single 'window', or each 3d device could be generating bitmaps for different windows. Sending lots of bitmaps around does of course require a good amount of bandwidth both on the network and inside the devices, so this may not be viable even if the networking (such as Infiniband) has sufficient bandwidth to cope. If it could work this way there'd be a great amount of flexibility exposed, but again there would be a 'bottleneck' in terms of the graphic card within the monitor, so it may be wise to 'keep it distributed', even in the case of a composition device, so that it can be upgraded or replaced if need be without impacting the rest of the system. Modularization With respect to modularization, the idea of using alternative components for the devices that would be plugged into the system, I mentioned before that NetPC and NetTv use cellular phone technology. This allows both devices to maintain a smaller footprint on the desktop and enables a fan-less infrastructure. The power requirements are dramatically reduced as well. Going beyond mobile phones, other mobile devices--MP3 players, MP4 players, laptops--all consume less power while delivering the computing and entertainment needs that their users expect. A laptop running on AC power consumes approximately 60-90w as compared to a full desktop that can use as much as 400w. Following the paradigm of familiar home entertainment systems it is possible to build a modular component PC. A stereo for example will play back CDs but the sound will be much more enjoyable with the addition of amplifiers, tweeters and sub-woofers. In the same way, the distributed PC could be built around a basic system--think something similar to Apple's Mac Mini--which can be expanded as needed. A graphics module to enhance the display, a network storage device, audio peripherals, etc. Each with their own processing capability (built on cellular components) to distribute the processing requirements of the applications that the user will run. All with a standard connector--USB. Bottom-line--it is possible even now to start building the distributed component PC with a little tweaking from off-the-shelf parts. As mentioned in the article, As mentioned in the article, power management would be a critical part of the distributed system as I see it; with the addition of potentially limitless peripherals to a system, each having their own processor and memory, minimised power usage is essential for each individual component. Being able to power-state-change components more cleanly is an advantage, but each device would need to strike a balance between the performance required to do its job and the power requirements of achieving that performance. For many devices, it is likely that extremely low MHz processors, as used in mobiles, would be sufficient to allow the device to do its job, and with most of the system employing such devices it is possible that power consumption equivalent to a laptop could be achieved. There may however, be devices requiring a bit more oomph, this is why I think it would be important to allow device vendors to choose hardware appropriate for their device, balancing power consumption against the increased performance of the device. With each device in its own box communicating over a protocol hardware vendors would indeed be able to pick whatever hardware is appropriate for their device, whether it be a 33MHz RISC processor or a 3GHz dual-core monster. I'm not sure about the Mac Mini as a good example or basis for a distributed system (at least not in the way I describe in the article). The Mac Mini is essentially a small form factor PC, and while it has a whole heap of expansion options in terms of USB, Firewire and Ethernet it still suffers from the problems of integrated systems as I describe in the article. For starters, the real hardware still resides in the main case, meaning upgrading memory and components such as the graphics card still require opening the case (which in this case is actually more difficult than opening a standard PC). Additionally, there's still the problem of drivers for devices having to reside on the hard drive of the main box, while this doesn't present much of a problem for the external peripherals it is a problem for the devices in the case as I describe in the article. With regards to expansion and the use of USB - I really like USB as a connection standard, it's got pretty much the most usable connector available and it handles both data and power transfer. For the kind of system I'm thinking of however, it would not be adequate (at least not in its current revision) - firstly, USB devices are far too dependent on the host system (i.e. a conventional PC) to be viable as standalone appliances that could be plugged together, the host system is effectively a bottleneck and a single point of failure and all USB devices have to share bandwidth on the bus (as opposed to switched systems like Infiniband, where each node gets full-speed full-duplex transfer rates). Additionally, while the bandwidth available on a Hi-Speed USB connector is reasonable (480Mbps, translating to about 60MB/s in theory but only roughly 30MB/s in practice) it is certainly not enough for transferring more intensive graphical data, particularly because of the shared bandwidth with the other USB devices, and AFAIK the latency window of USB is measured in milliseconds which I think is too high for a distributed system in general (really need latencies in the microseconds to get respectable response). For the low-end systems you describe it would certainly be enough, but remember that I'm trying to think of a system with a standard interconnect and protocol that could be used for any device or system, so building low-end systems using say USB and high-end systems using say InfiniBand would defeat this objective. For your bottom line I definitely agree - it is eminently possible to build a distributed component PC now through tweaking off-the-shelf parts. Tinker who commented above has achieved his own system using ethernet connected boxes. There are literally infinite ways to do it, but when you consider interoperability with ANY other device, and the requirements of keeping up with the demands of new and as yet unknown devices, as well as the need to provide performance for those who need it (thinking of gamers here) the number of correct ways to do it gets considerably smaller. Hence the need for a standard protocol and device interconnect, along with a shift from integrated PCs (with all drivers and applications, and the meat of the hardware, locked in a single box) to a TRUE distributed system where each device has its own software, is independent but can communicate with other devices easily because of a standardised interconnect. Matt this could be what you were after... Check this out: Thanks Dave Looks very interesting indeed! Will definitely be keeping an eye on how this develops.
http://www.freesoftwaremagazine.com/comment/71454
CC-MAIN-2016-18
refinedweb
15,436
51.82
#include <Mac80211.h> #include <Mac80211.h> Inherits BasicLayer. Inheritance diagram for Mac80211: For more info, see the NED file. [protected] Definition of the states Definition of the timer types Compute a backoff value. Compute the backoff value. [protected, virtual] start a new contention period Start a new contention period if the channel is free and if there's a packet to send. Called at the end of a deferring period, a busy period, or after a failure. Called by the HandleMsgForMe(), HandleTimer() HandleUpperMsg(), and, without RTS/CTS, by handleMsgNotForMe(). Compute a new contention window. Compute the contention window with the binary backoff algorithm. encapsulate packet Encapsulates the received network-layer packet into a MacPkt and set all needed header fields. Handle ACK and delete corresponding packet from queue Handle a broadcast packet. This packet is simply passed to the upper layer. No acknowledgement is needed. Called by handleLowerMsg(Mac80211Pkt *af) Handle a CTS frame. Called by HandleMsgForMe(Mac80211Pkt* af) Handle a frame which expected to be a DATA frame. Called by HandleMsgForMe() handle end of contention The node has won the contention, and is now allowed to send an RTS/DATA or Broadcast packet. The backoff value is deleted and will be newly computed in the next contention period handle end of SIFS Handle the end sifs timer. Then sends a CTS, a DATA, or an ACK frame handle the end of a transmission... Handle the end of transmission timer (end of the transmission of an ACK or a broadcast packet). Called by HandleTimer(cMessage* msg) Handle messages from lower layer. Handle all messages from lower layer. Checks the destination MAC adress of the packet. Then calls one of the three functions : handleMsgNotForMe(), handleBroadcastMsg(), or handleMsgForMe(). Called by handleMessage(). Implements BasicLayer. handle a message that was meant for me Handle a packet for the node. The result of this reception is a function of the type of the received message (RTS,CTS,DATA, or ACK), and of the current state of the MAC (WFDATA, CONTEND, IDLE, WFCTS, or WFACK). Called by handleLowerMsg() handle a message that is not for me or errornous Handle all ACKs,RTS, CTS, or DATA not for the node. If RTS/CTS is used the node must stay quiet until the current handshake between the two communicating nodes is over. This is done by scheduling the timer message nav (Network Allocation Vector). Without RTS/CTS a new contention is started. If an error occured the node must defer for EIFS. Called by handleLowerMsg() NAV timer expired, the exchange of messages of other stations is done. Handle the NAV timer (end of a defering period). Called by HandleTimer(cMessage* msg) Handle aframe wich is expected to be an RTS. Called by HandleMsgForMe() Handle self messages such as timer... handle timers handle time out Handle the time out timer. Called by handleTimer(cMessage* msg) Handle messages from upper layer. This implementation does not support fragmentation, so it is tested if the maximum length of the MPDU is exceeded. [virtual] Initialization of the module and some variables. First we have to initialize the module from which we derived ours, in this case BasicModule. This module takes care of the gate initialization. Reimplemented from BasicLayer. computes the duration of a transmission over the physical channel, given a certain bitrate Computes the duration of the transmission of a frame over the physical channel. 'bits' should be the total length of the MAC packet in bits. Called by the Blackboard whenever a change occurs we're interested in. Handle change nofitications. In this layer it is usually information about the radio channel, i.e. if it is IDLE etc. Reimplemented from BasicModule. send Acknoledgement Send an ACK frame.Called by HandleEndSifsTimer() send broadcast frame Send a BROADCAST frame.Called by handleContentionTimer() send CTS frame Send a CTS frame.Called by HandleEndSifsTimer() send data frame Send a DATA frame. Called by HandleEndSifsTimer() or handleEndContentionTimer() send RTS frame Send a RTS frame.Called by handleContentionTimer() Test if maximum number of retries to transmit is exceeded. Test if the maximal retry limit is reached, and delete the frame to send in this case. return a timeOut value for a certain type of frame Return a time-out value for a type of frame. Called by SendRTSframe, sendCTSframe, etc. Default bitrate. The default bitrate must be set in the omnetpp.ini. It is used whenever an auto bitrate is not appropriate, like broadcasts. sequence control -- to detect duplicates Number of frame transmission attempt. Incremented when the SHORT_RETRY_LIMIT is hit, or when an ACK or CTS is missing. take care of switchover times
http://mobility-fw.sourceforge.net/api/classMac80211.html
CC-MAIN-2018-05
refinedweb
766
59.7
Help required with limiting StartDrag();MrStuPid1973 Jul 26, 2010 8:25 AM Hi, Quite new still to AS3 so if someone can help me out, or point in the right direction, it would be greatly appreciated. Thank you for taking the time to look at this, and for any help anyone can offer. Stage size is set to 750 wide x 440 high and my hi res image is 1500 wide x 880 high. image is called mcImage. The hi res image on the stage that is scaled down to 50% on both X and Y axes. I have a zoom in button, a zoom out button and a reset button. All do pretty much what their name suggests. When you zoom in, it adjusts the Z axes of mcImage to make the image appear larger on the stage. So far so good. I then get the new co-ordinates of X and Y by using the localToGlobal feature and record them in a variable, passing them to the mouse Handler for the dragging of the image. The issue is, whatever I try in startDrag(); does not limit the size of the dragable image, nothing happens, though I am expecting it to allow me to drag the image around within it's boundary! I am sure that the code can be tidied up, but I am still learning a lot about AS3 and trying my hardest. I am hoping that it is something really obvious I am overlooking. *** Update *** Registration point of mcImage is 0,0. Code is below - sorry but it is 60+ lines long! import flash.geom.Rectangle; mcImage.width = mcImage.width/2; mcImage.height = mcImage.height/2; var recX = 0; var recY = 0; /*Button handlers*/ btnZoomOut.addEventListener(MouseEvent.CLICK, zoomImage); btnZoomIn.addEventListener(MouseEvent.CLICK, zoomImage); btnReset.addEventListener(MouseEvent.CLICK, zoomImage); function zoomImage(event:MouseEvent){ var Zoom = event.target.name switch(Zoom){ case"btnZoomIn": if (mcImage.z > -400)tnZoomOut": if (mcImage.z != 0)tnReset": mcImage.z = 0; mcImage.x = 0; mcImage.y = 0; recX = 0; recY = 0; break; } } /*Mouse handler for image drag*/ mcImage.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler); mcImage.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler); mcImage.addEventListener(MouseEvent.MOUSE_OUT, mouseUpHandler); var rec:Rectangle = new Rectangle(recX ,recY ,(recX-recX-(recX))*2 ,(recY-recY-(recY))*2); function mouseDownHandler(event:MouseEvent):void { var object = event.target; object.startDrag(false, rec); } function mouseUpHandler(event:MouseEvent):void { var object = event.target; object.stopDrag(); } 1. Re: Help required with limiting StartDrag();skarthiks Jul 27, 2010 12:04 AM (in response to MrStuPid1973) okay, i dint quite get what you are trying to do. So let me answer all the things that i think you are trying to do. First: (recX-recX-(recX))*2 I dont think you intended to do this ?. This will always be (0-0-0) * = 0. since you set recx=recy = 0; the rec will always be (0,0,0,0) since "rec" is not updated on zoomin\zoom out\mousedown etc. and startDrag second parameter is used to set a rectangle (parents coordinates) in which the whole image would be able to move on. I guess you want to have a boundary, and if you drag some part of the image will probably not be visible ? Like the below: If you want to do something like the above then you need to use a MASK layer. Please read about mask. Please let me know what you wanted to do, probably some screenshots....that will be useful. Karthik 2. Re: Help required with limiting StartDrag();MrStuPid1973 Jul 27, 2010 1:26 AM (in response to skarthiks) Hey Skarthiks Thanks for your reply, however (recX-recX-(recX))*2 (or something similar) is what I want to do as the recX & recY values do get changed each time you click on the zoomIn or zoomOut buttons. They get changed to the values by the localToGlobal method. I have done traces on the values and they are exactly what I expect them to be each time the button is clicked. They only get reset back to 0 when you click on the btnReset button. I want to be able to move the whole image, as is it that image that gets zoomed in on and becomes bigger than the stage size, so I need to be able to move it around. I have managed to do it with a simple single zoom (doubles the image size in one go) though when I try to have multiple zoom levels, it is this that causes the issue! Something similar to the link below! though without the thumbnail or the scroll buttons (for now anyway, I might add them in afterwards though) Thanks MrPid 3. Re: Help required with limiting StartDrag();skarthiks Jul 27, 2010 1:39 AM (in response to MrStuPid1973) Yes, for the kind od animation in the link you would have to use mask movieclip on top of the original image. And the "rec" that you provide in the startDrag should be slightly larger then the image size itself, so that the image has some space to move. rec should not be equal to the image size (x,y,width,height). To learn about mask, chk this link 4. Re: Help required with limiting StartDrag();MrStuPid1973 Jul 27, 2010 2:00 AM (in response to skarthiks) OK, was not too sure that I could use a MASK like that, I thought (being a newbie to Flash) that MASK's could only be used if the image in the background (in this case on the stage) was static and the MASK was dragged around. I did not realise that the MASk could be static and the background could be dragged about. Though if I still have to set the boundary for the "Rec" why do I need to use a MASK, why can I not still use the method I was using? I will look at the mask tutorials you set through and let you know how I get on! 5. Re: Help required with limiting StartDrag();skarthiks Jul 27, 2010 2:27 AM (in response to MrStuPid1973) The work that you are trying to achieve is like seeing, an image through a window. Here the window is a mask. and if the image is big then you should be able to drag and see within the bounds of the window (not the image). The startDrag paramater is just used to tell where all you can drag the image, for example, in a game, i dont want somebody to drag and object from the left side of the screen to the right, then i can use the parameter and I guess its not the right use case for you. Hope this helps Karthik P.s. If this helps, please mark the post as answered. 6. Re: Help required with limiting StartDrag();MrStuPid1973 Jul 28, 2010 2:08 AM (in response to skarthiks) Hi Karthik, I managed to get it to work without having to use the MASK option in the end without too much trouble! The problem was with the button identifier I had used, putting them all into one function and using the Case"" to determine what button had been called was the fault. Separating them into individual functions worked a treat! Thank you very much for you time and patience - I am going to look into the mask option (when I have time) just to see if it could neaten up my code though!
https://forums.adobe.com/thread/687701
CC-MAIN-2019-04
refinedweb
1,240
78.99
I'm appending a post to another group, lotsa links to Python which I won't go into here except here's a nice shot: (Zen of Python, alcove office, Linus Pauling House, Portland, Oregon) My purpose in passing this through to edu-sig is to illustrate this nomenclature "manga code", which means something similar to "pseudo code" except that pseudo-code doesn't execute (because it's not a real language, but a phony one made up to capture the essence). I'd say there's a twilight zone between pseudo- and manga- in that you might not need to run source, but if you *did* have time to build the real machine, you know that it could be run, i.e. a real emulator is definitely doable (MMX comes to mind, other academic languages). We've all heard Python referred to as "runnable pseudo-code" but here I think the opportunity is to drop "pseudo" (keeping it for contrast) and go with "manga code" in the sense of "cartoon simulation, fictional but still worth playing". People have different ways of pronouncing "manga" but that's true for Python as well (some say Pythun, whereas for others Python rhymes with thong, me in this latter camp).** Kirby ** Don't say "mah-no" though, if you mean the Novell product Mono. That's definitely "moe no" for Monkey. If you don't get that it's monkey, you lose half the branding, not to mention you'll sound like a bloody Anglophone who's had a few too many. ---------- Forwarded message ---------- From: kirby urner <kirby.urner at gmail.com> Date: Fri, Jun 12, 2009 at 4:53 PM Subject: Re: [wwwanderers] some business items To: Wanderers Oh wait, I did want to say I volunteered to start building "a Python data structure" from Glenn's holographic notes (a holograph means something else in this namespace, check dictionary **). The data structure I'm thinking of is: >>> thearchive = [("Title of Tape","Speaker","Date of Talk","number of copies"), (...,), ...] (the above being actual Python code, manga-code (executing), not pseudo-code (phony): >>> thearchive [('Title of Tape', 'Speaker', 'Date of Talk', 'number of copies'), (Ellipsis,), Ellipsis] Now you may think it selfish of me to build the inventory in Python (and I could use some help) but actually it's quite trivial, once we have this list, to spit it out as XML, JSON or whatever you consider "native" in your world. Spreadsheet? No problemo. Kirby ** for those who don't know: a single word search on Google, if on a valid word in the language, gets you a dictionary link in the upper right, give it a try. I didn't test this feature in Lithuania but I'm quite sure it'd work great (if Aldona is listening, or Hyzy) On Fri, Jun 12, 2009 at 4:44 PM, kirby urner<kirby.urner at gmail.com> wrote: > So I went back and decorated my proposal with a picture of Glenn > starting to take inventory this afternoon, gives a sense of the scale > of the operation: > > > > A secret of my blogs is that some pictures click through to an actual > photostream, where I've got a few more like the above, including some > close ups on titles, feast your eyes. > > Anyway, back to work, am not really involved in this project other > than to photo-document a little, help catalyze a social networking > exercise maybe, though Glenn didn't think anyone wanting to watch a > tape solo should be forbidden to do so, and duh we're not going to be > sending ISEPP police to doors of solo viewers. > > However, an electronic filing regarding the contents of said tape, > attached to your identity somehow, would be nice to get. > > We're collecting what Wanderers think about the tapes, not just the tapes. > > Given you're the people seeing a lot of these lectures in a very > literate town with above average connectivity (netness), your thoughts > actually have some historical interest, is how I'm spinning this (not > just empty flattery -- Portland was pretty special in our day, no ifs > ands or buts, Terry's work a big part of that). > > Kirby >
https://mail.python.org/pipermail/edu-sig/2009-June/009405.html
CC-MAIN-2018-26
refinedweb
698
56.93
At the moment when you create a new engine, its rakefile has such lines: APP_RAKEFILE = File.expand_path("../spec/dummy/Rakefile", __FILE__) load 'rails/tasks/engine.rake' It loads only selected db tasks under the global rake namespace and makes all the engine's rake tasks available under the app: namespace. The other approach would be to bring all the tasks of the engine to the global rake namespace by doing something like this: load File.expand_path("../spec/dummy/Rakefile", __FILE__) Could anyone explain me what is the reasoning behind this task selectivity and app: namespacing? It does seem clearer to me to see only really required for the development of the gem tasks in the global namespace, but is it the only reason? The problem is that some gems expect to see such tasks as db:test:prepare and db:abort_if_pending_migrations in the global namespace and fail to work properly when the tasks are in the app: namespace. So is it a fail on the side of these gems? I published this question on the Ruby on Rails: Core group as well, but somehow my post just didn't appear here, so I'm trying to post it here. Sorry if in the end the post appears at both the groups. on 2013-08-23 12.
https://www.ruby-forum.com/topic/4416577
CC-MAIN-2016-36
refinedweb
216
70.23
Table of Contents Extensible Stylesheet Language Transformations (XSLT) is provably Turing-complete. That is, given enough memory an XSLT stylesheet can perform any calculation a program written in any other language can perform. However, XSLT is not designed as a general purpose programming language; and attempting to use it as one inevitably causes pain (especially if you’re accustomed to procedural languages like Java instead of functional languages like Scheme). Instead XSLT is designed as a templating language. Used in this manner, it is extremely flexible, powerful, and easy to use. However, you do have to recognize what it is and is not good for. You could calculate Fibonacci numbers in XSLT, but Java will do a much better job of that. You could write a Java program that converts DocBook documents to XHTML, but XSLT will make the task much easier. Use the right tool for the right job. Fortunately, XSLT style sheets can be combined with Java programs so that each tool can be applied to the parts of the job for which it’s appropriate. XSLT is a transformation language. An XSLT stylesheet describes how documents in one format are converted to documents in another format. Both input and output documents are represented by the XPath data model. XPath expressions select nodes from the input document for further processing. Templates containing XSLT instructions are applied to the selected nodes to generate new nodes that are added to the output document. The final result document can be identical to the input document, a little different, or a lot different. Most of the time it’s somewhere in the middle. XSLT is based on the notion of templates. An XSLT stylesheet contains semi-independent templates for each element or other node that will be processed. An XSLT processor parses the stylesheet and an input document. Then it compares the nodes in the input document to the templates in the stylesheet. When it finds a match, it instantiates the template and adds the result to the output tree. The biggest difference between XSLT and traditional programming languages is that the input document drives the flow of the program rather than the stylesheet controlling it explicitly. When designing an XSLT stylesheet, you concentrate on which input constructs map to which output constructs rather than on how or when the processor reads the input and generates the output. In some sense, XSLT is a push model like SAX rather than a pull model like DOM. This approach is initially uncomfortable for programmers accustomed to more procedural languages. However, it does have the advantage of being much more robust against unexpected changes in the structure of the input data. An XSLT transform rarely fails completely just because an expected element is missing or misplaced or because an unexpected, invalid element is encountered. If you are concerned about the exact structure of the input data and want to respond differently if it’s not precisely correct (for instance, an XML-RPC server should respond to a malformed request with a fault document rather than a best-guess) validate the documents with a DTD or a schema before transforming them. XSLT doesn’t provide any means to do this. However, you can implement this in Java in a separate layer before deciding whether to pass the input document to the XSLT processor for transformation. An XSLT stylesheet contains examples of what belongs in the output document, roughly one example for each significantly different construct that exists in the input documents. It also contains instructions telling the XSLT processor how to convert input nodes into the example output nodes. The XSLT processor uses those examples and instructions to convert nodes in the input documents to nodes in the output document. Examples and instructions are written as template rules. Each template rule has a pattern and a template. The template rule is represented by an xsl:template element. The customary prefix xsl is bound to the namespace URI, and as usual the prefix can change as long as the URI remains the same. The pattern, a limited form of an XPath expression, is stored in this element’s match attribute. The contents of the xsl:template element form the template. For example, this is a template rule that matches methodCall elements and responds with a template consisting of a single methodResponse element: <xsl:template <methodResponse> <params> <param> <value><string>Hello</string></value> </param> </params> </methodResponse> </xsl:template> A complete XSLT stylesheet is a well-formed XML document. The root element of this document is xsl:stylesheet which has a version attribute with the value 1.0. In practice, stylesheets normally contain multiple template rules matching different kinds of input nodes, but for now Example 17.1 shows one that just contains one template rule: Example 17.1. An XSLT stylesheet for XML-RPC request documents <?xml version="1.0" encoding="ISO-8859-1"?> <xsl:stylesheet <xsl:template <methodResponse> <params> <param> <value><string>Hello</string></value> </param> </params> </methodResponse> </xsl:template> </xsl:stylesheet> Applying this stylesheet to any XML-RPC request document produces the following result: <?xml version="1.0" encoding="utf-8"?><methodResponse><params> <param><value><string>Hello</string></value></param></params> </methodResponse> The template in Example 17.1’s template rule consists exclusively of literal result elements and literal data that are copied directly to the output document from the stylesheet. It also contains some white-space only text nodes, but by default an XSLT processor strips these out. (You can keep the white space by adding an xml:space="preserve" attribute to the xsl:template element if you want.) A template can also contain XSLT instructions that copy data from the input document to the output document or create new data algorithmically. Perhaps the most common XSLT instruction is xsl:value-of. This returns the XPath string-value of an object selected by an XPath expression. For example, the value of an element is the concatenation of all the character data but none of the markup contained between the element’s start-tag and end-tag. Each xsl:value-of element has a select attribute whose value contains an XPath expression identifying the object to take the value of. For example, this xsl:value-of element takes the value of the root methodCall element: <xsl:value-of This xsl:value-of element takes the value of the root int element further down the tree: <xsl:value-of This xsl:value-of element uses a relative location path. It calculates the string-value of the int child of the value child of the params child of the context node (normally the node matched by the containing template): <xsl:value-of The xsl:value-of element can calculate the value of any of the four XPath data types (number, boolean, string, and node-set). For example, this expression calculates the value of e times π: <xsl:value-of In fact, you can use absolutely any legal XPath expression in the select attribute. This xsl:value-of element multiplies the number in the int element by ten and returns it: <xsl:value-of In all cases the value of an object is the XPath string-value that would be returned by the XPath string() function. When xsl:value-of is used in a template, the context node is a node matched by the template and for which the template is being instantiated. The template in Example 17.2 copies the string-value of the value element in the input document to the string element in the output document. Example 17.2. An XSLT stylesheet that echoes XML-RPC requests <?xml version="1.0" encoding="ISO-8859-1"?> <xsl:stylesheet <xsl:template <methodResponse> <params> <param> <value> <string> <xsl:value-of </string> </value> </param> </params> </methodResponse> </xsl:template> </xsl:stylesheet> If this stylesheet is applied to the XML document in Example 17.3, then the result is the XML document shown in Example 17.4. There are a number of GUI, command line, and server side programs that will do this, though our interest is going to be in integrating XSLT stylesheets into Java programs so I’m going to omit the details of exactly how this takes place for the moment. I’ll pick it up again in the next section. Example 17.3. An XML-RPC request document <?xml version="1.0"?> <methodCall> <methodName>calculateFibonacci</methodName> <params> <param> <value><int>10</int></value> </param> </params> </methodCall> Example 17.4. An XML-RPC response document <?xml version="1.0" encoding="utf-8"?> <methodResponse> <params> <param> <value> <string> 10 </string> </value> </param> </params> </methodResponse> The white space in the output is a little prettier here than in the last example because I used an xml:space="preserve" attribute in the stylesheet. More importantly, the content of the string element has now been copied from the input document. The output is a combination of literal result data from the stylesheet and information read from the transformed XML document. Probably the single most important XSLT instruction is the one that tells the processor to continue processing other nodes in the input document and instantiate their matching templates. This instruction is the xsl:apply-templates element. Its select attribute contains an XPath expression identifying the nodes to apply templates to. The currently matched node is the context node for this expression. For example, this template matches methodCall elements. However, rather than outputting a fixed response, it generates a methodResponse element whose contents are formed by instantiating the template for each params child element in turn: <xsl:template <methodResponse> <xsl:apply-templates </methodResponse> </xsl:template> The complete output this template rule generates depends on what the template rule for the params element does. That template rule may further apply templates to its own param children like this: <xsl:template <params> <xsl:apply-templates </params> </xsl:template> The param template rule may apply templates to its value child like this: <xsl:template <param> <xsl:apply-templates </param> </xsl:template> The value template rule may apply templates to all its element children whatever their type using the * wild card: <xsl:template <value> <xsl:apply-templates </value> </xsl:template> Finally one template rule may take the value of all the possible children of value at once using the union operator |: <xsl:template <string> <xsl:value-of </string> </xsl:template> This example descended straight down the expected tree, and mostly copied the existing markup. However, XSLT is a lot more flexible and can move in many different directions at any point. Templates can skip nodes, move to preceding or following siblings, reprocess previously processed nodes, or move along any of the axes defined in XPath. XSLT defines several default template rules that are used when no explicit rule matches a node. The first such rule applies to the root node and to element nodes. It simply applies templates to the children of that node but does not specifically generate any output: <xsl:template <xsl:apply-templates/> </xsl:template> This allows the XSLT processor to walk the tree from top to bottom by default, unless told to do something else by other templates. The default templates are overridden by any explicit templates. The second default rule applies to text and attribute nodes. It copies the value of each of these nodes into the output tree: <xsl:template <xsl:value-of </xsl:template> Together, these rules have the effect of copying the text contents of an element or document to the output but deleting the markup structure. Of course you can change this behavior by overriding the built-in template rules with your own template rules. Adding XPath predicates to match patterns and select expressions offers a lot of the if-then functionality you need. However, sometimes that’s not quite enough. In that case, you can take advantage of the xsl:if and xsl:choose elements. The xsl:if instruction enables the stylesheet to decide whether or not to do something. It contains a template. If the XPath expression in the test attribute evaluates to true, then the template is instantiated and added to the result tree. If the XPath expression evaluates to false, then it isn’t. If the XPath expression evaluates to something that isn’t a boolean, then it is converted to true or false using the XPath boolean() function described in the previous chapter. That is, 0 and NaN are false. All other numbers are true. Empty strings and node-sets are false. Non-empty strings and node-sets are true. For example, when evaluating an XML-RPC request you might want to check that the request document indeed adheres to the specification, or at least that it’s close enough for what you need it for. This requires checking that the root element is methodCall, that the root element has exactly one methodName child and one params child, and so forth. Here’s an XPath expression that checks for various violations of XML-RPC syntax (Remember that according to XPath empty node-sets are false and non-empty node-sets are true.): count(/methodCall/methodName) != 1 or count(/methodCall/params) != 1 or not(/methodCall/params/param/value) I could check considerably more than this, but this suffices for an example. Now we can use this XPath expression in an xsl:if test inside the template for the root node. If the test succeeds (that is, the request document is incorrect), then the xsl:message instruction terminates the processing: <xsl:template <xsl:if <xsl:message The request document is invalid. </xsl:message> </xsl:if> <xsl:apply-templates </xsl:template> The exact behavior of the xsl:message instruction is processor dependent. The message might be delivered by printing it on System.out, writing it into a log file, or popping up a dialog box. Soon, you’ll see how to generate a fault document instead. There is no xsl:else or xsl:else-if instruction. To choose from multiple alternatives, use the xsl:choose instruction instead. The xsl:choose instruction selects from multiple alternative templates. It contains one or more xsl:when elements, each of which contains a test attribute and a template. The first xsl:when element whose test attribute evaluates to true is instantiated. The others are ignored. There may also be an optional final xsl:otherwise element whose template is instantiated only if all the xsl:when elements are false. For example, when an XML-RPC request is well-formed but syntactically incorrect, the server should respond with a fault document. This template tests for a number of possible problems with an XML-RPC request and only processes it if none of the problems arise. Otherwise it emits an error message: <xsl:template <xsl:choose> <xsl:when Missing methodName </xsl:when> <xsl:when Multiple methodNames </xsl:when> <xsl:when Multiple params elements </xsl:when> <xsl:otherwise> <xsl:apply-templates </xsl:otherwise> </xsl:choose> </xsl:template> XSLT does not have any real exception handling or error reporting mechanism. In the worst case, the processor simply gives up and prints an error message on the console. This template, like every other template, is instantiated to create a node-set. Depending on which conditions are true, different nodes will be in that set. If there is an error condition, this set will contain a single text node with the contents, “Missing methodName”, “Multiple methodNames”, or “Multiple params elements”. Otherwise it will contain whatever nodes are created by applying templates to the methodCall child element. But in both cases a node-set is returned that is inserted into the output document. There is a second way a template can be instantiated. As well as matching a node in the input document, a template can be called by name using the xsl:call-template element. Parameters can be passed to such templates. Templates can even be called recursively. Indeed, it is recursion that makes XSLT Turing-complete. For example, here’s a template named faultResponse that generates a complete XML-RPC fault document when invoked:: <xsl:template <methodResponse> <fault> <value> <struct> <member> <name>faultCode</name> <value><int>0</int></value> </member> <member> <name>faultString</name> <value><string>Invalid request document</string></value> </member> </struct> </value> </fault> </methodResponse> </xsl:template> The xsl:call-template element applies a named template to the context node. For example, earlier you saw a root node template that terminated the processing if it detected an invalid document. Now it can call the fault template instead: <xsl:template <xsl:choose> <xsl:when <xsl:call-template </xsl:when> <xsl:otherwise> <xsl:apply-templates </xsl:otherwise> </xsl:choose> </xsl:template> Named templates can factor out common code that’s used in multiple places through top-down design, just as a complicated algorithm in a Java program may be broken into multiple methods rather than one large monolithic method. Indeed some large stylesheets including the DocBook XSL stylesheets that produced this book do use named templates for this purpose. However, named templates become even more important when you add parameters and recursion to the mix. Each template rule can have any number of parameters represented as xsl:param elements. These appear inside the xsl:template element before the template itself. Each xsl:param element has a name attribute and an optional select attribute. The select attribute provides a default value for that parameter when the template is invoked but can be overridden. If the select attribute is omitted, then the default value for the parameter is set by the contents of the xsl:param element. (For a non-overridable variable, you can use a local xsl:variable element instead.) For example, the parameters in this fault template specify the faultCode and the faultString. The default fault code is 0. The default fault string is Unspecified Error. <xsl:template <xsl:param <xsl:paramUnspecified Error</xsl:param> <methodResponse> <fault> <value> <struct> <member> <name>faultCode</name> <value> <int><xsl:value-of</int> </value> </member> <member> <name>faultString</name> <value> <string> <xsl:value-of </string> </value> </member> </struct> </value> </fault> </methodResponse> </xsl:template> XSLT is weakly typed. There is no type attribute on the xsl:param element. You can pass in pretty much any object as the value of one of these parameters. If you use such a variable in a place where an item of that type can’t be used and can’t be converted to the right type, then the processor will stop and report an error. The xsl:call-template element can provide values for each of the named parameters using xsl:with-param child elements, or it can accept the default values specified by the xsl:param elements. For example, this template rule for the root node uses different error codes and messages for different problems: <xsl:template <xsl:choose> <xsl:when <xsl:call-template <xsl:with-param <xsl:with-param Missing methodName </xsl:with-param> </xsl:call-template> </xsl:when> <xsl:when <xsl:call-template <xsl:with-param <xsl:with-param Multiple method names </xsl:with-param> </xsl:call-template> </xsl:when> <xsl:when <xsl:call-template <xsl:with-param <xsl:with-param Multiple params elements </xsl:with-param> </xsl:call-template> </xsl:when> <!-- etc. --> <xsl:otherwise> <xsl:apply-templates </xsl:otherwise> </xsl:choose> </xsl:template> I’m not sure I would always recommend this approach for validation. Most of the time writing a schema is easier. However, this technique can be used to verify things a schema can’t. For example, it could test that a value element contains either an ASCII string or a type element such as int, but not a type element and an ASCII string. The ability for a template to call itself (recursion) is the final ingredient of a fully Turing-complete language. For example, here’s a template that implements the factorial function: <xsl:template <xsl:param <xsl:param <xsl:choose> <xsl:when <xsl:value-of </xsl:when> <xsl:when <xsl:call-template <xsl:with-param <xsl:with-param </xsl:call-template> </xsl:when> <xsl:whenError: function undefined!</xsl:when> </xsl:choose> </xsl:template> The factorial template has two arguments, $arg and $return_value. $arg is the number whose factorial the client wants, and must be passed as parameter the first time this template is invoked. $return_value is initially 1. When $arg reaches zero, the template returns $return_value. However, if $arg is not 0, the template decrements $arg by 1, multiplies $return_value by the current value of $arg, and calls itself again. Functional languages like XSLT do not allow variables to change their values or permit side effects. This can seem a little strange to programmers accustomed to imperative languages like Java. The key is to remember that almost any task a loop performs in Java, recursion performs in XSLT. For example, consider the most basic CS101 problem, printing out the integers from 1 to 10. In Java it’s a simple for loop: for (int i=1; i <= 10; i++) { System.out.print(i); } However, in XSLT you’d use recursion in this fashion: <xsl:template <xsl:param <xsl:if <xsl:value-of <xsl:call-template <xsl:with-param </xsl:call-template> </xsl:if> </xsl:template> Similar recursive techniques can be used for other looping operations such as sums, averages, sorting, and more. Neither iteration nor recursion is mathematically better or fundamentally faster than the other. They both produce the same results in the end. The XSLT solution is more complex and less obvious than the Java equivalent. However, that has more to do with XSLT’s XML syntax than with recursio`n itself. In Java the same operation could be written recursively like this: public void fakeLoop(int i) { System.out.print(i); if (i < 10) fakeLoop(i++); } In fact, it has been proven that given sufficient memory any recursive algorithm can be transformed into an iterative one and vice versa.[1] Let’s look at a more complex example. Example 17.5 is a simple XSLT stylesheet that reads input XML-RPC requests in the form of Example 17.3 and converts them into output XML-RPC responses. Example 17.5. An XSLT stylesheet that calculates Fibonacci numbers <?xml version="1.0" encoding="ISO-8859-1"?> <xsl:stylesheet <xsl:template <xsl:choose> <!-- Basic sanity check on the input --> <xsl:when <xsl:apply-templates </xsl:when> <xsl:otherwise> <!-- Sanity check failed --> <xsl:call-template </xsl:otherwise> </xsl:choose> </xsl:template> <xsl:template <methodResponse> <params> <param> <value> <xsl:apply-templates </value> </param> </params> </methodResponse> </xsl:template> <xsl:template <int> <xsl:call-template <xsl:with-param </xsl:call-template> <:template <xsl:param <xsl:param <methodResponse> <fault> <value> <struct> <member> <name>faultCode</name> <value> <int><xsl:value-of</int> </value> </member> <member> <name>faultString</name> <value> <string> <xsl:value-of </string> </value> </member> </struct> </value> </fault> </methodResponse> </xsl:template> </xsl:stylesheet> However, although XSLT is Turing-complete in a theoretical sense, practically it is missing a lot of the functionality you’d expect from a modern programming language such as mathematical functions, I/O, and network access. To actually use this stylesheet as an XML-RPC server, we need to wrap it up in a Java program that can provide all this.
http://www.cafeconleche.org/books/xmljava/chapters/ch17.html
crawl-001
refinedweb
3,851
52.7
Building a Mobile Video Chat App for iOS Using Swift Building a Mobile Video Chat App for iOS Using Swift Bring multiparty video chat capabilities to your iOS with vidyo.io. And while Vidyo is built for Objective-C, fear not! It's Swift-compatible, too. Join the DZone community and get the full member experience.Join For Free Since Apple first introduced Swift in 2014, it has witnessed rapid adoption and become the programming language of choice for mobile app development on iOS. While some people prefer Objective-C, a large number of iOS developers are now moving to Swift. When it comes to building a high-quality group video chat application using vidyo.io, should you use Objective-C or Swift? The answer is either. Whichever programming language you prefer, vidyo.io has you covered. To quickly start building an iOS app, download the iOS package. The iOS package comes with the VidyoConnector reference application written in Objective-C. So if you are planning to use Objective-C, you are good to go. You can follow along with the quick start guide or check out the how-to video to initiate the process. But if you want to use Swift, fret not. The vidyo.io framework is completely compatible. You can use Swift by adding a bridging header that will add all of vidyo.io’s functionality to your project. This lets you take full advantage of the coding benefits in Swift. In this article, I’ll guide you through a step-by-step process to get your multiparty Swift video chat app off the ground. Required Software - Xcode – version 8 or above - VidyoClient-iOS framework Download the latest iOS package. Create a New Project Let’s begin by creating a new application on Xcode. From the template selection page you can select any template that suits your project, but for our sample purpose, select “Single View App” and click “Next.” This will bring you to the next screen, where you must enter the product name. For this exercise, I will name my product VidyoConnectorSwift, but you can obviously choose an appropriate name for your project. Make sure you select the language as “Swift.” After you click “Next,” Xcode asks you where to save the VidyoConnectorSwift project. Pick any folder (e.g., Documents) on your Mac and click “Create” to continue. Adding VidyoClient Framework Next, let’s copy the VidyoClientIOS.framework from the downloaded VidyoClient-iOSSDK package to our newly created project folder. You can find the framework file under the lib folder of the package. Once you copy the file, your project folder should look like this: To link this framework in our Xcode project, go back to your newly created project, select “VidyoConnectorSwift” on the left pane, then select “VidyoConnectorSwift” in “Targets” and select the “General” tab. Under “Embedded Binaries” click on the “+” icon. This will open up a pop-up menu, where you’ll select the “Add Other” option. Go to the project folder where you copied the VidyoClientIOS.framework and select it. Adding Keychain Sharing Capability The vidyo.io SDK needs the “Keychain Sharing” capability turned on so that it can install the Vidyo license and certificate and code-sign your application. To enable this, go to the VidyoConnectorSwift target and turn on “Keychain Sharing” under the “Capabilities” tab. Once you turn it on, it will automatically add your application bundle identifier to the keychain groups list. Click “+” to also add “VidyoLicense” to the list. Keychain Groups: - io.vidyo.VidyoConnectorSwift (your application ID) - VidyoLicense Update Info.plist Since we’re building a video chat application, this app will access both the camera and microphone. Apple requires you to ask permission from the user to gain access to these resources. We can do this by simply adding the description text in the info.plist file. Add two new entries under “Information Property List”: - Privacy – Microphone Usage Description - Privacy – Camera Usage Description Adding Bridging Header The current version of the VidyoClientIOS.framework is written in Objective-C. To access the objects from your Swift project, we are going to create a bridging header. To do so, hit ⌘N or go to File->New->File. Select “Header File” and click “Next.” Let’s name this VidyoConnectorSwift-Bridging-Header.h. This will create your header file, open it, and add the following code to reference the Vidyo connector objects: #ifndef VidyoConnectorSwift_Bridging_Header_h #define VidyoConnectorSwift_Bridging_Header_h #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> #import <VidyoClientIOS.framework/Headers/Lmi/VidyoClient/VidyoConnector_Objc.h> #endif /* VidyoConnectorSwift_Bridging_Header_h */ Next, you need to tell Xcode where your bridging header is located. Go back to your build settings and search for “Objective-C Bridging Header.” Add the relative path to the header file we just created: $(PROJECT_DIR)/VidyoConnectorSwift/VidyoConnectorSwift-Bridging-Header.h We still need one more setting in the build settings. Look for “Header Search Paths” and tell Xcode to look for header files under this directory: $(PROJECT_DIR) Now your Swift project is ready to consume Vidyo objects. Connecting to a Video Room Now that we’ve got the setup done, let's add some code to join a video conference. The single-view application comes with a default view controller, which is the starting point for your application. In this view controller, I added a UIView object and also added “Connect” and “Disconnect” buttons. I connected the UIView to an IBOutlet in its corresponding ViewController class, calling it “vidyoView.” Finally, I connected the buttons to an IBAction to register for the click events. @IBOutlet weak var vidyoView: UIView! @IBAction func connectClicked(_ sender: Any) { } @IBAction func disconnectClick(_ sender: Any) { } I am going to use vidyoView as my video conference UI. In other words, this is the view where I am going to tell the vidyo.io SDK to draw my preview and the remote participants. I will use the “Connect” and “Disconnect” button click events to join or leave the video call. Here are the steps to follow: - Initialize VidyoConnector VCConnectorPkg.vcInitialize() - Construct the VidyoConnector object and pass the UIView object where the preview and participants should be rendered. var connector = VCConnector(UnsafeMutableRawPointer(&vidyoView), viewStyle: .default, remoteParticipants: 4, logFileFilter: UnsafePointer("warning"), logFileName: UnsafePointer(""), userData: 0) - Tell the vidyoconnector object where to show the view and at what size connector.showView(at: &vidyoView, x: 0, y: 0, width: UInt32(vidyoView.frame.size.width), height: UInt32(vidyoView.frame.size.height)) - Connect to a video conference call connector.connect("prod.vidyo.io", token: "XXXX", displayName: "Sachin", resourceId: "demoRoom", connect: self) Note: In this step, to connect to a video conference call, you will need a valid token. A token is a short-lived authentication credential that you create for your users. Learn more about tokens and how to generate them. And that’s it! Your application is ready to join multiparty video conferences. Putting this all together, this is how the view controller class would look: class ViewController: UIViewController, VCIConnect { private var connector:VCConnector? @IBOutlet weak var vidyoView: UIView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. VCConnectorPkg.vcInitialize() connector = VCConnector(UnsafeMutableRawPointer(&vidyoView), viewStyle: .default, remoteParticipants: 4, logFileFilter: UnsafePointer("warning"), logFileName: UnsafePointer(""), userData: 0) connector?.showView(at: &vidyoView, x: 0, y: 0, width: UInt32(vidyoView.frame.size.width), height: UInt32(vidyoView.frame.size.height)) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func connectClicked(_ sender: Any) { connector?.connect("prod.vidyo.io", token: "XXXX", displayName: "Sachin", resourceId: "demoRoom", connect: self) } @IBAction func disconnectClick(_ sender: Any) { connector?.disconnect() } // MARK: - VCIConnect delegate methods func onSuccess() { print("Connection Successful") } func onFailure(_ reason: VCConnectorFailReason) { print("Connection failed \(reason)") } func onDisconnected(_ reason: VCConnectorDisconnectReason) { print("Call Disconnected") } } To see a complete project, along with both composited and custom view layout options, see the sample project shared on our GitHub page. Published at DZone with permission of Sachin Hegde , 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/building-a-mobile-video-chat-app-for-ios-using-swi
CC-MAIN-2020-05
refinedweb
1,340
50.63
Java - String Buffer & String Builder Classes The StringBuffer and StringBuilder classes are used when there is a necessity to make a lot of modifications to Strings of characters. Unlike Strings objects of type StringBuffer and Stringbuilder can be modified over and over again with out thread safety is necessary the best option is StringBuffer objects. Example: public class Test{ public static void main(String args[]){ StringBuffer sBuffer = new StringBuffer(" test"); sBuffer.append(" String Buffer"); System.ou.println(sBuffer); } } This would produce the following result: test String Buffer StringBuffer Methods: Here is the list of important methods supported by StringBuffer class: Here is the list of other methods (Except set methods ) which are very similar to String class:
http://www.tutorialspoint.com/cgi-bin/printversion.cgi?tutorial=java&file=java_string_buffer.htm
CC-MAIN-2014-15
refinedweb
117
57.2
Details - Type: Improvement - Status: Closed - Priority: Minor - Resolution: Fixed - Affects Version/s: None - - Component/s: MoreLikeThis - Labels:None Issue Links Activity - All - Work Log - History - Activity - Transitions Great Matthew! Very happy to see these distributed components issues moving forward. Any chance you can attach a couple junit tests with these patches? I'll take a look at the existing Unit tests. I'm not sure what type of test coverage my unit tests will have, considering this is distributed (multi-computer) and mult-threaded code. There are some distributed tests already that you can build from. Take a peak in the test package. Add some test cases, by no means complete. Description of Changes made for moreLikeThisComponent: Added a new purpose to ShardRequest This for new shard requests to execute boolean query that is now returned when isShard is true from process. Added method HandleResponse. Creates shard request for each element return in moreLikeThis during EXEC_QUERY stage. Every shard executes the MoreLikeThis query to find the best matches for a given document. Added finishedStage Checks if stage is GET_FIELDS and MLT == true. Loops through every shard reponse and finds those with the new MLT_RESULTS purpose and adds them to the response after they are sorted and trimmed for length and verified they are in the response. MoreLikeThisComponentTest.patch should have been marked. accept apache license. sorry What release of SOLR should one apply this patch to? (I tried an older build of 1.4 and got patching file org/apache/solr/handler/MoreLikeThisHandler.java patching file org/apache/solr/handler/component/MoreLikeThisComponent.java Hunk #2 FAILED at 51. 1 out of 2 hunks FAILED – saving rejects to file org/apache/solr/handler/component/MoreLikeThisComponent.java.rej patching file org/apache/solr/handler/component/ShardRequest.java ) It's on the top of the patch. 772437 — org/apache/solr/handler/MoreLikeThisHandler.java (revision 772437) +++ org/apache/solr/handler/MoreLikeThisHandler.java (working copy) Matt Woytowitz Software Enginneer ManTech International Corporation Phone: (703) 674-3674 Yep, I got that part figured out finally. Unfortunately I'm getting back 0 results when I pass the shards parameter, as opposed to when it is omited. returns: <lst name="moreLikeThis"> <result name="018639b9dfd5003c20c3ceb29df9d582" numFound="0" start="0" maxScore="0.0"/> <result name="83de9bc1953e36e44df8e95661983183" numFound="0" start="0" maxScore="0.0"/> </lst> where as returns <lst name="moreLikeThis"> <result name="018639b9dfd5003c20c3ceb29df9d582" numFound="1198" start="0" maxScore="3.3357687"/> ...result docs <result name="83de9bc1953e36e44df8e95661983183" numFound="487" start="0" maxScore="4.129801"/> ...result docs </lst> However, perhaps more pressing is that when the shards param is set my spellCheck component stops responding (I had to apply the distributed spellcheck patch as well). yikes... I poked around in the code, but couldn't really make any progress.. Any help would be greatly appreciated. -mike It's been 3 months since I looked at this. Sounds fimiliar. Here are the params I pass with every MLT Query. private int minTermFrequency = MoreLikeThis.DEFAULT_MIN_TERM_FREQ; private int minWordLength = MoreLikeThis.DEFAULT_MIN_WORD_LENGTH; private int maxWordLength = MoreLikeThis.DEFAULT_MAX_WORD_LENGTH; private int maxQueryTerms = MoreLikeThis.DEFAULT_MAX_QUERY_TERMS; private int minDocFreq = MoreLikeThis.DEFAULT_MIN_DOC_FREQ; private int maxTokensToParse = MoreLikeThis.DEFAULT_MAX_NUM_TOKENS_PARSED; .... params.add(MoreLikeThisParams.MLT, Boolean.TRUE.toString()); params.add(MoreLikeThisParams.SIMILARITY_FIELDS, similarFields.split(",")); params.add(MoreLikeThisParams.MIN_TERM_FREQ, minTermFrequency + ""); params.add(MoreLikeThisParams.MIN_WORD_LEN, minWordLength + ""); params.add(MoreLikeThisParams.MAX_WORD_LEN, maxWordLength + ""); params.add(MoreLikeThisParams.MAX_QUERY_TERMS, maxQueryTerms + ""); params.add(MoreLikeThisParams.MAX_NUM_TOKENS_PARSED, maxTokensToParse + ""); params.add(MoreLikeThisParams.MIN_DOC_FREQ, minDocFreq + ""); Are you using a stock solr config? Can you send me the solr config and schema.xml? Are you logging the incoming queries to solr? You should see three requests. Your request, the shard request to get scores and ids and finally a request to return the fields you requested for the best matches. What does the second query look like? Take a look at that in your browser. If you run that query what do your results look like? Matt Woytowitz Software Enginneer ManTech International Corporation Phone: (703) 674-3674 I had trouble getting this to work in my distributed setup so I changed the patch around (for better or worse) to make it flow in a way that made sense to me. Just wanted to post in case anybody else was having trouble. Some thoughts on response builder/ distributed components: It would be nice to allow components to add requests (in a natural way) to response builder after the QueryComponent has made it through finishedStage and merged all the results. This could optimize MLT so that instead of finding MLT for the top 5 hits from each shard, we find MLT for the top 5 hits overall. (maybe there's a way to do this, but I couldn't really find the intuition behind it) . (attached patch is a modified version of Matt's) mike mike_a@mit.edu I couldn't get the original patch to work on the 4.0 trunk or branch_3x. It would apply, but not compile. I did get the alternate patch to apply and compile with the branch_3x version downloaded last night. Part of that was changing the constant for the purpose to 0x800 since a different one with 0x400 had been added already. When I add a shards parameter, it no longer works and says "undefined field id" twice and spits out "request: " with the URL of the shard. Have things changed enough in the last several months that this patch will require reworking, or did I just miss something simple? If you need info from me, let me know how to get it. In the tail end of development cycle and won't have time to look at it till end of month. Patch is a year old at this point. I think the patch has a revision number on it. I would try to checking out from SVN that revision, then patch, then update. Hope that helps, Matt applied AlternateDistributedMLT.patch to trunk (rev 1003607) and got NPE 23:53:15,452 ERROR [SolrDispatchFilter] java.lang.NullPointerException at org.apache.solr.handler.component.MoreLikeThisComponent.finishStage(MoreLikeThisComponent.java:147) at org.apache.solr.handler.component.SearchHandler.handleRequestBody(SearchHandler.java:315) at org.apache.solr.handler.RequestHandlerBase.handleRequest(RequestHandlerBase.java:131) at org.apache.solr.core.SolrCore.execute(SolrCore.java:1325):1157) at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:388) at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216) at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182) at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765) at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:418)) fixed NPE but MLT still doesn't work correctly: i think it returns 'like' documents from shard where requested in query document is physically hosted Bulk move 3.2 -> 3.3 3.4 -> 3.5 Hmm - bummer - this issue has lots of action, lots of watchers, lots of votes, but has kind of fallen trough the cracks. Hopefully I can find some time to look at bringing the last patch up to trunk sometime soon. I modified the patch to apply to trunk, I'm not sure if it's working as expected (mainly because I'm not super familiar with MLT) but it builds. Might save someone some time. This patch works, but not perfect MLT distributed search works, but if i use more when one field with "mlt.fl", i get an "HTTP Error 400". With only one mlt-field, no problem. I haven't had a chance to really play with this lately, can you give an example of the query you are running? After spending a bit looking at this, it appears that something has changed since last this patch was written which is preventing this from working properly. I didn't write the original patch so I'm having difficulty figuring out specifically what is wrong. Currently I am getting the following when running this <lst name="moreLikeThis"> <null name="8001ed40-5b54-4ca6-9a17-ffb16179a1de"/> <null name="652bfc99-96dd-49a3-8232-057995788b93"/> <null name="f422dfbd-d534-490b-b86c-6d0e6586dc7c"/> <null name="a0eb8e1b-299e-41cc-a52c-36c2d75f7171"/> <null name="05e01ad4-9d7a-4399-931b-257494ed9385"/> <null name="894fa0ac-4ac7-4121-a9c5-45c24ba5e6dd"/> <null name="b70b4ac4-ac09-42d7-8728-2aa6e236b757"/> <null name="be92fa6b-fbf1-4688-8f2f-edbd659ec50e"/> <null name="4fa6fb91-8433-4bde-866c-0102b3070f88"/> <null name="04109cda-f7e1-4280-903c-e1564585b3e8"/> </lst> If I run with distrib=false this works so definitely is something with the patch. I tracked down what was causing the issue on my part, the original patch assumed the unique key field was "id" and in my index it's "key". I've updated the patch to look that up now. I also supplied multiple fields and that worked properly (as far as I can tell). Hi Jamie, Unfortunately, I can't reproduce this bug now, but i try it this week. I use edismax as default query handler. My queries looks like (default select with mlt-params): OR with mlt-handler: With more than one field in mlt.fl I get "HTTP 400" exceptions. Thanks for the new patch, I will test it this week I missed this recent activity - thanks for grabbing this torch Jamie! Perhaps we can get this in soon. So looks like we need some distrib tests for this - to start though, it looks like the single instance test fails with the latest patch. Have not had a chance to investigate why yet though. Alright - just looks like debug mode is the issue - not working right with MLT and the latest patch. I unfortunately can't test this now, I can try to take a look in the next week or so if you don't get to it before me Has anyone been able to test this yet? I unfortunately have not and don't think I'll have the time to do so in the near future. The patch was updated to trunk not too long ago so may not be too difficult to revive assuming the original patch worked as expected bulk fixing the version info for 4.0-ALPHA and 4.0 all affected issues have "hoss20120711-bulk-40-change" in comment rmuir20120906-bulk-40-change moving all 4.0 issues not touched in a month to 4.1 This patch fixes some formatting in the latest patch and adds the base for some tests as well as one test - it's currently failing. New Patch. Adds more tests. Fixes a couple bugs that prevented correct results. Fixes the debug path for the single node mlt. Results are not currently sorted the same way as they are on a single node. I don't really have a need or use for this, so if anyone that does could help with testing, that would be great. Okay - well, since I have some tests that pass and this doesn't mess with single node mlt, I'm just going to commit it. It's better than nothing and we can iterate on it as people try it out. [trunk commit] Mark Robert Miller SOLR-788: Distributed search support for MLT. [branch_4x commit] Mark Robert Miller SOLR-788: Distributed search support for MLT. further bug fixe and improvements can go in other issues I’m curious whether the change in the default value for the mlt.count parameter from 5 in 4.0 to 20 in 4.x is an intentional change or simply a bug that needs to be fixed. I mean, there is no mention in CHANGES.txt or Jira to note the impact on what a user will see. Unintentional change. [trunk commit] Mark Robert Miller SOLR-788: set mlt.count back to 5 [branch_4x commit] Mark Robert Miller SOLR-788: set mlt.count back to 5 Thanks, Mark! Is this fix a part of the official Solr 4.1 release now? Yes, though it may be rough around the edges - give it a try. I have Solr 4.1 setup, and trying to execute mlt searches - it doesn't seem to be working (unless I am doing something fundamentally wrong). Here's what I did:- 1. Setup Solr 4.1, modified the <luceneMatchVersion> field in solr config.xml to be Lucene_41. Also have the below entry enabled in the config file <requestHandler name="/mlt" class="solr.MoreLikeThisHandler"> </requestHandler> 2. We are running distributed Solr servers (about 30 of them, each pointing to their respective shards and the shards are not replicated). There is a Master Solr (in addition to the 30 slave Solrs) and all queries are directed to the Master. 3. Ran the following mlt query <id,content> are fields defined in our Solr schema. 4. Solr seems to execute the query and see the below error after a few minutes of trying to execute the above request <response> <lst name="responseHeader"> <int name="status">400</int> <int name="QTime">318230</int> <lst name="params"> <str name="mlt.mindf">1</str> <str name="fl">id,content</str> <str name="mlt.fl">content</str> <str name="q">microsoft</str> <str name="mlt.mintf">1</str> <str name="mlt">true</str> </lst> </lst> <lst name="error"> <str name="msg">org.apache.solr.search.SyntaxError: Cannot parse '+(content:urn:schemas content:xml:namespace content:prefix content:ns content:microsoft content:com:vml content:com:office:office content:v content:o) -id:nordstoga.com': Encountered " ":" ": "" at line 1, column 13. Was expecting one of: <AND> ... <OR> ... <NOT> ... "+" ... "-" ... <BAREOPER> ... "(" ... ")" ... "*" ... "^" ... <QUOTED> ... <TERM> ... <FUZZY_SLOP> ... <PREFIXTERM> ... <WILDTERM> ... <REGEXPTERM> ... "[" ... "{" ... <LPARAMS> ... <NUMBER> ... </str> <int name="code">400</int> </lst> </response> Am I doing this right? Why did you point out the mlt handler was enabled, but then you use the select handler? Does your select handler have the mlt component in it? You might want to take this to the user list. It seems that you may or may not get interesting terms, depending on which shard serves the request. (I was getting very confused, because my manually constructed URL was working, while my SolrJ request was not, until I noticed that the former was being served by shard1 and the latter by shard2.) I'm guessing you'll get no results if the shard that serves your request doesn't contain the document you're trying to query. I'll try to tighten up a test case and get it filed, but I thought I'd mention it here, in case anybody had suspicions. Suneel Marthi's issue above, where the derivative query passed to the shard is invalid, is similar to the issue I documented for numeric keys in SOLR-5521. Here, the query terms extracted from the bean for which we are searching for similar beans includes terms with embedded colons. When the MoreLikeThis component under the search handler builds a MoreLikeTheseQuery, the extracted query terms need to be quoted. This patch adds support for moreLikeThis to the distributed search.
https://issues.apache.org/jira/browse/SOLR-788?focusedCommentId=13254742&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel
CC-MAIN-2015-48
refinedweb
2,458
58.69
FRANCKC/MooseX-Net-API-0.12 - 18 Jul 2010 07:18:25 Net::PMP is a Perl client for the Public Media Platform API (). This class is mostly a namespace-holder and documentation, with one convenience method: client()....KARMAN/Net-PMP-0.006 - 06 May 2015 19:50:56 GMT - Search in distribution Net::Douban is a perl client wrapper on the Chinese website 'douban.com' API....REDICAPS/Net-Douban-1.14 - 14 Dec 2011 06:44:09 GMT - Search in distribution LETO/Net-Topsy-0.03 - 23 Sep 2009 01:21:590 - 11 Apr 2015 00:08:42 GMT - Search in distribution POE::Component::Github is a POE component that provides asynchronous access to the Github API <> to other POE sessions or components. It was inspired by Net::Github. The component handles communicating with the Github API an...BINGOS/POE-Component-Github-0.08 - 08 Mar 2011 01:20-1.006 (1 review) - 17 Aug 2014 08:36:59 GMT - Search in distribution RENEEB/Task-LiveDVD-FrankfurtPM-0.03 - 23 Oct 2013 12:07:55 GMT - Search in distribution
https://metacpan.org/search?q=MooseX-Net-API
CC-MAIN-2015-22
refinedweb
180
50.23
This is a Java Program to Compute GCD. Greatest Common Divisor of a given set of numbers is the highest number which divides exactly every number of the given set. Enter the two numbers as input. Now we use loops to find GCD of two given numbers. Here is the source code of the Java Program to Compute GCD. The Java program is successfully compiled and run on a Windows system. The program output is also shown below. import static java.lang.StrictMath.min; import java.util.Scanner; public class GCD { public static void main(String args[]) { int a, b, hcf = 1; Scanner s = new Scanner(System.in); System.out.print("Enter First Number:"); a = s.nextInt(); System.out.print("Enter Second Number:"); b = s.nextInt(); int n = min(a,b); for(int i = 2; i < n; i++) { while(a % i == 0 && b % i==0) { hcf = hcf * i; a = a / i; b = b / i; } } System.out.println("Greatest Common Divisor:"+hcf); } } Output: $ javac GCD.java $ java GCD Enter First Number:24 Enter Second Number:16 Greatest Common Divisor:8 Sanfoundry Global Education & Learning Series – 1000 Java Programs. Here’s the list of Best Reference Books in Java Programming, Data Structures and Algorithms.
http://www.sanfoundry.com/java-program-computing-gcd/
CC-MAIN-2017-30
refinedweb
202
60.51
logsumexp¶ - paddle. logsumexp ( x, axis=None, keepdim=False, name=None ) [source] This OP calculates the log of the sum of exponentials of xalong axis.\[\begin{split}logsumexp(x) = \\log\\sum exp(x)\end{split}\] - Parameters x (Tensor) – The input Tensor with data type float32, float64. axis (int|list|tuple, optional) – The axis along which to perform logsumexp calculations. axisshould be int, list(int) or tuple(int). If axisis a list/tuple of dimension(s), logsumexp is calculated along all element(s) of axis. axisor element(s) of axisshould be in range [-D, D), where D is the dimensions of x. If axisor element(s) of axisis less than 0, it works the same way as \(axis + D\) . If axisis None, logsumexp is calculated along all elements of x. Default is None. keepdim (bool, optional) – Whether to reserve the reduced dimension(s) in the output Tensor. If keep_dimis True, the dimensions of the output Tensor is the same as xexcept in the reduced dimensions(it is of size 1 in this case). Otherwise, the shape of the output Tensor is squeezed in axis. Default is False. name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name. - Returns Tensor, results of logsumexp along axisof x, with the same data type as x. Examples: import paddle x = paddle.to_tensor([[-1.5, 0., 2.], [3., 1.2, -2.4]]) out1 = paddle.logsumexp(x) # [3.4691226] out2 = paddle.logsumexp(x, 1) # [2.15317821, 3.15684602]
https://www.paddlepaddle.org.cn/documentation/docs/en/api/paddle/logsumexp_en.html
CC-MAIN-2021-25
refinedweb
248
52.15
Build Your First pip Package Build Your First pip Package If you're working in Python, you'll need to understand pip. In this post, we go through how to create and publish a pip package. Pip pip hooray! Join the DZone community and get the full member experience.Join For Free In this tutorial, we will learn how we can create a Python/pip package. If your requirements match any of these, this tutorial is for you. - You want to make your script platform independent. - You don't want to copy your executable script in every system you need. - You want to make your Python scripts publicly available to everyone and want to help the community. We are using pip to achieve the same. We will be able to install python script (bundled into pip package) easily on any system after following this tutorial. Code of this tutorial is available on GitHub here and pip package here. Note: Verified with Python 2 and Python 3 on *nix and windows. 1. Register Yourself The Python community maintains a repository similar to npm for open source packages. If you want to make your package publicly accessible you can upload it on PyPi. So, first of all, register yourself on PyPi:. I am assuming you have a GitHub account where you will upload your package code. If you want to keep your package private you can skip this step. We will use README.md directly from your GitHub project for this tutorial and it will be used as documentation of your package. 2. Checking the Required Tools Make sure you have Python and pip installed on your system. To check the installations: python -V # for python version (2/3) python -m pip --version The above commands should give you proper version outputs. If not, install Python and pip on your system. Install the required packages: - Setuptools: Setuptools is a package development process library designed for creating and distributing Python packages. - Wheel: The Wheel package provides a bdist_wheelcommand for setuptools. It creates .whl file which is directly installable through the pip installcommand. We'll then upload the same file to pypi.org. - Twine: The Twine package provides a secure, authenticated, and verified connection between your system and PyPi over HTTPS. - Tqdm: This is a smart progress meter used internally by Twine. sudo python -m pip install --upgrade pip setuptools wheel sudo python -m pip install tqdm sudo python -m pip install --user --upgrade twine 3. Setup Your Project - Create a package say, dokr_pkg. - Create your executable file inside the package, say, dokr. Create a script and without extensions ( dokr). #!/usr/bin/env python echo "hey there, this is my first pip package" - Make your script executable. chmod +x dokr - Create a setup file setup.py in your package. This file will contain all your package metadata information. import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name='dokr', version='0.1', scripts=['dokr'] , author="Deepak Kumar", author_email="deepak.kumar.iet@gmail.com", description="A Docker and AWS utility package", long_description=long_description, long_description_content_type="text/markdown", url="", packages=setuptools.find_packages(), classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], ) The following is metadata information: - Add a LICENSE to your project by creating a file called LICENSE. A sample license is available here. 4. Compiling Your Package Go into your package folder and execute this command: python setup.py bdist_wheel. This will create a structure like this: - build: build package information. - dist: Contains your .whl file. A WHL file is a package saved in the Wheel format, which is the standard built-package format used for Python distributions. You can directly install a .whl file using pip install some_package.whlon your system - project.egg.info: An egg package contains compiled bytecode, package information, dependency links, and captures the info used by the setup.py test command when running tests. 5. Install on Your Local Machine If you want to test your application on your local machine, you can install the .whl file using pip: python -m pip install dist/dokr-0.1-py3-none-any.whl 6. Upload on pip - Create pypirc: The Pypirc file stores the PyPi repository information. Create a file in the home directory - for Windows : C:\Users\UserName\.pypirc - for *nix : ~/.pypirc - And add the following content to it. Replace javatechywith your username. [distutils] index-servers=pypi [pypi] repository = username =javatechy 3. To upload your dist/*.whl file on PyPi, use Twine: python -m twine upload dist/* This command will upload your package on PyPi. This tutorial package is available here. 7. Conclusion We learned how to install and to create a pip package and make it available to everyone. This package can be easily installed on any machine that has pip by using the following commands: The source code can be found on GitHub and the pip package is on PyPi. If you enjoyed this post, check out Deepak's article on Dockerizing a Spring Boot Application. Opinions expressed by DZone contributors are their own. {{ parent.title || parent.header.title}} {{ parent.tldr }} {{ parent.linkDescription }}{{ parent.urlSource.name }}
https://dzone.com/articles/executable-package-pip-install
CC-MAIN-2019-47
refinedweb
856
59.6
Introduction In this tutorial, we will learn how to execute the Selenium code on the Safari browser. As we know, Selenium is compatible with multiple browsers. The different browsers need corresponding browser drivers, to run the Selenium script on them. However, the setup for Safari browser is little different from the other browsers like Chrome, Firefox, and IE. For Safari, Apple provides Safari driver for Selenium in the form of in-built plugin extension. All we have to do is to install that plugin. Now, let us go through all the steps required in detail. Pre-requisites The pre-requisites to perform the steps demonstrated in this tutorial are: - Download and install Java - Set up Java environment variables - Install Eclipse IDE - Download Selenium client Jars - Set Up Eclipse project with Selenium client Jars If any of the above steps are not completed, you will not be able to create your script and execute it. Please refer to the detailed individual tutorials available in our course for completing the above steps Set up for the Safari Browser Apple designed Safari Browser as a graphical web browser. It is the default browser on all Apple devices like Mac or iOS. In this tutorial, we will perform the following steps in order to run the Selenium script on the Safari: - Download Safari driver extension. - Execute the code. Download Safari driver - First, check the version of the Safari browser installed in your machine. To get the version, click on About Safari. It will show the current version installed. 2. Next, we need to add the Safari driver extension to the browser. For that, go to the Selenium official site and click on the latest version of the extension. 3. Click on SafariDriver.safariextz and click on Trust. It will add Safari Driver extension to your Safari browser. 4. Next, after adding the Safari driver extension, we need to do one more setting in the browser. Go to Safari > Preferences and click on Advanced. Select the check box for Show Develop menu at the bottom. This setting is done to allow the automation script to run on the browser. 5. Now, we will get Develop menu in which we should select the Allow Remote Automation option. Please select this option to allow the Safari driver to run the script on the browser. Now, after enabling Allow Remote Automation, Safari browser is ready to execute the Selenium script. Let us see what code changes are required when running with Safari browser. Code Changes For Safari browser, there is no need to set the driver path using System.setProperty in the automation script. Because Safari driver is added as an extension in the browser. But, we need to initialize driver instance to the Safari driver using the below line of code. //declare the instance of WebDriver to run on Safari browser WebDriver driver = new SafariDriver(); package seleniumAutomationTests; import org.openqa.selenium.WebDriver; import org.openqa.selenium.safari.SafariDriver; public class RunOnSafari { public static void main(String[] args) { // TODO Auto-generated method stub //declare the instance of WebDriver to run on Safari browser WebDriver driver = new SafariDriver(); //launch the application under test driver.get(""); //Print the title System.out.println(driver.getTitle()); //close the driver window driver.close(); } } Execution To execute the script, right click on the java class name in the package explorer and go to Run As > Java Application. It will start the execution of the automation script and perform the following: - Safari driver will start the Safari browser. - Launch the application under test on the browser. - Fetch the value of the page title of the web page and store it in a string. - Print the page title on the console - Close the web page and finish the execution of the script. Checking the output When we start the execution of the script, the application under test will start in a new Safari window. It will perform the actions as per the commands provided in the code. As a result, our test script will fetch the page title and driver.close() method will close the browser window. Common exceptions encountered: - SafariDriver requires Safari 10: It is thrown when the version of Safari browser is below Safari 10 as Safari driver requires at least Safari 10.x version. Therefore, resolve it by upgrading the version of the browser to the latest version. - Allow Remote Automation: It is thrown when Allow Remote Automation option is not selected under Develop menu in the Safari browser. Hence, restart the browser and enable the Allow Remote Automation before executing the script. Conclusion In this tutorial, we learned how to set up the Safari driver for executing the Selenium code on Safari browser. Safari driver is available as an extension to the browser. Therefore, we can add the extension to the browser. However, we don’t need to set the path of the driver in the script by using System.setProperty. Also, we can run the automation code on the browser simply by initializing the WebDriver instance to Safari driver.
https://www.tutorialcup.com/testing/selenium-tutorial/running-selenium-test-on-safari-browser.htm
CC-MAIN-2021-31
refinedweb
838
56.45
#include <Wt/WMediaPlayer.h> A media player. This widget implements a media player, suitable to play video or audio, and with a customizable user-interface. To support cross-browser playing of video or audio content, you may need to provide the contents appropriately encoded.). This widget relies on a third-party JavaScript component jPlayer, which is distributed together with Wt. The default user-interface can be themed using jPlayer themes. The theme is global (it applies to all media player instances), and is configured by loading a CSS stylesheet. The following code creates a video. Creates a new media player. The player is instantiated with default controls. Adds a source. Adds a media source. The source may be specified as a URL or as a dynamic resource. You may pass a null link if you want to indicate the media types you will use (later) without already loading data. Returns a control button. Clears all sources. Returns the user-interface controls widget. Returns the duration. The duration may be reported as 0 if the player has not yet loaded the media to determine the duration. Otherwise the duration is the duration of the loaded media, expressed in seconds. Returns a source. Returns the media source for the given encoding, which must have previously been added using addSource(). Mutes or unmutes the playback volume. Event that indicates that playback paused. The event is fired when playback has been paused. Returns the current playback rate. Event that indicates that playback started. The event is fired when playback has started (or is being continued). Returns a control progress bar. Returns the current player state. The state reflects in how far the media player has loaded the media, and has determined its characteristics. Refresh the widget. The refresh method is invoked when the locale is changed using WApplication::setLocale() or when the user hit the refresh button. The widget must actualize its contents in response.. Seeks to a time. If possible, the player sets the current time to the indicated time (expressed in seconds). Binds a control button. A control button is typically implemented as a WAnchor or a WPushButton (although any WInteractWidget can work). You should use this method in conjunction with setControlsWidget() to bind buttons in a custom control interface to media player functions. The default control widget implements all buttons using a WAnchor. Sets the user-interface controls widget. This sets a widget that contains the controls (buttons, text widgets, etc...) to allow the user to control the player. Widgets that implement the buttons, bars, and text holders should be bound to the player using setButton(), setText() and setProgressBar() calls. Setting a 0 widget will result in a player without controls. For an audio player this has the effect of being entirely invisible. The default controls widget is a widget that can be styled using a jPlayer CSS theme. Sets the playback rate. This modifies the playback rate, expressed as a ratio of the normal (natural) playback rate. The default value is 1.0 Binds a control progress bar. The progress bar for the MediaPlayerProgressBarId::Time indication should be contained in a WContainerWidget which bounds the width of the progress bar, rather than setting a width on the progress bar. This is because the progress bar may, in some cases, also be used to indicate which part of the media can be seeked, and for this its width is being manipulated. You should use this method in conjunction with setControlsWidget() to bind progress bars in a custom control interface to media player functions. Sets a text place-holder widget. This binds the widget that displays text such as current time and total duration of the loaded media. You should use this method in conjunction with setControlsWidget() to bind progress bars in a custom control interface to media player functions. Sets the media title. Sets the video size. This sets the size for the video. The actual size of the media player may be slightly larger, if the controlWidget take additional space (i.e. is not overlayed on top of the video). CSS Themes for the default jPlayer controls support two formats (480 x 270 and 640 x 360). The default video size is 480 x 270. Sets the volume. This modifies the volume, which must be a number between 0 and 1.0. The default value is 0.8 Event that indicates a time update. The event indicates that the currentTime() has changed. Returns the video height. Returns the video width. Returns the volume.
https://webtoolkit.eu/wt/doc/reference/html/classWt_1_1WMediaPlayer.html
CC-MAIN-2021-31
refinedweb
753
69.38
Technical Support On-Line Manuals RL-ARM User's Guide (MDK v4) #include <rl_usb.h> BOOL usbh_mem_init ( U8 idx, U32 *ptr_pool, U32 pool_sz ); The usbh_mem_init function initializes memory pool. The argument ctrl is the index of the controller (memory pool). The argument ptr_pool is the pointer to beginning of the memory pool. The argument pool_sz is the size of memory pool. The usbh_mem_init function is part of the RL-USB-Host Software Stack. The usbh_mem_init function returns one of the following manifest constants. usbh_mem_alloc, usbh_mem_free #include <rl_usb.h> U32 mpool[1024]; int main (void) { U8 *ptr_mem; .. if (!usbh_mem_init(0, (U32 *)&mpool, 4096)) { .. if (!usbh_mem_alloc (0, &ptr_mem, 8)) { .. usbh_mem_free (0, ptr.
http://www.keil.com/support/man/docs/rlarm/rlarm_usbh_mem_init.htm
CC-MAIN-2020-05
refinedweb
110
62.95
Getting Started With React And GraphQL Subscribe On YouTube DemoCode GraphQL is a way to send data over HTTP and is often presented as a revolutionary new way to think about APIs and seen as the successor of REST (Representational State Transfer). Indeed GraphQL is able to overcome major shortcomings of REST. GraphQL can be user in any application, web application or mobile app. In this tutorial you’ll learn how to use GraphQL in a React web application. To make use of GraphQL inside your React project we’ll be using the React Apollo library. If you like CodingTheSmartWay, then consider supporting us via Patreon. With your help we’re able to release developer tutorial more often. Thanks a lot! Setting Up The Project react-graphql $ cd react: Installing Dependencies The next step is to install needed dependencies. The following packages needs to be installed: - apollo-boost: Package containing everything you need to set up Apollo Client - react-apollo: View layer integration for React - graphql-tag: Necessary for parsing your GraphQL queries - graphql: Also parses your GraphQL queries The installation of these dependencies can be done by using the following NPM command: $ npm install apollo-boost react-apollo graphql-tag graphql Exploring The Initial Project Structure Having installed the dependencies we’re ready to take a look at the initial project structure: The important parts of the project are located in the src folder. The main entry point of the React application can be found in index.js. The code contained in this file is making sure that App component is rendered out to the DOM element with ID root. The implementation of App component can be found in App.js. Creating An Instance Of ApolloClient In order to be able to access a GraphQL service from our React application we need to create an instance of ApolloClient first. This is done in App.js by adding the following code: import ApolloClient from "apollo-boost"; const client = new ApolloClient({ uri: "[Insert URI of GraphQL endpoint]" }); First ApolloClient is imported from the apollo-boost library. A new instance of ApolloClient is created and stored in client. To create a new instance of ApolloClient you need to pass a configuration object to the constructor. This object must contain the uri property. The value of this property must be replaced which the URI of the GraphQL endpoint which should be accessed. Creating A GraphQL Endpoint To create an Apollo endpoint which can be used as the back-end for our React application you can choose between different options: - Implement a Node.js based GraphQL server by using Apollo Server () or the Express-GraphQL () library. You can follow the corresponding CodingTheSmartWay tutorials to setup the GraphQL server: - Apollo Server Introduction: - Creating A GraphQL Server With Node.js And Express: - Use Apollo Launchpad to create a GraphQL server online. Launchpad is an in-browser GraphQL server playground. You can write a GraphQL schema example in JavaScript, and instantly create a serverless, publicly-accessible GraphQL endpoint. - Use a preconfigured Apollo Launchpad like. This Launchpad exposes a GraphQL Online Courses API which we will be using for the following implementation steps. The corresponding endpoint of that Launchpad is, so that the value of the uri property needs to be set to that value: import ApolloClient from "apollo-boost"; const client = new ApolloClient({ uri: "" }); Connecting ApolloClient To Your React App Having established a connection to the GraphQL endpoint by using ApolloClient we now need to connect the instance of ApolloClient to the React app. To do so, please make sure to add the following lines of code in App.js: import { ApolloProvider } from "react-apollo"; ... const App = () => ( <ApolloProvider client={client}> <div> <h2>My first Apollo app</h2> </div> </ApolloProvider> ); Fist ApolloProvide is imported from the react-apollo library. The <ApolloProvider> element is then used in the component’s JSX code and is containing the template code which is used to render the component. Using Query Component To Request Data Within the src folder create a new file Courses.js and insert the following code: import React from 'react'; import { Query } from "react-apollo"; import gql from "graphql-tag"; const Courses = () => ( <Query query={gql` { allCourses { id title author description topic url } } `} > {({ loading, error, data }) => { if (loading) return <p>Loading...</p>; if (error) return <p>Error :(</p>; return data.allCourses.map(({ id, title, author, description, topic, url }) => ( <div key={id}> <p>{`${title} by ${author}`}</p> </div> )); }} </Query> ); export default Courses; This is the implementation of the Courses component. To retrieve data from the GraphQL endpoint this component makes use of another component from the React Apollo library: Query. The Query component makes it extremely easy to embed the GraphQL query directly in the JSX code of the component. Furthermore the Query component contains a callback method which is invoked once the GraphQL query is executed. Here we’re using the JavaScript map method to generate the HTML output for every single course record which is available in data.allCourses. Adding A Course Component So far the output of courses is done within the Courses component. In the next step we’re going to introduce a new component to our project: Course. This component should then contain the code which is needed to output a single course. Once this component is available in can be used in Courses component. First let’s add a new file Course.js to the project and insert the following lines of code: import React from 'react'; const Course = (props) => ( <div key={props.course.id}> <p>{`${props.course.title} by ${props.course.author}`}</p> </div> ); export default Course; The implementation of this component is quite simple. The current course is handed over to Course component as a property and is available via props.course. In order to make use of Course component in Courses component we first need to make sure that it’s imported in file Courses.js: import Course from './Course'; Now this component can be used to output each course inside the callback function which is passed to the call of map: return data.allCourses.map((currentCourse) => ( <Course course={currentCourse} /> )); Adding Bootstrap Because the user interface of our sample React application should look a little nicer, we’re going to use the Bootstrap framework in the next step. To add Bootstrap to the project just use the following NPM command: $ npm install bootstrap With this command we’re making sure that the Bootstrap framework is installed in the node_modules subfolder of our project. Next we need to import bootstrap.min.css from that location in index.js: import '../node_modules/bootstrap/dist/css/bootstrap.min.css'; With the import statement in place it’s possible to make use of Bootstrap’s CSS classes. First in App.js: const App = () => ( <ApolloProvider client={client}> <div className="container"> <nav className="navbar navbar-dark bg-primary"> <a className="navbar-brand" href="#">React and GraphQL - Sample Application</a> </nav> <div> <Courses /> </div> </div> </ApolloProvider> ); Second in Course.js: import React from 'react'; const Course = (props) => ( <div className="card" style={{'width': '100%', 'marginTop': '10px'}}> <div className="card-body"> <h5 className="card-title">{props.course.title}</h5> <h6 className="card-subtitle mb-2 text-muted">by {props.course.author}</h6> <p className="card-text">{props.course.description}</p> <a href={props.course.url}Go to course ...</a> </div> </div> ); export default Course; The final result should then look like the following: Conclusion With the release of React Apollo 2.1 it’s easier than ever to configure and connect Apollo to your React application. By using the brand new Query component you’re able to embed the GraphQL query inside your component. Using higher order components (like before) is no longer needed.: The Complete React Web App Developer Course Check out the great Complete React Web App Developer Course by Andrew Mead with thousands of students already enrolled: The Complete React Web App Developer Course - You’ll learn how to develop, test, and deploy React web applications - Learn how to setup and automate testing using Karma and Mocha - Understand the rich ecosystem of 3rd-party libraries like Redux and Webpack - Learn to style applications using the Foundation framework
https://codingthesmartway.com/getting-started-with-react-and-graphql/
CC-MAIN-2020-40
refinedweb
1,358
53.51
08 May 2012 11:33 [Source: ICIS news] SINGAPORE (ICIS) – ?xml:namespace> The company will decide when to restart the plant, depending on demand conditions, said the source. Zhengdan Chemical produced 4,500 tonnes of solvent oils every month at the Many buyers are expecting cuts in solvent oils prices in the coming days as crude prices are falling, traders said. The prices in east China are at yuan (CNY) 8,700-8,800/tonne ($1,381-1,397/tonne) for No 100 solvent oils and CNY8,300-8,400/tonne for No 105 solvent oils on 8 May, down by CNY100-200/tonne and CNY200-300/tonne on 30 April, respectively, according to C1 Energy,
http://www.icis.com/Articles/2012/05/08/9557145/chinas-jiangsu-zhengdan-chemical-halts-solvent-oil-unit-output.html
CC-MAIN-2015-22
refinedweb
116
63.73
Exploring 25K AWS S3 buckets. Today we are in 2018 and I’ve decided to check what is the current status of the problem. Additionally, I want to present my techniques of performing such research — if I missed any clever one, please let me know in the comments. Let’s start with some theory All the AWS S3 buckets can be accessible using the following URLs: https://[bucket_name].s3.amazonaws.com/ https://[aws_endpoint].amazonaws.com/[bucket_name]/ or using AWS CLI: $ aws s3 ls --region [region_name] s3://[bucket_name] Not often people point to the need of using a region parameter. However, some buckets don’t work without specifying a region. I don’t see a pattern when it works and when it doesn’t so a good practice is to always add this parameter :) So, generally speaking finding a valid bucket equals finding a subdomain of s3.amazonaws.comor [aws_endpoint].amazonaws.com . Below I’m gonna go through 4 methods which may be helpful in this task. Bruteforcing Each bucket name has to be unique and can contain only 3 to 63 alphanumeric characters with a few exceptions (can contain ‘-‘ or ‘.’ but it cannot be started or ended with). That being said, we’re weaponized with knowledge enough to find all S3 buckets, but let’s be honest — it would work rather for short names. Nevertheless, people tend to use some patterns in naming, e.g. [company_name]-dev, or [company_name].backups. Once you’re searching for a particular company’s bucket then you can easily automate a process of verifying such well known patterns using tools like LazyS3 or aws-s3-bruteforce. Let’s say we have a company called Rzepsky. A simple command: $ ruby lazys3.rb rzepsky reveals a rzepsky-dev bucket: But what if you want to harvest as many buckets as possible without any specific name to start with? Keep reading this post ;) Wayback Machine Have you ever heard about the Wayback Machine? Quoting Wikipedia: The Wayback Machine is a digital archive of the World Wide Web and other information on the Internet created by the Internet Archive. Some resources in this digital archive are stored on Amazon infrastructure. That being said, if the Wayback Machine has indexed just one photo on a S3 bucket, we can retrieve this information and check if this bucket contains any public resources. Even when the indexed photo is already removed (or access to it is denied) you still have the name of the bucket, what gives a hope for finding interesting files inside. For asking the Wayback Machine’s API, you can use a Metasploit module called enum_wayback: As you may remember from the beginning of this post you can refer to bucket’s content also using a URL with region specification. So, to get even better results, we can check subdomains of every possible Amazon S3 endpoint, by a simple bash one-liner: $ while read -r region; do msfconsole -x "use \ auxiliary/scanner/http/enum_wayback; set DOMAIN $region;\ set OUTFILE $region.txt; run; exit"; done < s3_regions.txt Very often the Wayback Machine gives you back few thousands of pictures placed in just one bucket. So, you have to do some operations to pull out only valid and unique bucket names. Programs like cut and awk are great friends here. The Wayback Machine gave me 23498 potential buckets in a form of 398,7 MB txt files. 4863 of those buckets were publicly open. Querying 3rd parties Another technique which I’d like to introduce is querying 3rd parties, like Google, Bing, VirusTotal etc. There are many tools which can automate the process of harvesting interesting information from external services. One of them is the Sublist3r: Again, we should search subdomains of each region and then pull out only unique bucket names. A quick bash one-liner: $ while read -r region; do python3 sublist3r.py -d $region \ > $region.txt; done < s3_regions.txt gives as the result 756 from which… only 1 bucket was collectable. Beer for the administrators! Searching in certificate transparency logs The last technique which I would like to present you is searching bucket names by watching certificate transparency logs. If you aren’t familiar with certificate transparency, I recommend you watching this presentation. Basically, every issued TLS certificate is logged and all those logs are publicly accessible. The main goal of this idea is to verify if any certificate is not mistakenly or maliciously used. However, the idea of public logs reveals all domains, including… yeah, S3 buckets too. Good news is that there’s already available tool which is doing a search for you — the bucket-stream. Even better news is that this tool is also verifying permissions to the bucket it found. So, let’s give it a shot: $ python3 bucket-stream.py --threads 100 --log After checking 571134 possibilities the bucket-scanner gave me back 398 valid buckets. 377 of them were open. Verifying the bucket’s content Alright, we found thousands of bucket names and what next? Well, you can for example check if any of those buckets allow for public or for Any authenticated AWS user (which is basically the same as public) access. For that purpose you can use my script BucketScanner — it simply lists all accessible files and also verifies the WRITE permissions to a bucket. However, for the purpose of this research I modified a bucket_reader method in the following way: def bucket_reader(bucket_name): region = get_region(bucket_name) if region == 'None': pass else: bucket = get_bucket(bucket_name) results = "" try: for s3_object in bucket.objects.all(): if s3_object.key: print "{0} is collectable".format(bucket_name) results = "{0}\n".format(bucket_name) append_output(results) break While it isn’t the most elegant way it does its job — if just one file was collectable in the bucket, then my modified scanner reports this bucket as collectable. The risks Among the publicly accessible files you can find really interesting ones. But leaking of sensitive data is not the only risk. Some buckets are publicly writable. For sure an attacker can use such bucket as a malware distribution point. It is even more scary if you’re using such bucket for distributing a legit software among your employees — just imagine such scenario: you’re guiding all newcomers to install a software from the company’s bucket and this software is already overwritten by an attacker with infected installer. The other variation of this scenario would be trolling S3 researchers — e.g. by uploading infected file with a tempting name, like “Salary report — 2017.pdf” (of course all responsible researchers always download untrusted files to sandboxed environment, right?) Another risk with publicly writable buckets is… that you can lose all your data. Even if you don’t have DELETE permissions to bucket’s objects, but just a WRITE permission you can still overwrite any file. That being said, if you overwrite any file with empty file it means that this file is no longer available for anyone. Let’s take a look at this example: The only mechanism which can save your data in such scenario is enabling a versioning. However, this mechanism can be expensive (it doubles the size of used space in your bucket) and not many people decide to use it. I’ve also heard an argument: Oh, c’mon it’s just a bucket for testing purpose. Well, if your “test” bucket becomes a storage for illegal content, then… sorry dude but it’s your credit card pinned to this account. Any brighter future? The problem with S3 buckets permissions still exists and I don’t expect a spectacular change in the nearest future. IMHO people give the public access, because it always works — you don’t have to worry about specifying permissions when a S3 service cooperates with other services. The other reason can be a simple mistake in configuring permissions (e.g. putting a “*” character in a wrong place in a bucket policy) or not understanding predefined groups (e.g. a group “Any authenticated AWS account” can be still set up via AWS CLI). Another problem is how to report such problems? There’s no email pinned to the bucket so you can never be sure who should you contact with. The names of buckets may indicate they belong to company X, but remember that anyone can loosely name it. So watch out for trollers! Summary For 24652 scanned buckets I was able to collect files from 5241 buckets (21%) and to upload arbitrary files to 1365 buckets (6%). Based on the results I can say with no doubt that the problem still exist. While some buckets are intentionally opened (e.g. serves some pictures, company brochures etc.), neither of them should be publicly writable. I’m pretty sure there are other cool methods of finding even more buckets, so the only reasonable countermeasure seems to be… setting right permissions to your bucket😃 Please find also my Seven-Step Guide to SecuRing your AWS Kingdom.
https://medium.com/securing/exploring-25k-aws-s3-buckets-f22ec87c3f2a
CC-MAIN-2018-51
refinedweb
1,492
63.49
Difference between revisions of "Clojure Scripting" Revision as of 07:41, 31 January 2009 Contents - 1 Clojure tutorial for ImageJ - 1.1 Language basics - 1.2 Calling methods and variables on a java object - 1.3 Calling static fields and methods: namespace syntax - 1.4 Defining variables: obtaining the current image - 1.5 Creating objects: invoking constructors - 1.6 Defining a closure - 1.7 Looping an array of pixels - 1.8 Executing commands from the menus - 1.9 Creating and using Clojure scripts as ImageJ plugins - 1.10 Using java beans for quick and convenient access to an object's fields - 2 Examples - 3 Appendix - 3.1 Defining the output stream - 3.2 Namespaces - 3.3 Forget/Remove all variables from a namespace - 3.4 JVM arguments - 3.5 Reflection - 3.6 Lambda functions - 3.7 Built-in documentation - 3.8 A fibonacci sequence: lazy and infinite sequences - 3.9 Creating shallow and deep sequences from java arrays - 3.10 Generating java classes in .class files from clojure code - 3.11 References, concurrency, transactions and synchronization - 3.12 Using try/catch/finally and throwing Exceptions - 3.13 Executing a command in a shell and capturing its output/Scripting*. The Clojure Interpreter binds it to the PrintWriter that prints to the interpreter text area, by executing any typed in code within the following binding: (binding [*out* (Clojure.Clojure_Interpreter/getStdOut)] ; any typed input here ) Namespaces -)): ; List all files)))
https://imagej.net/index.php?title=Clojure_Scripting&oldid=853&diff=prev
CC-MAIN-2020-24
refinedweb
236
55.3
Before we get to the central parts of the book, let us introduce essential concepts of software testing. Why is it necessary to test software at all? How does one test software? How can one tell whether a test has been successful? How does one know if one has tested enough? In this chapter, let us recall the most important concepts, and at the same time get acquainted with Python and interactive notebooks. Let's start with a simple example. Your co-worker has been asked to implement a square root function $\sqrt{x}$. (Let's assume for a moment that the environment does not already have one.) After studying the Newton–Raphson method, she comes up with the following Python code, claiming that, in fact, this my_sqrt() function computes square roots. def my_sqrt(x): """Computes the square root of x, using the Newton-Raphson method""" approx = None guess = x / 2 while approx != guess: approx = guess guess = (approx + x / approx) / 2 return approx Your job is now to find out whether this function actually does what it claims to do. If you're new to Python, you might first have to understand what the above code does. We very much recommend the Python tutorial to get an idea on how Python works. The most important things for you to understand the above code are these three: whilebodies are defined by being indented; x, approx, or guessis determined at run-time. while, if), assignments ( =), or comparisons ( ==, !=, <). With that, you can already understand what the above code does: Starting with a guess of x / 2, it computes better and better approximations in approx until the value of approx no longer changes. This is the value that finally is returned. To find out whether my_sqrt() works correctly, we can test it with a few values. For x = 4, for instance, it produces the correct value: my_sqrt(4) 2.0 The upper part above my_sqrt(4) (a so-called cell) is an input to the Python interpreter, which by default evaluates it. The lower part ( 2.0) is its output. We can see that my_sqrt(4) produces the correct value. The same holds for x = 2.0, apparently, too: my_sqrt(2) 1.414213562373095 If you are reading this in the interactive notebook, you can try out my_sqrt() with other values as well. Click on one of the above cells with invocations of my_sqrt() and change the value – say, to my_sqrt(1). Press Shift+Enter (or click on the play symbol) to execute it and see the result. If you get an error message, go to the above cell with the definition of my_sqrt(). To see how my_sqrt() operates, a simple strategy is to insert print() statements in critical places. You can, for instance, log the value of approx, to see how each loop iteration gets closer to the actual value: def my_sqrt_with_log(x): """Computes the square root of x, using the Newton–Raphson method""" approx = None guess = x / 2 while approx != guess: print("approx =", approx) # <-- New approx = guess guess = (approx + x / approx) / 2 return approx my_sqrt_with_log(9) approx = None approx = 4.5 approx = 3.25 approx = 3.0096153846153846 approx = 3.000015360039322 approx = 3.0000000000393214 3.0 Interactive notebooks also allow to launch an interactive debugger – insert a "magic line" %%debug at the top of a cell and see what happens. Unfortunately, interactive debuggers interfere with our dynamic analysis techniques, so we mostly use logging and assertions for debugging. Let's get back to testing. We can read and run the code, but are the above values of my_sqrt(2) actually correct? We can easily verify by exploiting that $\sqrt{x}$ squared again has to be $x$, or in other words $\sqrt{x} \times \sqrt{x} = x$. Let's take a look: my_sqrt(2) * my_sqrt(2) 1.9999999999999996 Okay, we do have some rounding error, but otherwise, this seems just fine. What we have done now is that we have tested the above program: We have executed it on a given input and checked its result whether it is correct or not. Such a test is the bare minimum of quality assurance before a program goes into production. So far, we have tested the above program manually, that is, running it by hand and checking its results by hand. This is a very flexible way of testing, but in the long run, it is rather inefficient: This is why it is very useful to automate tests. One simple way of doing so is to let the computer first do the computation, and then have it check the results. For instance, this piece of code automatically tests whether $\sqrt{4} = 2$ holds: result = my_sqrt(4) expected_result = 2.0 if result == expected_result: print("Test passed") else: print("Test failed") Test passed The nice thing about this test is that we can run it again and again, thus ensuring that at least the square root of 4 is computed correctly. But there are still a number of issues, though: Let us address these issues one by one. First, let's make the test a bit more compact. Almost all programming languages do have a means to automatically check whether a condition holds, and stop execution if it does not. This is called an assertion, and it is immensely useful for testing. In Python, the assert statement takes a condition, and if the condition is true, nothing happens. (If everything works as it should, you should not be bothered.) If the condition evaluates to false, though, assert raises an exception, indicating that a test just failed. In our example, we can use assert to easily check whether my_sqrt() yields the expected result as above: assert my_sqrt(4) == 2 As you execute this line of code, nothing happens: We just have shown (or asserted) that our implementation indeed produces $\sqrt{4} = 2$. Remember, though, that floating-point computations may induce rounding errors. So we cannot simply compare two floating-point values with equality; rather, we would ensure that the absolute difference between them stays below a certain threshold value, typically denoted as $\epsilon$ or epsilon. This is how we can do it: EPSILON = 1e-8 assert abs(my_sqrt(4) - 2) < EPSILON We can also introduce a special function for this purpose, and now do more tests for concrete values: def assertEquals(x, y, epsilon=1e-8): assert abs(x - y) < epsilon assertEquals(my_sqrt(4), 2) assertEquals(my_sqrt(9), 3) assertEquals(my_sqrt(100), 10) Seems to work, right? If we know the expected results of a computation, we can use such assertions again and again to ensure our program works correctly. assertEquals(my_sqrt(2) * my_sqrt(2), 2) assertEquals(my_sqrt(3) * my_sqrt(3), 3) assertEquals(my_sqrt(42.11) * my_sqrt(42.11), 42.11) Still seems to work, right? Most importantly, though, $\sqrt{x} \times \sqrt{x} = x$ is something we can very easily test for thousands of values: for n in range(1, 1000): assertEquals(my_sqrt(n) * my_sqrt(n), n) How much time does it take to test my_sqrt() with 100 values? Let's see. We use our own Timer module to measure elapsed time. To be able to use Timer, we first import our own utility module, which allows us to import other notebooks. import fuzzingbook_utils from Timer import Timer with Timer() as t: for n in range(1, 10000): assertEquals(my_sqrt(n) * my_sqrt(n), n) print(t.elapsed_time()) 0.02194777800468728 10,000 values take about a hundredth of a second, so a single execution of my_sqrt() takes 1/1000000 second, or about 1 microseconds. Let's repeat this with 10,000 values picked at random. The Python random.random() function returns a random value between 0.0 and 1.0: import random with Timer() as t: for i in range(10000): x = 1 + random.random() * 1000000 assertEquals(my_sqrt(x) * my_sqrt(x), x) print(t.elapsed_time()) 0.026926074991934 Within a second, we have now tested 10,000 random values, and each time, the square root was actually computed correctly. We can repeat this test with every single change to my_sqrt(), each time reinforcing our confidence that my_sqrt() works as it should. Note, though, that while a random function is unbiased in producing random values, it is unlikely to generate special values that drastically alter program behavior. We will discuss this later below. Such an automatic run-time check is very easy to implement: def my_sqrt_checked(x): root = my_sqrt(x) assertEquals(root * root, x) return root Now, whenever we compute a root with my_sqrt_checked()$\dots$ my_sqrt_checked(2.0) 1.414213562373095 we already know that the result is correct, and will so for every new successful computation. Automatic run-time checks, as above, assume two things, though: One has to be able to formulate such run-time checks. Having concrete values to check against should always be possible, but formulating desired properties in an abstract fashion can be very complex. In practice, you need to decide which properties are most crucial, and design appropriate checks for them. Plus, run-time checks may depend not only on local properties, but on several properties of the program state, which all have to be identified. One has to be able to afford such run-time checks. In the case of my_sqrt(), the check is not very expensive; but if we have to check, say, a large data structure even after a simple operation, the cost of the check may soon be prohibitive. In practice, run-time checks will typically be disabled during production, trading reliability for efficiency. On the other hand, a comprehensive suite of run-time checks is a great way to find errors and quickly debug them; you need to decide how many such capabilities you would still want during production. At this point, we may make my_sqrt() available to other programmers, who may then embed it in their code. At some point, it will have to process input that comes from third parties, i.e. is not under control by the programmer. Let us simulate this system input by assuming a program sqrt_program() whose input is a string under third-party control: def sqrt_program(arg): x = int(arg) print('The root of', x, 'is', my_sqrt(x)) We assume that sqrt_program is a program which accepts system input from the command line, as in $ sqrt_program 4 2 We can easily invoke sqrt_program() with some system input: sqrt_program("4") The root of 4 is 2.0 What's the problem? Well, the problem is that we do not check external inputs for validity. Try invoking sqrt_program(-1), for instance. What happens? Indeed, if you invoke my_sqrt() with a negative number, it enters an infinite loop. For technical reasons, we cannot have infinite loops in this chapter (unless we'd want the code to run forever); so we use a special with ExpectTimeOut(1) construct to interrupt execution after one second. from ExpectError import ExpectTimeout with ExpectTimeout(1): sqrt_program("-1") Traceback (most recent call last): File "<ipython-input-25-add01711282b>", line 2, in <module> sqrt_program("-1") File "<ipython-input-22-53e8ec8bb3ca>", line 3, in sqrt_program print('The root of', x, 'is', my_sqrt(x)) File "<ipython-input-1-47185ad159a1>", line 5, in my_sqrt while approx != guess: File "<ipython-input-1-47185ad159a1>", line 5, in my_sqrt while approx != guess: File "ExpectError.ipynb", line 59, in check_time TimeoutError (expected) The above message is an error message, indicating that something went wrong. It lists the call stack of functions and lines that were active at the time of the error. The line at the very bottom is the line last executed; the lines above represent function invocations – in our case, up to my_sqrt(x). We don't want our code terminating with an exception. Consequently, when accepting external input, we must ensure that it is properly validated. We may write, for instance: def sqrt_program(arg): x = int(arg) if x < 0: print("Illegal Input") else: print('The root of', x, 'is', my_sqrt(x)) and then we can be sure that my_sqrt() is only invoked according to its specification. sqrt_program("-1") Illegal Input But wait! What happens if sqrt_program() is not invoked with a number? Then we would try to convert a non-number string, which would also result in a runtime error: from ExpectError import ExpectError with ExpectError(): sqrt_program("xyzzy") Traceback (most recent call last): File "<ipython-input-29-8c5aae65a938>", line 2, in <module> sqrt_program("xyzzy") File "<ipython-input-26-ea86281b33cf>", line 2, in sqrt_program x = int(arg) ValueError: invalid literal for int() with base 10: 'xyzzy' (expected) Here's a version which also checks for bad inputs: def sqrt_program(arg): try: x = float(arg) except ValueError: print("Illegal Input") else: if x < 0: print("Illegal Number") else: print('The root of', x, 'is', my_sqrt(x)) sqrt_program("4") The root of 4.0 is 2.0 sqrt_program("-1") Illegal Number sqrt_program("xyzzy") Illegal Input We have now seen that at the system level, the program must be able to handle any kind of input gracefully without ever entering an uncontrolled state. This, of course, is a burden for programmers, who must struggle to make their programs robust for all circumstances. This burden, however, becomes a benefit when generating software tests: If a program can handle any kind of input (possibly with well-defined error messages), we can also send it any kind of input. When calling a function with generated values, though, we have to know its precise preconditions. In the case of my_sqrt(), for instance, computing $\sqrt{0}$ results in a division by zero: with ExpectError(): root = my_sqrt(0) Traceback (most recent call last): File "<ipython-input-34-24ede1f53910>", line 2, in <module> root = my_sqrt(0) File "<ipython-input-1-47185ad159a1>", line 7, in my_sqrt guess = (approx + x / approx) / 2 ZeroDivisionError: float division by zero (expected) In our tests so far, we have not checked this condition, meaning that a program which builds on $\sqrt{0} = 0$ will surprisingly fail. But even if we had set up our random generator to produce inputs in the range of 0–1000000 rather than 1–1000000, the chances of it producing a zero value by chance would still have been one in a million. If the behavior of a function is radically different for few individual values, plain random testing has few chances to produce these. We can, of course, fix the function accordingly, documenting the accepted values for x and handling the special case x = 0: def my_sqrt_fixed(x): assert 0 <= x if x == 0: return 0 return my_sqrt(x) With this, we can now correctly compute $\sqrt{0} = 0$: assert my_sqrt_fixed(0) == 0 Illegal values now result in an exception: with ExpectError(): root = my_sqrt_fixed(-1) Traceback (most recent call last): File "<ipython-input-37-55b1caf1586a>", line 2, in <module> root = my_sqrt_fixed(-1) File "<ipython-input-35-f3e21e80ddfb>", line 2, in my_sqrt_fixed assert 0 <= x AssertionError (expected) Still, we have to remember that while extensive testing may give us a high confidence into the correctness of a program, it does not provide a guarantee that all future executions will be correct. Even run-time verification, which checks every result, can only guarantee that if it produces a result, the result will be correct; but there is no guarantee that future executions may not lead to a failing check. As I am writing this, I believe that my_sqrt_fixed(x) is a correct implementation of $\sqrt{x}$, but I cannot be 100% certain. With the Newton-Raphson method, we may still have a good chance of actually proving that the implementation is correct: The implementation is simple, the math is well-understood. Alas, this is only the case for few domains. If we do not want to go into full-fledged correctness proofs, our best chance with testing is to This is what we do in the remainder of this course: Devise techniques that help us to thoroughly test a program, as well as techniques that help us checking its state for correctness. Enjoy! From here, you can move on how to Enjoy the read! There is a large number of works on software testing and analysis. For this book, we are happy to recommend "Software Testing and Analysis" \cite{Pezze2008} as an introduction to the field; its strong technical focus very well fits our methodology. Other important must-reads with a comprehensive approach to software testing, including psychology and organization, include "The Art of Software Testing" \cite{Myers2004} as well as "Software Testing Techniques" \cite{Beizer1990}. def shellsort(elems): sorted_elems = elems.copy() gaps = [701, 301, 132, 57, 23, 10, 4, 1] for gap in gaps: for i in range(gap, len(sorted_elems)): temp = sorted_elems[i] j = i while j >= gap and sorted_elems[j - gap] > temp: sorted_elems[j] = sorted_elems[j - gap] j -= gap sorted_elems[j] = temp return sorted_elems A first test indicates that shellsort() might actually work: shellsort([3, 2, 1]) [1, 2, 3] The implementation uses a list as argument elems (which it copies into sorted_elems) as well as for the fixed list gaps. Lists work like arrays in other languages: a = [5, 6, 99, 7] print("First element:", a[0], "length:", len(a)) First element: 5 length: 4 The range() function returns an iterable list of elements. It is often used in conjunction with for loops, as in the above implementation. for x in range(1, 5): print(x) 1 2 3 4 Your job is now to thoroughly test shellsort() with a variety of inputs. First, set up assert statements with a number of manually written test cases. Select your test cases such that extreme cases are covered. Use == to compare two lists. Solution. Here are a few selected test cases: # Standard lists assert shellsort([3, 2, 1]) == [1, 2, 3] assert shellsort([1, 2, 3, 4]) == [1, 2, 3, 4] assert shellsort([6, 5]) == [5, 6] # Check for duplicates assert shellsort([2, 2, 1]) == [1, 2, 2] # Empty list assert shellsort([]) == [] Second, create random lists as arguments to shellsort(). Make use of the following helper predicates to check whether the result is (a) sorted, and (b) a permutation of the original. def is_sorted(elems): return all(elems[i] <= elems[i + 1] for i in range(len(elems) - 1)) is_sorted([3, 5, 9]) True def is_permutation(a, b): return len(a) == len(b) and all(a.count(elem) == b.count(elem) for elem in a) is_permutation([3, 2, 1], [1, 3, 2]) True Start with a random list generator, using [] as the empty list and elems.append(x) to append an element x to the list elems. Use the above helper functions to assess the results. Generate and test 1,000 lists. Solution. Here's a simple random list generator: def random_list(): length = random.randint(1, 10) elems = [] for i in range(length): elems.append(random.randint(0, 100)) return elems random_list() [61, 23, 61, 68] elems = random_list() print(elems) [51, 47, 88, 14, 38] sorted_elems = shellsort(elems) print(sorted_elems) [14, 38, 47, 51, 88] assert is_sorted(sorted_elems) and is_permutation(sorted_elems, elems) Here's the test for 1,000 lists: for i in range(1000): elems = random_list() sorted_elems = shellsort(elems) assert is_sorted(sorted_elems) and is_permutation(sorted_elems, elems) Given an equation $ax^2 + bx + c = 0$, we want to find solutions for $x$ given the values of $a$, $b$, and $c$. The following code is supposed to do this, using the equation $$x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}$$ def quadratic_solver(a, b, c): q = b * b - 4 * a * c solution_1 = (-b + my_sqrt_fixed(q)) / (2 * a) solution_2 = (-b - my_sqrt_fixed(q)) / (2 * a) return (solution_1, solution_2) quadratic_solver(3, 4, 1) (-0.3333333333333333, -1.0) The above implementation is incomplete, though. You can trigger my_sqrt_fixed(). How does one do that, and how can one prevent this? Solution. Here are two inputs that trigger the bugs: with ExpectError(): print(quadratic_solver(3, 2, 1)) Traceback (most recent call last): File "<ipython-input-57-d23ed48ac7b4>", line 2, in <module> print(quadratic_solver(3, 2, 1)) File "<ipython-input-55-54638f6c293f>", line 3, in quadratic_solver solution_1 = (-b + my_sqrt_fixed(q)) / (2 * a) File "<ipython-input-35-f3e21e80ddfb>", line 2, in my_sqrt_fixed assert 0 <= x AssertionError (expected) with ExpectError(): print(quadratic_solver(0, 0, 1)) Traceback (most recent call last): File "<ipython-input-58-f797613c5ebb>", line 2, in <module> print(quadratic_solver(0, 0, 1)) File "<ipython-input-55-54638f6c293f>", line 3, in quadratic_solver solution_1 = (-b + my_sqrt_fixed(q)) / (2 * a) ZeroDivisionError: division by zero (expected) Solution. Here is an appropriate extension of quadratic_solver() that takes care of all the corner cases: def quadratic_solver_fixed(a, b, c): if a == 0: if b == 0: if c == 0: # Actually, any value of x return (0, None) else: # No value of x can satisfy c = 0 return (None, None) else: return (-c / b, None) q = b * b - 4 * a * c if q < 0: return (None, None) if q == 0: solution = -b / 2 * a return (solution, None) solution_1 = (-b + my_sqrt_fixed(q)) / (2 * a) solution_2 = (-b - my_sqrt_fixed(q)) / (2 * a) return (solution_1, solution_2) with ExpectError(): print(quadratic_solver_fixed(3, 2, 1)) (None, None) with ExpectError(): print(quadratic_solver_fixed(0, 0, 1)) (None, None) Solution. Consider the code above. If we choose the full range of 32-bit integers for a, b, and c, then the first condition alone, both a and b being zero, has a chance of $p = 1 / (2^{32} * 2^{32})$; that is, one in 18.4 quintillions: combinations = 2 ** 32 * 2 ** 32 combinations 18446744073709551616 If we can do a billion tests per second, how many years would we have to wait? tests_per_second = 1000000000 seconds_per_year = 60 * 60 * 24 * 365.25 tests_per_year = tests_per_second * seconds_per_year combinations / tests_per_year 584.5420460906264 We see that on average, we'd have to wait for 584 years. Clearly, pure random choices are not sufficient as sole testing strategy.
https://nbviewer.jupyter.org/github/uds-se/fuzzingbook/blob/master/docs/notebooks/Intro_Testing.ipynb
CC-MAIN-2019-43
refinedweb
3,606
59.13
An advanced form and widget framework for Zope 3 Project description z3c.form z3c.form provides an implementation for both HTML and JSON forms and according widgets. Its goal is to provide a simple API but with the ability to easily customize any data or steps. There are currently two maintained branches: - master with the latest changes - 3.x without the object widget overhaul and still including the ObjectSubForm and the SubformAdapter. Documentation on this implementation and its API can be found at Contents - z3c.form - Changelog - 4.1.2 (2019-03-04) - 4.1.1 (2018-11-26) - 4.1.0 (2018-11-15) - 4.0.0 (2017-12-20) - 3.5.0 (2017-09-19) - 3.4.0 (2016-11-15) - 3.3.0 (2016-03-09) - 3.2.10 (2016-03-09) - 3.2.9 (2016-02-01) - 3.2.8 (2015-11-09) - 3.2.7 (2015-09-20) - 3.2.6 (2015-09-10) - 3.2.5 (2015-09-09) - 3.2.4 (2015-07-18) - 3.2.3 (2015-03-21) - 3.2.2 (2015-03-21) - 3.2.1 (2014-06-09) - 3.2.0 (2014-03-18) - 3.1.1 (2014-03-02) - 3.1.0 (2013-12-02) - 3.0.5 (2013-10-09) - 3.0.4 (2013-10-06) - 3.0.3 (2013-09-06) - 3.0.2 (2013-08-14) - 3.0.1 (2013-06-25) - 3.0.0 (2013-06-24) - 3.0.0a3 (2013-04-08) - 3.0.0a2 (2013-02-26) - 3.0.0a1 (2013-02-24) - 2.9.1 (2012-11-27) - 2.9.0 (2012-09-17) - 2.8.2 (2012-08-17) - 2.8.1 (2012-08-06) - 2.8.0 (2012-08-06) - 2.7.0 (2012-07-11) - 2.6.1 (2012-01-30) - 2.6.0 (2012-01-30) - 2.5.1 (2011-11-26) - 2.5.0 (2011-10-29) - 2.4.4 (2011-07-11) - 2.4.3 (2011-05-20) - 2.4.2 (2011-01-22) - 2.4.1 (2010-07-18) - 2.4.0 (2010-07-01) - 2.3.4 (2010-05-17) - 2.3.3 (2010-04-20) - 2.3.2 (2010-01-21) - 2.3.1 (2010-01-18) - 2.3.0 (2009-12-28) - 2.2.0 (2009-10-27) - 2.1.0 (2009-07-22) - 2.0.0 (2009-06-14) - 1.9.0 (2008-08-26) - 1.8.2 (2008-04-24) - 1.8.1 (2008-04-08) - 1.8.0 (2008-01-23) - 1.7.0 (2007-10-09) - 1.6.0 (2007-08-24) - 1.5.0 (2007-07-18) - 1.4.0 (2007-06-29) - 1.3.0 (2007-06-22) - 1.2.0 (2007-05-30) - 1.1.0 (2007-05-30) - 1.0.0 (2007-05-24) Changelog 4.1.2 (2019-03-04) - Fix an edge case when field missing_value is not None but a custom value that works as None. That ended up calling zope.i18n NumberFormat.format with None what then failed. 4.1.1 (2018-11-26) - Fix FieldWidgets.copy(). It was broken since SelectionManager was reimplemented using OrderedDict. 4.1.0 (2018-11-15) - Add support for Python 3.7. - Deal with items with same name but different values in ordered field widget. [rodfersou] - Move homegrown Manager implementation to OrderedDict. [tomgross] - Adapt tests to lxml >= 4.2, zope.configuration >= 4.3 and zope.schema >= 4.7. 4.0.0 (2017-12-20) - Upgrade the major version 4 to reflect the breaking changes in 3.3.0. (Version 3.6 will be a re-release of 3.2.x not containing the changes since 3.3.0 besides cherry-picks.) Fixes: - Host documentation at 3.5.0 (2017-09-19) - Add support for Python 3.6. - Drop support for Python 3.3. - Avoid duplicated IDs when using a non-required field with z3c.formwidget.query.widget.QuerySourceRadioWidget. [pgrunewald] 3.4.0 (2016-11-15) - Drop support for Python 2.6. - Support Python 3.5 officially. - Fix TypeError: object of type ‘generator’ has no len(). Happens with z3c.formwidget.query. [maurits] - Turned items into a property again on all widgets. For the select widget it was a method since 2.9.0. For the radio and checkbox widgets it was a method since 3.2.10. For orderedselect and multi it was always a property. Fixes [maurits] - Fix handling of missing terms in collections. (See version 2.9 describing this feature.) - Fix orderedselect_input.js resource to be usable on browser layers which do not extend zope.publisher.interfaces.browser.IDefaultBrowserLayer. 3.3.0 (2016-03-09) - MAJOR overhaul of ObjectWidget: - low level unittests passed, but high level was not tops basic rule is that widgets want RAW values and all conversion must be done in ObjectConverter - ObjectSubForm and SubformAdapter is removed, it was causing more problems than good - added high level integration tests - Removed z3c.coverage from test extra. [gforcada, maurits] 3.2.10 (2016-03-09) - RadioWidget items are better determined when they are needed [agroszer] - CheckBoxWidget items are better determined when they are needed [agroszer] - Bugfix: The ChoiceTerms adapter blindly assumed that the passed in field is unbound, which is not necessarily the case in interesting ObjectWidget scenarios. Not it checks for a non-None field context first. [srichter] 3.2.9 (2016-02-01) - Correctly handled noValueToken in RadioWidget. This avoids a LookupError: --NOVALUE--. [gaudenz,ale-rt] - Added json method for forms and json_data method for widgets. [mmilkin] - Change javascript for updating ordered select widget hidden structure so it works again on IE11 and doesn’t send back an empty list that deletes all selections on save. Fixes [fredvd] - Started on Dutch translations. [maurits] 3.2.8 (2015-11-09) - Standardized namespace __init__. [agroszer] 3.2.7 (2015-09-20) - Remove “cannot move farther up/down” messages in ordered select widget. [esteele] - Updated Traditional Chinese translation. [l34marr] 3.2.6 (2015-09-10) - Fixed warnings in headers of locales files. Checked with msgfmt -c. [maurits] - Added Finnish translation. [petri] - Added Traditional Chinese translation. [l34marr] 3.2.5 (2015-09-09) - Fixed error on Python 3: NameError: global name ‘basestring’ is not defined. This fixes a bug introduced in version 3.2.1. [maurits] 3.2.4 (2015-07-18) - Fix ordered select input widget not working. [vangheem] - ReSt fix. [timo] 3.2.3 (2015-03-21) - 3.2.2 was a brown bag release. Fix MANIFEST.in to include the js file that has been added in 3.2.2. [timo] 3.2.2 (2015-03-21) - move js to separate file to prevent escaped entities in Plone 5. [pbauer] 3.2.1 (2014-06-09) - Add DataExtractedEvent, which is thrown after data and errors are extracted from widgets. Fixes - Remove spaces at start and end of text field values. - Explicitly hide span in orderedselect_input.pt. This only contains hidden inputs, but Internet Explorer 10 was showing them anyway. Fixes 3.2.0 (2014-03-18) - Feature: Added text and password widget HTML5 attributes required by plone.login. 3.1.1 (2014-03-02) - Feature: Added a consistent id on single checkbox and multi checkbox widgets. 3.1.0 (2013-12-02) - Feature: Added a consistent id on ordered selection widget. - Feature: Added a hidden template for the textlines widget. - Feature: added an API to render each radio button separately. 3.0.5 (2013-10-09) - Bug: Remove errors for cases where the key field of a dict field uses a sequence widget (most notably choices). The sequence widget always returns lists as widget values, which are not hashable. We convert those lists to tuples now within the dict support. 3.0.4 (2013-10-06) - Feature: Moved registration of translation directories to a separate ZCML file. - Bug: Fixed a typo in German translations. 3.0.3 (2013-09-06) - Feature: Version 2.9 introduced a solution for missing terms in vocabularies. Adapted sources to this solution, too. 3.0.2 (2013-08-14) - Bug: Fix unicode decode error in weird cases in checkbox.CheckboxWidget.update() and radio.RadioWidget.update() (eg: when term.value is an Plone Archetype ATFile) 3.0.1 (2013-06-25) - Bug: The alpha slipped out as 3.0.0, removed ZODB-4.0.0dev.tar.gz to reduce damage - Bug: Fixed a bug in widget.py def wrapCSSClass 3.0.0 (2013-06-24) - Feature: Added support for IDict field in MultiWidget. - Bug: Only add the ‘required’ CSS class to widgets when they are in input mode. - Bug: Catch bug where if a select value was set as from hidden input or through a rest url as a single value, it won’t error out when trying to remove from ignored list. Probably not the 100% right fix but it catches core dumps and is sane anyways. 3.0.0a3 (2013-04-08) - Feature: Updated pt_BR translation. - Bug: Fixed a bug where file input value was interpeted as UTF-8. 3.0.0a2 (2013-02-26) - Bug: The 3.0.0a1 release was missing some files (e.g. locales) due to an incomplete MANIFEST.in. 3.0.0a1 (2013-02-24) - Feature: Removed several parts to be installed by default, since some packages are not ported yet. - Feature: Added support for Python 3.3. - Feature: Replaced deprecated zope.interface.implements usage with equivalent zope.interface.implementer decorator. - Feature: Dropped support for Python 2.4 and 2.5. - Bug: Make sure the call to the method that returns the default value is made with a field which has its context bound. 2.9.1 (2012-11-27) Feautre: The updateWidgets method has received an argument prefix which allows setting the prefix of the field widgets adapter. This allows updating the common widgets prefix before the individual widgets are updated, useful for situations where neither a form, nor a widgets prefix is desired. Bug: Capitalize the messages ‘no value’ and ‘select a value’. This change has been applied also to the existing translations (where applicable). Bug: TextLinesConverter: Do not ignore newlines at the end of the inputted string, thus do not eat blank items Bug: TextLinesConverter: toFieldValue(), convert conversion exceptions to FormatterValidationError, for cases like got a string instead of int. 2.9.0 (2012-09-17) - Feature: Missing terms in vocabularies: this was a pain until now. Now it’s possible to have the same (missing) value unchanged on the object with an EditForm after save as it was before editing. That brings some changes with it: - MAJOR: unchanged values/fields do not get validated anymore (unless they are empty or are FileUploads) - A temporary SimpleTerm gets created for the missing value Title is by default “Missing: ${value}”. See MissingTermsMixin. - Feature: Split configure.zcml - Bug: SequenceWidget DISPLAY_MODE: silently ignore missing tokens, because INPUT_MODE and HIDDEN_MODE does that too. 2.8.2 (2012-08-17) - Feature: Added IForm.ignoreRequiredOnValidation, IWidgets.ignoreRequiredOnValidation, IWidget.ignoreRequiredOnValidation. Those enable extract and extractData to return without errors in case a required field is not filled. That also means the usual “Missing value” error will not get displayed. But the required-info (usually the *) yes. This is handy to store partial state. 2.8.1 (2012-08-06) - Fixed broken release, my python 2.7 windows setup didn’t release the new widget.zcml, widget_layout.pt and widget_layout_hidden.pt files. After enhance the pattern in MANIFEST.in everything seems fine. That’s probably because I patched my python version with the *build exclude pattern patch. And yes, the new files where added to the svn repos! After deep into this again, it seems that only previous added *.txt, *.pt files get added to the release. A fresh checkout sdist release only contains the *.py and *.mo files. Anyway the enhanced MANIFEST.in file solved the problem. 2.8.0 (2012-08-06) Feature: Implemented widget layout concept similar to z3c.pagelet. The new layout concept allows to register layout templates additional to the widget templates. Such a layout template only get used if a widget get called. This enhacement is optional and compatible with all previous z3c.form versions and doesn’t affect existing code and custom implementations except if you implemented a own __call__ method for widgets which wasn’t implemented in previous versions. The new __call__ method will lookup and return a layout template which supports additional HTML code used as a wrapper for the HTML code returned from the widget render method. This concept allows to define additional HTML construct provided for all widget and render specific CSS classes arround the widget per context, view, request, etc discriminators. Such a HTML constuct was normaly supported in form macros which can’t get customized on a per widget, view or context base. Summary; the new layout concept allows us to define a wrapper CSS elements for the widget element (label, widget, error) on a per widgte base and skip the generic form macros offered from z3c.formui. Note; you only could get into trouble if you define a widget in tal without to prefix them with nocall: e.g. tal:define=”widget view/widgets/foo” Just add a nocall like tal:define=”widget nocall:view/widgets/foo” if your rendering engine calls the __call__method by default. Also note that the following will also call the __call__ method tal:define=”widget myWidget”. Fixed content type extraction test which returned different values. This probably depends on a newer version of guess_content_type. Just allow image/x-png and image/pjpeg as valid values. 2.7.0 (2012-07-11) - Remove zope34 extra, use an older version of z3c.form if you need to support pre-ZTK versions. - Require at least zope.app.container 3.7 for adding support. - Avoid dependency on ZODB3. - Added IField.showDefault and IWidget.showDefault That controls whether the widget should look for field default values to display. This can be really helpful in EditForms, where you don’t want to have default values instead of actual (missing) values. By default it is True to provide backwards compatibility. 2.6.1 (2012-01-30) - Fixed a potential problem where a non-ascii vocabulary/source term value could cause the checkbox and readio widget to crash. - Fixed a problem with the datetime.timedelta converter, which failed to convert back to the field value, when the day part was missing. 2.6.0 (2012-01-30) - Remove “:list” from radio inputs, since radio buttons can be only one value by definition. See LP580840. - Changed radio button and checkbox widget labels from token to value (wrapped by a unicode conversion) to make it consistent with the parent SequenceWidget class. This way, edit and display views of the widgets show the same label. See LP623210. - Remove dependency on zope.site.hooks, which was moved to zope.component in 3.8.0 (present in ZTK 1.0 and above). - Make zope.container dependency more optional (it is only used in tests) - Properly escape JS code in script tag for the ordered-select widget. See LP829484. - Cleaned whitespace in page templates. - Fix IGroupForm interface and actually use it in the GroupForm class. See LP580839. - Added Spanish translation. - Added Hungarian translation. 2.5.1 (2011-11-26) - Better compatibility with Chameleon 2.x. - Added *.mo files missing in version 2.5.0. - Pinned minimum version of test dependency z3c.template. 2.5.0 (2011-10-29) Fixed coverage report generator script buildout setup. Note: z3c.pt and chameleon are not fully compatible right now with TAL. Traversing the repeat wrapper is not done the same way. ZPT uses the following pattern: <tal:block condition=”not:repeat/value/end”>, </tal:block> Chameleon only supports python style traversing: <tal:block condition=”not:python:repeat[‘value’].end”>, </tal:block> Upgrade to chameleon 2.0 template engine and use the newest z3c.pt and z3c.ptcompat packages adjusted to work with chameleon 2.0. See the notes from the z3c.ptcompat package: Update z3c.ptcompat implementation to use component-based template engine configuration, plugging directly into the Zope Toolkit framework. The z3c.ptcompat package no longer provides template classes, or ZCML directives; you should import directly from the ZTK codebase. Also, note that the PREFER_Z3C_PT environment option has been rendered obsolete; instead, this is now managed via component configuration. Attention: You need to include the configure.zcml file from z3c.ptcompat for enable the z3c.pt template engine. The configure.zcml will plugin the template engine. Also remove any custom built hooks which will import z3c.ptcompat in your tests or other places. You can directly use the BoundPageTemplate and ViewPageTempalteFile from zope.browserpage.viewpagetemplatefile if needed. This templates will implicit use the z3c.pt template engine if the z3c.ptcompat configure.zcml is loaded. 2.4.4 (2011-07-11) - Remove unneeded dependency on deprecated zope.app.security. - Fixed ButtonActions.update() to correctly remove actions when called again, after the button condition become false. 2.4.3 (2011-05-20) - Declare TextLinesFieldWidget as an IFieldWidget implementer. - Clarify MultiWidget.extract(), when there are zero items, this is now [] instead of <NO_VALUE> - Some typos fixed - Fixed test failure due to change in floating point representation in Python 2.7. - Ensure at least min_length widgets are rendered for a MultiWidget in input mode. - Added Japanese translation. - Added base of Czech translation. - Added Portuguese Brazilian translation. 2.4.2 (2011-01-22) - Adjust test for the contentprovider feature to not depend on the ContentProviderBase class that was introduced in zope.contentprovider 3.5.0. This restores compatibility with Zope 2.10. - Security issue, removed IBrowserRequest from IFormLayer. This prevents to mixin IBrowserRequest into non IBrowserRequest e.g. IJSONRPCRequest. This should be compatible since a browser request using z3c.form already provides IBrowserRequest and the IFormLayer is only a marker interface used as skin layer. - Add English translation (generated from translation template using msgen z3c.form.pot > en/LC_MESSAGES/z3c.form.po). - Added Norwegian translation, thanks to Helge Tesdal and Martijn Pieters. - Updated German translation. 2.4.1 (2010-07-18) - Since version 2.3.4 applyChanges required that the value exists when the field had a DictionaryField data manager otherwise it broke with an AttributeError. Restored previous behavior that values need not to be exist before applyChanges was called by using datamanager.query() instead of datamanager.get() to get the previous value. - Added missing dependency on zope.contentprovider. - No longer using deprecated zope.testing.doctest by using python’s built-in doctest module. 2.4.0 (2010-07-01) - Feature: mix fields and content providers in forms. This allow to enrich the form by interlacing html snippets produced by content providers. Adding html outside the widgets avoids the systematic need of subclassing or changing the full widget rendering. - Bug: Radio widget was not treating value as a list in hidden mode. 2.3.4 (2010-05-17) - Bugfix: applyChanges should not try to compare old and new values if the old value can not be accessed. - Fix DictionaryField to conform to the IDataManager spec: get() should raise an exception if no value can be found. 2.3.3 (2010-04-20) - The last discriminator of the ‘message’ IValue adapter used in the ErrorViewSnippet is called ‘content’, but it was looked up as the error view itself. It is now looked up on the form’s context. - Don’t let util.getSpecification() generate an interface more than once. This causes strange effects when used in value adapters: if two adapters use e.g. ISchema[‘some_field’] as a “discriminator” for ‘field’, with one adapter being more specific on a discriminator that comes later in the discriminator list (e.g. ‘form’ for an ErrorViewMessage), then depending on the order in which these two were set up, the adapter specialisation may differ, giving unexpected results that make it look like the adapter registry is picking the wrong adapter. - Fix trivial test failures on Python 2.4 stemming from differences in pprint’s sorting of dicts. - Don’t invoke render() when publishing the form as a view if the HTTP status code has been set to one in the 3xx range (e.g. a redirect or not-modified response) - the response body will be ignored by the browser anyway. - Handle Invalid exceptions from constraints and field validators. - Don’t create unnecessary self.items in update() method of SelectWidget in DISPLAY_MODE. Now items is a property. - Add hidden widget templates for radio buttons and checkboxes. 2.3.2 (2010-01-21) Reverted changes made in the previous release as the getContent method can return anything it wants to as long as a data manager can map the fields to it. So context should be used for group instantiation. In cases where context is not wanted, the group can be instantiated in the update method of its parent group or form. See also (So version 2.3.2 is the same as version 2.3.0.) 2.3.1 (2010-01-18) - GroupForm and Group now use getContent method when instantiating group classes instead of directly accessing self.context. 2.3.0 (2009-12-28) Refactoring - Removed deprecated zpkg slug and ZCML slugs. - Adapted tests to zope.schema 3.6.0. - Avoid to use zope.testing.doctestunit as it is now deprecated. 2.2.0 (2009-10-27) - Feature: Add z3c.form.error.ComputedErrorViewMessage factory for easy creation of dynamically computed error messages. - Bug: <div class=”error”> was generated twice for MultiWidget and ObjectWidget in input mode. - Bug: Replace dots with hyphens when generating form id from its name. - Refactored OutputChecker to its own module to allow using z3c.form.testing without needing to depend on lxml. - Refactored: Folded duplicate code in z3c.form.datamanager.AttributeField into a single property. 2.1.0 (2009-07-22) - Feature: The DictionaryFieldManager now allows all mappings (zope.interface.common.mapping.IMapping), even persistent.mapping.PersistentMapping and persistent.dict.PersistentDict. By default, however, the field manager is only registered for dict, because it would otherwise get picked up in undesired scenarios. - Bug: Updated code to pass all tests on the latest package versions. - Bug: Completed the Zope 3.4 backwards-compatibility. Also created a buidlout configuration file to test the Zope 3.4 compatibility. Note: You must use the ‘latest’ or ‘zope34’ extra now to get all required packages. Alternatively, you can specify the packages listed in either of those extras explicitely in your product’s required packages. 2.0.0 (2009-06-14) Features KGS 3.4 compatibility. This is a real hard thing, because z3c.form tests use lxml >= 2.1.1 to check test output, but KGS 3.4 has lxml 1.3.6. Therefore we agree on that if tests pass with all package versions nailed by KGS 3.4 but lxml overridden to 2.1.1 then the z3c.form package works with a plain KGS 3.4. Removed hard z3c.ptcompat and thus z3c.pt dependency. If you have z3c.ptcompat on the Python path it will be used. Added nested group support. Groups are rendered as fieldsets. Nested fieldsets are very useful when designing forms. WARNING: If your group did have an applyChanges() (or any added(?)) method the new one added by this change might not match the signature. Added labelRequired and requiredInfo form attributes. This is useful for conditional rendering a required info legend in form templates. The requiredInfo label depends by default on a given labelRequired message id and will only return the label if at least one widget field is required. Add support for refreshing actions after their execution. This is useful when button action conditions are changing as a result of action execution. All you need is to set the refreshActions flag of the form to True in your action handler. Added support for using sources. Where it was previosly possible to use a vocabulary it is now also possible to use a source. This works both for basic and contextual sources. IMPORTANT: The ChoiceTerms and CollectionTerms in z3c.form.term are now simple functions that query for real ITerms adapters for field’s source or value_type respectively. So if your code inherits the old ChoiceTerms and CollectionTerms classes, you’ll need to review and adapt it. See the z3c.form.term module and its documentation. The new z3c.form.interfaces.NOT_CHANGED special value is available to signal that the current value should be left as is. It’s currently handled in the z3c.form.form.applyChanges() function. When no file is specified in the file upload widget, instead of overwriting the value with a missing one, the old data is retained. This is done by returning the new NOT_CHANGED special value from the FileUploadDataConvereter. Preliminary support for widgets for the schema.IObject field has been added. However, there is a big caveat, please read the object-caveat.txt document inside the package. A new objectWidgetTemplate ZCML directive is provided to register widget templates for specific object field schemas. Implemented the MultiWidget widget. This widget allows you to use simple fields like ITextLine, IInt, IPassword, etc. in a IList or ITuple sequence. Implemented TextLinesWidget widget. This widget offers a text area element and splits lines in sequence items. This is usfull for power user interfaces. The widget can be used for sequence fields (e.g. IList) that specify a simple value type field (e.g. ITextLine or IInt). Added a new flag ignoreContext to the form field, so that one can individually select which fields should and which ones should not ignore the context. Allow raw request values of sequence widgets to be non-sequence values, which makes integration with Javascript libraries easier. Added support in the file upload widget’s testing flavor to specify ‘base64’-encoded strings in the hidden text area, so that binary data can be uploaded as well. Allow overriding the required widget attribute using IValue adapter just like it’s done for label and name attributes. Add the prompt attribute of the SequenceWidget to the list of adaptable attributes. Added benchmarking suite demonstrating performance gain when using z3c.pt. Added support for z3c.pt. Usage is switched on via the “PREFER_Z3C_PT” environment variable or via z3c.ptcompat.config.[enable/diable](). The TypeError message used when a field does not provide IFormUnicode now also contains the type of the field. Add support for internationalization of z3c.form messages. Added Russian, French, German and Chinese translations. Sphinx documentation for the package can now be created using the new docs script. The widget for fields implementing IChoice is now looked up by querying for an adapter for (field, field.vocabulary, request) so it can be differentiated according to the type of the source used for the field. Move formErrorsMessage attribute from AddForm and EditForm to the z3c.form.form.Form base class as it’s very common validation status message and can be easily reused (especially when translations are provided). Refactoring - Removed compatibility support with Zope 3.3. - Templates now declare XML namespaces. - HTML output is now compared using a modified version of the XML-aware output checker provided by lxml. - Remove unused imports, adjust buildout dependencies in setup.py. - Use the z3c.ptcompat template engine compatibility layer. Fixed Bugs - IMPORTANT - The signature of z3c.form.util.extractFileName function changed because of spelling mistake fix in argument name. The allowEmtpyPostFix is now called allowEmptyPostfix (note Empty instead of Emtpy and Postfix instead of PostFix). - IMPORTANT - The z3c.form.interfaces.NOVALUE special value has been renamed to z3c.form.interfaces.NO_VALUE to follow the common naming style. The backward-compatibility NOVALUE name is still in place, but the repr output of the object has been also changed, thus it may break your doctests. - When dealing with Bytes fields, we should do a null conversion when going to its widget value. - FieldWidgets update method were appending keys and values within each update call. Now the util.Manager uses a UniqueOrderedKeys implementation which will ensure that we can’t add duplicated manager keys. The implementation also ensures that we can’t override the UniqueOrderedKeys instance with a new list by using a decorator. If this UniqueOrderedKeys implementation doesn’t fit for all use cases, we should probably use a customized UserList implementation. Now we can call widgets.update() more then one time without any side effect. - ButtonActions update where appending keys and values within each update call. Now we can call actions.update() more then one time without any side effect. - The CollectionSequenceDataConverter no longer throws a TypeError: 'NoneType' object is not iterable when passed the value of a non-required field (which in the case of a List field is None). - The SequenceDataConverter and CollectionSequenceDataConverter converter classes now ignore values that are not present in the terms when converting to a widget value. - Use nocall: modifier in orderedselect_input.pt to avoid calling list entry if it is callable. - SingleCheckBoxFieldWidget doesn’t repeat the label twice (once in <div class="label">, and once in the <label> next to the checkbox). - Don’t cause warnings in Python 2.6. - validator.SimpleFieldValidator is now able to handle interfaces.NOT_CHANGED. This value is set for file uploads when the user does not choose a file for upload. 1.9.0 (2008-08-26) - Feature: Use the query() method in the widget manager to try extract a value. This ensures that the lookup is never failing, which is particularly helpful for dictionary-based data managers, where dictionaries might not have all keys. - Feature: Changed the get() method of the data manager to throw an error when the data for the field cannot be found. Added query() method to data manager that returns a default value, if no value can be found. - Feature: Deletion of widgets from field widget managers is now possible. - Feature: Groups now produce detailed ObjectModifiedEvent descriptions like regular edit forms do. (Thanks to Carsten Senger for providing a patch.) - Feature: The widget manager’s extract() method now supports an optional setErrors (default value: True) flag that allows one to not set errors on the widgets and widget manager during data extraction. Use case: You want to inspect the entered data and handle errors manually. - Bug: The ignoreButtons flag of the z3c.form.form.extends() method was not honored. (Thanks to Carsten Senger for providing a patch.) - Bug: Group classes now implement IGroup. This also helps with the detection of group instantiation. (Thanks to Carsten Senger for providing a patch.) - Bug: The list of changes in a group were updated incorrectly, since it was assumed that groups would modify mutually exclusive interfaces. Instead of using an overwriting dictionary update() method, a purely additive merge is used now. (Thanks to Carsten Senger for providing a patch.) - Bug: Added a widget for IDecimal field in testing setup. - Feature: The z3c.form.util module has a new function, createCSSId() method that generates readable ids for use with css selectors from any unicode string. - Bug: The applyChanges() method in group forms did not return a changes dictionary, but simply a boolean. This is now fixed and the group form changes are now merged with the main form changes. - Bug: Display widgets did not set the style attribute if it was available, even though the input widgets did set the style attribute. 1.8.2 (2008-04-24) - Bug: Display Widgets added spaces (due to code indentation) to the displayed values, which in some cases, like when displaying Python source code, caused the appearance to be incorrect. - Bug: Prevent to call __len__ on ITerms and use is None for check for existence. Because __len__ is not a part of the ITerms API and not widget.terms will end in calling __len__ on existing terms. 1.8.1 (2008-04-08) - Bug: Fixed a bug that prohibited groups from having different contents than the parent form. Previously, the groups contents were not being properly updated. Added new documentation on how to use groups to generate object-based sub-forms. Thanks to Paul Carduner for providing the fix and documentation. 1.8.0 (2008-01-23) - Feature: Implemented IDisplayForm interface. - Feature: Added integration tests for form interfaces. Added default class attribute called widgets in form class with default value None. This helps to pass the integration tests. Now, the widgets attribute can also be used as a indicator for updated forms. - Feature: Implemented additional createAndAdd hook in AddForm. This allows you to implement create and add in a single method. It also supports graceful abortion of a create and add process if we do not return the new object. This means it can also be used as a hook for custom error messages for errors happen during create and add. - Feature: Add a hidden widget template for the ISelectWidget. - Feature: Arrows in the ordered select widget replaced by named entities. - Feature: Added CollectionSequenceDataConverter to setupFormDefaults. - Feature: Templates for the CheckBox widget are now registered in checkbox.zcml. - Feature: If a value cannot be converted from its unicode representation to a field value using the field’s IFromUnicode interface, the resulting type error now shows the field name, if available. - Bug: createId could not handle arbitrary unicode input. Thanks to Andreas Reuleaux for reporting the bug and a patch for it. (Added descriptive doctests for the function in the process.) - Bug: Interface invariants where not working when not all fields needed for computing the invariant are in the submitted form. - Bug: Ordered select didn’t submit selected values. - Bug: Ordered select lists displayed tokens instead of value, - Bug: SequenceWidget displayed tokens instead of value. 1.7.0 (2007-10-09) - Feature: Implemented ImageButton, ImageAction, ImageWidget, and ImageFieldWidget to support imge submit buttons. - Feature: The AttributeField data manager now supports adapting the content to the fields interface when the content doesn’t implement this interface. - Feature: Implemented single checkbox widget that can be used for boolean fields. They are not available by default but can be set using the widgetFactory attribute. - Bug: More lingual issues have been fixed in the documentation. Thanks to Martijn Faassen for doing this. - Bug: When an error occurred during processing of the request the widget ended up being security proxied and the system started throwing TraversalError-‘s trying to access the label attribute of the widget. Declared that the widgets require the zope.Public permission in order to access these attributes. - Bug: When rendering a widget the style attribute was not honored. Thanks to Andreas Reuleaux for reporting. - Bug: When an error occurred in the sub-form, the status message was not set correctly. Fixed the code and the incorrect test. Thanks to Markus Kemmerling for reporting. - Bug: Several interfaces had the self argument in the method signature. Thanks to Markus Kemmerling for reporting. 1.6.0 (2007-08-24) -. 1.5.0 (2007-07-18) - Feature: Added a span around values for widgets in display mode. This allows for easier identification widget values in display mode. - Feature: Added the concept of widget events and implemented a particular “after widget update” event that is called right after a widget is updated. - Feature: Restructured the approach to customize button actions, by requiring the adapter to provide a new interface IButtonAction. Also, an adapter is now provided by default, still allowing cusotmization using the usual methods though. - Feature: Added button widget. While it is not very useful without Javascript, it still belongs into this package for completion. - Feature: All IFieldWidget instances that are also HTML element widgets now declare an additional CSS class of the form “<fieldtype.lower()>-field”. - Feature: Added addClass() method to HTML element widgets, so that adding a new CSS class is simpler. - Feature: Renamed “css” attribute of the widget to “klass”, because the class of an HTML element is a classification, not a CSS marker. - Feature: Reviewed all widget attributes. Added all available HTML attributes to the widgets. - Documentation: Removed mentioning of widget’s “hint” attribute, since it does not exist. - Optimization: The terms for a sequence widget were looked up multiple times among different components. The widget is now the canonical source for the terms and other components, such as the converter uses them. This avoids looking up the terms multiple times, which can be an expensive process for some applications. - Bug/Feature: Correctly create labels for radio button choices. - Bug: Buttons did not honor the name given by the schema, if created within one, because we were too anxious to give buttons a name. Now name assignment is delayed until the button is added to the button manager. - Bug: Button actions were never updated in the actions manager. - Bug: Added tests for textarea widget. 1.4.0 (2007-06-29) -. 1.3.0 (2007-06-22) Feature: In an edit form applying the data and generating all necessary messages was all done within the “Apply” button handler. Now the actual task of storing is factored out into a new method called “applyChanges(data)”, which returns whether the data has been changed. This is useful for forms not dealing with objects. Feature: Added support for hidden fields. You can now use the hidden mode for widgets which should get rendered as <input type="hidden" />. - Note: Make sure you use the new formui templates which will avoid rendering labels for hidden widgets or adjust your custom form macros. Feature: Added missing_value support to data/time converters Feature: Added named vocabulary lookup in ChoiceTerms and CollectionTerms. Feature: Implemented support for FileUpload in FileWidget. Added helper for handling FileUpload widgets: extractContentType(form, id) Extracts the content type if IBytes/IFileWidget was used. extractFileName(form, id, cleanup=True, allowEmtpyPostFix=False) Extracts a filename if IBytes/IFileWidget was used. Uploads from win/IE need some cleanup because the filename includes also the path. The option cleanup=True will do this for you. The option allowEmtpyPostFix allows you to pass a filename without extensions. By default this option is set to False and will raise a ValueError if a filename doesn’t contain an extension. Created afile upload data converter registered for IBytes/IFileWidget ensuring that the converter will only be used for fiel widgets. The file widget is now the default for the bytes field. If you need to use a text area widget for IBytes, you have to register a custom widget in the form using: fields['foobar'].widgetFactory = TextWidget Feature: Originally, when an attribute access failed in Unauthorized or ForbiddenAttribute exceptions, they were ignored as if the attribute would have no value. Now those errors are propagated and the system will fail providing the developer with more feedback. The datamanager also grew a new query() method that returns always a default and the get() method propagates any exceptions. Feature: When writing to a field is forbidden due to insufficient priviledges, the resulting widget mode will be set to “display”. This behavior can be overridden by explicitely specifying the mode on a field. Feature: Added an add form implementation against IAdding. While this is not an encouraged method of adding components, many people still use this API to extend the ZMI. Feature: The IFields class’ select() and omit() method now support two ketword arguments “prefix” and “interface” that allow the selection and omission of prefixed fields and still specify the short name. Thanks to Nikolay Kim for the idea. Feature: HTML element ids containing dots are not very good, because then the “element#id” CSS selector does not work and at least in Firefox the attribute selector (“element[attr=value]”) does not work for the id either. Converted the codebase to use dashes in ids instead. Bug/Feature: The IWidgets component is now an adapter of the form content and not the form context. This guarantees that vocabulary factories receive a context that is actually useful. Bug: The readonly flag within a field was never honored. When a field is readonly, it is displayed in “display” mode now. This can be overridden by the widget manager’s “ignoreReadonly” flag, which is necessary for add forms. Bug: The mode selection made during the field layout creation was not honored and the widget manager always overrode the options providing its value. Now the mode specified in the field is more important than the one from the widget manager. Bug: It sometimes happens that the sequence widget has the no-value token as one element. This caused displayValue() to fail, since it tried to find a term for it. For now we simply ignore the no-value token. Bug: Fixed the converter when the incoming value is an empty string. An empty string really means that we have no value and it is thus missing, returning the missing value. Bug: Fix a slightly incorrect implementation. It did not cause any harm in real-world forms, but made unit testing much harder, since an API expectation was not met correctly. Bug: When required selections where not selected in radio and checkbox widgets, then the conversion did not behave correctly. This also revealed some issues with the converter code that have been fixed now. Bug: When fields only had a vocabulary name, the choice terms adaptation would fail, since the field was not bound. This has now been corrected. Documentation: Integrated English language and content review improvements by Roy Mathew in form.txt. 1.2.0 (2007-05-30) - Feature: Added ability to change the button action title using an IValue adapter. 1.1.0 (2007-05-30) - Feature: Added compatibility for Zope 3.3 and thus Zope 2.10. 1.0.0 (2007-05-24) - Initial Release 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/z3c.form/4.1.2/
CC-MAIN-2020-10
refinedweb
6,917
60.82
Re: my microsoft publisher website will not publish to domain name - From: Maureen <Maureen@xxxxxxxxxxxxxxxxxxxxxxxxx> - Date: Mon, 14 Aug 2006 06:54:01 -0700 Hi David I've got IE back. From the start buton I went into 'Set programme access and defaults' and the box 'Add or remove programmes' came up. I clicked on custom and there was IE and Firefox with the option to change the default...so I did and it worked. Phew!! All back to normal now but Firefox is still there if I want to use it, I just reverse the process. I understand what you are saying about my photos but once 1&1 are hosting my website I don't suppose it will be an issue. Thanks once again, you certainly inspire me to use my brain over this computer, (but I couldn't do it at 4.28a.m!!) Maureen "DavidF" wrote: Maureen,. Whoops. It sounds like you chose FireFox as your default browser when you installed it. You needed to watch the options as you installed it. I am not sure of how you change it now. Perhaps right click the IE icon, properties, and under the Programs tab, click Reset Web Settings, and/or the box beside "Internet Explorer should check to see whether...". Then try the icon again. If that doesn't work, then perhaps delete the icon, and using Windows Explorer browse to C:\Program Files\Internet Explorer\iexplore.exe and right click that file, drag to the desktop, and choose Create Shortcut. Set the properties. For a Firefox shortcut, C:\Program Files\Mozilla Firefox\firefox.exe , right click and drag to desktop, create short cut. Then if none of that works, I guess I would try removing FireFox through add and remove, check the shortcut for IE again, and if it works, then reinstall FireFox and this time make sure it doesn't install as the default browser. You gotta be careful when you install programs. I always use Custom install if I have the choice so I can look at all the options before installing. And, I always manually set a system restore point before installing, just in case. As per the pictures...you remember me talking about how Publisher produces "smarter" code for IE, and "dumber" code for other browsers? Well it also produces different graphics for different browsers, and in your case, the images are not that great in FireFox. Just one of the limitations of using Publisher for building a website, that you will have to live with unless you import your images instead of embedding them...but that is another issue, for another time. DavidF "Maureen" <Maureen@xxxxxxxxxxxxxxxxxxxxxxxxx> wrote in message news:9009C034-9BBE-44F6-B6DD-8E0DA24C441B@xxxxxxxxxxxxxxxx Hi David Just to let you know that I downloaded Firefox. It takes a little time to sort out where things are in a different layout, but I'm sure I will get used to it. The only thing is I appear to have lost IE. When I click on the IE icon on my desktop it goes to Firefox. Is that something I did when I downloaded, I would quite like to have both browsers if I can so any ideas how I can restore IE? The good thing about Firefox, of course, is that my web site works fine in my domain name, Yipeee! The photographs are very fuzzy but is that because I uploaded the web site in IE? If I'm handing it all over to 1&1 it's not a problem and hopefully it will all be sorted by the end of the week. Be in touch again when it's all done. Maureen "Maureen" wrote: Hi David Just to let you know that I have just copied and pasted the article from David Bartosik's web site and it has worked perfectly, it's now saved in a Word Document. Thanks again.: - Re: my microsoft publisher website will not publish to domain name - From: DavidF - Re: my microsoft publisher website will not publish to domain name - From: DavidF - Re: my microsoft publisher website will not publish to domain name - From: Maureen - Re: my microsoft publisher website will not publish to domain name - From: Maureen - Re: my microsoft publisher website will not publish to domain name - From: DavidF - Prev by Date: Re: My website is slow to download - Next by Date: Re: my microsoft publisher website will not publish to domain name - Previous by thread: Re: my microsoft publisher website will not publish to domain name - Next by thread: Re: my microsoft publisher website will not publish to domain name - Index(es):
http://www.tech-archive.net/Archive/Publisher/microsoft.public.publisher.webdesign/2006-08/msg00226.html
crawl-002
refinedweb
774
68.7
Problem Statement Find all the subsets of a given set. Sample Test Cases Input: nums = [1,2,3] Output: [ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ] Problem Solution We will use the backtracking approach to solve this problem. Why backtracking? because backtracking technique is designed to generate every possible solution once. So the Approach is that if we have N number of elements inside an array, we have exactly two choices for each of them, either we include that element in our subset or we do not include it. The take or not take strategy builds a binary tree of choices returning only the leaves for each combination resulting in the power-set of the entire array . Complexity Analysis Here we are generating every subset using recursion. The total number of subsets of a given set of size n = 2^n. Time Complexity : O( 2^n) For every index i two recursive case originates, So Time Complexity is O(2^n). Space Complexity : O(n 2^n) We need to take into account the memory that is allocated by the algorithm not only on the stack but also on the heap. Each of the generated subsets is being stored in the subsets list, which will eventually contain 2n sets, each of size somewhere between 0 and n, so the space complexity is O(n 2^n). Code Implementation #include <bits/stdc++.h> using namespace std; void subsetsUtil(vector<int>& A, vector<vector<int> >& res, vector<int>& subset, int index) { res.push_back(subset); for (int i = index; i < A.size(); i++) { subset.push_back(A[i]); subsetsUtil(A, res, subset, i + 1); subset.pop_back(); } return; } vector<vector<int> > subsets(vector<int>& A) { vector<int> subset; vector<vector<int> > res; int index = 0; subsetsUtil(A, res, subset, index); return res; } int main() { vector<int> array = { 1, 2, 3 }; vector<vector<int> > res = subsets(array); for (int i = 0; i < res.size(); i++) { for (int j = 0; j < res[i].size(); j++) cout << res[i][j] << " "; cout << endl; } return 0; }
https://prepfortech.in/interview-topics/backtracking/print-all-possible-subsets-of-a-given-array
CC-MAIN-2021-17
refinedweb
341
54.93
The intent of the myUML project is that of providing a set of tools for the creation and manipulation of UML diagrams. This is the first release of any code from the project, and includes only the initial version of the "Use Case Diagram" portion of the project. In other words, the only UML diagrams considered in this release are the Use Case Diagrams. Things you can do with this first release: Code included in this release: "myUML" solution | \-- "myUML" project | \-- Actor.cs: The Actor class \-- ActorDisplay.cs: The ActorDiaplay Control \-- Anchor.cs: The Anchor class \-- App.ico: Standard application icon \-- AssemblyInfo.cs: Standard Assembly Information \-- Communication.cs: The Communication class \-- CommunicationDisplay.cs:The COmmunicationDisplay Control \-- IUMLtoXML.cs: The IUMLtoXML interface \-- TestEntry.cs: Entry form to the project \-- TestUseCases.cs: Form to work with Use Case Diagrams \-- UseCase.cs: The UseCase class \-- UseCaseDisplay.cs: The UseCaseDisplay Control Before we move on, a little note on nomenclature: if you have never heard of UML, you will probably find this project rather silly. I suggest you check online or on some good software engineering text book, since this article does not intend to explain what UML is and what it is used for. There are so many good references for UML that I find it hard to point you to any specific place other than Google and CodeProject. Since this first release deals with use case diagrams, though, let me define the following key terms (in my own words): A diagram representing what the depicted system does, from the point of view of an external observer; Use Case Diagrams are composed of Actors, Communications, and Use Cases (I refer to all three of them as "figures"); A figure, in a Use Case Diagram, representing a role that some user or component of the system plays in relationship to the use case depicted in the diagram; Actors are represented as stick-men; A figure, in a Use Case Diagram, representing some task or goal that the depicted system should complete or achieve; Use Cases are represented as ellipses; A figure, in a Use Case Diagram, representing the participation of an Actor to a given Use Case; in other words, if an Actor is linked to a Use Case by a Communication, it means that the Actor is somehow involved (it must either do something or provide some information) in the implementation of the Use Case; Communications are represented as lines linking Actors to Use Cases. Hope that avoids confusion down the line. For those of you in a hurry, or not much interested in the details I present later on, here's a quick summary of what you can do with this code. Compile it (I'm providing the source code), and start it up. You will be faced with a simple form with a single button ("Test Use Cases"). In future versions, there will be more buttons. Please, forgive the simple appearance of this splash form. Click on the button to access the tool that lets you work on Use Case Diagrams. At this point you should see a simple form with a white panel on the left-hand side, and a toolbar at the top with a few buttons. Here's a review of the buttons in the toolbar (in order, from left to right): To draw a new Use Case Diagram, click on the tools you need and start drawing in the white panel. It's a click-and-drag interface. You will notice that, as you draw your first figure, on the right-hand side of the form, a control will appear to display details regarding the figure you have just drawn. This detailed view appears only when you have a single figure selected, and lets you change its properties and appearance. In particular, it lets you move and resize the figures as you need (sorry, I haven't implemented yet the click-and-move-or-resize). You can select multiple figures by clicking on them while holding the Shift key down. To save your Use Case Diagram to file, click on the "Save Diagram" button. The diagram is saved in XML form (so, yes, you could tinker with it outside the myUML project, but you can also mess the data up ). To clear the Use Case diagram, click on the "Clear Diagram" button. To load a Use Case Diagram from a file, click on the "Open Diagram" button. That's pretty much all. The first thing I'd like to write about is the classes and interfaces in the project. Here's what I ended up with at the end: Anchor PointF IUMLtoXML SaveTo ReadFrom Communication UseCase Actor Paint CommunicationDisplay UserControl UseCaseDisplay ActorDisplay (Yes, once I'll expand the myUML project to include Class diagrams, I will be able to include a nice diagram here ) I am sure I could have done better (and, possibly, I'll go back and re-implement it all in some better way). However, this situation gave me enough stuff to think a bit about classes and interfaces. Here's what happened (in a sort-of-chronological way). At first I started out with a Communication class, a UseCase class, and an Actor class. Once I figured out the basics (see "Gory Details: Painting"), I looked at my code and realized that there was *a lot* of replication going on and, as I moved on in the project, I could easily forget to update the source in three thousand different places (ok, not three thousand, but you get the picture). By chance, at the same time I was reading Alexandrescu's book on generic template programming (yeah, that's another language, I know), the Gamma et Al. on Design Patterns, and a few other things on similar topics. So I figured it was a good chance to consider the myUML project and see if I could improve my classes-tree (which, at the time, was more like a forest of three single-node trees) and minimize the code replication. So, since we don't have templates...oops, *Generics* in C# (yet), I figured I'd look at interfaces to solve my problem. In short, the code replication I was facing, was due to the fact that the three basic figures (i.e. classes) in the project, all implement the same set of characteristics and behavior. Alas, they implement them in different ways, and, in some cases, they don't share all of these characteristics and behaviors. For instance, all three classes need to be painted to screen (i.e. they all implement a Paint method). However, the Communication class is painted in a rather different way than the other two (it's a line, while both the UseCase and Actor classes are bounded by a rectangle!). Even if we look at the UseCase and Actor classes, they are both painted within a certain rectangle, but their similarities -in regard to this behavior- end there (the UseCase has an ellipse within that rectangle, the Actor has a stick-man in it, and they display any text associated with them in different positions). So, thinking that interfaces could solve my problem, I started writing interfaces. I ended up with...hmm... 11 interfaces, each corresponding to a particular behavior I wanted to implement in one or more of the figures. Some interfaces also inherited from others. Then, I realized a tricky thing that nobody had ever pointed out to me in regard to interfaces: Interfaces define method signatures, but no implementation (chorus: "Duh!"). Sure, it seems obvious, but I didn't realize how annoying this can be until I actually wanted to take advantage of them. What I was looking for, really, was a way to implement multiple inheritance. And, I'm sad to say, even if you might have heard a thousand times that interfaces allow you to do just that, that's not exactly true. Interfaces let you get around the problem, in a sense, but they are not a "Divine Intervention" that you can use to get what the language does not give you (namely, "multiple inheritance"). Let me give you an example. Consider good old class inheritance. You have a base class (aptly named Base), implementing a certain method: Base using System; public class Base { public Base() { } protected void Foo() { Console.WriteLine("Hello World!"); } } I made Foo protected so that a class inheriting from Base would get access to it. And, here comes our class inheriting from Base: Foo using System; public class myClass : Base { public myClass() : base() { } } At this point, the following code compiles and produces the "Hello World!" output: myClass C1 = new myClass(); C1.Foo(); We are now free to override the Foo method in myClass, if we wish to provide a different behavior for that class. For instance: myClass using System; public class myClass : Base { public myClass() : base() { } public override void Foo() { Console.Writeline("I am overriding!"); } } On the other hand, consider the case of an interface, such as public interface Ifoo { void Foo(); } This simply means that any class "inheriting" (ok, ok, "implementing") this interface *must* provide an implementation of the Foo method in order to compile. So, we would have to do something like: using System; public class Base : Ifoo { public Base() { } public void Foo() { Console.Writeline("Hello World!"); } } At this point, if we were to implement myClass, we would have to provide a new implementation of the Foo method. Granted, we could make the Foo method in Base protected and inherit it, and possibly override it, but that simply replicates what we had to do with class inheritance. protected So, where does this leave us? My conclusion is (until someone enlightens me otherwise) that interfaces are a good thing in certain specific situations, but they do not replace the good ol' class inheritance system. Indeed, I included one interface in the myUML project. We will get to that shortly. First, let me give you an example of a case where an interface would be the correct tool to use. Consider the scenario where you are developing a Bag container, and you wish your bag to implement a "doubling" functionality. In other words, an application using a Bag object should be able to call: Bag myBag.Double(); and all the items in the Bag would be "doubled" (e.g.: an integer like 2 would become 4). Internally, your Bag class would probably use one of the standard collections objects to hold the objects it receives. Thus, when the Double method is invoked, you would parse through all of the objects in your internal collection, and double each. However, as soon as you put something in a collection, it is cast to object (again, when we will get generics, this scenario will change). So, in your doubling loop (which might be a foreach statement), you would have, for each object, code to figure out exactly what class the object belongs to, cast it to a reference of the appropriate type, and then double it (not to mention, value types and reference types would be treated differently). So, for example's sake, assume we are considering to store in the Bag object, of one of two classes (class Foo and class Bar). We would have: Double foreach Bar public class Foo { private int n = 0; public Foo(int x) { n = x; } public void Double() { n*=2; } } public class Bar { private string s = ""; public Bar(string x) { s = x; } public void Double() { s = s+s; } } using System; using System.Collections; public class Bag { private ArrayList list = new ArrayList; public Bag() { } public void AddFoo(Foo f) { list.Add(f); } public void AddBar(Bar b) { list.Add(b); } //Actually, why not this one? public void AddWidget(object o) { list.Add(o); } public void Double() { foreach(object o in list) { if(o is Foo) { Foo f = o as Foo; f.Double(); } else if (o is Bar) { Bar b = o as Bar; b.Double(); } //And..ehr, what if it's not a Foo, nor a Bar ? }//FOREACH } } Sure, might be ugly, but, with only a Foo and a Bar class to deal with, it's manageable. Ok, now that you're done with your Bag class, and it fits nicely in your application, time goes by and someone (generally a pointed-hair manager) decides that your Bag should be able to accept objects of type Foobar as well. Foobar So, you figure, you have to go back and add another "else if" case to your Bag.Double implementation. Sometimes things are not that simple. In the long term, this approach of "go-back-and-modify" is not a good thing. An interface would help you out by letting you define some requirement that any object stored in the bag *must* meet. Then, your code may assume that the objects in the list will meet that requirement, and you may deal with only that specific characteristic, regardless of the actual type of the objects. So, for instance: Bag.Double public interface IcanDouble //Idoubleable sounded odd { void Double(); } public class Bag { private ArrayList list = new ArrayList; public Bag() { } public void AddWidget(IcanDouble x) { list.Add(x); } public void Double() { foreach(IcanDouble x in list) x.Double(); } } Looks better, at least to my eyes! Now, your Foo and Bar classes need to implement the interface: public class Foo : IcanDouble { private int n = 0; public Foo(int x) { n = x; } public void Double() { n*=2; } } public class Bar : IcanDouble { private string s = ""; public Bar(string x) { s = x; } public void Double() { s = s+s; } } And, if they really want to add the Foobar class, they just need to make sure it implements the IcanDouble interface, providing a Double method (that does whatever it needs to do to double a Foobar object). IcanDouble Your Bag is now much more stable, because it relies upon the various classes it deals with to meet a certain requirement. In other words, the interface acts as a "public contract" that whatever class wants to work with the Bag must subscribe and respect. Incidentally, the Bag class itself provides a Double method, so we could make it "subscribe" the contract (by adding : IcanDouble to its first line) and we could store a Bag in a Bag. So, after I thought of this example, I figured that interfaces were cool, but they solve a problem that was not the problem I was having with the myUML project. So, how come I have the IUMLtoXML interface in the project? Well, simply put, I ended up in a situation similar to the one described above for the Bag class. The form that holds the various figures keeps them in a list (aptly named figures), and, when the user requests to save the Use case Diagram to file, I had some ugly code looking exactly like that series of if else-is else-is... in the first Bag class. By defining the IUMLtoXML interface, I simplified that code a lot: foreach(IUMLtoXML fig in figures) fig.SaveTo(xmlw); Granted, I still have other places in the code where the if else-if else-if... ugly code is found, but I am dealing with "only" three classes, so it's still manageable. Plus, I have time to go back and clear it all out.. now that I understand interfaces a bit better. Well, I must admit this is one thing I made more difficult than it had to be, but just in case you've never dealt with capturing keyboard events and figuring out things like "Is the user pressing the Shift key?", here's how I did it, followed by what not to do. First, I set to true the KeyPreview property of the form (in the Misc section of its properties). This lets the form peek at the key events that take place on any of the controls it contains. Be careful when setting this to true, since, if your controls are listening to these same events, you must synchronize the various listeners. Next, I provided two simple handlers for the form KeyDown and KeyUp events: true KeyPreview KeyDown KeyUp private void TestUseCases_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e) { if(e.Shift) shiftPressed=true; e.Handled=false; } private void TestUseCases_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e) { shiftPressed=e.Shift; } Where shiftPressed is a private bool variable of the form, set to true whenever the user is holding the shift key. shiftPressed private bool Now, what I did wrong before getting to this (who was that said that "failures are much more interesting than successes" ? Hoare, maybe?). I think my first approach was 99% correct (good, but not good enough!). I was using this handler for the KeyUp event: private void TestUseCases_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e) { shiftPressed=!e.Shift; } [chorus: "Uh?"] Well, let me explain my idea at the time: within the context of a KeyUp event, the event arguments should tell me what key(s) was/were released (just like they, for a KeyDown event, they tell me which key(s) was/were pressed). So, if the shift key is one of those that were released, I would find the Shift property of the event arguments set to true, right? *Wrong* It turns out that the key event arguments simply give you a "snapshot" of the keyboard's state at the time when the event is fired. So, since the KeyUp event is fired after the shift key is released, by that time the key is up, and the Shift property is set to false. Shift false The other mistake I made when dealing with this was to use MessageBoxes to try and debug the whole thing (A "Key has been pressed" message in the KeyDown handler, and a "Key has been released" message in the KeyUp handler). This, while usually it's a quick and dirty way to trace pieces of code, threw me off track even more. The presence of the MessageBox.Show statements, in fact, did something odd to the chain of events, and the KeyUp event appeared to never be fired. In truth, this was only because of the popping-up of the MessageBox in the KeyDown handler (and, with carefully timed "click-on-the-message-box-and-immediately-release-the-shift-key" I could verify that the KeyUp event was indeed fired and handled). MessageBox MessageBox.Show All in all, I got a big scare for nothing (ehr... "So, if I handle the KeyDown event, I can't intercept the KeyUp event?"). One of the basic functionalities implemented by the myUML project is, of course, that of letting the user draw new diagrams. This was my first experience with painting objects on screen in C#, and hence my first face-to-face with GDI+. Alas, even with the earlier Visual Studio 6.0, I never did much with GDI and such. So, I'm sure my code will look ugly to many of you who have more experience with drawing stuff on screen than I do. I am also sure I could improve the effectiveness of the code, and I will probably do, at some point in the future, when I will understand the Painting event better. But, for the time being, I'm rather content with what I have. So, let me share a few thoughts on this topic. Painting First and foremost, let me suggest, if you approach the painting problem for the first time, then you read as many different tutorials on the topic as possible. I'd guess that all of the books on C# will include at least half a chapter on the GDI+ basics. However, I found that each book (or online reference) tends to give you some examples without covering everything. Maybe there is a book out there that talks *only* about GDI+, but I haven't seen it yet. In any case, the best thing you can do is to read as many different examples as you can, and then mix and match as you need. In the myUML project, I had to allow the user to draw on screen (actually, only on the pnl_drawable Panel of my form) three types of figures. I decided to start out with the panel as-is, but I also realized I wanted to give the user, the freedom to use as much space as he wishes. For instance, maximizing the form will resize the panel to take up as much space as possible (ok, I still save some space for the other controls). So, the draw-able panel may potentially have scrollbars. This is the key point, I think. While painting per-se is a relatively simple operation, when you start thinking of scrollable controls, and painting on them, the whole deal becomes a bit confused. Let's take it one step at a time; I will consider the case of the UseCase class to show you how to implement this, but the same logic applies to the Communication and Actor classes. pnl_drawable Panel First of all, the painting begins at the form level. In my case, I created an event handler for the Paint event of the pnl_drawable Panel, but you could use a whole form as draw-able area, and hence handle the Paint event of the form. In any case, the signature for that event handler, which Visual Studio kindly provides for you, is: private void pnl_drawable_Paint(object sender, System.Windows.Forms.PaintEventArgs e) Admittedly, that doesn't seem to be much to work with, does it? Then again, the PaintEventArgs object actually holds a bunch of stuff that will prove rather useful. So, by using GDI+, if we wanted to paint an ellipse on the screen every time that the Paint event is fired, we could implement the paint handler like this: PaintEventArgs private void pnl_drawable_Paint(object sender, System.Windows.Forms.PaintEventArgs e) { Graphics g = e.Graphics; Pen pen = new Pen(Color.Black); RectangleF rectangle = new RectangleF(10,0f, 10,0f, 100.0f, 50.0f); g.DrawEllipse(pen, rectangle); } This draws an ellipse (just the outline of it) in black, within a rectangle with top-left corner at (10, 10) and with width 100 and height 50. Simple enough. And, you can go on and explore all of the GDI routines to draw and fill rectangles, ellipses, lines, and polygons! Ok, so in the myUML case, I didn't have the luxury of painting figures always in the same spot. So, in the form's Paint event, I decided to loop through the various figures defined in the figures ArrayList, and ask each one, in turn, to paint itself (note that the following is not exactly the code you will find in the project, as I will explain briefly): figures ArrayList private void pnl_drawable_Paint(object sender, System.Windows.Forms.PaintEventArgs e) { Graphics g = e.Graphics; //For each Figure in the figures ArrayList: foreach(object o in figures) { //Check what the figure is: if(o is Communication) { Communication tmpC = o as Communication; tmpC.Paint(g); } else if(o is UseCase) { UseCase tmpUC = o as UseCase; tmpUC.Paint(g); } else if(o is Actor) { Actor tmpA = o as Actor; tmpA.Paint(g); } }//FOREACH } Aye, aye, this is one of the places where I could develop an Ipaintable interface and simplify the code (see above "Not too gory details: classes and interfaces"). In any case, this could be paired by something like this in the UseCase class: Ipaintable public virtual void Paint(Graphics g) { RectangleF tmpRectangle = new RectangleF( anchors[UseCase.UseCaseAnchorsToInt(UseCaseAnchors.TopLeft)].Center, new SizeF(width, height)); if(filled) { Brush b = new SOlidBrush(color); g.FillEllipse(b, tmpRectangle); } if(bordered) { Pen pen = new Pen(brdColor); g.DrawEllipse(pen, tmpRectangle); } if(selected) { for(int i=0; i<NUM_USE_CASE_ANCHORS; ++i) anchors[i].Paint(g); }, arialFotn10, new SolidBrush(txtColor), txtPoint); } } Simple enough...apparently. Note how I called a Paint method of the Anchor class to let each Anchor paint itself, and how I used the Graphics.MeasureString method to calculate the size of the rectangle surrounding the text to be painted. This is a pretty intensive method, and it would be better to have it readily available instead of calculating it every time the UseCase is painted, but it requires a Graphics object to be used (and I have no Graphics object available when the Text property of the UseCase is being modified.. at least in this version). Graphics.MeasureString Graphics Text Anyway, it all looks simple and slick, but there is always a "but". In particular, this code does not work right if the surface over which you are painting is a scrollable one. This Paint method, in fact, does not account for the difference between "world coordinates" and "screen coordinates". Let me illustrate: if the surface that we will paint on is, say a 42x42 panel, when you click in the middle of it, your coordinates are (21, 21).. ALWAYS! Why am I stressing the "always" part? Because, if that same surface is a scrollable one, the game changes. With a scrollable surface, assuming your surface can show any point within a 84x84 area, you have a couple of scenarios: 0 42 84 0 42 84 | | | | | | -------------------- -------------------- 0-|XXXXXXXXX | 0-| XXXXXXXXX| |XXXXXXXXX | | XXXXXXXXX| |XXXXXXXXX | | XXXXXXXXX| |XXXXXXXXX | | XXXXXXXXX| |XXXX.XXXX | | XXXX.XXXX| |XXXXXXXXX | | XXXXXXXXX| |XXXXXXXXX | | XXXXXXXXX| |XXXXXXXXX | | XXXXXXXXX| |XXXXXXXXX | | XXXXXXXXX| 42-|XXXXXXXXX | 42-| XXXXXXXXX| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | 84-| | 84-| | -------------------- -------------------- Case A Case B The 'X' show which portion of the greater area the surface is showing; the coordinates at the top and left of the area are "world coordinates"; the '.' indicates where you are clicking. See the difference? In both cases, your surface tells you, you clicked at coordinates (21, 21), since you clicked in the middle of the surface. However, in Case A, this means you actually clicked at "world coordinates" (21, 21), while, in Case B, you are clicking at "world coordinates" (63, 21). So, if we don't consider this when painting objects, we end up painting them in wrong places. After all, when we create a new Usecase, we save its coordinates in terms of "world coordinates", since the "screen coordinates" may change based on the size and position of the draw-able panel itself. One more thing, before we look at the solution for this kind of problems: the clip area (or clip rectangle). Painting all the various graphics on screen is a rather resource intensive operation, and it takes place *Very Often*. So, in order to minimize the payload on the system, Windows provides (in the PaintEventArgs argument object of the Paint event) an important clue, named the ClipRectangle. This is a Rectangle object that indicates the area that you should repaint due to changes to the screen. For instance, consider the case where we have painted a rectangle to screen, and we have then moved some other object (say a window or form from another application) to overlap with the rectangle, like so: Usecase ClipRectangle Rectangle ----------- |XXXXXXXXX| |XXXXXXXXX| --------------|XXXXXXXXX| | |XXXXXXXXX| | |XXXXXXXXX| | |XXXXXXXXX| | ----------- | | | | ------------------- where the X'ed rectangle is the form from the other application. If we now move that other application's form out of the way, Windows would fire a Paint event for our rectangle, but the ClipRectangle property of the event arguments would tell us that we need to repaint *only* the portion that has just been un-covered, indicated in the following diagram with dots: ------------------- | ...| | ...| | ...| | ...| | | | | ------------------- This is used to paint the least required by the system in all of the graphical object managed by Windows. Of course, this is a simple example. What actually happens is that the Paint event is fired a number of times *as we move the other form out of the way*, but I think you get the picture (pun intended) by now. So, what does all this mean to our myUML project and its figures? Well, first of all, the Paint event handler from the form needs to consider the ClipRectangle when painting anything. Since we are asking each figure to paint itself, we will pass this on to the Paint methods of the UseCase (and Actor, and Communication) class. Additionally, the Paint handler passes on a scrollOffset Size object, which it gets directly from the pnl_drwable object. This Size describes the position of the scrollbars surrounding the panel, giving us a hint as to how we can reconcile the "world coordinates" and "screen coordinates" that we mentioned above. Furthermore, I defined two constants for the TestUseCases form (MAX_DRAW_WIDTH and MAX_DRAW_HEIGHT, both set to 1024 - I hope that's large enough) to describe the limits of the area that we may point on with our pnl_drawable Panel, and we pass those on to the Paint method of the UseCase (and Actor, and Communication) class. One more parameter I pass on is the PaintMode value that indicates if this UseCase (/Actor/Communication) should be painted in Standard mode or Outline mode. The Outline mode is used when the figure to be drawn is the one the user is currently drawing, and, generally, makes the figure paint itself by using a blue dashed line for its outline, without any filled area. The final result, for the UseCase, is: scrollOffset Size pnl_drwable TestUseCases MAX_DRAW_WIDTH MAX_DRAW_HEIGHT PaintMode Standard Outline public virtual void Paint(Graphics g, Rectangle clipRectangle, Size scrollOffset, int MAX_DRAW_WIDTH, int MAX_DRAW_HEIGHT, PaintMode pm) { //Check for clipRectangle + scrollOffset // to be in drawable range if (clipRectangle.Top+scrollOffset.Width < MAX_DRAW_WIDTH || clipRectangle.Left+scrollOffset.Height < MAX_DRAW_HEIGHT) { RectangleF tmpRectangle = new RectangleF( anchors[UseCase.UseCaseAnchorsToInt (UseCaseAnchors.TopLeft)].Center+scrollOffset, new SizeF(width, height)); Pen pen; //Depending on the PaintMode: switch(pm) { case PaintMode.Standard: //Filled? if(filled) { Brush b = new SolidBrush(color); g.FillEllipse(b, tmpRectangle); }//IF filled //Bordered? if(bordered) { pen = new Pen(brdColor); g.DrawEllipse(pen, tmpRectangle); }//IF bordered //Anchor Points (if selected) ? if(selected) { for(int i=0; i<NUM_USE_CASE_ANCHORS; i++) anchors[i].Paint(g, clipRectangle, scrollOffset, MAX_DRAW_WIDTH, MAX_DRAW_HEIGHT, pm); }//IF selected //Text?, new Font("Arial", 10), new SolidBrush(txtColor), txtPoint); }//IF text.Length>0 break; case PaintMode.Outline: //Paint online the border in dashed blue pen: pen = new Pen(Color.Blue, 2); pen.DashPattern = new float[] {5, 2}; g.DrawEllipse(pen, tmpRectangle.Left, tmpRectangle.Top, tmpRectangle.Width, tmpRectangle.Height); break; default: //Should never happen. break; }//SWITCH on pm }//IF clipRectangle+scrollOffset is in drawable range } Note how we define the tmpRectangle Rectangle (which will surround the UseCase) by considering the scrollOffset, the pnl_drwawable_Paint event handler passed us: tmpRectangle pnl_drwawable_Paint RectangleF tmpRectangle = new RectangleF( anchors[UseCase.UseCaseAnchorsToInt(UseCaseAnchors.TopLeft)].Center+ scrollOffset, new SizeF(width, height)); Also, we pass all of these parameters to the various Anchors, to let them paint appropriately: anchors[i].Paint(g, clipRectangle, scrollOffset, MAX_DRAW_WIDTH, MAX_DRAW_HEIGHT, pm); Fine and dandy, right? Well, not exactly. The fact that we consider the scrollOffset when we are painting implies that, when we created the figure, we set it by using the "world coordinates". So, in other words, when we create a new figure, we have to account for the scrollOffset of the panel (at that time) to set the figure appropriately. The TestUseCases form's handler for the MouseUp event is where we do this. Here's a minimized version: MouseUp private void pnl_drawable_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e) { if(drawing) { if(currTool!=UseCaseDiagramTool.None) { //Set the endPoint: PointF endPoint = new PointF(e.X, e.Y); //Get the scroll offset // (used to adjust the Points' coordinates): SizeF scrollOffset = new SizeF(this.pnl_drawable.AutoScrollPosition); //Variable used in more than one case: float minx=0.0f; float maxx=0.0f; float miny=0.0f; float maxy=0.0f; float theW=0.0f; float theH=0.0f; //Add a new figure to the figures ArrayList: only if the //startPoint and endPoint are at least MIN_FIGURE_SIZE away: float delta = PointDiff(startPoint, endPoint); if(delta>=MIN_FIGURE_SIZE) { //... switch(currTool) { //... case UseCaseDiagramTool.UseCase: //Make a new UseCase: adjust the Points' coordinates //with the scroll offset; use // the lowest (X,Y) pair as root, and //calculate the width and height: startPoint.X=(startPoint.X-scrollOffset.Width); startPoint.Y=(startPoint.Y-scrollOffset.Height); endPoint.X=(endPoint.X-scrollOffset.Width); endPoint.Y=(endPoint.Y-scrollOffset.Height); //... minx = Math.Min(startPoint.X, endPoint.X); maxx = Math.Max(startPoint.X, endPoint.X); miny = Math.Min(startPoint.Y, endPoint.Y); maxy = Math.Max(startPoint.Y, endPoint.Y); theW = (maxx-minx); theH = (maxy-miny); UseCase tmpUC = new UseCase(new PointF(minx, miny), theW, theH); tmpUC.Selected=true; //... figures.Add(tmpUC); break; //... }//SWITCH on currTool }//IF delta>=MIN_FIGURE_SIZE //Reset the startPoint and drawingPoint startPoint = new PointF(0.0f, 0.0f); drawingPoint = new PointF(0.0f, 0.0f); }//IF currTool!=DrawingTool.NONE //ELSE: do nothing: this should never happen! //Stop drawing: drawing=false; //... //Ask for a GUI refresh: this.pnl_drawable.Invalidate(); }//IF drawing //ELSE: do nothing. } Notice how we consider the scrollOffset by *subtracting* its dimensions from the startPoint and endPoint that are then used to define the UseCase. This is the similar operation to what we did when Painting the UseCase (in that case we were adding the scrollOffset to the coordinates of the UseCase), to balance it all out. startPoint endPoint Of course, if you read around, you will find out that GDI provides the Graphics.TranslateTransform method to perform this conversion between "world coordinates" and "screen coordinates" for you. However, it isn't that hard to do it yourself, is it? And, by implementing it yourself, you are in control, and you can understand what's going on (or at least try . Graphics.TranslateTransform So, once the painting issue was resolved, I realized I had already a bunch of code in the panel's MouseDown, MouseUp and MouseMove event handlers. After all, when you mouse-down on the panel, you might be starting a new drawing, or selecting a figure, or de-selecting all of the selected figures (if you click on no figure), and it all depends also on whether you are pressing the shift key or not... on a MouseUp, on the other hand, you might have finished drawing a new figure. So, I gave up, at least for the time being, on letting the user click and drag a figure on screen, or click on its Anchors and resize it (I admit that I did this partially because it all became a bit more complicated after I decided to let the user select multiple figures by shift-clicking..). So, once you draw a figure on screen, how can you move/resize it? For that matter, how can you change its color, or add some text to it? Hence, I figured the simple solution was to provide some custom controls to display the details of a given figure, and let the user interact with the control instead. MouseDown MouseMove Enter the CommunicationDisplay, UseCaseDisplay and ActorDisplay controls. For the most part, they are simple controls including a series of text boxes, buttons, checkboxes, and even a combo box to let the user modify the figure's properties. However, there are a couple of interesting things to be said about these controls. First, the way that the testUseCases form manages them. The custom controls are actually always there, but they are rendered invisible and disabled by the form if you have no figure selected, or more than one figure selected. Interestingly enough, in order to add the custom controls to the form in Visual studio's designer, I had to provide a parameter-less constructor for each (originally, I envisioned the controls as requiring you to pass a Communication, or UseCase, or Actor to the constructor to ensure they would never be in the state where they don't have a figure to display). This forces me to change the internal working of the controls to account for the situation where the control has been constructed but has no figure to display. When you run the application, though, you will never see this case, since, when that happens, the form hides the control directly. testUseCases Secondly, these custom controls gave me an opportunity to explore and experiment with custom events and event handling. In essence, I didn't want the controls themselves to have to deal with the consequences of the user changing some figure's attribute. For instance, aside from recording the change in its internal representation of the UseCase, when a user changes the Color of a UseCase in the UseCaseDisplay control, what should the control do? Color One option was to provide the control a reference to the actual UseCase in the surrounding form, and let the control apply changes to it (and force a refresh of the GUI in the form). Possible, but not nice. After all, tomorrow the UseCaseDisplay might be used in some place where there is no GUI to refresh. So, event-driven architecture to the rescue, it sounded like a perfect situation to use events and delegates. When the user changes some property in the control, the control signals the event to anyone who is interested. For each control, I defined a series of custom events, so that the application listening to events could quickly determine what exactly happened to the control. Here's how to do it (I will show, for example, what I did in regard to the user changing the color of a UseCase). In this case, I defined the UseCaseColorChangedEventArgs class (you'll find it in the UseCaseDiaplsy.cs file, before the UseCaseDisplay class itself): UseCaseColorChangedEventArgs public class UseCaseColorChangedEventArgs : System.EventArgs { public Color NewColor = Color.Black; public UseCaseColorChangedEventArgs(Color inC) : base() { NewColor=inC; } } This class inherits from the System.EventArgs class, has a single public property, and implements a simple constructor (which, note, calls the base's constructor as well). System.EventArgs In this case, we need an event handler for the UseCaseColorChanged event: UseCaseColorChanged public delegate void UseCaseColorChangedHandler(object sender, UseCaseColorChangedEventArgs e); As all event handlers, it gets a sender object, but the second parameter should be one of our newly created UseCaseColorChangedEventArgs. In this case, the user can click on the "Pick..." button next to the UseCase's color to select a new Color for the UseCase. Here's the handler for the click event on that button: private void btn_ColorPick_Click (object sender, System.EventArgs e) { ColorDialog cd = new ColorDialog(); cd.AllowFullOpen=false; cd.SolidColorOnly=true; cd.AnyColor=false; cd.Color=saveColor; DialogResult dr = cd.ShowDialog(this); if(dr==DialogResult.OK) { Color newColor = cd.Color; if(newColor!=saveColor) { saveColor = newColor; this.pnl_Color.BackColor=saveColor; if(!initializing) OnUseCaseColorChanged (new UseCaseColorChangedEventArgs(saveColor)); } } } Note how I am using the ColorDialog dialog, but I am restricting the number of colors that will be available through the dialog (I was trying to keep it simple by setting the ALlowFullOpen and AnyColor properties of the dialog to false (and the SolidCOlor property to true). Also note how I check if the newColor is different from the old one (the saveColor) before firing the event. After all, if the user does not select a *new* color, no change in the Color has taken place, right? ColorDialog ALlowFullOpen AnyColor SolidCOlor newColor saveColor So, next I change the background color of the pnl_Color Panel (a control in the UseCaseDisplay itself, so the display is responsible for updating it) to match the new color. Then, the following two lines: pnl_Color if(!initializing) OnUseCaseColorChanged (new UseCaseColorChangedEventArgs(saveColor)); In other words, if the display is currently being initialized (a situation marked by the initializing flag being true), we don't want to fire the event. Otherwise, we call the OnUseCaseColorChanged method. This sounds similar to the delegate we described in the previous step, but it's not: we have not defined this method yet. For instance, this OnUseCaseColorChanged method is called with one parameter, while the signature for the event handler mentioned two parameters! OnUseCaseColorChanged Remember how we defined the signature for an event handler for our event in step 2? It was public delegate void UseCaseColorChangedHandler(object sender, UseCaseColorChangedEventArgs e); Well, if you want to fire the event, you may want someone to receive it, right? So, in the UseCaseDisplay class I defined the following method (which is called, as we've seen, when the event needs to be fired): protected virtual void OnUseCaseColorChanged(UseCaseColorChangedEventArgs e) { if(UseCaseColorChanged!=null) UseCaseColorChanged(this, e); } The reason for this method is that it ensures that at least one event handler has been defined before firing the actual event (the if statement). That's why I call this an event dispatcher. The actual event handler, as we'll see in the next step, may be in some other class, but this method lets us avoid the trap where no such event handler was defined. Note how the method that we invoke to fire the event matches the signature we defined for the event handle in step 2. if In step 2 we defined the signature for an event handler for our custom event. Now it is time to provide the actual implementation. In the TestUseCases form, I added the following method: private void ucDisplay_UseCaseColorChanged(object sender, myUML.UseCaseColorChangedEventArgs e) { UpdateFigure(ucDisplay.UseCase); } This matches the signature we defined in step 2 (aside, of course, from the name of the method!). In the next step, we will ensure that the call from the event dispatcher in the UseCaseDisplay class will actually invoke this method. If you're using Visual Studio, this is simple: In your receiver component (in my case the TestUseCases form), select the custom control, and display its events. Find the event you wish to handle, and click to its right: a drop-down menu is available for you to select which method should handle the event. If you are not using Visual Studio, fear not: it's not that hard to do: When you create the custom control, and add it to the parent's object Controls array, you can add the event handler to the list of the "listeners" for the custom control with the following statement: Controls <the_control>.<event_name> += new <delegate_name>(<handler_name>); So, for instance: this.ucDisplay.UseCaseColorChanged += new myUML.UseCaseColorChangedHandler (this.ucDisplay_UseCaseColorChanged); Not too difficult, is it? This has been a simple overview of the "Event and Delegates" topic. There's much more to be said in regard, but I fear it would fall outside the scope of this article. Of course, I still think I should go back and let a user click-and-drag figures across the screen, and resize them by acting on their anchors. Plus, it would be nice to have a context-menu pop-up when you right click on a selected figure to let you change its properties on the fly, without using the custom controls. But then again, it's also nice to have the custom control pop-up and tell you more about the figure you selected... The last functionality I implemented in this first version of the myUML project is the ability to save Use Case Diagrams to file and load them from file. When I first approached this problem, I thought I'd implement it so that the diagrams could be saved to file in two different formats: PNG and XML. After looking at the PNG option for a while, I lost interest. After all, if you were to pass the saved diagram to some other application, the XML format would probably be a good choice. So, armed with a rough idea, and with some wisdom collected on the way regarding interfaces (again, see above "Not too gory details: classes and interfaces"), I made each of the relevant classes able to save and restore themselves to XML format, and I implemented the code behind the "Save Diagram" and "Open Diagram" buttons in the TestUseCases form. Mind you, the implementation is a first draft, and does not include much needed checks, but there is always time for improvements. Let me move "from the top down" to walk you through this functionality, as if we were the machine, reacting to the user asking us to save the diagram to file. After this, we will briefly see what happens when the user asks to load a diagram from a file. When you click on the "Save Diagram" button, the handler for clicks on the toolbar buttons dispatches you to the SaveDiagram routine. Here, the program lets the user specify where the diagram should be saved to (and adds for you the .xml extension if you don't type it). Once you picked a filename, the SaveDiagram routine opens a try block, and calls the SaveXML method (passing it the selected filename). The goal of having this call within a try block is that it allows us to catch at this level, any exception that might be thrown during the save operation. Knowing that a catch block is ready at this level to report to the user any problem, lets me move through the saving code without worrying too much about catching exceptions where they might be fired. After all, in all of the code performing the save, which we will see in a second, I could only catch the exception and re-throw it. In any case, here's the SaveXML method: SaveDiagram try SaveXML catch private void SaveXML(string fn) { XmlTextWriter xmlw = null; try { xmlw = new XmlTextWriter(fn, null); //Write header: xmlw.Formatting=Formatting.Indented; xmlw.WriteStartDocument(false); xmlw.WriteStartElement("UseCaseDiagram", null); xmlw.Flush(); foreach(IUMLtoXML fig in figures) fig.SaveTo(xmlw); } catch(Exception e) { StringBuilder sb = new StringBuilder ("An Error occurred while saving the Use Case Diagram\n"); sb.Append("to the specified file ('"); sb.Append(fn); sb.Append("')\nDetails:\n"); sb.Append(e.ToString()); throw new ApplicationException(sb.ToString()); } finally { if(xmlw!=null) { xmlw.Flush(); xmlw.Close(); } } } (Yeah, the try-catch block at this level is rather redundant, but it lets me use a finally clause to close the XmlTextWriter if something goes wrong). As you can see, I simply open a new XmlTextWriter, and set it up to use indented formatting. Then, I write the start of the document (i.e. the XML declaration), and parse through the figures in the figures ArrayList, treating each as an IUMLtoXML object. This is where I enjoyed one advantage of the interfaces. Since all of the objects I store in the figures ArrayList implement the IUMLtoXML interface, I am allowed to simply deal with the interface instead of each different class separately. finally XmlTextWriter The IUMLtoXML interface simply defines two methods: public interface IUMLtoXML { void SaveTo(XmlTextWriter x); void ReadFrom(XmlTextReader x); } And the Anchor, Communication, UseCase, and Actor class implement it. Note that the Actor class does not list the interface in its first line: public class Actor : UseCase However, since the UseCase class implemented the interface, the Actor class implicitly implements the interface. Sneaky, I know, and possibly not a good practice, but.. but it's good to know that it is possible, because sooner or later you might stumble upon some else's code that does just that! In any case, let's assume that our diagram included only a UseCase. Then, the loop in the SaveXML method will invoke the SaveTo method of the UseCase object: public virtual void SaveTo(XmlTextWriter x) { x.WriteStartElement("UseCase", null); x.WriteAttributeString("Width", width.ToString()); x.WriteAttributeString("Height", height.ToString()); x.WriteAttributeString("Filled", filled.ToString()); x.WriteAttributeString("Color", color.ToArgb().ToString()); x.WriteAttributeString("Bordered", bordered.ToString()); x.WriteAttributeString("BrdColor", brdColor.ToArgb().ToString()); x.WriteAttributeString("Text", text); x.WriteAttributeString("TxtColor", txtColor.ToArgb().ToString()); x.WriteStartElement("TopLeft", null); anchors[0].SaveTo(x); x.WriteEndElement(); x.WriteEndElement(); x.Flush(); } As you can see, it's pretty straight-forward stuff. The XmlTextWriter class has a bunch of methods to let you write whatever you need. In this case, we open a UseCase element, and add a few attributes to it (note how I'm using the int representation of the Colors of the UseCase!). As it is always the case with XML data, I then had the option of adding more attributes or let the UseCase element contain a child element. In order to apply some good practice, I decided to go for the containment option. Hence, I open a new attribute (named TopLeft, for it will describe the top-left corner of the UseCase), and asked the top-left corner of the UseCase (an Anchor object) to save itself to the XmltextWriter. int TopLeft XmltextWriter The Anchor's SaveTo method does pretty much the same: public void SaveTo(XmlTextWriter x) { x.WriteStartElement("Anchor", null); x.WriteAttributeString("X", center.X.ToString()); x.WriteAttributeString("Y", center.Y.ToString()); x.WriteEndElement(); x.Flush(); } Note how this solution creates an element (the TopLeft element) that simply contains another element. A bit redundant, but good enough for a first version. Plus, it simulates the object hierarchy at hand: the UseCase object, in fact, contains a top-left corner, which is indeed an Anchor instance. Anyway, writing to file was simple enough. Now, let's see what happens when you click on the "Open Diagram" button. The TestUseCases' button click handler dispatches you to OpenDiagram. In there, I first check if you have any figure on screen (if so, I ask you if you wish to save your current diagram), and then ask you to pick a file to be loaded (again, assuming the file will have .xml extension). Finally, we move to the ReadXML method (again, within a try block that lets us catch any exception and report to the user via standard MessageBox). Here's the ReadXML method: OpenDiagram ReadXML private void ReadXML(string fn) { XmlTextReader xmlr = null; try { xmlr = new XmlTextReader(fn); xmlr.WhitespaceHandling=WhitespaceHandling.None; while(xmlr.Read()) { switch(xmlr.NodeType) { case XmlNodeType.Element: switch(xmlr.Name) { case "Communication": Communication tmpC = new Communication(); tmpC.ReadFrom(xmlr); figures.Add(tmpC); break; case "UseCase": UseCase tmpUC = new UseCase(); tmpUC.ReadFrom(xmlr); figures.Add(tmpUC); break; case "Actor": Actor tmpA = new Actor(); tmpA.ReadFrom(xmlr); figures.Add(tmpA); break; default: break; }//SWITCH on Element's Name break; default: break; }//SWITCH }//WEND } catch(Exception e) { StringBuilder sb = new StringBuilder ("An Error occurred while opening the Use Case Diagram\n"); sb.Append("from the specified file ('"); sb.Append(fn); sb.Append("')\nDetails:\n"); sb.Append(e.ToString()); throw new ApplicationException(sb.ToString()); } finally { if(xmlr!=null) xmlr.Close(); this.pnl_drawable.Invalidate(); } } Notice how I set the XmlTextReader to ignore all white space, and how I move from one element in the document to the next by using the XmlTestReader.Read() method. The while loop will terminate once the XmltextReader.read() method returns false (which is usually at the end of the file being read, or when something bad happens). Within the loop, I have two switch statements (arguably, one of the most confusing configuration of source code possible in modern programming languages ). We are lucky, though: the outer switch loop could really be a simple if statement, since it includes only one case (plus the default case). I used the switch statement instead of the if statement, since I can see more cases being added in future releases. Anyway, the outer switch is based on the type of node that the XmlTextReader is currently pointing to. We do something only for Elements, but we could add cases as needed to deal, for instance, with document declaration nodes, comments, and such. XmlTextReader XmlTestReader.Read() while XmltextReader.read() switch Element If the XmlTextReader is pointing to an element (going back to the file we saved not long ago, this would happen on the second iteration of the encompassing while loop, since the XmlTextReader will first be pointing to the document declaration), we enter the second switch statement, which is based on the name of the node in question. Within this switch, we do something only if we are pointing to a node names as "Communication", "UseCase", or "Actor". If you are following the code and looking at the file we saved above, you will notice that, on the second iteration of the outer while loop, we enter the inner switch statement but we don't do anything. In fact, we are currently pointing to the root node of our XML file (the "UseCaseDiagram" node). So, we step through and end up at the top of the while loop again. This time, after calling XmlTextReader.Read(), we end up pointing to the "UseCase" node we saved in the file. The Read method, in fact, does not distinguish between siblings and children. It simply moves to the next element XML node in the file. UseCaseDiagram XmlTextReader.Read() Read So, now that we enter the inner switch. While pointing to the "UseCase" element, we instantiate a new UseCase object, and ask it to read itself from the XmlTextReader. After the UseCase is done with this, we simply add it to the figures ArrayList of the testUseCases form. Before we look at the UseCase.readFrom method, notice how the finally clause in this method ensures that we close the XmlTextReader and invalidate the pnl_drawable Panel (so that the GUI gets refreshed and we see all the figures we have just loaded). UseCase.readFrom The UseCase.readFrom method is rather simple: public virtual void ReadFrom(XmlTextReader x) { float w = 0.0f; float h = 0.0f; while(x.MoveToNextAttribute()) { switch(x.Name) { case "Width": w = float.Parse(x.Value); break; case "Height": h = float.Parse(x.Value); break; case "Filled": filled=(x.Value==true.ToString()); break; case "Color": color = Color.FromArgb(int.Parse(x.Value)); break; case "Bordered": bordered = (x.Value==true.ToString()); break; case "BrdColor": brdColor= Color.FromArgb(int.Parse(x.Value)); break; case "Text": text = x.Value; break; case "TxtColor": txtColor = Color.FromArgb(int.Parse(x.Value)); break; default: break; } }//WEND bool b = x.Read(); if(x.NodeType==XmlNodeType.Element && x.Name=="TopLeft") { x.Read(); anchors[0].ReadFrom(x); }//WEND while(x.NodeType!=XmlNodeType.EndElement) x.Read(); //Set width and height AFTER the TopLeft corner has been set: this.Width=w; this.Height=h; } We are assuming that the XmltextReader is pointing to an Element node, named "UseCase". If this is not the case, it would be good (i.e. something to do in the next version) to throw an exception. We use the XmltextReader.MoveToNextAttribute to run through the attributes of the UseCase node, and, for each, we set the corresponding property in the UseCase object. As we used the integer representation of the Colors, here we use the Color.FromArgb(int) method to reconstruct the Color that is represented by the XML attribute. Something else to be noticed is that we do not set the width and height of the UseCase immediately. The reason for this will be explained in a minute. XmltextReader XmltextReader.MoveToNextAttribute Colors Color.FromArgb(int) Once we are done with the attributes (and note how we don't do anything if the attributes are not named as we expect them), we call XmltextReader.Read() to move to the next node, which should be the "TopLeft" child of the UseCase. If, at this point, we are indeed pointing to an Element XML node, named "TopLeft", then we ask our top-left Anchor to read itself from the XmlTextReader. Note how we have to interpose an XmltextReader.Read() before we do this. This is the result of having the "TopLeft" element contain the Anchor element. If we didn't have this call, in fact, when we pass the XmlTextReader to the Anchor, it would still be pointing to the "TopLeft" node instead of the actual "Anchor" element. In any case, the Anchor will simply read the attributes from the XML node. Once the Anchor has read itself, note how the UseCase.ReadFrom method implements a little loop: XmltextReader.Read() UseCase.ReadFrom while(x.NodeType!=XmlNodeType.EndElement) x.Read(); This ensures that we move forward until we are pointing to an EndElement. In particular, it ensures that we get to the closing tag for the "TopLeft" element that surrounds the Anchor. Without this loop, when the ReadFrom method returns control, we would be out of synch with the expectation of the calling function (namely, the TestUseCases.ReadXML method) and we would end up in trouble. EndElement TestUseCases.ReadXML Finally, we set the UseCase's width and height. Now, we are doing this at the end of the method, after we read and set the top-left Anchor, AND we are doing this by calling the UseCase's public attributes because those attributes actually move all of the Anchors of the UseCase based on the location of the top-left anchor and the dimensions of the UseCase. As I said in the beginning, this is a first version of the myUML project. What does this mean? First and foremost, it means that many functionalities have not been implemented yet. In particular, you can only draw and modify Use Case Diagrams. The myUML project is envisioned to include other types of diagrams (classes diagrams, and sequence diagrams just to mention two). Secondly, it means that some functionalities have been implemented in a "first draft/prototype" way. For instance, you can't drag the figures around, but you can move them by changing their location in the corresponding display control. Same goes for resizing them. Thirdly, the code itself might enjoy a healthy refresh in the near future, to make it stronger, faster, better.. I am publishing this code as-is, and you certainly should feel free to use, re-use and modify it as you need (for non-commercial purpose, of course). Hope you will find it interesting, and don't forget to have fun with it! This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below. A list of licenses authors might use can be found here public interface IFoo { FooImplementation Implementation{get;} } public interface IBar { BarImplementation Implementation{get;} } public class FooImplementation { public void DoSomethingFooLike() {} } public class BarImplementation { public void DoSomethingBarLike() {} } public class MyClass : IFoo, IBar { private FooImplementation fooImplementation = new FooImplementation(); private BarImplementation barImplementation = new BarImplementation(); FooImplementation IFoo.Implementation {get{return fooImplementation;}} BarImplementation IBar.Implementation {get{return barImplementation;}} } General News Suggestion Question Bug Answer Joke Praise Rant Admin Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
http://www.codeproject.com/Articles/5102/The-myUML-Project?msg=634245
CC-MAIN-2016-30
refinedweb
9,695
61.46
This is a short introduction to Microsoft's Surface technology. The best way to quickly get an impression of the actual thing would be to watch this short video. I guess, formally, Surface is a combination of hardware that has some new input qualities and software APIs that come along with it to support them. The parody (also a recommended watch) describes it as 'a computer that is a big ass table’. For those of you who haven’t watched the movie, Surface is a table that has a computer screen on its surface. You can interact with it by touching the screen, which is far from new, but you can do it in multiple spots simultaneously (multiple users, multiple fingers of one user...), and you can place objects on it and have the Surface recognize them and interact with them. Microsoft identifies four key concepts in Surface: It seems Microsoft is also aiming towards wireless technologies, enabling data transfer between devices placed on the Surface. The industry always thinks of new ways to interact with computers. While some of these ways are clearly very cool, their usefulness is not always that evident. Microsoft hopes to have Surface integrated into our life in places computers don’t go today, using its unique attributes. They hope to have it in social occasions where people would use it to interact with each other (casinos, waiting rooms, conferences etc.). They would also like to use the object recognition capabilities to have the computer provide extra information regarding physical objects (in stores and such). Surface also seems to be naturally suited for manipulating visual information such as maps and photos (for military situation rooms?). Home use of Surface doesn’t seem to be close at the moment with a price tag of $12,500 (developer’s edition goes for $15,000), and I cannot imagine anyone programming on it (unless programming for it). Maybe an architect would find it useful for work purposes. I would be disappointed if it would turn out to be a bit fancier touch screen kiosk. Time will tell. Some of the concepts behind Surface are out there since the eighties. There are even a few commercial products available. (Wikipedia quotes Steven Spielberg on Minority Report commentary saying that the concept of the input device used by Tom Cruise in the film came from consultation with Microsoft during the making of the movie.) Microsoft has an edge since it has a strong stand in the world of programming, and used it to make developing for Surface as easy as it could. Microsoft has also proven that it can make a reasonable hardware job when properly motivated. Under the hood, Surface is a PC, running Vista, hidden in a table. The table projects the output on its surface, and has five infra-red cameras looking up to the surface and filming whatever is going on there. The computer also has a wired Ethernet 10/100, wireless 802.11 b/g, and Bluetooth 2.0. Surface physical objects recognition is based on physical tags with patterns printed on them. These patterns represent a GUID and an orientation. The Surface plumbing parses the data and tells you what the GUID of the object placed on the table is and its orientation. Tags can be printed by developing parties, and they only need to be infra-red visible so they can even be transparent. Microsoft introduced Surface's API during PDC2008. The movie is available here if you are willing to deal with the technical difficulties and its length (about an hour and a quarter). Should you choose to watch the movie, read no further, it is all taken from there. If you like picture recognition, or manipulation, or DSP, you may get everything the cameras see and do whatever with it (I wouldn’t know where to start): Alternatively, you can have the API do its magic and tell you where fingers and objects are touching the screen, and in what orientation etc. If you like having the higher levels, you would be glad to learn that Microsoft introduced a set of WPF controls that are very similar to controls we already work with. The new controls can function in multi-touch scenarios and are configurable to produce a 'real world' feel. Standard WPF controls are designed to work in an environment that has only one source of input. This means that we are safe to assume that button release over a mouse should fire the 'button click' event. For Surface, the button might be pressed by more than one user at a time, so the event is supposed to be fired only once all fingers are off of it. In other cases, a control might want to respond to an occasion where it receives more than one input at the same time (as with the 'enlarge picture' you have probably seen if you have watched any Surface video or Minority Report). Some times, controls need to be costumed to produce 'real world' behavior. For instance, a hand movement in an increasing speed where the hand lifts off from the table at the end of the movement would be the real world for 'throwing this picture to the other side' (try it on your desk). This is relevant with the mouse too (and supported in some applications), but not nearly as critical as it is for Surface. To support all this stuff, Microsoft introduced a library of WPF controls, where Button is replaced with SurfaceButton etc. Theoretically, all you need to do in order to migrate an application into Surface is import the namespace into your XAML and initiate a few 'Find and Replace' actions on your WPF. That said, Surface applications are still fundamentally different from other applications as they should be designed 'lying on their back', accessible from all sides, and supporting physical objects. If you wrap your head around this, you might find that you need some extra tools. These tools are provided in the form of Scatter control and TagVisualizer. Button SurfaceButton Scatter TagVisualizer Scatter control is the Surface version for ItemsControl. It has an ItemsSource property. It can use an ItemTemplate etc. The Scatter control scatters its items on the Surface. It also provides them with the ability to be dragged (or tossed) around on the Surface, change size, and so forth. You can use it to determine some 'real world' attributes such as friction etc. ItemsControl ItemsSource ItemTemplate The TagVisualizer class is the way you attach a visual representation to a physical object, or rather to a tag. As mentioned, tags are actually small labels representing a GUID and a direction. The lower level APIs read and parse the information and places the appropriate visualization. As you can see, there is no code. I really wanted to produce some nifty XAML for this article, but unfortunately, Microsoft has not provided the developers community with a Surface emulation. Such emulation (and access to the Surface developers network) is only available for companies who joined the program (and purchased a development unit). This week, Microsoft announced its intention to widen the Surface community and allow access to Surface resources to all Microsoft partners. So far, I have not been able to join in (they seem to be having some technical problems – could it be that the servers are overcrowded?). Microsoft is investigating MMI (Man-Machine Interface) in various directions. They are currently working on an XBox answer to Nintendo WII based on cameras watching the user and recognizing movements (something done in the movies industry for a very long time now). They have Surface, and they probably have a few other surprises up their sleeves and they are not alone out there. As mentioned earlier, the usages are not always very clear at first sight, but the concepts of multi-touch and objects recognition are probably here to stay. It is nice to know that even if you are not quite there yet, your WPF investment can be leveraged for this new stuff. It is also nice to know that some people out there are working on new and exciting stuff. If you have survived thus far, I am glad this exciting technology caught your attention as it did mine. You might want to watch the PDC 2008 video, and maybe check in on the Surface website. I suspect we would be hearing a lot about Surface soon, and PDC 2009 would probably be a good place to look for some more. The folks here at The Code Project have opened a category for Surface and I hope we will get to see some real Surface-WPF.
http://www.codeproject.com/Articles/38201/Microsoft-Surface-Intro?msg=4348637
CC-MAIN-2015-06
refinedweb
1,448
60.04
Can someone please point me in the right direction. I have downloaded a GIT project Namshi/JOSE which is a JWT signing and verification library. I have a directory structure shown below. All my unit tests (inside the folder tests work perfectly, so the composer.json and bootstrap.php files are okay. But when I try and add my own test, in the folder myTests->simpleTest.php as below what ever I try I can't get the namespace to resolve the class SimpleJWS. The namespace for the library is Namshi/JOSE. My simple test calling code is: <?php use Namshi\JOSE\SimpleJWS; //require_once ("../src/Namshi/JOSE/SimpleJWS.php"); $jws = new SimpleJWS(array( 'alg' => 'RS256' )); Fatal error: Class 'Namshi\JOSE\SimpleJWS' not found "autoload": { "psr-4": { "Namshi\\JOSE\\": "src/Namshi/JOSE/" } }, "autoload-dev": { "psr-4": { "Namshi\\JOSE\\Test\\": "tests/Namshi/JOSE/Test/" } Your thinking about the autoloading is correct, but as you're stating, your test file lives under "myTests"; your autoload-dev simply points to the wrong directory "tests/Namshi/JOSE/Test/" while your file lies in "myTests". "autoload-dev": { "psr-4": { "Namshi\\JOSE\\Test\\": "myTests" } } Please also make sure, your FQCN (fully-qualified class name) of your test class is Namshi\JOSE\Test\simpleTest. <?php namespace Namshi\JOSE\Test; class simpleTest {} According to the comments below you were missing the include of the autoloading in your testsuite.
https://codedump.io/share/eob7QNdZeNol/1/php-namespace-error-class-not-found-within-composer-project
CC-MAIN-2017-13
refinedweb
229
57.87
Original text by Or Cohen Executive Summary Lately, I’ve been investing time into auditing packet sockets source code in the Linux kernel. This led me to the discovery of CVE-2020-14386, a memory corruption vulnerability in the Linux kernel. Such a vulnerability can be used to escalate privileges from an unprivileged user into the root user on a Linux system. In this blog, I will provide a technical walkthrough of the vulnerability, how it can be exploited and how Palo Alto Networks customers are protected. A few years ago, several vulnerabilities were discovered in packet sockets (CVE-2017-7308 and CVE-2016-8655), and there are some publications, such as this one in the Project Zero blog and this in Openwall, which give some overview of the main functionality. Specifically, in order for the vulnerability to be triggerable, we need the kernel to have AF_PACKET sockets enabled (CONFIG_PACKET=y) and the CAP_NET_RAW privilege for the triggering process, which can be obtained in an unprivileged user namespace if user namespaces are enabled (CONFIG_USER_NS=y) and accessible to unprivileged users. Surprisingly, this long list of constraints is satisfied by default in some distributions, like Ubuntu. Palo Alto Networks Cortex XDR customers can prevent this bug with a combination of the Behavioral Threat Protection (BTP) feature and Local Privilege Escalation Protection module, which monitor malicious behaviors across a sequence of events, and immediately terminate the attack when it is detected. Technical Details (All of the code figures on this section are from the 5.7 kernel sources.) Due to the fact that the implementation of AF_PACKET sockets was covered in-depth in the Project Zero blog, I will omit some details that were already described in that article (such as the relation between frames and blocks) and go directly into describing the vulnerability and its root cause. The bug stems from an arithmetic issue that leads to memory corruption. The issue lies in the tpacket_rcv function, located in (net/packet/af_packet.c) . The arithmetic bug was introduced on July 19, 2008, in the commit 8913336 (“packet: add PACKET_RESERVE sockopt”). However, it became triggerable for memory corruption only in February 2016, in the commit 58d19b19cd99 (“packet: vnet_hdr support for tpacket_rcv“). There were some attempts to fix it, such as commit bcc536 (“net/packet: fix overflow in check for tp_reserve”) in May 2017 and commit edb58be (“packet: Don’t write vnet header beyond end of buffer”) in August 2017. However, those fixes were not enough to prevent memory corruption. Let’s first have a look at the PACKET_RESERVE option:In order to trigger the vulnerability, a raw socket (AF_PACKET domain, SOCK_RAW type ) has to be created with a TPACKET_V2 ring buffer and a specific value for the PACKET_RESERVE option. The headroom that is mentioned in the manual is simply a buffer with size specified by the user, which will be allocated before the actual data of every packet received on the ring buffer. This value can be set from user-space via the setsockopt system call. Figure 1. Implementation of setsockopt – PACKET_RESERVE As we can see in Figure 1, initially, there is a check that the value is smaller than INT_MAX. This check was added in this patch to prevent an overflow in the calculation of the minimum frame size in packet_set_ring. Later, it’s verified that pages were not allocated for the receive/transmit ring buffer. This is done to prevent inconsistency between the tp_reserve field and the ring buffer itself. After setting the value of tp_reserve, we can trigger allocation of the ring buffer itself via the setsockopt system call with optname of PACKET_RX_RING: Figure 2. From manual packet – PACKET_RX_RING option. This is implemented in the packet_set_ring function. Initially, before the ring buffer is allocated, there are several arithmetic checks on the tpacket_req structure received from user-space: Figure 3. Part of the sanity checks in the packet_set_ring function. As we can see in Figure 3, first, the minimum frame size is calculated, and then it is verified versus the value received from user-space. This check ensures that there is space in each frame for the tpacket header structure (for its corresponding version) and tp_reserve number of bytes. Later, after doing all the sanity checks, the ring buffer itself is allocated via a call to alloc_pg_vec: Figure 4. Calling the ring buffer allocation function in the packet_set_ring function. As we can see from the figure above, the block size is controlled from user-space. The alloc_pg_vec function allocates the pg_vec array and then allocates each block via the alloc_one_pg_vec_page function: Figure 5. alloc_pg_vec implementation. The alloc_one_pg_vec_page function uses __get_free_pages in order to allocate the block pages: Figure 6. alloc_one_pg_vec_page implementation. After the blocks allocation, the pg_vec array is saved in the packet_ring_buffer structure embedded in the packet_sock structure representing the socket. When a packet is received on the interface, the socket bound to the tpacket_rcv function will be called and the packet data, along with the TPACKET metadata, will be written into the ring buffer. In a real application, such as tcpdump, this buffer is mmap’d to the user-space and packet data can be read from it. The Bug Now let’s dive into the implementation of the tpacket_rcv function (Figure 7). First, skb_network_offset is called in order to extract the offset of the network header in the received packet into maclen. In our case, this size is 14 bytes, which is the size of an ethernet header. After that, netoff (which represents the offset of the network header in the frame) is calculated, taking into account the TPACKET header (fixed per version), the maclen and the tp_reserve value (controlled by the user). However, this calculation can overflow, as the type of tp_reserve is unsigned int and the type of netoff is unsigned short, and the only constraint (as we saw earlier) on the value of tp_reserve is to be smaller than INT_MAX. Figure 7. The arithmetic calculation in tpacket_rcv Also shown in Figure 7, if the PACKET_VNET_HDR option is set on the socket, sizeof(struct virtio_net_hdr) is added to it in order to account for the virtio_net_hdr structure, which should be right beyond the ethernet header. And finally, the offset of the ethernet header is calculated and saved into macoff. Later in that function, seen in Figure 8 below, the virtio_net_hdr structure is written into the ring buffer using the virtio_net_hdr_from_skb function. In Figure 8, h.raw points into the currently free frame in the ring buffer (which was allocated in alloc_pg_vec). Figure 8. Call to virtio_net_hdr_from_skb function in tpacket_rcv Initially, I thought it might be possible to use the overflow in order to make netoff a small value, so macoff could receive a larger value (from the underflow) than the size of a block and write beyond the bounds of the buffer. However, this is prevented by the following check: Figure 9. Another arithmetic check in the tpacket_rcv function. This check is not sufficient to prevent memory corruption, as we can still make macoff a small integer value by overflowing netoff. Specifically, we can make macoff smaller than sizeof(struct virtio_net_hdr), which is 10 bytes, and write behind the bounds of the buffer using virtio_net_hdr_from_skb. The Primitive By controlling the value of macoff, we can initialize the virtio_net_hdr structure in a controlled offset of up to 10 bytes behind the ring buffer. The virtio_net_hdr_from_skb function starts by zeroing out the entire struct and then initializing some fields within the struct based on the skb structure. Figure 10. Implementation of the virtio_net_hdr_from_skb function. However, we can set up the skb so only zeros will be written into the structure. This leaves us with the ability to zero 1-10 bytes behind a __get_free_pages allocation. Without doing any heap manipulation tactics, an immediate kernel crash will occur. POC A POC code for triggering the vulnerability can be found in the following Openwall thread. Patch I submitted the following patch in order to fix the bug. Figure 11. My proposed patch for the bug. The idea is that if we change the type of netoff from unsigned short to unsigned int, we can check whether it exceeds USHRT_MAX, and if so, drop the packet and prevent further processing. Idea for Exploitation Our idea for exploitation is to convert the primitive to a use-after-free. For this, we thought about decrementing a reference count of some object. For example, if an object has a refcount value of 0x10001, the corruption would look as follows: Figure 12. Zeroing out a byte in an object refcount. As we can see in Figure 13 below, after corruption, the refcount will have a value of 0x1, so after releasing one reference, the object will be freed. However, in order to make this happen, the following constraints have to be satisfied: - The refcount has to be located in the last 1-10 bytes of the object. - We need to be able to allocate the object at the end of a page. - This is because get_free_pages returns a page-aligned address. We used some grep expressions along with some manual analysis of code, and we came out with the following object: Figure 13. Definition of the sctp_shared_key structure. It seems like this object satisfies our constraints: - We can create an sctp server and a client from an unprivileged user context. - Specifically, the object is allocated in the sctp_auth_shkey_create function. - We can allocate the object at the end of a page. - The size of the object is 32 bytes and it is allocated via kmalloc. This means the object is allocated in the kmalloc-32 cache. - We were able to verify that we can allocate a kmalloc-32 slab cache page behind our get_free_pages allocation. So we will be able to corrupt the last object in that slab cache page. - Because of the reason 4096 % 32 = 0, there is no spare space in the end of the slab page, and the last object is allocated right behind our allocation. Other slab cache sizes may not be good for us, such as 96 bytes, because 4096 % 96 != 0. - We can corrupt the highest 2 bytes of the refcnt field. - After compilation, the size of key_id and deactivated is 4 bytes each. - If we use the bug to corrupt 9-10 bytes, we will corrupt the 1-2 most significant bytes of the refcnt field. Conclusion I was surprised that such simple arithmetic security issues still exist in the Linux kernel and haven’t been previously discovered. Also, unprivileged user namespaces expose a huge attack surface for local privilege escalation, so distributions should consider whether they should enable them or not. Palo Alto Networks Cortex XDR stops threats on endpoints and coordinates enforcement with network and cloud security to prevent successful cyber attacks. To prevent the exploitation of this bug, the Behavioral Threat Protection (BTP) feature and Local Privilege Escalation Protection module in Cortex XDR would monitor malicious behaviors across a sequence of events and immediately terminate the attack when detected.
https://movaxbx.ru/2020/10/11/cve-2020-14386-privilege-escalation-vulnerability-in-the-linux-kernel/
CC-MAIN-2021-04
refinedweb
1,833
51.28
- 11 Apr, 2014 26 commits. Also convert mp_obj_is_integer to an inline function. Overall this decreased code size (at least on 32-bit x86 machine). It regressed a bit after implementing float/complex equality. Now it should be improved, and support more equality tests. It has (again) a fast path for ints, and a simplified "slow" path for everything else. Also simplify the way str indexing is done (now matches tuple and list). Addresses issue #462. Pairs are limited to tuples so far. A specific target can define either MP_ENDIANNESS_LITTLE or MP_ENDIANNESS_BIG to 1. Default is MP_ENDIANNESS_LITTLE. TODO: Autodetect based on compiler predefined macros? - 10 Apr, 2014 14 commits - Andrew Scheller authored make 'make clean' cleaner ;-) Working towards trying to support compile-time constants (see discussion in issue #227), this patch allows the compiler to look inside arbitrary uPy objects at compile time. The objects to search are given by the macro MICROPY_EXTRA_CONSTANTS (so they must be constant/ROM objects), and the constant folding occures on forms base.attr (both base and attr must be id's). It works, but it breaks strict CPython compatibility, since the lookup will succeed even without importing the namespace. Can do this now that the stack size calculation is improved..
https://gitrepos.estec.esa.int/taste/uPython-mirror/-/commits/8f1931754002b0904c62e481d9dcae2f6e1913e2/py
CC-MAIN-2022-40
refinedweb
205
59.6
For many large applications C++ is the language of choice and so it seems reasonable to define C++ bindings for OpenCL. The interface is contained with a single C++ header file cl.hpp and all definitions are contained within the namespace cl. There is no additional requirement to include cl.h and to use either the C++ or original C bindings it is enough to simply include cl.hpp. The bindings themselves are lightweight and correspond closely to the underlying C API. Using the C++ bindings introduces no additional execution overhead. For detail documentation on the bindings see: The OpenCL C++ Wrapper API 1.1 (revision 04) The following example shows a general use case for the C++ bindings, including support for the optional exception feature and also the supplied vector and string classes, see following sections for decriptions of these features.
https://fossies.org/dox/ViennaCL-1.7.1/
CC-MAIN-2016-44
refinedweb
142
55.95
We have been exploring the NIO enhancements in Java 7 and in this post I will explain about creating links- Hard links and Soft links in Java. And this feature is part of Java 7. also read: A link is kind of substitute name to access a particular file/directory, something like an alias to the file/directory. This way it allows us to refer to a file/directory by more than one name. There are 2 types of links that can be created: - Symbolic Links: These links refer to the file/directory path. And using these links can be used to directly operate on the path they refer to. In my daily work I use a lot of symbolic links and they are really flexible. In this case if the file to which the link refers to is deleted, the link continues to exist but it is not a valid link. - Hard Links: These links are more stricter than symbolic links which refer to the physical location of the file. If the content of the original file is changed, the link also gets updated whereas if the original file is deleted, the link continues to exist and is valid file. Creating Symbolic Links in Java Not all operating systems support creating symbolic links. The program I tried on Windows couldn’t create a symbolic link. But for creating symbolic link we make use of the Files.createSymbolicLink method which takes the link path as well as the target path, where both link and target are instances of type Path. Creating Hard links in Java On Windows I was able to create the Hard links and for this we make use of Files.createLink method which takes in link path and the target path. Lets look at the example where both soft link and hard links are created: Note: I tried this sample on Windows and Linux, but you can get better results in Linux, because I am not sure how to list the links in Windows. public class LinkTest { public static void main(String[] args) throws IOException { Path file1 = Paths.get("test1"); System.out.println(file1.toRealPath()); Path hLink = Paths.get("test1.hLink"); Path sLink = Paths.get("test1.symLink"); try{ Files.createSymbolicLink(sLink, file1); }catch(UnsupportedOperationException ex){ System.out.println("This OS doesn't support creating Sym links"); } try{ Files.createLink(hLink, file1); System.out.println(hLink.toRealPath()); }catch(UnsupportedOperationException ex){ System.out.println("This OS doesn't support creating Sym links"); } } } Pro Java 7 NIO.2 addresses the three primary elements that offer new input/output (I/O) APIs in Java 7, giving you the skills to write robust, scalable Java applications. Creating Hard links and Soft links for a file in Java… Thank you for submitting this cool story – Trackback from JavaPins…
https://javabeat.net/creating-hard-links-and-soft-links-for-a-file-in-java/
CC-MAIN-2017-47
refinedweb
465
64.61
using namespace std;to create the array, you can create it by referring to the namespace explicitly upon the array's creation like: std::tr1::array<int, 3> myArray; #include "classthis.h"in the StdAfx.h file, run it, and everything works fine. However, when I de-comment the #include <array>I once again get the error message above. All the other code involved is just the standard windows forms setup in visual c++ 2010. using namespace std;in C++? using namespace std;, does not add a name to the current scope, it only makes the names accessible from it. This means that:
http://www.cplusplus.com/forum/windows/89711/
CC-MAIN-2016-36
refinedweb
103
68.26
#include <aio.h> int aio_fsync(int op, struct aiocb *aiocbp); The aio_fsync() function asynchronously forces returns when the synchronization request has been initiated or queued to the file or device (even when the data cannot be synchronized immediately). If op is O_DSYNC, all currently queued I/O operations are completed as if by a call to fdatasync(3C); that is, as defined for synchronized I/O data integrity completion. If op is O_SYNC, all currently queued I/O operations are completed as if by a call to fsync(3C); that is, as defined for synchronized I/O file integrity completion. If the aio_fsync() function fails, or if the operation queued by aio_fsync() fails, then, as for fsync(3C) and fdatasync(3C),(3C) and aio_return(3C) in order to determine the error status and return status, respectively, of the asynchronous operation while it is proceeding. When the request is queued, the error status for the operation is EINPROGRESS. When all data has been successfully transferred, the error status will be reset to reflect the success or failure of the operation. If the operation does not complete successfully, the error status for the operation will be set to indicate the error. The aio_sigevent member determines the asynchronous notification to occur when all operations have achieved synchronized I/O completion (see signal.h(3HEAD)). All other members of the structure referenced by aiocbp are ignored. If the control block referenced by aiocbp becomes an illegal address prior to asynchronous I/O completion, then the behavior is undefined. If the aio_fsync() function fails or −1. In the event that any of the queued I/O operations fail, aio_fsync() returns the error condition defined for read(2) and write(2). The error will be returned in the error status for the asynchronous fsync(3C) operation, which can be retrieved using aio_error(3C). The aio_fsync() function has a transitional interface for 64-bit file offsets. See lf64(5). See attributes(5) for descriptions of the following attributes: fcntl(2), open(2), read(2), write(2), aio_error(3C), aio_return(3C), aio.h(3HEAD), fcntl.h(3HEAD), fdatasync(3C), fsync(3C), signal.h(3HEAD), attributes(5), lf64(5), standards(5)
https://docs.oracle.com/cd/E36784_01/html/E36874/aio-fsync-3c.html
CC-MAIN-2021-17
refinedweb
362
52.29
Remotair Remotair is a concept of transmitting device input events (gestures, accelerometer, camera etc.) into receiving flash or AIR application. Remotair consists of one transmitting application installed on a mobile device or a tablet and one receiving application running on a PC. In order to pair transmitting and receiving application, RTMFP protocol is used. The receiver API is public and released under MIT license. You can download Remotair application from Android market (link only works on android devices) or see the Android application details on AppBrain. For a receiving application you may use the demo application located on remotair.yoz.sk or you can build your own one using Remotair Receiver API. What is remotair capable of? The current version of Remotair transmitter is available for Android devices and is capable of transmit touch events and gestures, keyboard events (using native keyboard or custom buttons), accelerometer, geolocation/GPS microphone and camera. Accelerometer, geolocation, microphone and camera can be transmitted in background mode, that means user can interact with touch or keys while mentioned sensors/inputs are being transmitted at the same time (e.g. accelerometer + camera + gestures). How can I use it? For now, to see what is Remotair all about, install transmitter application to your Android device and click connect. Once you get the channel number, run receiver demo. Now those two apps connects via P2P. Once they are connected, you can start clicking different views in transmitter and see the log or custom event handling view on receiver side. Demo video featuring Keyboard, Mouse, Touch, Gesture, Accelerometer, Geolocation, Camera, Microphone: - Remotair Loves onBoard – Using samsung galaxy tab to remotely control system mouse using Remotair android app. - Shumps with Remotair – Playing Shmups with Remotair using nexus one - Live video transmitting from RC car – Live video transmmitting from an Android mounted on a RC-ed toy using #remotair - Running Windows on Android using Remotair – Remote control of Windows via android device and #remotair Imagine you have a RC model of a car or a helicopter, you can mount your mobile device onto it, turn transmitting camera and microphone on and you are ready to controll the model while sitting before PC see and hear everything. Or, you build and cutting edge flash game that can be controlled by accelerometer and joysticks etc. Remotair Receiver API All the necessary classes can be downloaded from github and classes.yoz.sk. Check out the demo application built over the api on remotair.yoz.sk. The basic application may look something like this: import flash.events.AccelerometerEvent; import sk.yoz.remotair.events.GenericConnectorEvent; import sk.yoz.remotair.net.GenericConnector; import sk.yoz.remotair.net.Receiver; private var receiver:Receiver = new Receiver( GenericConnector.HANDSHAKE_URL, GenericConnector.DEVELOPER_KEY, GenericConnector.CHANNEL_SERVICE); private function connect(channel:String):void // channel = 1234 etc. { receiver.connectChannel(channel); receiver.addEventListener(GenericConnectorEvent.PEER_CONNECTED, onPeerConneceted); receiver.accelerometerEvents.addEventListener(AccelerometerEvent.UPDATE, onAccelerometerUpdate); } private function onPeerConneceted(event:GenericConnectorEvent):void { // transmitting application on your device is now connected with this app } private function onAccelerometerUpdate(event:AccelerometerEvent):void { trace(event.accelerationX, event.accelerationY); } Transmitter Here is a list of events dispatched with each view on transmitter. The most of those are native ActionScript events, plus some custom: Keyboard View - TextEvent: TextEvent.TEXT_INPUT - TextEvent: RemotairEvent.TEXT_CHANGE - KeyboardEvent: KeyboardEvent.KEY_DOWN - KeyboardEvent: KeyboardEvent.KEY_UP Numbers and Arrows View - KeyboardEvent: KeyboardEvent.KEY_DOWN - KeyboardEvent: KeyboardEvent.KEY_UP Gamepad View - KeyboardEvent: KeyboardEvent.KEY_DOWN - KeyboardEvent: KeyboardEvent.KEY_UP - JoystickEvent: JoystickEvent.CHANGE Mouse View - Touch View - TouchEvent: TouchEvent.TOUCH_BEGIN - TouchEvent: TouchEvent.TOUCH_END - TouchEvent: TouchEvent.TOUCH_MOVE - TouchEvent: TouchEvent.TOUCH_OUT - TouchEvent: TouchEvent.TOUCH_OVER - TouchEvent: TouchEvent.TOUCH_ROLL_OUT - TouchEvent: TouchEvent.TOUCH_ROLL_OVER - TouchEvent: TouchEvent.TOUCH_TAP Gestures View - GestureEvent: GestureEvent.GESTURE_TWO_FINGER_TAP - PressAndTapGestureEvent: PressAndTapGestureEvent.GESTURE_PRESS_AND_TAP - TransformGestureEvent: GestureEvent.GESTURE_PAN - TransformGestureEvent: TransformGestureEvent.GESTURE_ROTATE - TransformGestureEvent: TransformGestureEvent.GESTURE_SWIPE - TransformGestureEvent: TransformGestureEvent.GESTURE_ZOOM Joystick View - JoystickEvent: JoystickEvent.CHANGE Remote Desktop View When view initialized, RemotairEvent.INIT_REMOTE_DESKTOP is sent with data containing widht and height of the device screen and channel name to be created. - RemotairEvent: RemotairEvent.INIT_REMOTE_DESKTOP - - KeyboardEvent: KeyboardEvent.KEY_UP Accelerometer View - AccelerometerEvent: AccelerometerEvent.UPDATE - StatusEvent: StatusEvent.STATUS Camera View The main function of this view is to attachCamera over NetStream, that can be handled by Receiver.stream - CameraEvent: CameraEvent.CAMERA_PUBLISHED - CameraEvent: CameraEvent.CAMERA_UNPUBLISHED - CameraEvent: CameraEvent.CAMERA_UPDATED Microphone View The main function of this view is to attachAudio over NetStream, that can be handled by Receiver.stream - MicrophoneEvent: MicrophoneEvent.MICROPHONE_PUBLISHED - MicrophoneEvent: MicrophoneEvent.MICROPHONE_UNPUBLISHED - MicrophoneEvent: MicrophoneEvent.MICROPHONE_UPDATED Geolocation View - GeolocationEvent: GeolocationEvent.UPDATE - StatusEvent: StatusEvent.STATUS Receiver Transmitted events are dispatched into Receiver class. You may notice there are some custom events, that should be selfexplanatory by code or once debuged. - Receiver.remotairEvents: RemotairEvent - Receiver.viewEvents: ViewEvent - Receiver.mouseEvents: MouseEvent - Receiver.keyboardEvents: KeyboardEvent - Receiver.textEvents: TextEvent - Receiver.joystickEvents: JoystickEvent - Receiver.cameraEvents: CameraEvent - Receiver.microphoneEvents: MicrophoneEvent - Receiver.activityEvents: ActivityEvent - Receiver.statusEvents: StatusEvent - Receiver.accelerometerEvents: AccelerometerEvent - Receiver.touchEvents: TouchEvent - Receiver.gestureEvents: PressAndTapGestureEvent, TransformGestureEvent, GestureEvent - Receiver.geolocationEvents: GeolocationEvent More reading: wow, amazing! and thanks for sharing. How was the Android app created? any chance we could see the source code? brad426, sorry I am not willing to open the android source for now. but I can answer you any questions you have about it. feel free to ask No questions yet…. I will need to try on my own first. will ask if i get stuck. P.S. great blog Sounds great, i can’t wait the demo video brad426, YopSolo thnx demo video is ready, see it in article or on youtube very cool demo. I have been messing around with the android transmitter app for the last few days ( using your android app to connect to my swf ) interesting times ahead…. brad426, feel free to drop here some feedback, I am willing to make the api understandable as much as possible… so – does it work for you? any issues? Yeah, everything works great. I haven’t picked up on any issues/bugs. To be honest, I haven’t looked too deep into the api ( like how GenericConnector actually works), but using it is very easy. You did a great job! Cool, I like to hear that. I have uploaded crossdomain file for channel service domain, so it works now for third party .swf files… + check out gamepad view in version 0.1.5 Hi Jozef, great app. I have Samsung Galaxy S (2.2.1 I9000XXYJY)and camera doesn’t work. Everything else works great. Do I need to change some android setting? Thanks Hi parizer, what exactly does it mean it does not work? – is camera button disabled? – does it show a page with camera settings? – can you see something in camera preciew? – is there a problem with transmitting it into receiving application? Hi Jozef, This is all I get: – – I tried to create AIR file, and camera doesn’t work if I am using Camera.getCamera() and with CameraUI() it works OK. So problem (bug) is in my Galaxy S? btw. your app is awesome! @parizer, thank you for your feedback and for noticing the issue. I guess that must be some Galaxy S specific thing. I am not sure how to make it work for now, maybe with next air version or android version, it gets fixed itself … I believe with CameraUI you can only catch already saved image/video not live streaming Hard reset fixed problem and now camera works ok (getCamera() etc…) Hard reset deleted all my installed apps, and now I can’t find Remotair on Market. Error info: “Not found. The requested item could not be found.” It’s listed on AppBrain but not on Android Market (btw. I am from Croatia) It’s working now. Thank you! @parizer, cool to hear you made it work. I had to republished the remotair app into market this morning, should work fine now […] been wanting to play with ever since checking out Jozef Chúťka’s (aka @jozefchutka) Remotair application. In fact, I could have built this thing using Remotair, but I wanted to get my hands dirty with a […] […] desktop app you have downloaded is just a demo, you can use Remotair api to build your own desktop application and to include your own […] Works perfectly fine on Nexus S. It’s going to become one of the must-have android apps, if it’s not yet. Hi Jozef Do you think it is possible to get the Remotair Application on the iPhone? Have you developed it using AS3 or native Android Code? Thanks webfraggle Hi webfraggle, it is developed using AS3, so there is almost no problem porting it to iPhone/iPad … only one issue – I am not iOS developer, not having account and all the stuff. would you like to use it with your iphone? Hum. Sending everything to a web page in Slovakia to get the data back in your living room makes everything quite slow. Is it possible to have a local mode, like a Lighttpd server on the PC-side and you connect to 192.168.some.thing on the android device ? Hi Glav, do not get confused here. onlything that goes through my gateway is a simple handshake – translates your number 1234 into something than can be used for connecting peered device. Besides that flash always runs on client and RTMFP is smart enough to find the shortest roundtrip through the network to use just your home router if possible. Is there a chance to get the Remotair.apk ? by download it directly from a link or my e-mail; cannot access the Android Market… Many Thx. hi Nicholas, try google “remotair apk”, androidzoom.com looks promising did that and received an e-mail with a link which seems that be invalid one: “There are no matches in Android Market for: ‘pname:air.sk.yoz.remotair’ It seems that there is no chance to get that *.apk file be downloaded directlly on my computer and from there to install it in my Android device… ok …sending via email I have been reading alot about the app and everything seems promising, but I don’t understand if it works by sending any information online to any specific location as a P2P program? hi trix, remotair uses native rtmfp (p2p) protocol available in flash player. the current implementation in remotair rquires your devices (e.g. pc+smartphone) to be connected to internet for a handshake, then after devices are paired I believe shortest possible path/circuit is used for communication dude, this does not work on playbook can you help me, i am not yet a developer so i dont know what you guys are takling about so forgive me , but i am excited to see how your app works. hi Donnell, this application is primarily for devs, anyway you can see how it works on videos on … if you can not connect, please read the comment above your one Like some of the commenters above, I would like to work without an internet connection required. Would it be possible to do the handshake locally, or use a direct connection to the device (or desktop)? Adam, sorry currently the possibility to to pair devices without being online is not implemented, however flash player has the capabilites of doing it (using local router). Unfortunately I have no time to do more development on remotair for now Ok, but is it possible to do a direct connection (via IP)? If you had an idea on how to do it, I’d love to know as I’m probably going to have to do that anyway. Adam, I believe its not possible to direct connect over rtmfp, it is possible to connect using lan (local router), read more on @Jozef Cool. That was exactly what I wanted. Have you published the source for either the PlayBook or Android client of Remotair (I would really like to see the PlayBook code.)? Adam, reciever is open sourced on , transmitter sources (android app, playbook etc.) are not released open. I have spent 2 months trying to find a multicast P2P app for Playbook where the objective is to livestream the screen of one Playbook to the other Playbooks in order to show a Power Point presentation. You might have the answer. A medical doctor developed such an app for iPads it is very simplistic without being simple! Seems to connect Bluetooth, WiFi, etc. I have tried DLNA, VLC, HTML5 and finally Adobe Air when I came across your products. Can you change OnStream to stream the screen contents instead of the cameras? Is the catch that each unit have to handshake via your FMS so it won’t work on a LAN not connected to the internet? Very good work you do and pleasure to get to know your work. Oscar hi oscar, unfortunately, flash/air has native api for streaming webcams only not the desktop screen. I am not saying its not doable through an air application however it would require some os specific native extensions. For windows there are some utils that can stream your screen into a virtual webcam that you can stream via onStream, if you find something like this for android you can get closer. onStream as well as Remotair use rtmfp that use cirrus server for a handshake. Even there is api to handshake and communicate via local router, due to lack of time I am currently not planning to implement it into my apps Hi Jozef, thanks for quick answer. I have now compiled an app that does native P2P screen live streaming on my local LAN without FMS thanks to your useful links above. A last question, has RIM blocked access to the screen/graphicscard for Playbook (I have noticed there is no RemoteDesk app for remote controlling Playbook)? oscar, I have no info about plabook native remote controling pc or vice versa Hi, Jozef. The project is realy great! I’ve been so impressed! My question. If we talk about RTMFP, why we should pair android device and pc viewer? Can we see the viceo from one android camera on a few viewers simultaneously? Thank you. hi Denis, in general, using rtmfp you can share your camera with any number of viewers you want. Remotair implementation expects 1 sender and 1 transmitter only… The down side of streaming to multiple receivers may be the upload traffic from the sender, as he streams the video p2p to everyone, or have a look at NetGroup to get advantage of some more advanced p2p stuff Thank you Josef for a quick reaction. I am not deep in all this (for example, I do not understand, what does it mean “have a look at NetGroup” But I think, the most one advantage of RTMFP vs RTMP is posibility to sent video to multiple recievers without increasing camera’s net chanel load. I thought, I can see this in Remotair, as it declared to use rtmfp, but the it’s implementation expects 1 to 1. Would you advise me any (opensource would be perfect)project, where I could see a 1 to N broadcasting via RTMFP (not using cyrus). Denis, I think adobe provides nice and simple api for p2p stuff. There are also some frameworks around it like , but if you are flash developer, the native api in flash/air is sufficient to do such an app. If you do not want to use cirrus, you can use own redevous server or you can do even without one – when creating p2p groups within LAN
http://blog.yoz.sk/2010/12/remotair/
CC-MAIN-2015-35
refinedweb
2,557
58.38
NoiseStim not working Hello all, I'm trying to create a coarse noise patch in OpenSesame using psychopy's NoiseStim function. However, when I try to run it, using the code below, I get the error: 'module' object has no attribute 'NoiseStim'. Is NoiseStim somehow not supported in OpenSesame, or am I missing something else? Is there a nice alternative function that I could use? Best, Jasper from psychopy import visual, event, core, monitors noise1 = visual.NoiseStim(win, units='pix', mask='circle', ori=1.0, pos=(0, 0), size=(512, 512), sf=None, phase=0, color='white', opacity=1, blendmode='add', contrast=1.0, texRes=512, imageComponent='Phase',, filter=False, interpolate=False, depth=-1.0) noise1.show() win.flip() event.waitKeys(keyList = ['space']) Hi Jasper, This is not about whether Opensesame supports noise stim or not, but whether the version of Psychopy that is installed has this feature included. (When you import Psychopy and create a window like that, you bypass Opensesame's canvasses). I think Opensesame's default Psychopy version is 1.85, NoiseStim was introduced with 1.90. Therefore, upgrading psychopy should do the trick (see here how to: Eduard That seems doable ;) Thank you!
http://forum.cogsci.nl/discussion/comment/17209/
CC-MAIN-2020-05
refinedweb
197
58.48
Scroll down to the script below, click on any sentence (including terminal blocks!) to jump to that spot in the video!Cool, got it! Show me the script! Course: Symfony 3 Security: Beautiful Authentication, Powerful Authorization Tutorial In AppBundle, create a new directory called Doctrine and a new class called HashPasswordListener: If this is your first Doctrine listener, welcome! They're pretty friendly. Here's the idea: we'll create a function that Doctrine will call whenever any entity is inserted or updated. That'll let us to do some work before that happens. Implement an EventSubscriber interface and then use Command+ N or the "Code"->"Generate" menu, select "Implement Methods" and choose the one method: getSubscribedEvents(): In here, return an array with prePersist and preUpdate: These are two event names that Doctrine makes available. prePersist is called right before an entity is originally inserted. preUpdate is called right before an entity is updated. Next, add public function prePersist(): When Doctrine calls this, it will pass you an object called LifecycleEventArgs, from the ORM namespace. This method will be called before any entity is inserted. How do we know what entity is being saved? With $entity = $args->getEntity(). Now, if this is not an instanceof User, just return and do nothing: Now, on to encoding that password. Symfony comes with a built-in service that's really good at encoding passwords. It's called security.password_encoder and if you looked it up on debug:container, its class is UserPasswordEncoder. We'll need that, so add a __construct() function and type-hint a single argument with UserPasswordEncoder $passwordEncoder. I'll hit Option+ Enter and select "Initialize Fields" to save me some time: In a minute, we'll register this as a service. Down below, add $encoded = $this->passwordEncoder->encodePassword() and pass it the User - which is $entity - and the plain-text password: $entity->getPlainPassword(). Finish it with $entity->setPassword($encoded): That's it: we are encoded! So now also handle update, in case a User's password is changed! The two lines that actually do the encoding can be re-used, so let's refactor those into a private method. To shortcut that, highlight them, press Command+ T - or go to the "Refactor"->"Refactor this" menu - and select "Method". Call it encodePassword() with one argument that's a User object: Tip I didn't mention it, but you also need to prevent the user's password from being encoded if plainPassword is blank. This would mean that the User is being updated, but their password isn't being changed. Super nice! Now that we have that, copy prePersist, paste it, and call it preUpdate. You might think that these methods would be identical... but not quite. Due to a quirk in Doctrine, you have to tell it that you just updated the password field, or it won't save. The way you do this is a little nuts, and not that important: so I'll paste it in: Ok, the event subscriber is perfect! To hook it up - you guessed it - we'll register it as a service. Open app/config/services.yml and add a new service called app.doctrine.hash_password_listener. Set the class. And you guys know by now that I love to autowire things. It doesn't always work, but it's great when it does: Finally, to tell Doctrine about our event subscriber, we'll add a tag. This is something we talked about in our services course: it's a way to tell the system that your service should be used for some special purpose. Set the tag to doctrine.event_subscriber: The system is complete. Before creating or updating any entities, Doctrine will call our listener. Let's update our fixtures to try it.
https://symfonycasts.com/screencast/symfony3-security/encoding-user-password
CC-MAIN-2018-39
refinedweb
628
66.13
This In-depth Tutorial On C++ Trees Explains Tree Types, Tree Traversal Techniques and Basic Terminology With Pictures And Example Programs: In this C++ Series, so far we have seen the linear data structure of both static and dynamic nature. Now we will proceed with the non-linear data structure. The first data structure in this category is “Trees”. Trees are non-linear hierarchical data structures. A tree is a collection of nodes connected to each other by means of “edges” which are either directed or undirected. One of the nodes is designated as “Root node” and the remaining nodes are called child nodes or the leaf nodes of the root node. In general, each node can have as many children but only one parent node. Nodes of a tree are either at the same level called sister nodes or they can have a parent-child relationship. Nodes with the same parent are sibling nodes. What You Will Learn: Trees In C++ Given below is an Example tree with its various parts. Let us go through the definitions of some basic terms that we use for trees. - Root node: This is the topmost node in the tree hierarchy. In the above diagram, Node A is the root node. Note that the root node doesn’t have any parent. - Leaf node: It is the Bottom most node in a tree hierarchy. Leaf nodes are the nodes that do not have any child nodes. They are also known as external nodes. Nodes E, F, G, H and C in the above tree are all leaf nodes. - Subtree: Subtree represents various descendants of a node when the root is not null. A tree usually consists of a root node and one or more subtrees. In the above diagram, (B-E, B-F) and (D-G, D-H) are subtrees. - Parent node: Any node except the root node that has a child node and an edge upward towards the parent. - Ancestor Node: It is any predecessor node on a path from the root to that node. Note that the root does not have any ancestors. In the above diagram, A and B are the ancestors of E. - Key: It represents the value of a node. - Level: Represents the generation of a node. A root node is always at level 1. Child nodes of the root are at level 2, grandchildren of the root are at level 3 and so on. In general, each node is at a level higher than its parent. - Path: The path is a sequence of consecutive edges. In the above diagram, the path to E is A=>B->E. - Degree: Degree of a node indicates the number of children that a node has. In the above diagram, the degree of B and D is 2 each whereas the degree of C is 0. Types Of C++ Trees The tree data structure can be classified into the following subtypes as shown in the below diagram. #1) General Tree The general tree is the basic representation of a tree. It has a node and one or more child nodes. The top-level node i.e. the root node is present at level 1 and all the other nodes may be present at various levels. A General Tree is shown in the below figure. As shown in the above figure, a general tree may contain any number of subtrees. The nodes B, C, and D are present at level 2 and are sibling nodes. Similarly, nodes E, F, G, and H are also sibling nodes. The nodes present at different levels may exhibit a parent-child relationship. In the above figure, nodes B, C and D are children of A. Nodes E and F are children of B whereas nodes G and H are children of D. The general tree is demonstrated below using the C++ implementation: #include <iostream> using namespace std; //declaration for new tree node struct node { int data; struct node *left; struct node *right; }; //allocates new node struct node* newNode(int data) { // declare and allocate new node struct node* node = new struct node(); node->data = data; // Assign data to this node // Initialize left and right children as NULL node->left = NULL; node->right = NULL; return(node); } int main() { /*create root node*/ struct node *rootNode = newNode(10); cout<<"General tree created is as follows:"<<endl; cout<<"\t\t\t "<<rootNode->data<<endl; cout<<"\t\t\t "<<"/ "<<"\\"<<endl; rootNode->left = newNode(20); rootNode->right = newNode(30); cout<<"\t\t\t"<<rootNode->left->data<<" "<<rootNode->right->data; cout<<endl; rootNode->left->left = newNode(40); cout<<"\t\t\t"<<"/"<<endl; cout<<"\t\t "<<rootNode->left->left->data; return 0; } Output: General tree created is as follows: 10 / \ 20 30 / 40 #2) Forests Whenever we delete the root node from the tree and the edges joining the next level elements and the root, we obtain disjoint sets of trees as shown below. In the above figure, we obtained two forests by deleting the root node A and the three edges that were connecting the root node to nodes B, C, and D. #3) Binary Tree A tree data structure in which each node has at most two child nodes is called a binary tree. A binary tree is the most popular tree data structure and is used in a range of applications like expression evaluation, databases, etc. The following figure shows a binary tree. In the above figure, we see that nodes A, B, and D have two children each. A binary tree in which each node has exactly zero or two children is called a full binary tree. In this tree, there are no nodes that have one child. A complete binary tree has a binary tree that is completely filled with the exception of the lowest level that is filled from left to right. The binary tree shown above is a full binary tree. Following is a simple program to demonstrate a binary tree. Note that the output of the tree is the inorder traversal sequence of the input tree. #4) Binary Search Tree The binary tree that is ordered is called the binary search tree. In a binary search tree, the nodes to the left are less than the root node while the nodes to the right are greater than or equal to the root node. An example of a binary search tree is shown below. In the above figure, we can see that the left nodes are all less than 20 which is the root element. The right nodes, on the other hand, are greater than the root node. The binary search tree is used in searching and sorting techniques. #5) Expression Tree A binary tree that is used to evaluate simple arithmetic expressions is called an expression tree. A simple expression tree is shown below. In the above sample expression tree, we represent the expression (a+b) / (a-b). As shown in the above figure, the non-leaf nodes of the tree represent the operators of the expression while the leaf nodes represent the operands. Expression trees are mainly used to solve algebraic expressions. Tree Traversal Techniques We have seen linear data structures like arrays, linked lists, stacks, queues, etc. All these data structures have a common traversing technique that traverses the structure only in one way i.e. linearly. But in the case of trees, we have different traversal techniques as listed below: #1) In order: In this traversal technique, we traverse the left subtree first till there are no more nodes in the left subtree. After this, we visit the root node and then proceed to traverse the right subtree until there are no more nodes to traverse in the right subtree. Thus the order of inOrder traversal is left->root->right. #2) Pre-order: For preorder traversal technique, we process the root node first, then we traverse the entire left subtree and finally, we traverse the right subtree. Hence the order of preorder traversal is root->left->right. #3) Post-order: In the post-order traversal technique, we traverse the left subtree, then the right subtree and finally the root node. The order of traversal for the postorder technique is left->right->root. If n is the root node and ‘l’ and ’r’ are left and right nodes of the tree respectively, then the tree traversal algorithms are as follows: In order (lnr) algorithm: - Traverse left subtree using inOrder(left- Subtree). - Visit the root node(n). - Traverse right subtree using inOrder(right- subtree). Preorder (nlr) algorithm: - Visit the root node(n). - Traverse left subtree using preorder(left-subtree). - Traverse the right subtree using preorder(right-subtree). Postorder (lrn) algorithm: - Traverse left subtree using postOrder(left-subtree). - Traverse the right subtree using postOrder(right-subtree). - Visit the root node(n). From the above algorithms of traversal techniques, we see that the techniques can be applied to a given tree in a recursive fashion to get the desired result. Consider the following tree. Using the above traversal techniques, the traversal sequence for the above tree is given below: - InOrder traversal : 2 3 5 6 10 - PreOrder traversal : 6 3 2 5 10 - PostOrder traversal: 2 5 3 10 6 Conclusion Trees are a non-linear hierarchical data structure that is used in many applications in the software field. Unlike linear data structures that have only one way to traverse the list, we can traverse trees in a variety of ways. We had a detailed study of traversal techniques and the various types of trees in this tutorial. => Take A Look At The C++ Beginners Guide Here
https://www.softwaretestinghelp.com/trees-in-cpp/
CC-MAIN-2021-17
refinedweb
1,597
71.85
1 /* $OpenBSD: a_bool.c,v 1.8 2017/01/29 17:49:22 beck Exp $ */ 61 #include <openssl/asn1t.h> 62 #include <openssl/err.h> 63 64 int 65 i2d_ASN1_BOOLEAN(int a, unsigned char **pp) 66 { 67 int r; 68 unsigned char *p; 69 70 r = ASN1_object_size(0, 1, V_ASN1_BOOLEAN); 71 if (pp == NULL) 72 return (r); 73 p = *pp; 74 75 ASN1_put_object(&p, 0, 1, V_ASN1_BOOLEAN, V_ASN1_UNIVERSAL); 76 *(p++) = (unsigned char)a; 77 *pp = p; 78 return (r); 79 } 80 81 int 82 d2i_ASN1_BOOLEAN(int *a, const unsigned char **pp, long length) 83 { 84 int ret = -1; 85 const unsigned char *p; 86 long len; 87 int inf, tag, xclass; 88 int i = 0; 89 90 p = *pp; 91 inf = ASN1_get_object(&p, &len, &tag, &xclass, length); 92 if (inf & 0x80) { 93 i = ASN1_R_BAD_OBJECT_HEADER; 94 goto err; 95 } 96 97 if (tag != V_ASN1_BOOLEAN) { 98 i = ASN1_R_EXPECTING_A_BOOLEAN; 99 goto err; 100 } 101 102 if (len != 1) { 103 i = ASN1_R_BOOLEAN_IS_WRONG_LENGTH; 104 goto err; 105 } 106 ret = (int)*(p++); 107 if (a != NULL) 108 (*a) = ret; 109 *pp = p; 110 return (ret); 111 112 err: 113 ASN1error(i); 114 return (ret); 115 }
https://fossies.org/linux/libressl/crypto/asn1/a_bool.c
CC-MAIN-2019-26
refinedweb
189
72.19
- Advertisement Sagar_IndurkhyaMember Content Count1312 Joined Last visited Community Reputation253 Neutral About Sagar_Indurkhya - RankContributor getting sockets to work Sagar_Indurkhya posted a topic in General and Gameplay ProgrammingI'm trying to write two programs, a C program and a Scheme program that can talk to each other using sockets. The Scheme program acts as the server, and the C program as the client. I can get it to work if the Scheme program acts as the client and the C program as the server, but not the other way around. Is there anything obvious I'm missing? The C Client program: #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <string.h> #include <errno.h> #include <iostream> using namespace std; #define SERVER_IP "127.0.0.1" #define ADDR_LEN (sizeof(struct sockaddr)) #define PORT 20000 extern int errno; int main() { int fd_client; struct sockaddr_in serv_addr; char buf[256]; int check_ret; buf[0] = '\0'; fd_client = socket(AF_INET, SOCK_STREAM, 0); if(fd_client < 0) { printf("error creating socket. errno is %d\n", errno); exit(1); } serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(PORT); serv_addr.sin_addr.s_addr = inet_addr(SERVER_IP); bzero(&(serv_addr.sin_zero), 8); check_ret = connect(fd_client, (struct sockaddr *) &serv_addr, ADDR_LEN); if(check_ret < 0) { printf("Connect error. Errno is %d\n", errno); exit(1); } cout << "Entering read loop..." << std::endl; while(1) { printf("READ : "); read(fd_client, buf, 256); printf("%s", buf); bzero(buf, 256); } return 0; } and the scheme server program: (define mySS (open-tcp-server-socket 20000)) (define myPort (tcp-server-connection-accept mySS #t #f)) (write-char #\z myPort) (flush-output myPort) ; stuff should appear on the client side now! politics and gamedev Sagar_Indurkhya replied to spraff's topic in GDNet LoungeAt one point my rating dropped below 128. Now it's back over 1000! Perhaps I hold the record for biggest change in rating? An interesting math problem... Sagar_Indurkhya replied to Chad Seibert's topic in GDNet LoungeI think it's probably easier to solve the problem in base 2, and then show somehow that a solution in base 2 maps to the existence of a solution in base 10. This Simple Problem Deserves A Simple Answer!!! Sagar_Indurkhya replied to EmptyVoid's topic in GDNet LoungeYou want to take 3 probability density functions that are identical and combine them to get a new PDF that has the same form. The normal distribution does just this; if you add several normal dist's, you get another normal dist. For x1, x2, and x3, do the following: for x1, let CDF(y1) = x1, and solve for y1. Now you have y1, y2, and y3, three normally distributed numbers. Then let CDF(z) = y1 + y2 + Y3. z is your random number. There will be some linear scaling of the inputs required, and the new normal PDF that is generated must be normalized, but the basic idea is correct. Now as for solving the inverse CDF equation, I'm sure you can find something on the internet or just use a reverse lookup table. Olives Sagar_Indurkhya replied to Marmin's topic in GDNet LoungeMmmm Olives. After reading this thread, I decided I had to taste some olives (which I hadn't tasted in a long time) and immediately walked to the store and bought a jar. Pimiento-stuffed green olives and some bread is what I'm having now. That is all. Why do we enjoy coding? Sagar_Indurkhya replied to evanofsky's topic in GDNet Lounge`, Foreword for Structure and Interpretation of Computer Programs. Nerd Sniping Sagar_Indurkhya replied to HappyCoder's topic in GDNet LoungeQuote:Original post by Talroth Been awhile since I studied that branch of physics (aka, high school, 6 years ago maybe?) but isn't that an impossible circuit anyway? The solution to computing the theoretical effective resistance of this circuit requires mathematical machinery well beyond that taught in traditional high schools (which I'm assuming ends at single variable calculus). EDIT: although yes, I do think high school students should be able to recognize this circuit is impossible to build exactly. :) But I think you can get a reasonable approximation of it with today's fabrication techniques. Something to chew on for the math savy Sagar_Indurkhya replied to Jesper T's topic in GDNet LoungeI believe you can obtain the solution by just taking the laplace transform of the 2nd order homogenous equation, and then working the algebra and doing the inverse transform. I should know how to do this, so I'll brush up on my Laplace Transforms later today. Here is what I have so far: y'' + y'/x - k^2*y = 0 Now take the laplace transform: [s^2*X(s) - s*X(0) - X'(0)] + [integral(X'(z) dz, s, infinity)] - k^2*X(s) = 0 Now solve for X(s). Then do the inverse laplace transform! Note that you will have constants emerging for the y(0) and the y'(0). Optimizing Java Bytecode Sagar_Indurkhya posted a topic in General and Gameplay ProgrammingI'm in the process of practicing for a competition by writing several complicated algorithms in java. Part of the goal is to minimize the total number of bytecode instructions that the JVM executes (and each round I'm allowed to use up to a limit between 1,000 and 10,000 bytecodes). My main focus is on writing the algorithms cleverly, but since at some points in my application I'm looping, I figure that even small unnecessary things will eat up lots of bytecodes if I'm not weary. Also it intrigues me. :) One thing I have kept in mind is that even if my algorithm when compiled into java bytecode might take up 50,000 bytecode instructions, but if a lot of it is branching etc, then I can still get away with not executing most of them. Any tips and pointers? I've never really thought about optimizing at bytecode level in Java (since the emphasis in Java seems to be that you DON"T want to be doing this level of optimization, but it's the nature of competition). Reading the signal from a phone line Sagar_Indurkhya posted a topic in GDNet LoungeI'm trying to read the raw signal from a phone line via a C/C++ or Python library. I was wondering if anyone has run into anything like this? DIY project with old printer Sagar_Indurkhya posted a topic in GDNet LoungeI've recently acquired an old printer that was going to be thrown out but I saved it and want to do some kind of interesting project with it. It's USB interfaced Epson Stylus Photo R200. I googled around for DIY type projects but couldn't find much for printers... does anyone have any ideas? I thought the fact that it can move the ink cartridge printer part very very precisely is something I would like to take advantage of (otherwise I would have just stripped it for spare motors, etc). Designing Digital Circuits in bases greater than 2 Sagar_Indurkhya posted a topic in General and Gameplay ProgrammingI'm trying to design digital circuits for base n, n >= 2. Suppose n = 5. Then I have a vector of inputs, x = <x0, x1, x2>, each of which can be 0, 1, 2, 3 or 4. For a given input vector, I have an output vector y = <y0, y1, y2>, each of which can be 0, 1, 2, 3 or 4. For some input vectors, the output is "Don't Care" as in it doesn't matter what the output is. What I want to do is derive an optimized circuit built from logic gates. These *logic gates* should operate in base n (5 in this case), so I don't want to simply decompose everything into our traditional boolean logic gates. (and I want to automate this process so a computer program can do this). I've been looking around. I got some books on boolean algebra, and studied karnaugh maps, but those don't seem to tend themselves towards automation. I've started trying to decipher the Espresso heuristic logic minimizer, but I was wondering if anyone knew of any other methods. A last note, this work is for purely theoretical purposes, and is actually intended for studying chemical computing. Random Number Generator Sagar_Indurkhya posted a topic in General and Gameplay ProgrammingI am currently searching for a good random number generator for use with C/C++. Specifically, I need to generate uniform and normal distributions. This is for a scientific simulation application. I know that the standard rand() function apparently doesn't make the cut as being random enough, so what are some good alternatives? So far I've found this one: C/C++ Function styles for returning data as well as return code Sagar_Indurkhya replied to hydrogen's topic in General and Gameplay ProgrammingStore a global CURRENT_RETURN_CODE; In each function, right at the end, set the value of the global CURRENT_RETURN_CODE to whatever you want. Then after you call a function, just check the value of the global variable! Sure it's not a great OOP approach. But You could probably turn that into some type of static return code class or something. As long as you check the return code from a function call before calling any other functions (who would then overwrite the CURRENT_RETURN_CODE), this should work for any possible setup (excluding multi-threaded coded which I do not know much about). Ubuntu is driving me deaf! Sagar_Indurkhya replied to Sagar_Indurkhya's topic in GDNet LoungeVolume's not muted. Yeah I tried alsactl. At this point I'm too frustrated. My university gives out Red Hat Enterprise for free on campus. I really liked how everything was very easy in Ubuntu to configure /install, etc, so I was wondering if Red Hat Linux Enterprise would be a step in the gentoo direction too much? - Advertisement
https://www.gamedev.net/profile/54730-sagar_indurkhya/
CC-MAIN-2018-43
refinedweb
1,655
63.19
Dear friend, in this article I will take you from the backdoor of C# code execution and show you the step-by-step operation of code execution in C#. Dear friend, in this article I will take you from the backdoor of C# code execution and show you the step-by-step operation of code execution in C#. You might think that "I do not bother at all with an execution plan or I don't want to poke my nose into it". Yes, you are right to a certain point, because code execution may not help you to increase your CTC. (Yes I am talking about salary , the first thing that comes to mind after getting an interview call... Ha Ha.) It will however make you a better programmer from a good programmer or increase your peace of mind when you see the same output produced by the computer after executing the same program in your mind. And us developer people generally ignore it because the .NET framework is trained enough to execute code properly to get the desired output.Here we will start our journey by observing a very small example and gradually we will proceed to complex ones and in our journey we will try to concentrate on a few things that we have studied in our college days but not seen practically.Let me ask you one question. Do you still remember assembly language programming? If you are not a chip level programmer then it's a blur in your mind and most probably you are trying to recap a few instructions of the 8085 or 8086 microprocessor from your good old college days. I am talking about low-level programming because the IL code produced by the .NET Framework is very similar to assembly level programming. And if you have a good idea of that then this tutorial will be a piece of cake for you.Understanding a few instructions at firstLet's learn a few IL code instructions produced by .NET. Before beginnig that, a quick review is nevcessary for a better understanding. Actually the number of instruction sets depends on the computer architecture. If you use an 8-bit computer (what the hell, man; people are using 64-bit and still now you are in 8 bits!! Ha Ha) then the total number of instructions will be 256. For your 64-bit system calculation remains for you . Obviously our interest will be those instructions that we need to understand to read this article completely. With those instructions let's clear up a few basic theoretical concepts, as in the following: That is however too much theory. Let's see it in action.How does it get the result in your day 1 program?Yes, I am talking about the "Hello World" program. Let's print one hello world message in a program and see the execution steps. In the following my simple name print program is: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; using System.IO; using System.Net; using System.Net.NetworkInformation; namespace Test1 { class Program { static void Main(string[] args) { Console.WriteLine("Sourav Kayal"); } } And here is the IL code:Start to discuss the step-by-step of code execution. IL_0000 : ldstr "sourav Kayal" : Load string constant onto stack IL_0005: call: Call to WriteLine() function with value of top of stack IL_000a: ret: Return from the function. Here we are seeing the printing of a simple string in the console output window. At first the string is loaded into the stack (because this is the argument of the WriteLine function) then the WriteLine function is called and the argument value is taken from the top of the stack.Note: The point is clear here; before calling a function it is necessary for the argument to be loaded onto the stack. If you don't believe that then wait for the next few examples.The following prints a string by declaring it first. string name = "Sourav Kayal"; Console.WriteLine(name); } This is the corresponding IL code. IL_0000: ldstr : Load String constant onto stack IL_0005:stloc.0 : Store data (here a string) in local-0 variable from top of stack. IL_0006:ldloc.0 : Load data onto the stack from local variable-0 IL_0007:call : Call to WriteLine() static function. IL_000c:ret : Return from the program. In this program we are also seeing at first the string constant is created on the stack and then it's loaded to a local variable. And when we are using this local variable in our WriteLine() function as a argument at first the value of local variable is being loaded onto the stack and then it's passed as an argument. Here we can clearly see again "Before calling a function it is necessary to push the argument onto the stack".Sourav, stop working with Strings and show something else.Then let me show an example with an integer value. Here is my code: int a = 100; Console.WriteLine(a); } In this program we are creating one integer variable and initializing it with the value 100 and passing it as an argument of the WriteLine() function. The following is the IL code window. Here we will see a very similar output with the String allocation process not much different. IL_0000 : ldc.i4.s : Load numeric constant onto stack IL_0002 : stloc.0 : Store value to local variable from top of the stack. IL_0003 :ldloc.0 : Load local variable data onto stack. (See, again the value is being loaded onto the stack.) IL_0004 :call : Call to the static function with an argument from the top of the stack. Let's see how the addition operation is performed on the stack.Here is the very simple program for the addition operation. Let's see the line-by-line execution. int b = 100; Console.WriteLine(a+b); The output IL code window is here. IL_0000: ldc.i4.s : Load integer constant onto stack (first variable). IL_0002:stloc.0 : Move the top of the stack to a local variable. (0 indicating first variable.) IL_0003:ldc.i4.s : Load an integer constant onto the stack (second variable). IL_0005:stloc.1 : Move top of stack to local variable(1 indicating second variable). IL_0006:ldloc.0 : Load local variable 0 (first variable) on stack. IL_0007.ldloc.1 : Load local variable 1 (second variable) on stack. IL_0008:add : Perform add operation. (See, the Add operation is performed with the stack value, top two values.) Note: Before any arithmetic operation the necessary values need to be loaded onto the stack. You may try with subtraction or division. We return value the happily, but where is the value returned?Why? The value is returned to the caller function?Very frequently we write a return statement to return something from a function and when we began learning programming our teacher taught us that when we return something from a function it is returned to the caller function. (My teacher also told me that.) But here we will see what happens exactly, when we return some value from a function.Here is my simple code. static Int32 Call() return 100; Call(); }In the right side my main function IL code is shown and the left window contains the body of the Call function. This call function returns the value (100) to the Main function but if we closely look at the IL code of the Call() function then we will see the value is created on the top of the stack (ldc.i4.s) then the control is being returned from the Call function and along with the return statement is the attached value.Note: the Return statement does not return anything, just keeps the latest value on the stack.ConclusionHere I have tried to represent a few first days of programming concepts in my own style. If we really like it (or even dislike it) then please leave your valuable comment in the following. Don't forget "Your single comment is enough to reduce my sleep time in half due to preparation of a more interesting document in part 2". View All
https://www.c-sharpcorner.com/UploadFile/dacca2/look-under-the-hood-of-C-Sharp-program-execution-part-1/
CC-MAIN-2021-21
refinedweb
1,361
65.73
This is the ninth lesson in a series introducing 10-year-olds to programming through Minecraft. Learn more here. Let's take a closer look at our Block class. package net.minecraft.block; public class Block { public static final StepSound soundWoodFootstep = new StepSound("wood", 1.0F, 1.0F); public float blockHardness; protected Icon blockIcon; private String unlocalizedName; public Block(int id, Material material) { ... } protected void initializeBlock() { ... } public void setStepSound(StepSound sound) { ... } } Packages Every class is contained in a package. If we're creating a new kind of Block (e.g. RiverBankBlock) in our own package (e.g. mc.jb.first), then we need to import the package that Block lives in. Our source code file, RiverBankBlock.java might look like this: package mc.jb.first; import net.minecraft.block; public class RiverBankBlock extends Block { .... } If we didn't include the import statement, the compiler would get confused because it wouldn't know where to find the class definition for Block. Visibility Parameters: Method parameters are only accessible within a given method. In our Block class, there is no way to use the sound parameter from the setStepSound method in the initializeBlock method. Fields: All fields defined in a class are accessible in any method within that class. Derived classes: Only fields marked public and protected in a parent class are accessible in child classes. Our RiverBankBlock class could access blockIcon and blockHardness from Block, but not unLocalizedName. Non-derived classes: If we create an object ourselves (using the new keyword), we only have access to its public fields and methods. Lifetime In general, we won't need to worry too much about how long an object exists. However, there is a special keyword called static that we will come across while creating mods. Static method: A method that can be called without creating an instance of the class. Here's a class with static methods we'll use when creating our own type of block: public class MinecraftForge { public static void setBlockHarvestLevel( Block block, String toolClass, int harvestLevel) { .... } } To call this method, we use the name of the class itself rather than an instance (variable) name. Block block = new Block(); MinecraftForge.setBlockHarvestLevel( block, ....); Static field: A field that can be accessed without creating an instance of the class. Looking back at our Block example, if we want to call setStepSound, we first need to have an instance of Block either as a method parameter or as a variable we created ourself. However, anyone can use the public field soundWoodFootstep "directly", like this: StepSound sound = Block.soundWoodFootstep;
http://www.jedidja.ca/classes-and-objects-part-two/
CC-MAIN-2018-05
refinedweb
426
58.48
Packaging Objects to Preserve Encapsulation Packages Explained One of the major features provided by the various Java releases was that of packages. Many structured programmers are familiar with the concept of code libraries. In some ways, packages can be thought of in the same way as code libraries - but they have many important differences. Perhaps the best way to describe a package is to actually show packages. This can be easily accomplished by inspecting a file called rt.jar. Remember that a Java program is run inside of a virtual machine. The operative term here is virtual. When you run a Java application you do so by invoking the Java executable java.exe. After you install the SDK, you can find the java.exe file in the bin directory of the Java installation as seen in figure 5. Figure 5. The great thing about using a virtual machine, and specifically in the case of Java, is that your Java code can be run on any computer that has a virtual machine installed. The not-so-great thing is that there are computers that do not have a Java virtual machine installed. Thus, if you ship your application to a computer without a resident Java virtual machine, that computer will not be able to run your application. Another problem, and this can get somewhat sticky, is that the target computer may have a version of the SDK that is different from the version that you developed the application with. So, you may ask how we can safely ship an application if we have 2 unknowns: - Don't know if the target computer has Java installed. - If it does, what version of the SDK does it have installed? You may have guessed that the way to solve this problem is to actually ship the version of the JVM with your application. In this way, you know that the application will run with the same version of the JVM that you developed it with. Some may find it odd that you would think of shipping a virtual machine with the application; however, this is a viable solution because you don't need to ship the entire SDK. You may have noticed in figure 5 that the SDK contains several directories (some installation may have different directory names): - bin - demo - include - jre - lib The virtual machine java.exe is, as we have seen, in the bin directory. Many of the other directories include the tools you will need for development. However, all that you need to ship with the application is a subset of the SDK. The directory jre contains all this material you need to execute a Java application. The name jre stands for java runtime environment. The jre can be bundled with your application to ensure that it will run on a target machine. Inside the jre directory is a file called rt.jar that we can use to illustrate our package example. Figure 6 shows the jre with the file rt.jar highlighted. Figure 6 The extension jar stands for Java Archive. The great thing about these jar files is that they are built on zip technology (just like WinZip). In fact, you can actually use Winzip to open a jar file as seen in figure 7. Figure 7 The only visible difference between a regular zip file and a jar file is the first file Manifest.mf which designates this as a Java jar file. For example, when you want to develop Java Swing applications you must include the rt.jar file in your classpath and then import the Swing package that is included in the rt.jar file. You can easily find the Swing package inside the rt.jar file as seen in figure 8. Figure 8 In figure 8, the class Boxview.class is selected. The file Boxview.class is part of the swing package and you can see that the packages are identified on the far right under the Path column. Using packages is how Java bundles the development tools as well as the runtime environment. We can create our own packages to make development much more secure and productive. With this background on packages complete, we can now see how to create our own packages to solve the problem we encountered above when inheritance appears to break encapsulation. Packaging Solution Let's create a design that will solve the problem we began this discussion with. Make the following changed to Mammal as seen in listing 8. // Class Mammal package Mammals; // add this line public class Mammal { protected String color; public void growHair(){ System.out.println("Hair Growing"); } } Listing 8 The line in red creates a package called Mammal. Once this is created we can use and distribute this library and we can place the appropriate class files inside. A Java package, to a certain degree, equates to a directory and its corresponding directory structure. Thus, to physically create our Mammals package we can simply create a sub-directory called Mammals. Inside your application directory, which here is called Packaging, create a subdirectory called Mammals and move the Mammal class inside this directory. Now let's compile the project again and see what happens. Listing 9 shows how you need to adjust your compilation syntax. Note that you must include the directory path for the new package. c:j2sdk1.4.2_05binjavac -classpath . ./Mammals/Mammal.java c:j2sdk1.4.2_05binjavac -classpath . Dog.java Listing 9 When we run this we see that the Dog class cannot find the Mammal source code to extend it - just as we expected since we moved the Mammal.java file. This can be seen in figure 9. Figure 9 To address this problem we simply import the Mammal package in the Dog class as can be seen in the red line in listing 10. //Class Dog import Mammals.*; public class Dog extends Mammal{ private int barkFrequency; public void bark(){ System.out.println("Dog Barking"); color = "blue"; } } Listing 10 Listing 11 shows the necessary added line in the Packaging class. import Mammals.*; public class Packaging { public static void main (String args[]){ Mammal mammal = new Mammal(); mammal.growHair(); mammal.color = "blue"; } } Listing 11 This deals successfully with the problem of the Dog class finding the Mammal class; however, an error message appears when the Package class is compiled as can be seen in figure 10. Figure 10 The error message states that the color attribute is protected and thus cannot be accessed from the Package application. Actually, this is exactly the behavior that we want! Now the color attribute can be successfully accessed from the Dog class (which is a valid inheritance relationship) - but not from the application (which we want to avoid like the plague per our encapsulation rule). Protected Status There is one more issue to explore in this discussion of packages. There is actually another type of access modifier - one we will call default protected, or package protected. Take a look at listing 12 and the red line of code. // Class Mammal package Mammals; public class Mammal { String color; public void growHair(){ System.out.println("Hair Growing"); } } Listing 12 Notice in this case that the color attribute appears to have no access modifier; however, it is provided a default access modifier. This default modifier is basically a protected modifier within the package only - it excludes subclasses. Thus, when we really do use the protected access modifier, this includes the inheritance hierarchy tree. Perhaps we can call this inheritance protected. When we compile with this version of the Mammal class we get the results seen in figure 11. Figure 11 This is because the Dog class is not in the Mammals package. We can solve this problem by including Dog in the Mammals package. Take a look at the red line of code in listing 13. //Class Dog package Mammals; public class Dog extends Mammal{ private int barkFrequency; public void bark(){ System.out.println("Dog Barking"); color = "blue"; } } Listing 13 When we compile this we get the desired result. Dog is now part of the Mammals package so it has access to the attributes in Mammal; however, the application Packaging cannot access them. Conclusion At first, the encapsulation/inheritance dilemma covered in the past 2 articles may seem confusing. In fact, you may start to wonder if the whole paradigm is simply too intricate for its own good. Yet, once you finally do understand the issues behind these examples, they really do become interesting intellectual exercises and useful development techniques. We have seen that at one level encapsulation and inheritance do conflict with each other. However, using Java packaging, you can successfully enforce both the inheritance rule and the encapsulation rule.. About the Author Page 2 of 2 Comment and Contribute.
https://www.developer.com/design/article.php/10925_3546936_2/www.javasoft.com
CC-MAIN-2017-43
refinedweb
1,458
55.13
Instructions for Form 1120-PC U.S. Property and Casualty Insurance Company Section references are to the Internal Revenue Code unless otherwise noted. Contents Photographs of Missing Children Unresolved Tax Issues . . . . . . . How To Get Forms and Publications . . . . . . . . . . . . . IRS E-Services . . . . . . . . . . . . General Instructions . . . . . . . . . Purpose of Form . . . . . . . . . . . Who Must File . . . . . . . . . . . . . When To File . . . . . . . . . . . . . . Where To File . . . . . . . . . . . . . Who Must Sign . . . . . . . . . . . . Paid Preparer Authorization . . . Other Forms That May Be Required . . . . . . . . . . . . . . . Consolidated return . . . . . . . . . Statements . . . . . . . . . . . . . . . Assembling the Return . . . . . . . Accounting Methods . . . . . . . . . Accounting Periods . . . . . . . . . Rounding Off to Whole Dollars . Recordkeeping . . . . . . . . . . . . . Depository Methods of Tax Payment . . . . . . . . . . . . . . . Estimated Tax Payments . . . . . Interest and Penalties . . . . . . . . Specific Instructions . . . . . . . . . Period Covered . . . . . . . . . . . . Address . . . . . . . . . . . . . . . . . . Employer Identification Number . Item A . . . . . . . . . . . . . . . . . . . Item E . . . . . . . . . . . . . . . . . . . Taxable Income . . . . . . . . . . . . Tax Computation and Payments Schedule A . . . . . . . . . . . . . . . Schedule B, Part I . . . . . . . . . . Schedule B, Part II . . . . . . . . . . Schedule C . . . . . . . . . . . . . . . Schedule E . . . . . . . . . . . . . . . Schedule F . . . . . . . . . . . . . . . Schedule G . . . . . . . . . . . . . . . Schedule H . . . . . . . . . . . . . . . Schedule I . . . . . . . . . . . . . . . . Schedule L . . . . . . . . . . . . . . . Schedule M-1 . . . . . . . . . . . . . Index . . . . . . . . . . . . . . . . . . . . Page .... 1 ..... 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 2 2 2 2 2 2 3 3 3 3 4 4 4 4 4 5 income taxes if (1) the gross receipts for the taxable year are $600,000 or less, and over half of the gross receipts consist of premiums; or (2) if a specified mutual insurance company, the gross receipts for the taxable year are $150,000 or less, and over 35 percent of the gross receipts consist of premiums. For additional information, including exceptions and transition rules, see section 501(c)(15)(A). • Charitable contributions made in January 2005 for the relief of victims in areas affected by the Indian Ocean tsunami may be treated as if made on December 31, 2004. • Corporations can file new Form 8895, Section 965(f) Election for Corporations that are U.S. Shareholders of a Controlled Foreign Corporation, to elect the 85% dividends-received deduction on repatriated dividends received under section 965. Changes are made to Form 1120-PC, Schedule C, lines 10 and 24. • For tax years beginning after October 22, 2004, corporations can elect to be taxed on income from qualifying shipping activities using an alternative tax method. See page 10. • Corporations can elect to deduct a limited amount of business start-up and organizational costs paid or incurred after October 22, 2004. See page 11. • Corporations cannot deduct certain interest paid or incurred in tax years beginning after October 22, 2004, on an underpayment of tax from certain undisclosed transactions. See page 12. • For charitable contributions of certain property made after June 3, 2004, a corporation must file Form 8283 and obtain a qualified appraisal if claiming a deduction of more than $5,000. See page 13. • For charitable contributions of patents and certain other intellectual property made after June 3, 2004, corporations will receive a reduced deduction but can deduct certain qualified donee income. See page 13. • Special rules apply to charitable contributions after 2004 of used motor vehicles, boats, or airplanes with a claimed value of more than $500. See section 170(f)(12). • The deduction for certain travel, meals, and entertainment expenses incurred Cat. No. 64537I Department of the Treasury Internal Revenue Service after October 22, 2004, is limited to the amount treated as compensation to officers, directors, and more-than-10% shareholders. See section 274(e)(2). • If the corporation is an expatriated entity or a partner in an expatriated entity, the corporation’s taxable income cannot be less than its inversion gain for the tax year. See section 78. ... 5 ... 5 ... 5 ... 6 ... 6 ... 6 ... 6 ... 6 ... 6 ... 6 . . 6-9 . 9-15 . . 15 . . 15 15-17 . . 17 . . 18 . . 18 . . 19 . . 19 . . 20 . . 20 . . 21: • A “fresh look” at a new or ongoing problem. • Timely acknowledgment. • The name and phone number of the individual assigned to its case. • Updates on progress. • Timeframes for action. • Speedy resolution. • Courteous service. When contacting the Taxpayer Advocate, the corporation should be What’s New • For tax years beginning after December 31, 2003, an insurance company, other than a life insurance company, is generally exempt by calling 1-877-777-4778 (toll free). Persons who have access to TTY/TDD equipment can call 1-800-829-4059 and ask for the Taxpayer Advocate assistance. If the corporation prefers, it can call, write, or fax the Taxpayer Advocate in its area. See Pub. 1546, The Taxpayer Advocate Service of the IRS, for a list of addresses and fax numbers. 3676). You can also get most forms and publications at your local IRS office. IRS E-Services Make Taxes Easier Now more than ever before, businesses can enjoy the benefits of filing and paying their federal taxes electronically. Whether you rely on a tax professional or handle your own taxes, the IRS offers you convenient programs to make taxes easier. • You can e-file your Form 940 and 941 employment tax returns, Form 1099, and other information returns. Visit for more information. • You can pay taxes online or by phone using the free Electronic Federal Tax Payment System (EFTPS). Visit or call 1-800-555-4477 for more information. Use these electronic options to make filing and paying taxes easier. and reserves, or otherwise ceases to be taxed under section 831, but continues its corporate existence while winding up and liquidating its affairs, should file Form 1120, U.S. Corporation Income Tax Return. Life insurance companies. Life insurance companies should file Form 1120-L, U.S. Life Insurance Company Income Tax Return. When To File. Private delivery services. Corporations. General Instructions Purpose of Form Use Form 1120-PC, U.S. Property and Casualty Insurance Company Income Tax Return, to report the income, gains, losses, deductions, credits, and to figure the income tax liability of insurance companies, other than life insurance companies.. Who Must File Every domestic nonlife insurance company and every foreign corporation that would qualify as a nonlife insurance company subject to taxation under section 831, if it were a U.S. corporation, must file Form 1120-PC. This includes organizations described in section 501(m)(1) that provide commercial-type insurance and organizations described in section 833. Exceptions. A nonlife insurance company that is: • Exempt under section 501(c)(15) should file Form 990, Return of Organization Exempt from Income Tax. • Subject to taxation under section 831, and disposes of its insurance business CD-ROM Order Pub. 1796, Federal Tax Products on CD-ROM, and get: • Current year forms, instructions, and publications. • Prior year forms, instructions, and publications. • Frequently requested tax forms that can (plus a $5 handling fee). ! Where To File File the corporation’s return at the applicable IRS address listed below. If the corporation’s principal business, office, or agency is located in: The United States A foreign country or U.S. possession (or the corporation is claiming the possessions corporation tax credit under sections 30A and 936) Use the following Internal Revenue Service Center address: Ogden, UT 84201-0012 By phone and in person You can order forms and publications by calling 1-800-TAX-FORM (1-800-829- Philadelphia, PA 19255-0012 -2- Instructions for Form 1120-PC Extension. File Form 7004, Application for Automatic Extension of Time To File Corporation Income Tax Return, to request a 6-month extension of time to file.-PC, the paid preparer’s space should remain blank. Anyone who prepares Form 1120-PC returns, amended returns, or requests for filing extensions by rubber stamp, mechanical device, or computer software program.. The authorization cannot be revoked. However, the authorization will automatically end no later than the due date (excluding extensions) for filing the corporation’s 2005 tax return. Other Forms That May Be Required The corporation may have to file some of the forms listed below. See the form for more information. For a list of additional forms the corporation may need to file, see Other Forms That May Be Required in the Instructions for Forms 1120 and 1120-A. • Form W-2, Wage and Tax Statement. Use this form to report wages, tips, and other compensation, and withheld income, social security, and Medicare taxes for employees. • Form 720, Quarterly Federal Excise Tax Return. Use this form to report and pay41, Employer’s Quarterly Federal Tax Return. Employers must file this form. Also, see Trust fund recovery penalty on page 5. • Form 1099-MISC, Miscellaneous Income. Use this form to report payments: to providers of health and medical services, of rent or royalties, nonemployee compensation, etc. Note. Every corporation must file Form 1099-MISC if it makes payments of rents, Paid Preparer Authorization If the corporation wants to allow the IRS to discuss its 2004 tax return with the paid preparer who signed it, check the “Yes” box in the signature area of the return. This authorization applies only to the individual whose signature appears in the “Paid that the corporation has shared with the preparer Instructions for Form 1120-PC commissions, or other fixed or determinable income (see section 6041) totaling $600 or more to any one person in the course of its trade or business during the calendar year. • Form 1122, Authorization and Consent of Subsidiary Corporation To Be Included in a Consolidated Income Tax Return. File this form if this is the first year a consolidated return is being filed. • Form 5471, Information Return of U.S. Persons With Respect to Certain Foreign Corporations. This form is filed by a domestic nonlife insurance company that. See Question 4 of Schedule N (Form 1120). • Form 5472, Information Return of a 25% Foreign-Owned U.S. Corporation or a Foreign Corporation Engaged in a U.S. Trade or Business. This form is filed by a domestic nonlife insurance company that is 25% or more foreign-owned. See Question 6 on page 19. • Form 8302, Electronic Deposit of Tax Refund of $1 Million or More. This form must be filed to request an electronic deposit of a tax refund of $1 million or more. • Form 8621, Return by a Shareholder of a Passive Foreign Investment Company or Qualified Electing Fund. A domestic nonlife insurance company uses this form to make certain elections by shareholders in a passive foreign investment company and to figure certain deferred taxes. • Form 8816, Special Loss Discount Account and Special Estimated Tax Payments for Insurance Companies. This form must be filed by any insurance company that elects to take an additional deduction under section 847. • Form 8895, Section 965(f) Election for Corporations that are U.S. Shareholders of a Controlled Foreign Corporation. Use this form to elect the dividends-received deduction on repatriated dividends received under section 965.). File supporting statements for each corporation included in the consolidated -3- return. Do not use Form 1120-PC. Enter the totals for the consolidated group on Form 1120-PC. Attach consolidated balance sheets and a reconciliation of consolidated retained earnings. For more information on consolidated returns, see the regulations under section 1502. Note. If a nonlife insurance company is a member of an affiliated group, file Form 1120-PC as an attachment to the consolidated return in lieu of filing supporting statements. Across the top of page 1 of Form 1120-PC, write “Supporting Statement to Consolidated Return.” 6. Additional schedules in alphabetical order. 7. Additional forms in numerical order. Complete every applicable entry space on Form 1120-PC. put the corporation’s name and EIN on each supporting statement or attachment. rules for determining when economic performance takes place. Change in Accounting Method To change its method of accounting used to report taxable income (for income as a whole or for the treatment of any material item), the corporation must file Form 3115, Application for Change in Accounting Method. For more information, see Form 3115 and Pub. 538, Accounting Periods and Methods. and item 67 in the List of Automatic Accounting Method Changes. Section 481(a) adjustment. The corporation corporation can elect to use a 1-year adjustment period if the net section 481(a) adjustment for the change is less than $25,000. The corporation must complete the appropriate lines of Form 3115 to make the election. Include any net positive section 481(a) adjustment on Schedule A, line 13. If the net section 481(a) adjustment is negative, report it on Schedule A, line 31. Accounting Methods An accounting method is a set of rules used to determine when and how income and expenses are reported. Figure taxable income using the method of accounting regularly used in keeping the corporation’s books and records. Generally, permissible methods include: • Cash, • Accrual, or • Any other method authorized by the Internal Revenue Code. The gross amounts of underwriting and investment income should be computed on the basis of the underwriting and investment exhibit of the NAIC annual statement to the extent not inconsistent with the Internal Revenue Code and its Regulations. In all cases, the method used must clearly show taxable income. Accrual method. Generally, a corporation must use the accrual method of accounting if its average annual gross receipts exceed $5 million. See section 448(c). Under the accrual method, an amount is includible in income when: 1. All the events have occurred that fix the right to receive the income, which is the earliest of the date (a) the required performance takes place, (b) payment is due, or (c) payment is received and 2. Statements NAIC annual statement. Regulations section 1.6012-2(c) requires that the NAIC annual statement be filed with Form 1120-PC. A penalty for the late filing of a return may be imposed for not including the annual statement when the return is filed. Stock ownership in foreign personal holding companies (FPHC). Attach the statement required by section 551(c) if: 1. The corporation owned 5% or more in value of the outstanding stock of a FPHC and 2. The corporation was required to include in its gross income any undistributed FPHC income from a FPHC.. Assembling the Return To ensure that the corporation’s tax return is correctly processed, attach all schedules and other forms after page 8, Form 1120-PC, and in the following order: 1. Schedule N (Form 1120). 2. Form 8302. 3. Form 4136. 4. Form 4626. 5. Form 851.). Instructions for Form 1120-PC -4- If two or more amounts must be added to figure the amount to enter on a line, include cents when adding the amounts and round off only the total. to an authorized depositary (a commercial bank or other financial institution authorized to accept federal tax deposits). Make checks or money orders payable to that depositary. If the corporation prefers, it can-PC” corporation owes tax when it files Form 1120-PC, do not CAUTION include the payment with the tax return. Instead, mail or deliver the payment with Form 8109 to an authorized depositary, or use EFTPS, if applicable. end of the tax year. Form 4466 must be filed before the corporation files its income tax return.. CAUTION ! Foreign insurance companies, see Notice 90-13, 1990-1 C.B. 321, before computing estimated tax. Interest and Penalties Interest. Interest is charged on taxes paid late even if an extension of time to file is granted. Interest is also charged on penalties imposed for failure to file, negligence, fraud, substantial valuation misstatements, and substantial understatements of tax have to pay a penalty of; or Form 945, Annual Return of Withheld Federal Income Tax (see Other Forms That May Be Required on page 3). The trust fund recovery penalty may be imposed on all persons determined by the IRS to have been responsible for collecting, accounting for, and paying over these taxes, and who acted willfully in not doing so. The penalty is equal to the unpaid trust fund tax. See the instructions for Form 720 or Pub. 15 (Circular E), Employer’s Tax Guide, for details, including the definition of responsible persons. Other penalties. Other penalties can be imposed for negligence, substantial Depository Methods 2005 if: • The total deposits of such taxes in 2003 were more than $200,000 or • The corporation was required to use EFTPS in 2004. If the corporation is required to use EFTPS and fails to do so, it may be subject to a 10% penalty. If the corporation is not required to use EFTPS, it can participate voluntarily. To enroll in or get more information about EFTPS, call 1-800-555-4477 or 1-800-945-8400. To enroll online, visit. Depositing on time. For EFTPS deposits to be made timely, the corporation must initiate the transaction at least 1 business day before the date the deposit is due. Estimated Tax Payments Generally, the following rules apply to the corporation does not use EFTPS, use the deposit coupons (Forms 8109) to make deposits of estimated tax. For more information on estimated tax payments, including penalties that apply if the corporation fails to make required payments, see the instructions for line 15 on page 9.. Be sure to have your EIN ready when you call. Do not send deposits directly to an IRS office; otherwise, the corporation may have to pay a penalty. Mail or deliver the completed Form 8109 with the payment Instructions for Form 1120-PC -5- understatement of tax, and fraud. See sections 6662 and 6663. Specific Instructions Period Covered Generally, file the 2004 return for calendar year 2004. However, if an insurance company joins in the filing of a consolidated return, it may adopt the tax year of the common parent corporation even if that year is not a calendar year. For a fiscal. Generally, a foreign corporation making either election must file its return with the Internal Revenue Service Center, Philadelphia, PA 19255. schedule showing the computation. See section 953(d) for more details. “controlled group” means any parent-subsidiary group, brother-sister group, or combined group. See the definitions below. Parent-subsidiary group. A parent-subsidiary • The common parent corporation. Brother-sister group. A brother-sister group is two or more corporations if 5 or fewer persons who are individuals, estates, or trusts directly or indirectly. For tax years beginning after October 22, 2004, the definition of brother-sister group does not include (1) above, but only for purposes of the taxable income brackets, alternative minimum tax exemption amounts, and accumulated earnings credit. Combined group. A combined group is three or more corporations each of which is a member of a parent-subsidiary group or a brother-sister group, and one of which is: • A common parent corporation included in a group of corporations in a parent-subsidiary group, and also • Included in a group of corporations in a brother-sister group. For more details on controlled groups, see section 1563. Line 3a. Members of a controlled group are entitled to one $50,000, one $25,000, and one $9,925,000 taxable income bracket amount (in that order) on line 3a. Instructions for Form 1120-PC Employer Identification Number (EIN) Enter the corporation’s EIN. If the corporation does not have an EIN, it must apply for one. An EIN can be applied for: • Online — Click on the EIN link at. The EIN is issued immediately once the application information is validated. • By telephone at 1-800-829-4933 from 7:00 a.m. to 10:00 p.m. in the corporation’s local time zone. • By mailing or faxing Form SS-4, Application for Employer Identification Number. If the corporation has not received its EIN by the time the return is due, enter “Applied for” in the space for the EIN. For more details, see Pub. 583. Note. The online application process is not yet available for corporations with addresses in foreign countries or Puerto Rico. Item E. Final Return, Name Change, Address Change, or Amended Return Indicate a final return, name change, address change, or amended return by checking the appropriate box. Note. If a change of address occurs after the return is filed, use Form 8822, Change of Address, to notify the IRS of the new address.. Note. If Schedule C, line 10 was completed, see Minimum taxable income on page 15. Item A. Section 953 Elections Check the applicable box if the corporation is a foreign corporation and elects under: 1. Section 953(c)(3)(C) to treat its related person insurance income as effectively connected with the conduct of a trade or business in the United States or 2. Section 953(d) to be treated as a domestic corporation. Tax Computation and Payments Line 3 Members of a controlled group. A member of a controlled group must check the box on line 3 and complete lines 3a and 3b of the Form 1120-PC. The term -6- can. Equal apportionment plan. If no apportionment plan is adopted, members of a controlled group must divide the amount in each taxable income bracket equally among themselves. For example, Controlled Group AB consists of Corporation A and Corporation B. They do not elect an apportionment plan. Therefore, each corporation is entitled to: • $25,000 (one-half of $50,000) on line 3a(1), • $12,500 (one-half of $25,000) on line 3a(2), and • $4,962,500 (one-half of $9,925,000) on line 3a(3). Line 3 3b(1). Enter the corporation’s share of the additional 5% tax on line 3b(1). Line 3b(2). Enter the corporation’s share of the additional 3% tax on line 3b(2). Tax Rate Schedule If the amount on line 1 or line 2, Form 1120-PC, page 1 is: Of the amount over — 197(f)(9)(B) in the total for line 4. On the dotted line next to line 4, enter “Section 197” and the amount. For more information, see Pub. 535, Business Expenses.. Over — $0 50,000 75,000 100,000 335,000 10,000,000 15,000,000 18,333,333 But not over — $50,000 75,000 100,000 335,000 10,000,000 15,000,000 18,333,333 ----- Tax is: 15% $0 $ 7,500 + 25% 50,000 13,750 + 34% 75,000 22,250 + 39% 100,000 113,900 + 34% 335,000 3,400,000 + 35% 10,000,000 5,150,000 + 38% 15,000,000 35% 0) in the amount entered on line 4. On the dotted line next to line 4, enter “Section 1291” and the amount. Do not include on line 4 any interest due under section 1291(c)(3). Instead, show the amount of interest owed in the bottom margin of page 1 and enter Tax Computation Worksheet for Members of a Controlled Group (keep for your records) Note. Each member of a controlled group must compute its tax using this worksheet. 1. Enter taxable income (page 1, line 1 or line 2) . . . . . . . . . . . . . 3b. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13. If the taxable income of the controlled group exceeds $15 million, enter this member’s share of the smaller of: 3% of the taxable income in excess of $15 million, or $100,000. See the instructions for line 3b. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14. Total. Add lines 8 through 13. Enter here and on line 4, page 1 Line 4 Most corporations figure their tax by using the Tax Rate Schedule, on this page. Exceptions apply to members of a controlled group. See the Tax Computation Worksheet for Members of a Controlled Group, on this page. Members of a controlled group must attach a statement showing the computation of the tax entered on line 4. Instructions for Form 1120-PC -7- Line 6. Alternative minimum tax (AMT). A corporation that is not a small corporation exempt from the AMT CAUTION (see page 8). details. ! Vehicles that qualify for this credit are not eligible for the deduction for clean-fuel vehicles under section 179A. Line 8c. General Business Credit Enter on line 8c the corporation’s total general business credit. If the corporation is filing Form 8844, Empowerment Zone and Renewal Community Employment Credit, or Form 8884, New York Liberty Zone Business Employee Credit, or Form 8835 (see list below) with a credit from Section B, check the “Form(s)” box, enter the form number in the space provided, and include the allowable credit on line 8c. If the corporation is required to file Form 3800, General Business Credit, check the “Form 3800” box and include the allowable credit on line 8c. If the corporation is not required to file Form 3800, check the “Form(s)” box, enter the form number in the space provided, and include on line 8c the allowable credit from the applicable form listed below. • Investment Credit (Form 3468). • Work Opportunity Credit (Form 5884). • Credit for Alcohol Used as Fuel (Form 6478). • Credit for Increasing Research Activities (Form 6765). • Low-Income Housing Credit (Form 8586). • Disabled Access Credit (Form 8826). • Enhanced Oil Recovery Credit (Form 8830). • Renewable Electricity and Refined Coal Production Credit (Form 8835). • Indian Employment Credit (Form 8845). • Credit for Contributions to Selected Community Development Corporations (Form 8847). • Welfare-to-Work Credit (Form 8861). • Biodiesel Fuels Credit (Form 8864). • New Markets Credit (Form 8874). • Credit for Small Employer Pension Plan Startup Costs (Form 8881). • Credit for Employer-Provided Childcare Facilities and Services (Form 8882). • Low Sulfur Diesel Fuel Production Credit (Form 8896). Line 8d. Credit for prior year minimum tax. To figure the minimum tax credit and any carryforward of that credit, use Form 8827, Credit for Prior Year Minimum Tax — Corporations. Also see Form 8827 if any of the corporation’s 2003 nonconventional source fuel credit or qualified electric vehicle credit was disallowed solely because of the tentative minimum tax limitation. See section 53(d). Line 8e. Qualified zone academy bond credit. Enter the amount of any credit from Form 8860, Qualified Zone Academy Bond Credit. Line 10. Foreign corporations. A foreign corporation carrying on an insurance business in the United States is taxed as a domestic schedule showing the kind and amount of income, the tax rate, and the amount of tax. Enter the tax on line 9. However, see Reduction of section 881 tax, below. Note. Interest received from certain portfolio debt investments that were issued after July 18, 1984, is not subject to the tax. See section 881(c) for details. See section 842 for more information. Minimum effectively connected net investment income. See section 842(b) and Notice 89-96, 1989-2 C.B. 417, for the general rules for computing this amount. Also, see Rev. Proc. 2004-55, 2004-34 I.R.B. 343, for the domestic asset/liability percentages and domestic investment yields needed to compute this amount. Any additional income required by section 842(b) must be included in taxable income (e.g., Schedule A, line 13)..: • At least 60% of it’s adjusted ordinary gross income for the tax year is PHC income and • At any time during the last half of the tax year more than 50% in value of its outstanding stock is directly or indirectly owned by five or fewer individuals. See Schedule PH (Form 1120), U.S. Personal Holding Company Tax, for definitions and details on how to figure the tax. A foreign PHC (defined in section 552) must file Form 5471. Exemption for small corporation. A corporation is treated as a small corporation exempt from the AMT for its tax year beginning in 2004 2004 did not exceed $7.5 million ($5 million if the corporation had only 1 prior tax year). Line 8a. Foreign tax credit. To find out when a corporation can take the credit for payment of income tax to a foreign country or U.S. possession, see Form 1118, Foreign Tax Credit — Corporations. Line 8b. Other Credits Include any other credits on line 8b. On the dotted line to the left of the entry space, write the amount of the credit and identify it. Possessions tax credit. The Small Business Job Protection Act of 1996 repealed the possessions credit. However, existing credit claimants may qualify for a credit under the transitional rules. 8b any credit from Form 8834, Qualified Electric Vehicle Credit. Line 12. Other Taxes Include any of the following taxes and interest in the total on line 12. Check the Instructions for Form 1120-PC -8-. Other. Additional taxes and interest amounts can be included in the total entered on line 12. certain nondealer installment obligations (section 453A(c)). • Interest due on deferred gain (section 1260(b)). • For tax years beginning after October 22, 2004, tax on notional shipping income. See Income from qualifying shipping activities on page 10. How to report. If the corporation checked the “Other” box, attach a schedule showing the computation of each item included in the total for line 12 and identify the applicable Code section and the type of tax or interest. Line 13. Total Tax Include any deferred tax on the termination of a section 1294 election applicable to shareholders in a qualified electing fund in the amount entered on line 13. See Form 8621, Part V, and How to report below. Instructions for Form 1120-PC Subtract any deferred tax on the corporation’s share of undistributed earnings of a qualified electing fund (see Form 8621, Part II). How to report. Attach a schedule. Section 847(8) requires that if a corporation carries back net operating losses or capital losses that arise in years after a year in which a section 847 deduction was claimed, then the corporation must recompute the tax benefit attributable to the previously claimed section 847 deduction taking into account the loss carrybacks. Tax benefits also include those derived from filing a consolidated return with another insurance company (without regard to section 1503(c)). Therefore, if the recomputation changes the amount of the section 847 tax benefit, then the taxpayer must provide a computation schedule and attach it to Form 8816. on page 7. Line 14i. Other credits and payments. Enter the amount of any other credits the corporation may take and/or payments made. Write to the left of the entry space, an explanation of the entry.. Total payments. Add the amounts on lines 14f through 14i and enter the total on line 14j. Line 15. 2004 or • Its prior year’s tax. See section 6655 for details and exceptions, including special rules for large corporations..) If Form 2220 is attached, check the box on line 15 and enter the amount of any penalty on that line. Line 18.—Taxable Income Gross income. Under section 832, gross amounts of underwriting and investment income should be computed on the basis of the underwriting and investment exhibit of the NAIC annual statement to the extent not inconsistent with the Internal Revenue Code and its Regulations. Extraterritorial income. Gross income generally does not include extraterritorial income that is qualifying foreign trade income. However, the extraterritorial income exclusion is reduced by 20% for transactions after 2004, unless made under a binding contract with an unrelated -9- person in effect on September 17, 2003, and at all times thereafter. Use Form 8873, Extraterritorial Income Exclusion, to figure the exclusion. Include the exclusion in the total for “Other deductions” on line 31. Income from qualifying shipping activities. For tax years beginning after October 22, 2004, the disposition of a qualifying vessel under section 1359. Report the section 1352(1) tax on page 1, line 4, and report the section 1352(2) tax on page 1, line 12. For page 1, line 12, check the “Other” box and attach a schedule that shows the computation of the section 1352(2) amount.: 1. Private activity bond which is not a qualified bond as defined by section 141; 2. Arbitrage bond as defined by section 148; or 3. above.: 1. Taxable income (computed without gains or losses from sales or exchanges of capital assets); or: 1. Mortgage guaranty insurance, must maintain a mortgage guaranty account; 2. Lease guaranty insurance, must maintain a lease guaranty account; and 3. schedule schedule. If the corporation has only one item of other income, describe it in parentheses on line 13. Examples of other income to report on line 13 are: 1. The amount of credit for alcohol used as fuel (determined without regard to the limitation based on tax) entered on Form 6478, Credit for Alcohol Used as Fuel. 2. Refunds of taxes deducted in prior years to the extent they reduced income subject to tax in the year deducted (see section 111). Do not offset current year taxes against tax refunds. 3. The amount of any deduction previously taken under section 179A that is subject to recapture. The corporation must recapture the benefit of any allowable deduction for clean-fuel vehicle property (or clean-fuel vehicle refueling property) if the property later ceases to qualify. See Regulations section 1.179A-1 for details. 4. Ordinary income from trade or business activities of a partnership (from Schedule K-1 (Form 1065 or Form 1065-B)). Do not offset ordinary losses against ordinary income. Instead, include the losses on line 31. Show the partnership’s name, address, and EIN on a separate statement attached to this return. If the amount entered is from more than one partnership, identify the amount from each partnership. Instructions for Form 1120-PC -10- Deductions Limitations on certain deductions.. For costs paid or incurred before October 23, 2004, the corporation must capitalize them unless it elects to amortize these costs over a period of 60 months or more. For costs paid or incurred after October 22, 2004, the following rules apply separately to each category of costs. • The corporation can details on the election for business start-up costs, see section 195 and attach the statement required by Regulations section 1.195-1(b). For more details on the election for organizational costs, see section 248 and attach the statement required by Regulations Instructions for Form 1120-PC section 1.248-1(c). Report the deductible amount of these costs and any amortization on line 31, Schedule A. For amortization that begins during the 2004 tax year, complete and attach Form 4562. Reducing certain expenses for which credits are allowable. For each credit listed below, the corporation must reduce the otherwise allowable deductions for expenses used to figure the credit by the amount of the current year credit. • Work opportunity credit. • Research credit. • Disabled access credit. • Enhanced oil recovery credit. • Empowerment zone and renewal community employment credit. • Indian employment credit. • Welfare-to-work credit. • Credit for small employer pension plan startup costs. • Credit for employer-provided childcare facilities and services. • New York Liberty Zone business employee credit. • Low sulfur diesel fuel production credit. If the corporation has any of these credits, figure each current year credit before figuring the deduction for expenses on which the credit is based. Line 15. Compensation of officers. Enter deductible officers’ compensation on line 15. 15. (See Disallowance of deduction for employee compensation in excess of $1 million, below.) Attach a schedule for all officers using the following columns: 1. Name of officer. 2. Social security number. 3. Percentage of time devoted to business. 4.. • Commissions based on individual The deduction limit does not apply to: performance,. Line 16. Salaries and wages. Enter the total salaries and wages paid for the tax year, reduced by the amount claimed on: • Form 5884, Work Opportunity Credit, line 2, • Form 8844, Empowerment Zone and Renewal Community Employment Credit, line 2, • Form 8845, Indian Employment Credit, line 4, • Form 8861, Welfare-to-Work Credit, line 2, and • Form 8884, New York Liberty Zone Business Employee Credit, line 2. Do not include salaries and wages deductible elsewhere on the return, such as elective contributions to a section 401(k) cash or deferred arrangement or amounts contributed under a salary reduction SEP agreement or a SIMPLE IRA plan. If the corporation provided taxable fringe benefits to its employees, CAUTION such as the personal use of a car, do not deduct as wages the amount allocated for depreciation and other expenses that are claimed elsewhere on the return (e.g., Schedule A, line 22 or line 31). ! Line 18. the vehicle lease expense may have to be reduced by an amount called the inclusion amount. The corporation may have an inclusion amount if: -11- The lease term began: And the vehicle’s FMV on the first day of the lease exceeded: After 12/31/03 and before 1/1/05 . . $17,500 After 12/31/02 and before 1/1/04 . . $18,000 After 12/31/98 but before 1/1/03 . . $15,500 If the lease term began before January 1, 1999, see Pub. 463, Travel, Entertainment, Gift, and Car Expenses, to find out if the corporation has an inclusion amount. The inclusion amount for lease terms beginning in 2005 will be published in the Internal Revenue Bulletin in early 2005. See Pub. 463 for instructions on figuring the inclusion amount. Line 19.. See section 164(d) for the apportionment of taxes on real property between a seller and a purchaser. Line 20a. Interest. Note. Do not offset interest income against interest expense.: • Interest on indebtedness incurred or continued to purchase or carry obligations if the interest is wholly exempt from income tax. For exceptions, see section 265(b). • Interest and carrying charges on straddles. Generally, these amounts must be capitalized. See section 263(g). • section 1.263A-8 through 1.263A-15 for definitions and more information. •: • Interest on which no tax is imposed (see section 163(j)). • Foregone interest on certain below-market-rate loans (see section 7872). • Original issue discount on certain high-yield discount obligations. (See section 163(e) to figure the disqualified portion.) • Interest which is allocable to unborrowed policy cash values of life insurance, endowment, or annuity contracts issued after June 8, 1997. See section 264(f). Attach a statement showing the computation of the deduction. Line 20b. Less tax-exempt interest expense. Enter interest paid or accrued during the tax year on indebtedness incurred or continued to purchase or carry obligations if the interest is wholly exempt from income tax. For exceptions, see section 265(b). Line 21. Charitable contributions. Enter contributions or gifts actually paid within the tax year to or for the use of charitable and governmental organizations described in section 170(c) and any unused contributions carried over from prior years. Corporations reporting taxable income on the accrual method can be more than 10% of taxable income (line 37, Schedule A) computed without regard to the following. • Any deduction for contributions. • The deduction for dividends received. • Any net operating loss (NOL) carryback to the tax year under section 172. • Any capital loss carryback to the tax year under section 1212(a)(1). tax year, the 10% limit is applied using obtains, discussed below. For more information on charitable contributions, including substantiation and recordkeeping requirements, see section 170 and the related regulations and Pub. 526, Charitable Contributions. Contributions of property other than cash. If a corporation (other than a closely held or personal service corporation) contributes property other than cash and claims over a $500 deduction. Instructions for Form 1120-PC -12- included, show the amount and how it was determined. Contributions after June 3, 2004. For contributions of certain property made after June 3, 2004, a corporation must file Form 8283 and get a qualified appraisal if claiming a deduction of more than $5,000. Do not attach the appraisal to the tax return unless claiming a deduction of more than $500,000 or, for art, a deduction of $20,000 or more. See Form 8283. Contributions of used vehicles. Special rules apply to contributions after 2004 of used motor vehicles, boats, or airplanes with a claimed value of more than $500. See section 170(f)(12). Reduced deduction for contributions of certain property. For a charitable contribution of property, the corporation, • Contributions of any property to or for the use of certain private foundations except for stock for which market quotations are readily available (section 170(e)(5)), and • Any patent or certain other intellectual property contributed after June 3, 2004. See section 170(e)(1)(B). However, the corporation can deduct certain qualified donee income from this property. See section 170(m).. See section 170(e)(6). Line 22. Depreciation. Include on line 22 depreciation and the part of the cost that the corporation elected to expense under section 179 of certain property. See Form 4562 and its instructions. Line 23. Depletion. See sections 613 and 613A for percentage depletion rates applicable to natural deposits. Also, see Instructions for Form 1120-PC section 291 for the limitation on the depletion deduction for iron ore and coal (including lignite). for details. See Pub. 535 for more information on depletion.. Line: • Make special estimated tax payments equal to the tax benefit from the deduction and •: 1. Where the premium deposits for the policy are the same (regardless of the length of the policy) and schedule, listing by type and amount, all allowable deductions under sections 832(c)(1) and (10) (net of the annual statement change in undiscounted unpaid loss adjustment expenses) that are not deductible on lines 15 through 30. Examples of amounts to include are: • Certain business start-up and organizational costs that the corporation elects to deduct. See page 11. 13. Show the partnership’s name, address, and EIN on a separate statement attached to this return. If the amount -13- entered is from more than one partnership, identify the amount from each partnership. • Extraterritorial income exclusion (from Form 8873, line 52a or 52b). • Deduction for clean-fuel vehicle and certain refueling property (see Pub. 535). • Dividends paid in cash on stock held by an employee stock ownership plan. However, a deduction may only be taken if, according to the plan, the dividends are: a. Paid in cash directly to the plan participants or beneficiaries; b. Paid to the plan, which distributes them in cash to the plan participants or their beneficiaries no later than 90 days after the end of the plan year in which the dividends are paid; c. At the election of the participants or their beneficiaries; (i) payable as provided under a or b above or (ii) paid to the plan and reinvested in qualifying employer securities; or d. Used to make payments on a loan described in section 404(a)(9). See section 404(k) for more details and the limitation on certain dividends. CAUTION ! Do not deduct fines or penalties paid to a government for violating any law. cannot deduct an expense paid or incurred for use of a facility (such as a yacht or hunting lodge) for an activity usually considered entertainment, amusement, or recreation. Amounts treated as compensation. Generally, the corporation may be able to deduct otherwise nondeductible meals, travel, and entertainment deduction for otherwise nondeductible meals, travel, and entertainment expenses incurred after October 22, 2004, is limited to the amount treated as compensation. See section 274(e)(2). section 170(f)(9). For more information on lobbying expenses, see section 162(e). For more information on other deductions that may apply to corporations, see Pub. 535. Line schedule schedule showing the computation of the NOL deduction. Also complete item 12 on Schedule I. pre-acquisition losses that may offset Instructions for Form 1120-PC The following special rules apply. -14- recognized built-in gain may be limited (see section 384).). For details on the NOL deduction, see Pub. 542, section 172, section 844, and Form 1139, Corporation Application for Tentative Refund. Line 37. Taxable income. If line 37 (figured without regard to the rules discussed under Minimum taxable income, below) Schedule I, item 11, on page 19. See Form 1139 for details, including other elections that may be available, which must be made no later than 6 months after the due date (excluding extensions) of the corporation’s tax return. Minimum taxable income. The corporation’s taxable income cannot be less than the largest of the following amounts. • The amount of nondeductible CFC dividends under section 965. This amount is equal to the difference between line 10(b) and line 24(b) of Form 1120-PC, Schedule C. • The inversion gain of the corporation for the tax year, if the corporation is an expatriated entity or a partner in an expatriated entity. For details, see section 7874.. spent on foreclosed property before the property is held for rent. Line 11. Depreciation. Enter depreciation on assets only to the extent that the assets are used to produce gross investment income reported on lines 1 through 7 of Schedule B. schedule. Deductions Income Line 1a, column (a). Gross interest. Enter the gross amount of interest income including all tax-exempt interest income. Instructions for Form 1120-PC -15- means tax-exempt interest and dividends for which a deduction is allowable under section 243, 244, or 245 (other than 100% dividends). 100% dividend means any dividend if the percentage used for purposes of determining the deduction allowable under section 243, 244, or 245(b) is 100%. A special rule applies to certain dividends received by a foreign corporation. member of the affiliated group is made as if no consolidated return was filed. See section 832(g). Line 4. Enter dividends received on preferred stock of a less-than-20%-owned public utility that is subject to income tax and is allowed the deduction provided in section 247 for dividends paid. Line 5. Enter dividends received on preferred stock of a 20%-or-more-owned Lines 1 through 25: 1. All dividends (other than 100% dividends) received on stock acquired after August 7, 1986, and 2. 100% dividends received on stock acquired after August 7, 1986, to the extent that such dividends are attributable to prorated amounts (see definition above). In the case of an insurance company that files a consolidated return, the determination with respect to any dividend paid by a member to another public utility that is subject to income tax and is allowed the deduction provided in section 247 for dividends paid. Line 6. Enter the U.S.-source portion of dividends that: • Are received from less-than-20%-owned foreign corporations and • Qualify for the 70% deduction under section 245(a). To qualify for the 70% deduction, the corporation must own at least 10% of the foreign corporation by vote and value. Also include dividends received from a less-than-20%-owned foreign sales corporation (FSC) that: • Are attributable to income treated as effectively connected with the conduct of a trade or business within the United States (excluding foreign trade income) and • Qualify for the 70% deduction under section 245(c)(1)(B). Line 7. Enter the U.S.-source portion of dividends that: • Are received from 20%-or-more-owned foreign corporations and •. Enter dividends received from wholly owned foreign subsidiaries that are eligible for the 100% deduction under section 245(b). In general, the deduction under section 245(b) applies to dividends paid out of the earnings and profits of a foreign corporation for a tax year during which: • All of its outstanding stock is directly or indirectly owned by the domestic corporation receiving the dividends and •. Enter qualifying dividends from Form 8895. Instructions for Form 1120-PC -16- Line 11, column (b). Enter foreign dividends not reportable on lines 3, 6, 7, 8, column (b), and 10. Include on line 11 the corporation’s share of the ordinary earnings of a qualified electing fund from line 1c, Form 8621. Exclude distributions of amounts constructively taxed in the current year or in prior years under subpart F (sections 951 through 964). Line 12, column (b). Include income constructively received from controlled foreign corporations under subpart F. This amount should equal the total subpart F income reported on Schedule I of Form 5471. Line 13, column (b). Include gross-up for taxes deemed paid under sections 902 and 960. Line 14, column that, for the tax year of the trust in which the dividends are paid, qualifies under sections 856 through 860. 4. Dividends not eligible for a dividends-received deduction, which include the following. a... c. Dividends on any share of stock to the extent the corporation is under an obligation (including a short sale) to make related payments with respect to positions in substantially similar or related property. 5. Any other taxable dividend income not properly reported above (including distributions under section 936(h)(4)). Line 18. showing how the amount on line 18 was figured. Line 25, column (b). Generally, line 25, column (b), cannot exceed the amount from the worksheet below. However, in a year in which an NOL occurs, this limitation does not apply even if the loss is created by the dividends-received deduction. See sections 172(d) and 246(b). Schedule E—Premiums Earned Definitions Undiscounted unearned premiums means the unearned premiums shown in the annual statement filed for the year ending with or in the tax year. Applicable interest rate means the annual rate determined under section 846(c)(2) for the calendar year the premiums are received.. Line 1. Enter gross premiums written on insurance contracts during the tax year, less return premiums and premiums paid for reinsurance. See Regulations section 1.832-4. Lines 2a and 4a. Include on lines 2a and 4a: 1. All life insurance reserves, as defined in section 816(b) (but determined under section 807) and 2. All unearned premiums of a Blue Cross or Blue Shield organization to which section 833 applies.. Lines 2c and 4c. The amount of discounted unearned premiums at the end of any tax year must be the present value of those premiums (as of such time and separately with respect to premiums Worksheet for Schedule C, line 25 (keep for your records) 1. Refigure the amount from Schedule A, line 35 or Schedule B, line 19, whichever applies, without any adjustment under section 1059 and without any capital loss carryback to the tax year under section 1212(a)(1) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2. Enter the sum of the amounts from line 23, column (b) (without regard to wholly owned foreign subsidiary dividends) and line 9, column (b) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3. Subtract line 2 from line 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4. Multiply line 3 by 80% . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5. Add lines 17, 20, 22, and 23 (without regard to FSC dividends), column (b), and the portion of the deduction on line 18, column (b), that is attributable to dividends received from 20%-or-more-owned corporations . . . . . . . . . . . . . . . . . . . . . . 6. Enter the smaller of line 4 or line 5. If line 5 is greater than line 4, stop here; enter the amount from line 6 on line 25, column (b). Do not complete the rest of this worksheet . . . . . . . . . . . . . . . . . . 7. Enter the total amount of dividends received from 20%-or-more-owned corporations that are included on lines 2, 3, 5, 7, and 8 (without regard to FSC dividends), column (b) . . . . . 8. Subtract line 7 from line 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9. Multiply line 8 by 70% . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10. Subtract line 5 from line 25, column (b) (without regard to FSC dividends) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11. Enter the smaller of line 9 or line 10 . . . . . . . . . . . . . . . . . . . . . 12. Dividends-received deduction after limitation (section 246(b)). Add lines 6 and 11. Enter the result here and on line 25, column (b) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Instructions for Form 1120-PC -17- received in each calendar year) determined by using: 1. The amount of the undiscounted unearned premiums at such time; 2. The applicable interest rate; and 3.) for more information. Schedule F—Losses Incurred Line 1. Losses paid. Enter the total losses paid on insurance contracts during the tax year less salvage and reinsurance recovered during the tax year.. • Unpaid losses related to disability Special rules apply with respect to: insurance (other than credit disability insurance), • Noncancelable accident and health insurance, • Cancelable accident and health insurance, and • 2004 are published in Rev. Proc. 2004-69, 2004-49 I.R.B. 906. The applicable interest rates and loss payment pattern for 2002 and 2003 are published in Rev. Proc. 2003-17, 2003-6 I.R.B. 427, and Rev. Proc. 2004-9, 2004-2 I.R.B. 275, estimated salvage discount factors for 2003 are published in Rev. Proc. 2004-10, 2004-2 I.R.B. 288. The 2004 estimated salvage and reinsurance rates are published in Rev. Proc. 2004-70, 2004-49 I.R.B. 918. Instructions for Form 1120-PC -18- 1120) any sales reported on this schedule. Schedule H—Special Deduction and Ending Adjusted Surplus for Section 833 Organizations Line 5. Beginning adjusted surplus. If the corporation was a section 833 organization in 2003, it should enter the amount from Schedule H, line 10, of its 2003 Form 1120-PC. Generally, the adjusted surplus as of the beginning of any tax year is an amount equal to the adjusted surplus as of the beginning of the preceding tax year: 1. Increased by the amount of any adjusted taxable income for the preceding tax year or 2. Decreased by the amount of any adjusted net operating loss for the preceding tax year. If 2004 is the first tax year the taxpayer qualifies as a section 833 organization, see section 833(c)(3)(C) to determine the adjusted surplus as of the beginning of the 2004 tax year. For purposes of the computation of the adjusted surplus, the terms “adjusted taxable income” and “adjusted net operating loss” mean the taxable income or the net operating loss, respectively, determined with the following modifications: 1. Without regard to the deduction determined under section 833(b)(1); 2. Without regard to any carryover or carryback to that tax year; and 3. By increasing gross income by an amount equal to the net exempt income for the tax year. Line 6. Special deduction., and 245 by the amount of any decrease in deductions allowable for the Instructions for Form 1120-PC tax year because of section 832(b)(5)(B) when the decrease is caused by the deductions under sections 243, 244, and 245. Enter the result on line 8b. Schedule I—Other Information The following instructions apply to page 7, Form 1120-PC. Be sure to complete all of the items that apply to the corporation. Question 4 Check the “Yes” box if: • The corporation is a subsidiary in an affiliated group (defined below), but is not filing a consolidated return for the tax year with that group or • The corporation is a subsidiary in a parent-subsidiary controlled group (defined on page 6). Any corporation that meets either of the requirements above should check the “Yes” box. corporations.).: • A foreign citizen or nonresident alien. • An individual who is a citizen of a U.S. possession (but who is not a U.S. citizen or resident). • A foreign partnership. • A foreign corporation. • Any foreign estate or trust within the meaning of section 7701(a)(31). • A foreign government (or one of its agencies or instrumentalities) to the extent that corporation checked “Yes”, 10 Show any tax-exempt interest received or accrued. Include any exempt-interest dividends received as a shareholder in a mutual fund or other RIC. Item 11 If the corporation has an NOL for its 2004 tax year, it. See Pub. 542, section 172, and Form 1139 for more details. Corporations filing a consolidated return must also attach the statement required by Temporary Regulations section 1.1502-21T(b)(3)(i) or (ii). Question 6 Check the “Yes” box if one foreign person owned at least 25% of (a) the total voting power of all classes of stock of the corporation entitled to vote or (b) the total value of all classes of stock of the corporation. Item 12 Enter the amount of the NOL carryover to the tax year from prior years, even if -19- some of the loss is used to offset income on this return. The amount to enter is the total of all NOLs generated in prior years but not used to offset income (either as a carryback or carryover) to a tax year prior to 2004. Do not reduce the amount by any NOL deduction reported on Schedule A, line 36b. • The excess of additional pension liability over unrecognized prior service cost. • Guarantees of employee stock (ESOP) debt. • Compensation related to employee stock award plans. If the total adjustment to be entered on line 27 is a negative amount, enter the amount in parentheses. number . . . . . . . . . 97 hr., 48 min. Schedule L—Balance Sheets per Books Note. All insurance companies required to file Form 1120-PC must complete Schedule L. The balance sheet should agree with the corporation’s books and records. In the case of a consolidated return, report total consolidated assets, liabilities, and shareholder’s equity for all corporations joining in the return. See the discussion of consolidated returns on page 3 of these instructions. Line 1. Cash. Include certificates of deposit as cash on this line. Line 5. Tax-exempt securities. Include on this line: • State and local government obligations, the interest on which is excludable from gross income under section 103(a) and • Stock in a mutual fund or other RIC that distributed exempt-interest dividends during the tax year of the corporation. Line 18. Insurance liabilities. Include on this line: • Undiscounted unpaid losses. • Loss adjustment expenses. • Unearned premiums. See section 846 for more information. Line 27. Adjustments to shareholders’ equity. Some examples of adjustments to report on this line include: • Unrealized gains and losses on securities held “available for sale.” • Foreign currency translation adjustments. Schedule M-1— Reconciliation of Income (Loss) per Books With Income per Return Line 5c. Travel and entertainment. Include on line 5c any of the following. • Meals and entertainment expenses not deductible under section 274(n). • Expenses for the use of an entertainment facility. • The part of business gifts over $25. • Expenses of an individual over $2,000 which are allocable to conventions on cruise ships. • Employee achievement awards over $400. • The cost of entertainment tickets over RIC. Also report this same amount on Schedule I, item 10. Learning about the law or the form . . . . . . . . . . . . . . . . . 37 hr., 40 min. Preparing the form . . . . . . . Copying, assembling, and sending the form to the IRS 68 hr., 50 min. 8 hr., 2 2. -20- Instructions for Form 1120-PC Index A Accounting methods: Change in accounting method . . . . . . . . . . . . . . . . 4 Accounting periods . . . . . . . . . 4 Address Change . . . . . . . . . . . . 6 Adjustments to shareholders’ equity . . . . . . . . . . . . . . . . . . . 20 Affiliated group . . . . . . . . . . . . 19 Amended Return . . . . . . . . . . . 6 Assembling the return . . . . . . 4 B Backup withholding . . . . . . . . . 9 Business startup expenses . . . . . . . . . . . . . . . . 11 C Charitable contributions . . . . . . . . . . . . 12 Consolidated return . . . . . . . . . 3 Controlled group: Brother-sister . . . . . . . . . . . . . 6 Combined group . . . . . . . . . 6 Member of . . . . . . . . . . . . . . . 6 Parent-subsidiary . . . . . . . . . 6 D Deductions . . . . . . . . . . . . . . . . 11 Definitions: 100% dividend . . . . . . . . . . 16 Acquisition date . . . . . . . . . 15 Applicable interest rate . . . . . . . . . . . . . . . . . . . 17 Applicable statutory premium recognition pattern . . . . . . . . . . . . . . . . 17 Prorated amounts . . . . . . . 16 Undiscounted unearned premiums . . . . . . . . . . . . . 17 Depository method of tax payment: Deposits With Form 8109 . . . . . . . . . . . . . . . . . . . 5 Electronic deposit requirement: Depositing on time . . . . . 5 E Electronic deposit of tax refund of $1 million or more . . . . . . . . . . . . . . . . . . . . . 9 Electronic Federal Tax Payment System (EFTPS): Depositing on time . . . . . . . 5 Employer identification number . . . . . . . . . . . . . . . . . . . 6 Estimated tax payments . . . . . . . . . . . . . 5, 9 Estimated tax penalty . . . . . . . 9 Extension of time to file . . . . . 3 F Final Return . . . . . . . . . . . . . . . . 6 Foreign corporations . . . . . . . . 8 Foreign person . . . . . . . . . . . . 19 Foreign tax credit . . . . . . . . . . . 8 Forms and publications, how to get . . . . . . . . . . . . . . . . . . . . 2 G General business credit . . . . . 8 Golden parachute payments . . . . . . . . . . . . . . . 11 I Insurance liabilities . . . . . . . . 20 Interest: Late payment of tax . . . . . . 5 L Limitation on dividends-received deduction . . . . . . . . . . . . . . . 17 Limitations on deductions . . . . . . . . . . . . . . 11 Lobbying expenses . . . . . . . . 14 M Minimum tax: Alternative . . . . . . . . . . . . . . . . 8 Prior year, credit for . . . . . . 8 N NAIC annual statement . . . . . 4 Name Change . . . . . . . . . . . . . . 6 Net operating loss . . . . . . . . . 14 O Other deductions . . . . . . . . . . 13 Overpaid estimated tax . . . . . 5 Owner’s country . . . . . . . . . . . 19 P Paid preparer authorization . . . . . . . . . . . . . 3 Penalties: Estimated tax penalty . . . . . 9 Late filing of return . . . . . . . 5 Late payment of tax . . . . . . 5 Other penalties . . . . . . . . . . . 5 Trust fund recovery penalty . . . . . . . . . . . . . . . . . 5 Pension, profit-sharing, etc. plans . . . . . . . . . . . . . . . . . . . . 13 Period covered . . . . . . . . . . . . . 6 Personal holding company tax . . . . . . . . . . . . . . . . . . . . . . . 8 R Recordkeeping . . . . . . . . . . . . . 5 S Schedule: A......................... 9 B, Part I . . . . . . . . . . . . . . . . . 15 B, Part II . . . . . . . . . . . . . . . . 15 C . . . . . . . . . . . . . . . . . . . . . . . . 15 E . . . . . . . . . . . . . . . . . . . . . . . . 17 F . . . . . . . . . . . . . . . . . . . . . . . . 18 G . . . . . . . . . . . . . . . . . . . . . . . 18 H . . . . . . . . . . . . . . . . . . . . . . . . 19 I . . . . . . . . . . . . . . . . . . . . . . . . . 19 L . . . . . . . . . . . . . . . . . . . . . . . . 20 M-1 . . . . . . . . . . . . . . . . . . . . . 20 Section 953 Election . . . . . . . . 6 Special estimated tax payments: Prior year(s) special estimated tax payments to be applied . . . . . . . . . . . 9 Tax benefit rule . . . . . . . . . . . 9 Stock ownership in foreign corporations . . . . . . . . . . . . . . 4 T Tax and payments . . . . . . . . . . 6 Tax computation worksheet for members of a controlled group . . . . . . . . . . . . . . . . . . . . 7 Tax rate schedule . . . . . . . . . . 7 Tax-exempt securities . . . . . 20 Transactions between related taxpayers . . . . . . . . . . . . . . . 11 Transfers to a corporation controlled by the transferor . . . . . . . . . . . . . . . . . 4 Travel, meals, and entertainment . . . . . . . . . . . 14 U Unresolved tax issues . . . . . . 1 W When to file: Extension . . . . . . . . . . . . . . . . 2 Where to file . . . . . . . . . . . . . . . . 2 Who must file: Exceptions . . . . . . . . . . . . . . . 2 Life insurance companies . . . . . . . . . . . . . 2 Who must sign . . . . . . . . . . . . . 3 Worksheets: Members of a controlled group, tax computation . . . . . . . . . . . . 7 Schedule C . . . . . . . . . . . . . . 17 ■ Instructions for Form 1120-PC -21-
https://www.scribd.com/document/544248/US-Internal-Revenue-Service-i1120pc-2004
CC-MAIN-2018-47
refinedweb
10,074
57.77
Since the availability of the Solaris 10 Operating System in January 2005, its popularity (using the number of registered users as a yardstick) has exploded: As of August 2006, in excess of platform as a viable target for their software. This article explains why developers should make Solaris their primary development and deployment platform, and also explains how to develop software on the Solaris OS. This article assumes that C will be used as the programming language of choice, although much of the information is relevant to other high-level languages. The discussion is aimed at two kinds of people: The article also assumes the use of the Solaris 10 (or newer) release, although most of it is relevant to previous versions. CDDL. However, the most important reason for the popularity of the Solaris OS is arguably the vast wealth of features it offers. In no particular order, these include Solaris Zones (the ability to partition a machine into numerous virtual machines, each of which is isolated from the others), DTrace (a comprehensive dynamic tracing tool for investigating system behavior, safely on production machines), a new IP stack with vastly increased performance, and most recently, ZFS (a 128-bit, state-of-the-art file system, with end-to-end error checking and correction, a simple command-line interface, and virtually limitless storage capacity). stick to multiplatform OS, supporting both SPARC and x86 architectures (a community-driven port to Power is in the works, too). Although there was a hiccup and so on. Perhaps the most compelling reason to develop software on the Solaris OS is the wealth of professional-grade development tools available for it.), performance analyzers, and so on. The Sun Studio 11 suite is the product of choice for Solaris OS developers. Available as a free download from the developers.sun.com, Studio 11 software is a collection of professional-grade compilers and tools. It includes C, C++, and FORTRAN compilers, code analysis tools, an integrated development environment (IDE), the dbx source-level debugger, editors, and so on. dbx Other tools included with Studio 11 software are cscope (an interactive source browser), ctrace (a tool to generate a self-tracing version of our programs), cxref (a C program cross-referencer), dmake (for distributed parallel makes), and lint (the C program checker -- historically also known as a C program defluffer!). cscope ctrace cxref dmake lint Solaris Modular Debugger Guide and Solaris Performance and Tools by McDougall, Mauro, and Gregg (in Bibliography) for more information about mdb. gcc gdb mdb In the author's experience, most (if not all) of the time, the Sun Studio compiler produces better (that is, faster) code than that generated by gcc, so the Sun Studio compiler should be used if at all possible. To ensure our code is portable between compilers, we should test that it compiles cleanly at the maximum warning level with both gcc and Sun's compiler (the Sun Studio C compiler, cc), before using the latter for the final production build. (The author finds it disheartening that many supposedly portable open-source projects rely on "gccisms" and cannot be compiled with Sun's compiler without a fair amount of work. It is the author's opinion that the fact that gcc is available on many platforms is no excuse for such poor engineering.) cc Now that we've explored the reasons why we would choose Solaris as our primary development platform, let's explore how to actually go about doing so. To successfully build software using the Solaris OS, we must first ensure that all the tools we need are installed on our development machine. This means that when we install the Solaris OS, we must select at least the "Developer" metacluster. (The "Full" or "Full + OEM" metaclusters, being supersets of the Developer metacluster, will also work and are probably the best option for people new to the Solaris OS.) An optional (but highly recommended) step is to install the Sun Studio 11 compilers and tools. The next step is to make sure that our PATH is correctly set: /usr/ccs/bin is required for various tools (including the linker, ld, sccs, and make), and /usr/sfw/bin is required for gcc and its companion tools (this directory also contains numerous programs that are not directly related to development). If the Sun Studio tools are installed, their directory must also be in our PATH. By default, the Sun Studio tools are installed in /opt/SUNWspro/bin, so this directory (or wherever the Sun Studio tools were installed) must also be added to our PATH. /usr/ccs/bin ld sccs make /usr/sfw/bin /opt/SUNWspro/bin One problem that people new to the Solaris OS sometimes come across is the inclusion of /usr/ucb in their PATH. This directory contains programs that are used to provide compatibility for legacy SunOS 4.x applications and scripts. SunOS shipped with a C compiler, so /usr/ucb contains cc, which is a script that invokes the C compiler with command-line options suitable for generating programs that rely on BSD semantics and behavior. For modern applications, this is most likely not what we want, so it is important to make sure that /usr/ucb is after /usr/ccs/bin and /opt/SUNWspro/bin in our PATH (or perhaps even better, not in our PATH at all). /usr/ucb With the right software installed, and our PATH appropriately set, we're ready to start building programs. A program called make is used to build programs. It uses the concept of dependencies to determine which steps are required to produce the required results. For example, suppose our program consists of several C files, which we compile. All the files will be compiled and the resulting object files will be linked together. If we subsequently modify one of the source files, make will determine that only the modified file needs to be compiled, and will link the newly created object file with those from the previous build. The rules and dependencies used to build our program are described in a file called Makefile, which the make program uses to determine its actions. However, make is pretty smart and has a number of built-in rules which it uses, even if there is no Makefile. One of these built-in rules describes how to create an executable program from a C source file, a fact we take advantage of in the following examples. Makefile The file /usr/share/lib/make/make.rules contains the standard rules and definitions used by make, and contains entries for programs written in C, C++, FORTRAN, and Java, as well as some other languages. Some of the standard rules for programs written in C include: /usr/share/lib/make/make.rules .a .i Let's look at a few examples, using the simple counter program shown in the following: 1 #include <stdio.h> 2 int main () 3 { 4 int i; 5 for (i = 0; i < 10; i++) 6 printf ("i = %d\n", i); 7 return (0); 8 } Example: Building With Sun's Compiler and make Our first example runs Sun's make using the defaults: rich@marrakesh4098# make counter cc -o counter counter.c Example: Building With Sun's Compiler and gmake gmake The next example runs GNU's version of make, gmake, using the defaults: rich@marrakesh4100# gmake counter cc counter.c -o counter Notice that even though the arguments to cc are reversed, the end result is the same. A detailed look at make is beyond the scope of this article, but we should note that the default rules for make (and gmake) use the CC environment variable to determine the name of the compiler. If CC is unset, cc is used by default. (Interested readers are referred to the respective manual pages for more details about make, gmake, and Makefiles.) CC Makefiles Example: Building With gcc and make Our final example sets the CC variable before calling make: rich@marrakesh4103# CC=gcc make counter gcc -o counter counter.c Notice that this time, gcc is used to compile counter.c rather than cc (we can use a similar invocation with gmake if that is the build tool we want to use). counter.c Many programs, especially those that are more than moderate in size and complexity, link with libraries other than the default C library. These libraries either come with the Solaris OS, or are third-party libraries installed by the system administrator (be they commercially supplied, downloaded from places like Blastwave.org or Sunfreeware.com, or compiled locally). We link with these libraries, which are also called shared objects, by passing the name of the library to the compiler with the -l flag. For example, to link with libfoo.so, we would use -lfoo. This works fine for system libraries that are installed under /usr/lib, but what about other libraries? -l libfoo.so -lfoo /usr/lib The correct place for these libraries to be installed is a library-specific location under /opt, although many sites still adhere to the deprecated practice of storing them under /usr/local (see the filesystem(5) man page for more about this). However, "somewhere under /opt" leaves a lot of room for interpretation, so we need to tell the linker where to find the libraries we want our program to use. We do this by passing the -L flag to the linker. For example, -L/opt/local/lib would tell the linker to look for libraries in /opt/local/lib in addition to the default locations. /opt /usr/local filesystem -L -L/opt/local/lib /opt/local/lib The problem with -L is that it is only used when the program is linked. The loader needs to be able to find the libraries at runtime. The correct way to do this is to set the library run path, by passing the -R flag to the linker, using the same syntax as the -L flag. The incorrect way to do this is to set the LD_LIBRARY_PATH environment variable to the appropriate location. Unfortunately, a lot of software relies on this method of locating libraries. This problem is easily remedied for programs for which we have the source. We can simply edit the Makefile and rebuild it. For commercial applications, we must petition the vendor to build future versions of their programs correctly. -R LD_LIBRARY_PATH We should point out that there is one legitimate use of LD_LIBRARY_PATH: when we are developing a new version of a library. We can then use the environment variable to override the compiled-in run path. We can run our (correctly linked) programs with LD_LIBRARY_PATH unset, which will use the current version of the library, and then set it to our development area when we are ready to test the new version of the library. For the sake of emphasis, it is worth repeating that we should not set LD_LIBRARY_PATH in our session start-up scripts (for example, .profile or .login). If a program to which we do not have the source relies on LD_LIBRARY_PATH, we should write a wrapper script that sets it before invoking the desired program. .profile This article has described why developers (both commercial and open-source) should choose Solaris as their platform of choice, for both development and deployment. The reasons include: We also described how to build software on the Solaris platform, using both Sun Studio compilers and gcc. We described how to install the Solaris OS in a manner suitable for software development, and how to ensure that our PATH is set correctly. We briefly discussed make and gmake. And we ended with a discussion about shared objects (dynamically linked libraries), and how to avoid runtime problems by not using LD_LIBRARY_PATH (unless we are developing a new version of a library). The author's book, Solaris Systems Programming, published 2005, is considered essential for readers developing Solaris applications. Many books in the Solaris 10 Software Developer Collection are also worth reading or at least being aware of. McDougall, Richard; Mauro, Jim; and Gregg, Brendan. Solaris Performance and Tools, ISBN 0-13-156819-1. Prentice Hall PTR, 2007. Oram, Andrew, and Talbott, Steve. Managing Projects with make, ISBN 0-937175-90-0. Sebastopol, Calif.: O'Reilly and Associates, 1991. Solaris Modular Debugger Guide. Sun Microsystems, 2002. Teer, Rich. Solaris Systems Programming, ISBN 0-201-75039-2. Prentice Hall PTR, 2005. Rich Teer is an independent Solaris consultant who has been an active member of the Solaris community for more than 10 years. He is the author of the best-selling Sun Microsystems Press book, Solaris Systems Programming, and numerous Solaris OS-related articles. He was a member of the OpenSolaris pilot program and currently serves on the OpenSolaris Community Advisory Board (CAB). Rich lives in Kelowna, British Columbia, with his wife, Jenny. His web site can be found at.
http://developers.sun.com/solaris/articles/build_sw_on_solaris.html
crawl-001
refinedweb
2,146
59.64