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
mp has asked for the wisdom of the Perl Monks concerning the following question: In CPAN, is it possible for two different modules to ever share the same tar.gz file name but different authors? For example, there is a module: Text-Repository-1.04.tar.gz. It resides in $CPAN/authors/id/D/DA/DARREN/Text-Repository-1.04.tar.gz. Is it possible for a different Text-Repository-1.04.tar.gz to ever reside in some other author's directory and be a different module, or are there safeguards in place to prevent this? I did parse 02packages.details.txt.gz looking for cases where a file name appeared in multiple author directories, but the only one I could find where this had occurred was HTML-Summary-0.017.tar.gz A/AW/AWRIGLEY/HTML-Summary-0.017.tar.gz and T/TG/TGROSE/HTML-Summary-0.017.tar.gz PAUSE (The Perl Authors Upload Server, the backend part of CPAN) provides a mechanism to register your namespace, to prevent collisions, but this operates only on the namespace itself, the filename is not necessarily closely related to the namespace (such as the LWP modules being in a file called lib-www-perl). I don't believe there is anything that prevents the same filename from being used more than once however (other than the restriction that you can't upload a file with the same name into your own directory a second time, even if you delete the original). PAUSE accepted the upload, so there is nothing in place to prevent file names from being reused by a different author. PAUSE does prevent the same filename from being uploaded again by the same author. There is a reason the CPAN faq says that you should ask on the modules list before releasing anything to cpan. Abigail | | Yes No Results (63 votes). Check out past polls.
https://www.perlmonks.org/?node_id=243403
CC-MAIN-2022-21
refinedweb
318
54.52
If you’re on a Linux system, you can use the pyGTK library. It’s got a clipboard feature. Here’s how to use it (code thanks to Thomas Lee): import pygtk pygtk.require('2.0') import gtk # get the clipboard clipboard = gtk.clipboard_get() # read the clipboard text data. you can also read image and # rich text clipboard data with the # wait_for_image and wait_for_rich_text methods. text = clipboard.wait_for_text() # set the clipboard text data clipboard.set_text('Hello!') # make our data available to other applications clipboard.store() Here is the gtk.clipboard documentation. Another Alternative An alternative to the GTK library is the Xsel command line program. It should work for any Linux (or Unix?) with X. And this is how you would use it (at least according to these guys): #Copy from the clipboard: import os s = popen('xsel').read() #Paste to the clipboard: import os os.popen('xsel', 'wb').write(s) Posted by Greg Pinero (Primary Searcher) on Jul 20th, 2007 and is filed under Ubuntu. Both comments and pings are currently closed. Add this post to Del.icio.us - Digg pygtk should work without Gnome. xclip works too. FYI on OS X there are pbcopy and pbpaste command line programs. pbcopy pbpaste Thanks for the tips guys. I’ll update the post to say it will work without Gnome. © 2014, Blended Technologies LLC Entries (RSS) and Comments (RSS).
http://www.answermysearches.com/python-how-to-copy-and-paste-to-the-clipboard-in-linux/286/
CC-MAIN-2014-15
refinedweb
229
70.29
Writing Custom I/O Some programmers aren't big fans of overloading the standard operators for user-defined C++ classes. This includes writing custom inserters and extractors. However, many programmers prefer creating their own custom input/output operators. This introduction takes you through the steps of creating first a custom inserter (output) and then a custom extractor (input). Create the class Create your class without regards to the input or output. Include get and set functions for retrieving and setting individual values within an object. The following example is a Student class for use in this section. Here are the contents of the Student.h include file: class Student { public: explicit Student(const char* pszName = "", long id = 0, double gpa = 0.0); // the get and set functions for this class string getName() const; void setName(string& s); long getID() const; void setID(long nID); double getGPA() const; void setGPA(double dGPA); }; This code doesn't include the implementation of the get and set methods. Their details should not influence the creation of the inserter and extractor. The assumption above is that the set functions perform some type of checks to detect invalid input — for example, setGPA() should not allow you to set the grade point average to a value outside of the range 0.0 to 4.0. Create a simple inserter The inserter should output a Student object either for display or to a file. The following prototype would be added to the Student.h include file: ostream& operator<<(ostream& out, const Student& s); The inserter is declared with a return type of ostream& and returns the object passed to it. Otherwise, a command like the following would not work: cout << "My student is " << myStudent << endl; The object returned from << myStudent is used in the << endl that follows. The implementation of this inserter is straightforward (normally this would appear in the Student.cpp file): ostream& operator<<(ostream& out, const Student& s) { int prev = out.precision(2); out << s.getName() << " (" << s.getID() << ")" << "/" << s.getGPA(); return out; } Try it out and make adjustments So let's see how this inserter works: // CustomIO - develop a custom inserter and extractor #include <cstdlib> #include <cstdio> #include <iostream> #include "student.h" using namespace std; int main(int argc, char* pArgs[]) { Student s1("Davis", 123456, 3.5); cout << s1 << endl; Student s2("Eddins", 1, 3); cout << s2 << endl; cout << "Press Enter to continue..." << endl; cin.ignore(10, '\n'); cin.get(); return 0; } This generates the following output: Davis (123456) /3.5 Eddins (1) /3 If this is okay, then you're done. However, for professional applications, you probably want to implement a few output rules like the following (these are just examples): *A school at which student IDs are six digits in length. If the number is less than a full six digits, then the number should be padded on the left with zeros. *Grade point averages are normally displayed with two digits after the decimal point. Fortunately there are controls that implement these features. However, be a little careful before adjusting output formatting. For example, suppose the inserter you wanted to output an integer parameter is in hexadecimal format. Users of the inserter would be quite surprised if all subsequent output appeared in hex rather than decimal. Therefore it's important to record what the previous settings are and restore them before returning from our inserter. One version of the gussied up inserter appears as follows: ostream& operator<<(ostream& out, const Student& s) { out << s.getName() << " ("; // force the id to be a six digit field char prevFill = out.fill('0'); out.width(6); out << s.getID(); out.fill(prevFill); // now output the rest of the Student int prevPrec = out.precision(3); ios_base::fmtflags prev=out.setf(ios_base::showpoint); out << ")" << "/" << s.getGPA(); out.precision(prevPrec); out.setf(prev); return out; } You can see that the inserter outputs the student's name just as before. However, before outputting the student's ID, it sets the field width to six characters and sets the left fill character to 0. The field width applies to only the very next output so it's important to set this value immediately before the field you want to impact. Because it lasts for only one field, it is not necessary to record and restore the field width. Once the field has been output, the fill character is restored to whatever it was before. Similarly the precision is set to three digits and the decimal point is forced on before displaying the grade point average. This forces a 3 to display as 3.00. The resulting output appears as follows: Davis (123456)/3.50 Eddins (000001)/3.00 The extractor The job of creating the extractor actually starts with the inserter. Notice that in creating the output format for my Student object, the programmer added certain special markings that would allow an extractor to make sure that what it's reading is actually a Student. For example, she included parentheses around the student ID and a slash between it and the GPA. My extractor can read these fields to make sure that it's staying in sync with the data stream. In overview, the extractor will need to accomplish the following tasks: *Read the name (a character string). *Read an open parenthesis. *Read an ID (an integer). *Read a closed parenthesis. *Read a slash. *Read the GPA (a floating point number). It will need to do this while all the time being aware of whether a formatting problem occurs. What follows is my version of the Student extractor: istream& operator>>(istream& in, Student& s) { // read values (ignore extra white space) string name; long nID; double dGPA; char openParen = 0, closedParen = 0, slash = 0; ios_base::fmtflags prev = in.setf(ios_base::skipws); in >> name >> openParen >> nID >> closedParen >> slash >> dGPA; in.setf(prev); // if the markers don't match... if (openParen!='(' || closedParen!=')' || slash!='/') { // ...then this isn't a legal Student in.setstate(ios_base::failbit); return in; } // try to set the student values try { s.setName(name); s.setID(nID); s.setGPA(dGPA); } catch (...) { // something's not right - flag the failure in.setstate(ios_base::failbit); throw; } return in; } This inserter starts by reading each of the expected fields as previously outlined in the flow chart. If any of the marker characters is missing (the open parenthesis, closed parenthesis, and slash), then this is not a legal Student object. The approved way to indicate such a failure is set the failbit in the input object. This will stop all further input until the failure is cleared. The next step is to actually attempt to store these values into the Student. For example, all of the markers may have been present, but the value read for the grade point average may have been 8.0, a value that is clearly out of our predefined range of 0 through 4.0. Assuming that the Student object includes checks for out-of-range values in its set methods, the call to setGPA() will throw an exception which is caught in the extractor. Again, the extractor sets the failbit. Whether the extractor rethrows the exception is up to the programmer. It's much better to rely on the setGPA() method to detect the range problem than to implement such a check in the extractor itself. Better to let the Student object protect its own state than to rely on external functions. Use these new methods The following (very) simple CustomIO program shows how these inserter and extractor methods are used. This example along with the custom Student inserter and extractor are available at Dummies.com: int main(int argc, char* pArgs[]) { Student s1("Davis", 123456, 3.5); cout << s1 << endl; Student s2("Eddins", 1, 3); cout << s2 << endl; cout << "Input a student object:"; cin >> s1; if (cin.fail()) { cout << "Error reading student " << endl; cin.clear(); } else { cout << "Read: " << s1 << endl; } cout << "Press Enter to continue..." << endl; cin.ignore(10, '\n'); cin.get(); return 0; } The output from this program (when provided a legal student as input appears as follows: Davis (123456)/3.50 Eddins (000001)/3.00 Input a student object:Laskowski (234567)/3.75 Read: Laskowski (234567)/3.75 Press Enter to continue... Notice that the Davis student displays just as we wanted: the student id is surrounding by parentheses and the grade point average appears with two digits after the decimal point. This latter is true even for the somewhat problematic Eddins student. The Laskowski student is accepted as input because it has all of the proper marks of a valid student: parentheses and slashes in all the right places. Check out what happens if we leave something off, however: Input a student object:Laskowski 234567/3.75 Error reading student This small program shows two very important habits that you should develop: Check the fail flag by calling fail() after every input. Clear the fail flag as soon as you've acknowledged the failure by calling clear(). ALL subsequent requests for input will be ignored until you've cleared the fail flag.
http://www.dummies.com/how-to/content/writing-custom-io.html
CC-MAIN-2016-07
refinedweb
1,503
65.42
A. How useful/cumbersome is the following trick of using the same function for getter as well as setter, by returning a reference? B. How good is the practice of adding const to the end of function declarations in case of getters and setters? #include <iostream> class A { int varReadWrite_; int varReadOnly_; int varRestricted_; public: A() : varReadOnly_(25) {} virtual ~A() {} int& varReadWrite() { return varReadWrite_; } int varReadOnly() { return varReadOnly_; } int varRestricted() { return varRestricted_; } void setVarRestricted(int i); //throwable }; int main(int argc, char *argv[]) { A a; a.varReadWrite() = 45; std::cout << a.varReadOnly() << a.varReadWrite() << std::endl; return 0; } class A { int mA; public: int& a; A(int a_ = 0) : mA(a_), a(mA) {} }; The implicitly-declared or defaulted copy constructor for class T is defined as deleted if... T has non-static data members that cannot be copied (have deleted, inaccessible, or ambiguous copy constructors); A. How useful/cumbersome is the following trick of using the same function for getter as well as setter, by returning a reference? Returning a reference to your internal members in general is not recommended since this way you give an easy access to others so they could change your object internal state without using any method provided by the object's class API. Thus, it will be very difficult to track this kind of changes in the code. In general changes in the internal state of an object should only be possible through methods that belongs to the class API. B. How good is the practice of adding const to the end of function declarations in case of getters and setters? if you refer to adding const for methods like: void PrintState() const Then in general this doesn't make sense for setters. Const in this case means This method doesn't change the object state. So it's a commitment that you give to the caller to say: I will not change the object state by this call. In general it's very good practice since it helps you during the design to think about your methods and see which one is really modifying the object state or not. Additionally, it's a defensive programming since it's recursive: if you pass this object to some method by reference (through a pointer or reference) he can't call const methods unless this method is marked as const also. So this prevents from changing the object state by error.
https://codedump.io/share/8c4gw8xl8tkR/1/reference-return-for-setter
CC-MAIN-2017-30
refinedweb
405
57.1
Suppose you wrote some C# code like this: var str1 = "ThisIsAString"; var str2 = "ThisIsAnotherString"; As you’d expect, each string is stored in the resulting built binary and also in memory when the binary is loaded, resulting in 2 separate strings. Now suppose you wrote this code instead: var str1 = "ThisIsAString"; var str2 = "ThisIsAString"; The strings are identical: would there be a copy of each? How do we find out? Here’s one way to find out: Start VS 2010 File->New->Project->C#-> Windows Console Application. Paste in the code sample below. Hit F11 to step into the program, then Ctrl-F11 (or right-click->Go to disassembly) to see the code being executed. Open a couple windows Debug->Windows->Registers Debug->Windows->Memory 1 Right click the memory window and choose to show the memory contents as 4 byte integers. Step to the line indicated (after register eax has been set to the string’s address). Then drag the EAX value (0x023c96e4 in my sample) to the Memory window. You can actually see (and optionally change!) the string “ThisIsAString” in memory as Unicode, with every other byte being 0. System.String is a CLR Class. For every CLR class, the first integer is the ClassId: so System.String has a ClassId = 51acfb08 in this process. The ClassId could be different when you restart the process. The next integer (0x0000000d = 13) is the length of the string (13 Unicode bytes). Following that, you can see the “ThisIsAString” in memory. So now you know how to examine the code that gets executed when handling strings. The variable “str2” is assigned the same string value. Is that value stored twice in memory? From the assembly code, we see that register EAX is set to the same value (03392088h) for “str2” as “str1”, so we know the two identical strings have been coalesced. Another way to see the code: open a Visual Studio Command Prompt and use ILDasm: Ildasm “C:\Users\calvinh\AppData\Local\Temporary Projects\ConsoleApplication1\bin\Debug\ConsoleApplication1.exe” Exercises: 1. Try running this with Project->Properties->Build->Platform Target x64 2. Try using a Release build, rather than Debug (the default) <Code> using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; using System.Reflection; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { var str1 = "ThisIsAString"; var str2 = "ThisIsAString"; // 2nd copy to see compiler coalesce var str3 = ""; var str4 = new String('a', 0); var str5 = "" + ""; var str6 = "This" + "IsAString"; } } } </Code>
https://blogs.msdn.microsoft.com/calvin_hsia/2012/07/19/examine-the-layout-of-managed-strings-in-memory/
CC-MAIN-2017-17
refinedweb
417
58.58
use Opcode; authors shall not in any case be liable for special, incidental, consequential, indirect or other similar damages arising from the use of this software. Your mileage will vary. If in any doubt do not use it. The opset and opset_to_ops functions can be used to convert from a list of operators to an opset and vice versa. Wherever a list of operators can be given you can use one or more opsets. See also Manipulating Opsets below. In a list context it returns a list of all the operator names. (Not yet implemented, use @names = opset_to_ops(full_opset).) Most of the other Opcode functions call verify_opset automatically and will croak if given an invalid opset.. It's designed to be used as a handy command line utility: perl -MOpcode=opdump -e opdump perl -MOpcode=opdump -e 'opdump Eval' eqiv aslice av2arylen rv2hv helem hslice each values keys exists delete quotemeta trans chop schop chomp schomp match split qr list lslice splice push pop shift unshift reverse concat repeat join range anonlist anonhash Note that despite the existance. custom -- where should this go atan2 sin cos exp log sqrt These ops are not included in :base_core because they have an effect beyond the scope of the compartment. rand srand lock threadsv :base_core :base_mem :base_loop :base_io :base_orig :base_thread?) SystemV Interprocess Communications: msgctl msgget msgrcv msgsnd semctl semget semop shmctl shmget shmread shmwrite entereval -- can be used to hide code from initial compile require dofile caller -- get info about calling environment and args reset dbstate -- perl -d version of nextstate(ment) opcode syscall dump chroot Safe(3) --- Opcode and namespace limited execution compartments Split out from Safe module version 1, named opcode tags and other changes added by Tim Bunce.
http://www.linuxmanpages.com/man3/Opcode.3.php
crawl-003
refinedweb
288
57.91
Deletes a queue. Code sample Java To learn how to install and use the client library for Cloud Tasks, see Cloud Tasks client libraries. import com.google.cloud.tasks.v2.CloudTasksClient; import com.google.cloud.tasks.v2.QueueName; import java.io.IOException; public class DeleteQueue { public static void main(String[] args) throws IOException { // TODO(developer): Replace these variables before running the sample. String projectId = "my-project-id"; String locationId = "us-central1"; String queueId = "my-queue"; deleteQueue(projectId, locationId, queueId); } // Delete a queue using the Cloud Tasks client. public static void deleteQueue(String projectId, String locationId, String queueId) throws IOException { // Instantiates a client. try (CloudTasksClient client = CloudTasksClient.create()) { // Construct the fully qualified queue path. String queuePath = QueueName.of(projectId, locationId, queueId).toString(); // Send delete queue request. client.deleteQueue(queuePath); System.out.println("Queue deleted: " + queueId); } } } Node.js To learn how to install and use the client library for Cloud Tasks, see Cloud Tasks client libraries. // Imports the Google Cloud Tasks library. const cloudTasks = require('@google-cloud/tasks'); // Instantiates a client. const client = new cloudTasks.CloudTasksClient(); async function deleteQueue() { // Get the fully qualified path to the queue const name = client.queuePath(project, location, queue); // Send delete queue request. await client.deleteQueue({name}); console.log(`Deleted queue '${queue}'.`); } deleteQueue(); Python To learn how to install and use the client library for Cloud Tasks, see Cloud Tasks client libraries. def delete_queue(project, queue_name, location): """Delete a task queue.""" from google.cloud import tasks_v2 # Create a client. client = tasks_v2.CloudTasksClient() # Get the fully qualified path to queue. queue = client.queue_path(project, location, queue_name) # Use the client to delete the queue. client.delete_queue(request={"name": queue}) print("Deleted queue") What's next To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.
https://cloud.google.com/tasks/docs/samples/cloud-tasks-delete-queue?hl=he&skip_cache=true
CC-MAIN-2022-05
refinedweb
293
53.58
On Dec 18, 2007 5:32 AM, Troy A. Griffitts <scribe at crosswire.org>. We would all have to agree on an interface > though, so I'd appreciate hearing from other frontend developers on the > proposed functionality and interface.. Agreed. > Are we planning to handle any type of key lists with this interface? > e.g., both Verse and GenBook references? We could do this in a later edition. My problem with having this is that I do not see as much use for it. The main difference between the two (as I see it) is that a GenBook key is module specific, while a passage can be used with any Bible. While it is possible that you may want to link to relevant commentary, dictionary or genbook entries for a particular topic, it doesn't strike me as quite so compelling. Another potential difference between a passage and a GenBook entry is that a passage will typically have a comparatively small body of text, while an entry has a potentially unbounded body of text, which may affect how the verse list is displayed (for example, think about the typical search results dialog for verses - verses can be previewed well, whole chapters present more difficulty, and a typical entry from the ISBE would contain far too much text to display). > We also try to keep the std namespace out of the public interfaces the > best we can. It makes bindings easier to implement, thus, where the > interface methods accept std::string, they should accept const char * or > SWBuf if they are intentionally non-const. Fair enough. > think that the ideas give fundamentally different ways of organising information, in the same way as tags and folders are a different way of organising information. My proposal has always been about tagging at the user level. Passage lists are only a convenient vehicle for implementing tagging.. > I realize this doesn't map directly to the purpose that Jonathan > intended. I don't know if there is an easy delineation to give us > multiple uses. I cannot think of a straightforward way to integrate too many different ideas, which is why I try to propose a problem and find a solution that solves that problem well. In a nutshell, my solution is intended to provide an efficient way of creating and managing a potentially entire Bible network of topics and associations, and then displaying these associations while browsing the Bible. Most conventional UIs will break down under this (especially hierarchically based ones). I would prefer to have a unified Sword standard, but it may be easier for me to implement it first in BPBible/Python to show exactly what my problem is and how I plan to solve it, then open it up for discussion again. Jon
http://www.crosswire.org/pipermail/sword-devel/2007-December/026486.html
CC-MAIN-2014-52
refinedweb
462
58.11
#3 — How PWAs works and how I implemented it with React and Webpack More technical details about PWAs, Service Workers, React and Webpack This article is part of the PWAs learning month of my Learning Lab challenge. I will explain more about PWAs, what is the lifecycle of a Service Worker, how to debug it and measure performance, and also how I implemented it with React and Webpack for my project Kanbanote. If you don’t know what is a PWA I invite you to read this article: Advanced information about PWAs and Service Workers PWAs are made of lot of pure-engineering optimisations “Amazon’s calculated that a page load slowdown of just one second could cost it $1.6 billion in sales each year.” Time is money, that is why there are a lot of optimisations in the world of web and around PWA. Those optimisations include different techniques such as: - Asynchronous rendering - Minification — Concatenation of all your files together - Route based code splitting which separates the Single Page App (SPA) in different bundle which you load separately - Use of the different caches (see Caching strategies below) - Reducing the size of images (and even having every image in different sizes for different devices) - Compression of the files - Use of HTTP/2 - Managing your files priorities with the Preload, Prefetch, Async, Defer proprieties If you are interested about this performance topic I invite you to read these two articles and check this Web launch checklist - Twitter Lite and High Performance React Progressive Web Apps at Scale — - Preload, Prefetch and priorities in Chrome — - Web launch checklist — Lifecycle of Service Workers A service worker is a script that runs in background of your browser separated from your website. You can use this script to cache files, send push notification or do other background task like updating your page for example. Before starting developing it’s important to understand well the lifecycle of a Service Worker. Check as reference this simplified graph of the Lifecycle of Service Workers from Google Developers and below I will explain what happens at each step: Installing: In order to install the Service Worker you need to register it in your page like this. if ('serviceWorker' in navigator) { navigator.serviceWorker .register('./service-worker.js') .then(function() { console.log('Service Worker Registered'); }); } The browser will then start to install it and then downloads the statics assets you specified. If it fails downloading them all the installation fails and the Service Worker will not activate. Activated: Then the activation event is triggered where you can handle your previous cache, delete it for example. Each Service Worker has a defined scope (the route of the website, for example “/” will give the access to the whole site) where it can act. The Service Worker will not do anything until you open another page or reload this page. Fetch/Message: Then the fetch event will be triggered to be able to answer to the networks requests. Here is how a simplified Service Worker looks like. var cacheName = 'sw-version-1'; // the cache version var filesToCache = [ '/', // files you need to cache (can be anything), never cache the SW itself, ]; self.addEventListener('install', function(e) { console.log('[ServiceWorker] Install'); e.waitUntil( caches.open(cacheName).then(function(cache) { console.log('[ServiceWorker] Caching app shell'); return cache.addAll(filesToCache); }) ); });(); }); self.addEventListener('fetch', function(e) { console.log('[ServiceWorker] Fetch', e.request.url); e.respondWith( caches.match(e.request).then(function(response) { return response || fetch(e.request); }) ); }); I you want to know more about the lifecycle of Service Workers here are two very good links: - Service Workers: an Introduction — - The Service Worker Lifecycle — Caching strategies The caching strategy is how you will use the cache, when to update it, and when to get the data from your network. There are different strategies such as: - Cache only — Only using the cache and always - Cache and network at the same time — So we get the fastest response - Cache, falling back to network — It’s an offline first strategy, you first get the data from the cache and if it doesn’t work you get them from the network - Network, failing back to cache — We first try to get data from the network and if it fails we load them from the cache - Cache then network — We first use the data from the cache and then update them using the network I invite you to check this two websites to know more about all the caching strategies and how to implement them : - The offline cookbook — - ServiceWorker Cookbook — How to debug In order to debug there are two tools in Chrome, the first is the application Tab of Chrome developer tool. You have a “Service Workers” section, a section for “Manifest” and a section for all the storage. The Cache storage contains the assets cached by the Service Workers. In the Service Workers section you have different options very useful as “offline” or “update on reload” that I recommend you to use when you start. The second to see all the SW installed in chrome just open a tab and open this “chrome://serviceworker-internals/” How to mesure performance Google Lighthouse is the tool to measure the performance of a website, its responsiveness and also its progressive web apps capabilities. It gives you a score of your website and tells you what to improve. You can install it as a Chrome extension or even a command line tool. Limitations of Service Workers The first and most important limitation of Service Workers is the compatibility, a lot of browsers are not supporting it yet. You can check at anytime the current compatibility here: As you can see, it’s not working in iOS devices yet. It’s more an android thing, indeed it’s google pushing toward that! And very recently Apple refused to support PWAs, read more about this here: When creating your Service Worker you will define required and optional files to cache, if the required files to cache fail, the Service Worker won’t install. Be careful. How to apply it to your own project - Define what needs to be display immediately. - Define what are the key UI component. - Define what are the resources related (script, images) that you will need in the cache. - Define what is the data to cache (javascript objects), and select a storage. You can use Localstorage or IndexedDB (in the article they use Localstorage, they recommend to use the library Localforage to use easily IndexedDB as you would use Localstorage). - Define a caching strategy. - Implement it using sw-precache, a library to generate your Service Workers recommended by Google Chrome (and made by them). Let’s implement it for Kanbanote Now that we all know what are the PWAs and how to create a Service Worker, let’s see how I implemented it for Kanbanote. Kanbanote is a service that I created that turns your Evernote as a Kanban board. Before creating Service Worker, and manifest file I had to make it work fully for mobile and define what are the PWA features I need. As I describe in the preparation phase, I need to: - Implement the drag’n’drop for touch. - Use a Service Worker to cache the javascript and style files of the Single Page App. - Use IndexedDB or Local storage to cache the data to make the loading feel faster (and see the previous data before loading the data from Evernote). For this reason I want a cache first strategy. At the time I wrote this article, Kanbanote 2 is in production and Kanbanote 3 only available in beta. You can see below how they are in term of look. Kanbanote 2 was made of a backend in PHP, still used for Kanbanote 3, and a frontend built in angularJS. I didn’t use any dependency management tool, so I was loading them myself. To be honest my level of coding was low, so it was my code quality. Let’s see now how I evolved in Kanbanote 3. Kanbanote 3 technologies stack In order to implement this PWA features it’s important to understand Kanbanote’s stack and the limitation of it. Kanbanote is using a backend made with PHP (using different modules and not a big framework). This backend has two roles. First, to handle the authentication with Evernote, once authenticated, it renders a page containing the Single Page App (SPA). The second part of the backend is just an API that is used by the SPA. Kanbanote’s frontend is a SPA made with React, Redux, and bundled with Webpack. As you can imagine I had to redevelop the whole frontend part. Moreover I use Circle CI to build, test and put in production easily. If you are not familiar with those technologies I invite you to have a look on: - React — A Javascript library to build interfaces, the official React website - A cartoon intro to redux, an article which explains well what is redux - Webpack, the official website, which explains very well what it does Also I used the Yeoman (a command line generating tool) generator fountain JS. It gave me gulp, webpack, sass, and react scaffolded, and also gave me a great command line too. The limitations Because I am using webpack, in order to escape the HTTP cache, the js and css files changes names everytime we build the project. That is why it’s impossible to specify the file names in the Service Worker. I then started to search how to solve this issue and I found the library Offline-plugin to generate a Service Worker for a project bundled with webpack. Moreover, since I am using React with Redux, I looked for a library to save the whole state instead of caching manually. Also, I found a solution in the same article about React and PWA that I recommend. This library is called Redux-persist. How to create the manifest.json The manifest.json that contains the data to display in the splash-screen can be made easily. In order not to have any syntax issue I recommend the following very good generator. Web App Manifests are one of the key pieces to making your web app look and feel like a native app. Learn more While…tomitm.github.io You just have to fill the form, copy the “manifest.json”, paste it in a file called “manifest.json” and copy the content of <head> in the <head> of your main html file. And that’s it! Then you can debug it in Chrome developer tools. Also try to add Kanbanote to your homescreen in Chrome mobile and you will be able to see the splashscreen. How to create the Service Worker for Webpack with Offline-plugin Offline-plugin is very easy to use. First, start adding it as a dependency in your project. npm install offline-plugin --save-dev Second, add it in the plugins part of the webpack config file. const OfflinePlugin = require('offline-plugin'); module.exports = { module: { // ... plugins: [ // ... new OfflinePlugin() ] // ... } } Finally, add the runtime in your main javascript entry file. import * as OfflinePluginRuntime from 'offline-plugin/runtime'; OfflinePluginRuntime.install(); And that’s it! Actually that wasn’t it 😅, I had a lot of problems due to the structure of my folders: - I have a folder “/public” containing my “index.php” which is served - Every time I build my project I put the whole bundle in “/public/assets”. This folder contains the “index.html” of the SPA and the app-*.js, vendor-*.js, and everything else - I had to set my public path to /assets - For some reason the manifest.json does not work if it’s not in the same folder as the sw.js (the Service Worker file generated), I had to move it to the root of the project every time I build the project using a gulp script. - Because of that I couldn’t leave the sw.js in the “assets” folder I had to move it in “public” so I had to force all the automatically cache file path to have the suffix “/assets”. I used for that the rewrite(asset) function that I defined in the options. - Last problem was that I couldn’t cache the route that is serving the SPA, because the permission is handled by the backend. If the page was cached before being authenticated it will give the home page. If it was cached after being authenticated it will always remain authenticated and the frontend may throw some errors. You can see how my config of the plugin looks like at the end after solving these problems. const OfflinePlugin = require('offline-plugin'); module.exports = { module: { // ... plugins: [ // ... new OfflinePlugin({ // I needed this credential line to make it cache the authenticated page (that I excluded at the end) ServiceWorker: { prefetchRequest: { credentials: 'same-origin' }, } externals: [ // some images that I wanted to cache 'app/images/favicon.png', 'app/images/icon.png', 'app/images/logoL.png', ], // the public path for the SW.js publicPath: '/', // the excluded files that redirects to the login page excludes: [ '/', '/board' ], rewrites(asset) { // the rewrite to match with the real publicPath that we can see below return `/assets/${asset}`; } }) ], output: { path: path.join(process.cwd(), conf.paths.dist), filename: '[name]-[hash].js', publicPath: '/assets/' }, // ... } } If you are using webpack I fully recommend you this plugin! offline-plugin — Offline plugin (ServiceWorker, AppCache) for webpack ()github.com How to implement Redux Persist Redux Persist is also very easy to use. First, add redux persist as a dependency npm install redux-persist --save Then, add these lines to your store import {persistStore, autoRehydrate} from 'redux-persist'; const store = createStore( reducer, // ... compose( applyMiddleware( ...middlewares ), autoRehydrate() // add this line ) ); persistStore(store) // and this one And that’s it! Every time your state will be updated it will be persisted in the localstorage. Once you reload the project the latest state saved in your localstorage will be loaded, it works very well. But again, that wasn’t it 😂, of course! I had a few problems. - It’s not a real problem, just that one of my goals was to save the state using the IndexedDB and not the localstorage. This is very easy, you have to load the “localforage” dependency to your project, import it in the file and set when running “persistStore()”. - In Kanbanote’s navbar there is a “syncing” spinner, rotating when an API call is running. Basically it’s a variable from the state which is incremented when the call start, and decremented when the calls is ended or fails. The problem was that the state of this icon was also saved and even though when I load the project I always reset its value, it didn’t work. The reason is the asynchronous way of working: when I launch the app the state is empty, and then Redux-persist will put the latest value saved of it. This was actually easy to fix, there is a way to blacklist the different reducers of your store. But this only works when the reducers are well separated, and that couldn’t solve my next problem. - For the same reason of asynchronous, I had another issue. Let’s imagine my Kanban contains two different Boards, A and B. The default board is always the first, so A. If you load Kanbanote for the first time it will open this default board, so the A. If you open B and close Kanbanote, and reopen it. The last state will contain B, and then the API call will call the default board. Because of asynchronous I couldn’t get the value of the latest board before doing the call otherwise I could ask to load the data of the right board. After struggling a lot I saved this problem by saving the latest board opened in a cookie of the backend. In order to solve 1, and 2 here is how my code looks like. import {persistStore, autoRehydrate} from 'redux-persist'; import localForage from 'localforage'; // to save the data in IndexedDB const store = createStore( reducer, // ... compose( applyMiddleware( ...middlewares ), autoRehydrate() ) ); // The storage changed to IndexedDB thanks to localForage and the reducers that are blacklisted persistStore(store, {storage: localForage, blacklist: ['sync', 'errors']}); So I spent a lot of time to understand and solve this last 3rd issue and at the end I somehow made it, it works, not perfectly but good enough to be used and deployed to production. I also recommend this library which is very good when your state is well defined. Other issues Rather than the issues describes below, my new version of Kanbanote has also a few little problems: - When changing board or pre-loading the page (using the state persisted) some UI actions may disappear, this is due by the fact that some part of the state are replaced by the data coming from the API, it’s due to a bad architecture of the state. It’s my first Redux project, so everything is not perfect, and state architecture is the first thing to do so if you are not trained well enough, bad things like this can happen. - The drag’n’drop is very sensible, I use React-dnd with the Touch-backend, where there is not long-touch detection. That is why the library is providing a touch delay, which is working fine when trying from the desktop (in mobile mode), but not when trying in my real android device. To solve this at the end I left more space to be able to scroll up and down without drag’n’dropping and also I added a vibration when a note is dragging. - I tested after finishing the project on an iOS device, the drag’n’drop doesn’t work at all for some reason. Since I don’t have any iOS device it’s hard to me to debug this. The final result Tada !! Here it is: I hope you will like it, it’s made with a lot of work and a lot of love. Just for you to know I use Kanbanote in a daily basis (or even in a hourly basis) so I will always make it working well. How my learning month ended I invite you to check out the feedback of How I learnt Progressive Web Apps in a month and implemented it article.
https://medium.com/learning-lab/how-pwas-works-and-how-i-implemented-it-with-react-and-webpack-523381b1b7a4
CC-MAIN-2017-47
refinedweb
3,056
60.45
getopt_longcode into the generated parser getopt_long Gengetopt is a tool to write command line option parsing code for C programs. This is Edition 2.22.6 of the Gengetopt manual. This file documents GNU Gengetopt version 2.22.6. This manual is for GNU Gengetopt (version 2.22.6, 2 November 2012), a tool to write command line option parsers. This manual is written for C and C++ programmers, specifically the lazy ones. If you've written any non-trivial C program, you've had to deal with argument parsing. It isn't particularly difficult, nor is it particularly exciting. It is one of the classic programming nuisances, which is why most books on programming leave it as an exercise for the reader. Gengetopt can save you from this work, leaving you free to focus on the interesting parts of your program. Thus your program will be able to handle command line options such as: myprog --input foo.c -o foo.o --no-tabs -i 100 *.class And both long options (those that start with --) and short options (start with - and consist of only one character) can be handled (see Terminology for further details). For standards about short and long options you may want to take a look at the GNU Coding Standards (). Gengetopt can also generate a function to save the command line options into a file (see Basic Usage), and a function to read the command line options from a file (see Configuration files). Of course, these two kinds of files are compliant. Generated code works also if you use GNU Autoconf and GNU Automake and it is documented with Doxygen comments. In particular, PACKAGE, PACKAGE_NAME and VERSION are used in the generated code to print information. Gengetopt is free software; you are free to use, share and modify it under the terms of the GNU General Public License that accompanies this manual.. Gengetopt was originally written by Roberto Arturo Tena Sanchez. It is currently maintained by Lorenzo Bettini. A primordial version of Terminology was written by Adam Greenblatt. See the file INSTALL for detailed building and installation instructions; anyway if you're used to compiling Linux software that comes with sources you may simply follow the usual procedure, i.e. untar the file you downloaded in a directory and then: cd <source code main directory> ./configure make make install Note: unless you specify a different install directory by --prefix option of configure (e.g. ./configure --prefix=<your home>), you must be root to run make install. Files will be installed in the following directories: executables /prefix/bin docs /prefix/share/doc/gengetopt examples /prefix/share/doc/gengetopt/examples additional files /prefix/share/gengetopt Default value for prefix is /usr/local but you may change it with --prefix option to configure. You can download it from GNU's ftp site: or from one of its mirrors (see). I do not distribute Windows binaries anymore; since, they can be easily built by using Cygnus C/C++ compiler, available at. However, if you don't feel like downloading such compiler, you can request such binaries directly to me, by e-mail (find my e-mail at my home page) and I can send them to you. Archives are digitally signed by me (Lorenzo Bettini) with GNU gpg (). My GPG public key can be found at my home page (). You can also get the patches, if they are available for a particular release (see below for patching from a previous version). This project's git repository can be checked out through the following clone instruction1:. Gengetopt has been developed under GNU/Linux, using gcc (C++), and bison (yacc) and flex (lex), and ported under Win32 with Cygnus C/C++compiler, available at. For developing gengetopt, I use the excellent GNU Autoconf2, GNU Automake3 and GNU Libtool4. Since version 2.19 I also started to use Gnulib - The GNU Portability Library5, “a central location for common GNU code, intended to be shared among GNU packages” (for instance, I rely on Gnulib for checking for the presence and correctness of getopt_long function, Use Gnulib). Moreover GNU Gengen () is used for automatically generating the code that generates the command line parser. Actually, you don't need all these tools above to build gengetopt because I provide generated sources, unless you want to develop gengetopt. The code generated by gengetopt relies on the getopt_long function that is usually in the standard C library; however, there may be some implementations of the C library that don't include it; we refer to No getopt_long, for instructions on how to check whether getopt_long is part of the library and how to deal with their lacking (using autoconf and automake). If you downloaded a patch, say gengetopt-1.3-1.3.1-patch.gz (i.e., the patch to go from version 1.3 to version 1.3.1), cd to the directory with sources from the previous version (gengetopt-1.3) and type: gunzip -cd ../gengetopt-1.3-1.3.1.patch.gz | patch -p1 and restart the compilation process (if you had already run configure a simple make should do). The command line options, which have to be handled by gengetopt generated function, are specified in a file (typically with .ggo extension). This file consists of sentences with the formats shown below (these sentences are allowed to span more than one line). Statements in {} are optional (the option sentences need not to be given in separate lines): package "<packname>" version "<version>" purpose "<purpose>" usage "<usage>" description "<description>" versiontext "<versiontext>" args "<command line options>" option <long> <short> "<desc>" {details="<detailed description>"} {argtype} {typestr="<type descr>"} {values="<value1>","<value2>",...} {default="<default value>"} {dependon="<other option>"} {required} {argoptional} {multiple} {hidden} option <long> <short> "<desc>" flag <on/off> section "section name" {sectiondesc="optional section description"} text "a textual sentence" Where: package PACKAGEand PACKAGE_NAMEgenerated by autoconf. This is required, unless you use autoconf. If package is specified, then it will be used to print the program name in the output of --help and --version, and also when printing errors (from within the generated parser). If it is not specified, then PACKAGE will be used when printing errors, and PACKAGE_NAME in the output of --help and --version. Note that if PACKAGE_NAME is empty, then PACKAGE will be used also in this case. version VERSIONgenerated by autoconf. This is required, unless you use autoconf. purpose usage description versiontext --version. This would be used, for example, to display copyright and licensing information. args args8 you can specify options that will be added to the command line options of gengetopt itself. For instance, if you always run gengetopt on your input file with the options --no-handle-error --string-parser -u, you can add these options in the input file like this: args "--no-handle-error --string-parser -u" and remove those recurrent options from the command line. Optional. long -) and a dot ( .). No spaces allowed. The name of the variables generated to store arguments (see later in this section) are long options converted to be legal C variable names. This means that .and -are both replaced by _. short -is specified, then no short option is considered for the long option (thus long options with no associated short options are allowed). Since version 2.22 you can also specify ?as the short option. desc --help. Wrapping will be automatically performed. details --detailed-help9, which will be automatically generated. Thus, these further details will NOT be printed with --help. Wrapping will be automatically performed. Optional. Note that if --strict-hidden is used, options that are hidden (See Hidden options.) will not appear in the output of --detailed-help, even if those options have details. argtype string, int, short, long, float, double, longdoubleor longlong. If the option is an enumerated one (see Options with enumerated values) the type can also be enum. If no type is specified the option does not accept an argument. typestr --help(e.g., "filename"instead of simply STRING, or "portnumber"instead of simply INT). values enum. More on this feature can be found in Options with enumerated values. default multipleflag (Multiple Options) but only by giving a single default value. It is not possible to specify a list of default values. dependon required requiredor optional. This specifies whether such option must be given at each program invocation. These keywords were introduced in release 2.17. Before, you had to use the keywords yesor no. You can still use these keywords but their use is not advised since they are not much explicative. If not specified, an option is considered mandatory; if you do not want this behavior, you can require that by default options are considered optional, by using the command line option --default-optional11. argoptional =in case you use a long option, and avoid spaces if you use short option. For instance, if the option with optional argument is -B|--bar, use the following command line syntax: -B15or --bar=15, and NOT the following one -B 15nor --bar 15. By using this specification together with default you can obtain an option that even if not explicitly specified will have the default value, and if it is specified without an argument it will have, again, the default value. multiple requiredflag. See Multiple Options. hidden --helpbut it can still be specified at command line12. When hidden options are used, the command line option --full-helpwill also be generated. This will also print hidden options13. Hidden options are also displayed in the output of --detailed-help, if it is present, along with any details that those options have. Note that when --strict-hidden is used, hidden options do not appear as described above, although they can still be given on the comand line. That is to say, the --full-help option is not generated, and hidden options do not appear in the output of --detailed-help, even if they have details. on/off onor off. This is the state of the flag when the program starts. If user specifies the option, the flag toggles. For strings (delimited by ") the following convention is adopted14: a string spanning more than one line will be interpreted with the corresponding line breaks; if the line break is not desired one can use the backslash \ to break the line without inserting a line break. A line break in a string can also be inserted with the string \n. Here are some examples: "This string will be interpreted into two lines exactly as it is" "This string is specified with two lines \ but interpreted as specified in only one line \ i.e., without explicit line break" "This string\nwill have a line break" Moreover, if the character " must be specified in the string, it will have to be escaped with the backslash15: "This string contains \"a quoted string\" inside" The part that must be provided in the correct order is option <long> <short> "<desc>" while the other specifications can be given in any order16. Thus, for instance option <long> <short> "<desc>" {argtype} {typestr="<type descr>"} is the same as option <long> <short> "<desc>" {typestr="<type descr>"} {argtype} # in any place (but in strings) of the line and ends in the end of line. Notice that the options -h,--help and -V,--version are added automatically; however, if you specify an option yourself that has h as short form, then only is added17. The same holds for -V,--version. In case hidden options are used, See Hidden options, the command line option --full-help will also be generated. This will print also the hidden options18. Note, though, that when --strict-hidden is used, this is not the case and --full-help is not generated. If there's at least one option with details, the command line option --detailed-help will also be generated. This will print also the details for options and hidden options19 (except when --strict-hidden is used). Options can be part of sections, that provide a more meaningful descriptions of the options. A section can be defined with the following syntax (the sectiondesc is optional) and all the options following a section declaration are considered part of that sections: section "section name" {sectiondesc="optional section description"} Notice that the separation in sections is stronger than separation in groups of mutually exclusive options (see Group options). Furthermore, sections should not be inserted among group options (but only externally). A section makes sense only if it is followed by some options. If you don't specify any option after a section, that section will not be printed at all. If you need to simply insert some text in the output of --help, then you must use text, explained in the next paragraph. You can insert, among options, a textual string that will be printed in the output of --help20: text "\nA text description with possible line\nbreaks" Of course, you can use this mechanism even to manually insert blank lines among options with an empty text string: text "" You can also specify the list of values that can be passed to an option (if the type is not specified, the option has type string). More on this feature can be found in Options with enumerated values.. Here's an example of such a file (the file is called sample1.ggo) # Name of your program package "sample1" # don't use package if you're using automake # Version of your program version "2.0" # don't use version if you're using automake # Options option "str-opt" s "A string option, for a filename" string typestr="filename" optional text "\nA brief text description" text " before the other options.\n" option "my-opt" m "Another integer option, \ this time the description of the option should be \"quite\" long to \ require wrapping... possibly more than one wrapping :-) \ especially if I\nrequire a line break" int optional option "int-opt" i "A int option" int yes section "more involved options" sectiondesc="the following options\nare more complex" text "" option "flag-opt" - "A flag option" flag off option "funct-opt" F "A function option" optional details="\nA." section "last option section" option "long-opt" - "A long option" long optional option "def-opt" - "A string option with default" string default="Hello" optional option "enum-opt" - "A string option with list of values" values="foo","bar","hello","bye" default="hello" optional option "secret" S "hidden option will not appear in --help" int optional hidden option "dependant" D "option that depends on str-opt" int optional dependon="str-opt" text "\nAn ending text." The simplest way to use gengetopt is to pass this file as the standard input, i.e.: gengetopt < sample1.ggo By default gengetopt generates cmdline.h and cmdline.c. Otherwise we can specify these names with a command line option: gengetopt < sample1.ggo --file-name=cmdline1 --unamed-opts The option --unamed-opts allows the generated command line parser to accept also names, without an option (for instance you can pass a file name without an option in front of it, and also use wildcards, such as *.c, foo*.? and so on). These are also called parameters (see Terminology). You can specify an optional description for these additional names (default is FILES). In cmdline1.h you'll find the generated C struct: /** @file cmdline1.h * @brief The header file for the command line option parser * generated by GNU Gengetopt version 2.22.6 *. * DO NOT modify this file, since it can be overwritten * @author GNU Gengetopt by Lorenzo Bettini */ #ifndef CMDLINE1_H #define CMDLINE1_H /* If we use autoconf. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdio.h> /* for FILE */ #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ #ifndef CMDLINE_PARSER_PACKAGE /** @brief the program name (used for printing errors) */ #define CMDLINE_PARSER_PACKAGE "sample1" #endif #ifndef CMDLINE_PARSER_PACKAGE_NAME /** @brief the complete program name (used for help and version) */ #define CMDLINE_PARSER_PACKAGE_NAME "sample1" #endif #ifndef CMDLINE_PARSER_VERSION /** @brief the program version */ #define CMDLINE_PARSER_VERSION "2.0" #endif /** @brief Where the command line options are stored */ struct gengetopt_args_info { const char *help_help; /**< @brief Print help and exit help description. */ const char *detailed_help_help; /**< @brief Print help, including all details and hidden options, and exit help description. */ const char *full_help_help; /**< @brief Print help, including hidden options, and exit help description. */ const char *version_help; /**< @brief Print version and exit help description. */ char * str_opt_arg; /**< @brief A string option, for a filename. */ char * str_opt_orig; /**< @brief A string option, for a filename original value given at command line. */ const char *str_opt_help; /**< @brief A string option, for a filename help description. */ int my_opt_arg; /**< @brief Another integer option, this time the description of the option should be \"quite\" long to require wrapping... possibly more than one wrapping :-) especially if I require a line break. */ char * my_opt_orig; /**< @brief Another integer option, this time the description of the option should be \"quite\" long to require wrapping... possibly more than one wrapping :-) especially if I require a line break original value given at command line. */ const char *my_opt_help; /**< @brief Another integer option, this time the description of the option should be \"quite\" long to require wrapping... possibly more than one wrapping :-) especially if I require a line break help description. */ int int_opt_arg; /**< @brief A int option. */ char * int_opt_orig; /**< @brief A int option original value given at command line. */ const char *int_opt_help; /**< @brief A int option help description. */ int flag_opt_flag; /**< @brief A flag option (default=off). */ const char *flag_opt_help; /**< @brief A flag option help description. */ const char *funct_opt_help; /**< @brief A function option help description. */ long long_opt_arg; /**< @brief A long option. */ char * long_opt_orig; /**< @brief A long option original value given at command line. */ const char *long_opt_help; /**< @brief A long option help description. */ char * def_opt_arg; /**< @brief A string option with default (default='Hello'). */ char * def_opt_orig; /**< @brief A string option with default original value given at command line. */ const char *def_opt_help; /**< @brief A string option with default help description. */ char * enum_opt_arg; /**< @brief A string option with list of values (default='hello'). */ char * enum_opt_orig; /**< @brief A string option with list of values original value given at command line. */ const char *enum_opt_help; /**< @brief A string option with list of values help description. */ int secret_arg; /**< @brief hidden option will not appear in --help. */ char * secret_orig; /**< @brief hidden option will not appear in --help original value given at command line. */ const char *secret_help; /**< @brief hidden option will not appear in --help help description. */ int dependant_arg; /**< @brief option that depends on str-opt. */ char * dependant_orig; /**< @brief option that depends on str-opt original value given at command line. */ const char *dependant_help; /**< @brief option that depends on str-opt help description. */ unsigned int help_given ; /**< @brief Whether help was given. */ unsigned int detailed_help_given ; /**< @brief Whether detailed-help was given. */ unsigned int full_help_given ; /**< @brief Whether full-help was given. */ unsigned int version_given ; /**< @brief Whether version was given. */ unsigned int str_opt_given ; /**< @brief Whether str-opt was given. */ unsigned int my_opt_given ; /**< @brief Whether my-opt was given. */ unsigned int int_opt_given ; /**< @brief Whether int-opt was given. */ unsigned int flag_opt_given ; /**< @brief Whether flag-opt was given. */ unsigned int funct_opt_given ; /**< @brief Whether funct-opt was given. */ unsigned int long_opt_given ; /**< @brief Whether long-opt was given. */ unsigned int def_opt_given ; /**< @brief Whether def-opt was given. */ unsigned int enum_opt_given ; /**< @brief Whether enum-opt was given. */ unsigned int secret_given ; /**< @brief Whether secret was given. */ unsigned int dependant_given ; /**< @brief Whether dependant was given. */ char **inputs ; /**< @brief unamed options (options without names) */ unsigned inputs_num ; /**< @brief unamed options number */ } ; /** @brief The additional parameters to pass to parser functions */ struct cmdline_parser_params { int override; /**< @brief whether to override possibly already present options (default 0) */ int initialize; /**< @brief whether to initialize the option structure gengetopt_args_info (default 1) */ int check_required; /**< @brief whether to check that all required options were provided (default 1) */ int check_ambiguity; /**< @brief whether to check for options already specified in the option structure gengetopt_args_info (default 0) */ int print_errors; /**< @brief whether getopt_long should print an error message for a bad option (default 1) */ } ; /** @brief the purpose string of the program */ extern const char *gengetopt_args_info_purpose; /** @brief the usage string of the program */ extern const char *gengetopt_args_info_usage; /** @brief the description string of the program */ extern const char *gengetopt_args_info_description; /** @brief all the lines making the help output */ extern const char *gengetopt_args_info_help[]; /** @brief all the lines making the full help output (including hidden options) */ extern const char *gengetopt_args_info_full_help[]; /** @brief all the lines making the detailed help output (including hidden options and details) */ extern const char *gengetopt_args_info_detailed_help[]; /** * **argv, struct gengetopt_args_info *args_info, struct cmdline_parser_params *params); /** * Save the contents of the option struct into an already open FILE stream. * @param outfile the stream where to dump options * @param args_info the option struct to dump * @return 0 if everything went fine, NON 0 if an error took place */ int cmdline_parser_dump(FILE *outfile, struct gengetopt_args_info *args_info); /** * Save the contents of the option struct into a (text) file. * This file can be read by the config file parser (if generated by gengetopt) * @param filename the file where to save * @param args_info the option struct to save * @return 0 if everything went fine, NON 0 if an error took place */ int cmdline_parser_file_save(const char *filename, struct gengetopt_args_info *args_info); /** * Print the help */ void cmdline_parser_print_help(void); /** * Print the full help (including hidden options) */ void cmdline_parser_print_full_help(void); /** * Print the detailed help (including hidden options and details) */ void cmdline_parser_print_detailed_help(void); /** * Print the version */ void cmdline_parser_print_version(void); /** * Initializes all the fields a cmdline_parser_params structure * to their default values * @param params the structure to initialize */ void cmdline_parser_params_init(struct cmdline_parser_params *params); /** * Allocates dynamically a cmdline_parser_params structure and initializes * all its fields to their default values * @return the created and initialized cmdline_parser_params structure */ struct cmdline_parser_params *cmdline_parser_params_create(void); /** * Initializes the passed gengetopt_args_info structure's fields * (also set default values for options that have a default) * @param args_info the structure to initialize */ void cmdline_parser_init (struct gengetopt_args_info *args_info); /** * Deallocates the string fields of the gengetopt_args_info structure * (but does not deallocate the structure itself) * @param args_info the structure to deallocate */ void cmdline_parser_free (struct gengetopt_args_info *args_info); /** * Checks that all the required options were specified * @param args_info the structure to check * @param prog_name the name of the program that will be used to print * possible errors * @return */ int cmdline_parser_required (struct gengetopt_args_info *args_info, const char *prog_name); extern const char *cmdline_parser_enum_opt_values[]; /**< @brief Possible values for enum-opt. */ #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* CMDLINE1_H */ First of all, notice that the argv parameter (typically corresponding to the homonimous argument of your program's main function) is declared as char ** and not as char *const *21. Actually, the version of getopt_long in libc uses prototypes with char *const *argv that are incorrect because getopt_long and getopt_long_only can permute argv; this is required for backward compatibility (e.g., for LSB 2.0.1)22. So, it is better to declare argv as char ** in the generated parser functions. The <option>_given field is set to 1 when an argument for <option> has been specified (otherwise it is 0)23. This fields also counts the times a multiple option is specified (see Multiple Options). If the option accepts an argument and it is not of flag type The <option>_arg field is set to the value passed at the command line. The <option>_arg field has the corresponding C type specified in the file passed to gengetopt. Notice that if an option has a default value, then the corresponding <option>_arg will be initialized with that value but the corresponding <option>_given will NOT be initialized to 1. Thus, <option>_given will effectively inform you if the user has specified that command line option. The additional field <option>_orig is always a string containing the original value passed at the command line. This may be different, for instance, in case of numerical arguments: gengetopt converts the passed value (a string) into the corresponding numerical type; due to conversions, float representations, etc., this may not correspond exactly to the original value passed at command line. It can also be different when enumerated options are used (see above): in particular the <option>_arg field will contain a value taken from the specified list, while <option>_orig contains the (non-ambiguous) prefix specified at the command line. The user can always access this original value by using <option>_orig instead of <option>_arg, as he sees fit24. For instance, gengetopt itself uses the original value when it saves the command line options into a file (see the _file_save function in the following). However, apart from very specific command line processing, the user might hardly need the <option>_orig field, and can be always safely use <option>_arg. The <option>_help contains the string (concerning this very option) that is printed when --help command line is given. If it is of flag type, only the field <option>_flag is generated. The strings cmdline_parser_purpose and cmdline_parser_usage contain the purpose as specified in the input file and the generated “usage” string as printed when --help command line is given. Finally, the string array cmdline_parser_help contains the strings (one for each option) printed when --help command line is given (this array is terminated by a null string element). If hidden options are used also the cmdline_parser_full_help array is available (containing also help strings concerning hidden options). If at least one option has details, then the cmdline_parser_detailed_help array is available (containing also help strings concerning hidden options and details for options). All these strings can be used by the programmer to build a customized help output25. Even if <option>_given is 0, the corresponding <option>_arg is set to default value (if one has been specified for <option>). However, in this case, the <option>_orig is set to NULL. Notice that by default the generated function is called cmdline_parser (see the command line options below, to override this name), and it takes the arguments that main receives and a pointer to such a struct, that it will be filled. Another version, cmdline_parser2, can be specified more arguments. Since you typically need this second version only in conjunction with other “kinds” of parsers such as configuration files and multiple parsers, you can find more details about it in Configuration files. IMPORTANT: The array passed to the parser function (that in turn is passed to getopt_long is expected to have in the first element (of index 0) the name of the program that was invoked. This will be used, for instance, for printing possible errors. cmdline_parser_free can be called to deallocate memory allocated by the parser for string and multiple options. cmdline_parser_init can be called to initialize the struct (it is not mandatory, since it is done automatically by the command line parser). cmdline_parser_file_save26 can be used to save the command line options into a file. The contents of this file are consistent with the configuration files (Configuration files). Notice that if an option has a default value, this option will be saved into the file only if it was passed explicitly at command line (or read from a configuration file), i.e., default values will not be saved into the file. Alternatively, you can use cmdline_parser_dump27 that takes as the first parameter an already open stream ( FILE *) instead of a file name. And here's how these functions can be used inside the main program: /* main1.cc */ /* we try to use gengetopt generated file in a C++ program */ /* we don't use autoconf and automake vars */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <iostream> #include "stdlib.h" #include "cmdline1.h" using std::cout; using std::endl; int main (int argc, char **argv) { gengetopt_args_info args_info; cout << "This one is from a C++ program" << endl ; cout << "Try to launch me with some options" << endl ; cout << "(type sample1 --help for the complete list)" << endl ; cout << "For example: ./sample1 *.* --funct-opt" << endl ; /* let's call our cmdline parser */ if (cmdline_parser (argc, argv, &args_info) != 0) exit(1) ; cout << "Here are the options you passed..." << endl; for ( unsigned i = 0 ; i < args_info.inputs_num ; ++i ) cout << "file: " << args_info.inputs[i] << endl ; if ( args_info.funct_opt_given ) cout << "You chose --funct-opt or -F." << endl ; if ( args_info.str_opt_given ) cout << "You inserted " << args_info.str_opt_arg << " for " << "--str-opt option." << endl ; if ( args_info.int_opt_given ) cout << "This is the integer you input: " << args_info.int_opt_arg << "." << endl; if (args_info.flag_opt_given) cout << "The flag option was given!" << endl; cout << "The flag is " << ( args_info.flag_opt_flag ? "on" : "off" ) << "." << endl ; if (args_info.enum_opt_given) { cout << "enum-opt value: " << args_info.enum_opt_arg << endl; cout << "enum-opt (original specified) value: " << args_info.enum_opt_orig << endl; } if (args_info.secret_given) cout << "Secret option was specified: " << args_info.secret_arg << endl; cout << args_info.def_opt_arg << "! "; cout << "Have a nice day! :-)" << endl ; cmdline_parser_free (&args_info); /* release allocated memory */ return 0; } Now you can compile main1.cc and the cmdline1.c generated by gengetopt and link all together to obtain sample1 executable: gcc -c cmdline1.c g++ -c main1.cc g++ -o sample1 cmdline1.o main1.o (Here we assume that getopt_long is included in the standard C library; see Installation and No getopt_long). Now let's try some tests with this program: $ ./sample1 -s "hello" --int-opt 1234 This one is from a C++ program Try to launch me with some options (type sample1 --help for the complete list) For example: ./sample1 *.* --funct-opt Here are the options you passed... You inserted hello for --str-opt option. This is the integer you input: 1234. The flag is off. Have a nice day! :-) You can also pass many file names to the command line (this also shows how flags work): $ ./sample1 *.h -i -100 -x This one is from a C++ program Try to launch me with some options (type sample1 --help for the complete list) For example: ./sample1 *.* --funct-opt Here are the options you passed... file: cmdline1.h file: cmdline2.h file: cmdline.h file: getopt.h This is the integer you input: -100. The flag is on. Have a nice day! :-) And if we try to omit the --int-opt (or -i), which is required, we get an error: $ ./sample1 This one is from a C++ program Try to launch me with some options (type sample1 --help for the complete list) For example: ./sample1 *.* --funct-opt sample1: `--int-opt' (`-i') option required! Now, let's test the enumerated options, notice the use of a prefix for specifying an acceptable value, and the difference between the actual passed value and the one recorded in <option>_arg: $ ./sample1 -i 10 --enum-opt h ... enum-opt value: hello enum-opt (original specified) value: h ... While the next one raises an ambiguity error (between "bar" and "bye"): $ ./sample1 -i 10 --enum-opt b ... ./sample1: ambiguous argument, "b", for option `--enum-opt' Here is the output of --help of the parser generated from sample1.ggo by specifying the following options to gengetopt: --long-help -u --show-required (see Invoking gengetopt for further explanation for these command line options). last option section: --long-opt=LONG A long option --def-opt=STRING A string option with default (default=`Hello') --enum-opt=STRING A string option with list of values (possible values="foo", "bar", "hello", "bye" default=`hello') -D, --dependant=INT option that depends on str-opt An ending text. Notice how filename is printed instead of STRING for the option --str-opt (since typestr was used in the sample1.ggo file) and how the description of --my-opt is wrapped to 80 columns, and how the \n is actually interpreted as a newline request. Also the usage string is wrapped. Moreover, since -S,--secret is an hidden option (See Hidden options.) it is not printed; if you wanted that to be printed, you should use --full-help. The option --func-opt has also the details, but they are not printed with Finally, notice how the text strings are printed in the help output (and the empty line after the “more involved options” section achieved with an empty text string). Instead, here is the output of --detailed-help of the parser generated from sample1.ggo. You may want to compare this output with the one produced by --help (See Output of --help.); in particular, you may notice that the hidden option --secret is actually printed and the details of --func-opt are printed too: A. last option section: --long-opt=LONG A long option --def-opt=STRING A string option with default (default=`Hello') --enum-opt=STRING A string option with list of values (possible values="foo", "bar", "hello", "bye" default=`hello') -S, --secret=INT hidden option will not appear in --help -D, --dependant=INT option that depends on str-opt An ending text. If you're curious you may want to take a look at the generated C file cmdline1.c. You may find other examples in /prefix/share/doc/gengetopt/examples or in the tests of the source tarbal. This is the output of gengetopt --help: gengetopt This program generates a C function that uses getopt_long function to parse the command line options, validate them and fill a struct. Usage: gengetopt [OPTIONS]... -h, --help Print help and exit --detailed-help Print help, including all details and hidden options, and exit -V, --version Print version and exit Main options: -i, --input=filename input file (default std input) -f, --func-name=name name of generated function (default=`cmdline_parser') -a, --arg-struct-name=name name of generated args info struct (default=`gengetopt_args_info') -F, --file-name=name name of generated file (default=`cmdline') --output-dir=path output directory --header-output-dir=path header output directory --src-output-dir=path source output directory -c, --c-extension=ext extension of c file (default=`c') -H, --header-extension=ext extension of header file (default=`h') -l, --long-help long usage line in help --default-optional by default, an option is considered optional if not specified otherwise -u, --unamed-opts[=STRING] accept options without names (e.g., file names) (default=`FILES') The parser generated is thought to be used to parse the command line arguments. However, you can also generate parsers for configuration files, or strings that contain the arguments to parse, by using the following two options. -C, --conf-parser generate a config file parser -S, --string-parser generate a string parser (the string contains the command line) Additional options: -G, --include-getopt adds the code for getopt_long in the generated C file -n, --no-handle-help do not handle --help|-h automatically --no-help do not add --help|-h automatically -N, --no-handle-version do not handle --version|-V automatically --no-version do not add --version|-V automatically -e, --no-handle-error do not exit on errors --show-required[=STRING] in the output of help will specify which options are mandatory, by using the optional passed string (default=`(mandatory)') --strict-hidden completely hide hidden options -g, --gen-version put gengetopt version in the generated file (default=on) --set-package=STRING set the package name (override package defined in the .ggo file) --set-version=STRING set the version number (override version defined in the .ggo file) --show-help show the output of --help instead of generating code --show-full-help show the output of --full-help (i.e., including hidden options) instead of generating code --show-detailed-help show the output of --detailed-help (i.e., including details and hidden options) instead of generating code --show-version show the output of --version instead of generating code Please refer to the info manual for further explanations. The options should be clear; in particular: --func-name --func-nameis given, cmdline_parseris taken by default; --output-dir --output-dir28 is given, the files are generated in the current directory; --src-output-dir --header-output-dir --arg-struct-name gengetopt_args_info) --long-help --default-optional --unamed-opts sample1 *.h). You can specify an optional description for these additional names (default is FILES). --no-handle-help --no-handle-version --no-handle-help( --no-handle-version) is given the command line option --help|-h( --version|-V) is not handled automatically, so the programmer will be able to print some other information; then the function for printing the standard help (version) response can be used; this function is called <parser-name>_print_help( <parser-name>_print_version), where <parser-name>is the name specified with --func-nameor the default, cmdline_parser. In case hidden options are used, See Hidden options, also the function <parser-name>_print_full_helpwill be generated; if detailsare used for at least one option, then also the function <parser-name>_print_detailed_helpwill be generated. Notice that, although the programmer can handle these options manually, the parser will return after finding one of these options: the other command line options, if any, will be ignored. In case you want to have full control on --help|-h, --version|-V, you should use the following options: --no-help --no-version --help|-hand --version|-V, respectively. The programmer will then be able to add these options in the input file and handle them as he sees fit. Notice that --no-helpwill also disable the automatic options --detailed-helpand --full-help. The programmer can still define options with short character hand Vas he wants, but he cannot define options helpand version, unless he specifies --no-helpand --no-version, respectively (otherwise an error will be printed). An example using these options and manually handles --helpand --versioncan be found in test_manual_help_cmd.ggo and test_manual_help.c in the examples directory. --no-handle-error --no-handle-erroris given, an error in the parsing does not provoke the exit of the program; instead, since the parser function, in case of an error, returns a value different 0, the program can print a help message, as gengetopt itself does in case of an error (try it!). --show-required --show-requiredis given, possibly with a string, in the output of --helpwill be made explicit which options are actually required, See Basic Usage. --strict-hidden --full-helpoption will not be added, and hidden options will not show-up in the output of --detailed-help, even if they have details. See Hidden options. --gen-version --conf-parser --string-parser --include-getopt getopt_longinto the generated parser C file. This will make your generated parser much bigger, but it will be compiled in any system, even if getopt_longis not part of the C library where your program is being compiled. See also No getopt_long. --show-help --show-full-help --show-version --full-helpand --versioncommand lines without generating any code, See Automatically added options. For instance, I use the --show-helpoption to generate a texinfo file with the output of help (this also shows an example of use of --set-packageand --set-version): ../src/gengetopt --show-help -i ../src/cmdline.ggo \ -- help_output.texinfo You may have already guessed it: gengetopt uses gengetopt itself for command line options, and its specification file is cmdline.ggo in the source directory. In particular the command line for gengetopt itself is generated with the following command: gengetopt --input=cmdline.ggo --no-handle-version \ --no-handle-help --no-handle-error Indeed when --help|-h is passed on the command line, gengetopt will call cmdline_parser_print_help() and then the lines for reporting bugs. When --version|-V is passed, it will call cmdline_parser_print_version() and then prints a copyright. If an error occurs it prints a message on the screen: $ ./gengetopt --zzzz ./gengetopt: unrecognized option `--zzzz' Run gengetopt --help to see the list of options. An argument is an element of the argv array passed into your C or C++ program by your operating system. An option is an argument that begins with -, or --. A value is an argument, or part of an argument, that is associated with a particular option (an option may also not accept any value). For example, in > ls --width=80 ls is called with one argument, --width=80, which is an option that has a value, 80, while in > ls --width 80 ls is called with two arguments, --width, which is an option, and 80 which might or might not be a value. In this case, whether the 80 is treated as a value associated with the preceding --width option, or as the name of a file to list depends on how ls parses the --width option. The order in which options are specified is usually unimportant: > ls -a -l > ls -l -a both do exactly the same thing. An parameter is an argument that is not an option. For example, in > cp --archive source dest cp is called with three arguments, the option --archive, the parameter source, and the parameter dest. Unlike options, the order in which parameters are specified usually is important: > cp --archive --verbose source dest > cp --verbose --archive source dest > cp --archive source --verbose dest > cp --archive --verbose dest source The first three cp commands do the same thing, but the fourth one is completely different. If you're new to Gengetopt, you may wish to skip the rest of this section. It goes into more detail about different sorts of options, and how they are parsed. Note that some parameters may begin with - or --. Equivalently, not all arguments that begin with - or -- are options. Consider > ls -- -file > tar -c -f - . > ../foo.tar The ls command has two arguments; the first argument, -- is ignored by ls, but causes the -file argument to be interpreted as a parameter. The tar command has four arguments. The -c argument tells tar to create an archive; the -f argument, which takes a value, -, tells tar that the archive should be written onto the standard output, and the fourth argument, ., tells tar what directories to include in the archive. (The remaining two items, > and ../foo.tar, tell the shell to redirect the tar command's output to the file ../foo.tar. The tar command doesn't even see them.) The GNU convention is that - by itself is always interpreted as a value or parameter, while the first -- by itself is always ignored, but causes all subsequent arguments to be interpreted as parameters. Gengetopt always behaves this way. A short option is an option that begins with -. Not including the leading dash, short options must be one character long: > ls -a -l -t --width=80 The -a, -l, and -t options are all short options. Multiple short options may be combined into a single argument: > ls -alt --width=80 is equivalent to the above example. A long option is an option that begins with - or --. Ignoring the leading punctuation, long options may be one or more characters long: > ls --all -fs The ls command has two arguments; the long option --all, and the pair of short options -fs. Long options need not have synonymous short options; after all, complex programs like cc have more long options than there are valid short option characters; it wouldn't be possible to assign a short option to each of them. Short options are encouraged, but not required, to have a synonymous long option. Long options may be abbreviated, as long as the abbreviation is not ambiguous. Gengetopt automatically treats unambiguous abbreviations as synonyms. Short options may have values just like long options, but if several short options are grouped together into one argument, only the last one may have a value. Values in the same argument as a long option are delimited by an equals sign, values in the same argument as a short option are not: > ls --width 60 # ok, value is "60" > ls --width=60 # ok, value is "60" > ls -w60 # ok, value is "60" > ls -w 60 # ok, value is "60" > ls -w=60 # unexpected, value is "=60" > ls -T7 -w60 # ok, value for -T is 7, value for -w is 60 > ls -T7w60 # unexpected, value for -T is "7w60", no -w at all A required option must be present, otherwise an error will be raised. A multiple option is an option that may appear more than once on the command line. Gengetopt would create a tidy array for multiple options (see Multiple Options, for further details about dealing with multiple options). You can also specify the list of values that can be passed to an option (if the type is not specified, the option has type string).. Since version 2.22 options with values can be given a specific type (the default is string). If you give a numeric type to such options, gengetopt will check that the enumerated values are actually valid values for that numeric type. As for other options, the <option>_arg field will have the specified type, while the <option>_orig field will always be a string ( char *) storing the (non-ambiguous) prefix specified at the command line. For such an option, no matter what its type is, an array of strings, <parser-name>_<option>_values, will be generated that contains all the strings representing the possible accepted values. An option with enumerated values can also be given the type enum; in that case, a C enum type is also generated with name enum_<option>; the values of such C enum will be generated according this pattern: <option>_arg_<value>, where value is the value specified in the input file, and the starting value is always 0. An additional value is generated to represent the null/empty value, with the pattern <option>__NULL (note the double underscore) with integer value -1. For instance, if we specify in the input file the following option option "myopt" ... ... values="FOO","180","BAR" enum ... then the following C enum will be generated: enum enum_myopt { myopt__NULL = -1, myopt_arg_FOO = 0, myopt_arg_180, myopt_arg_BAR }; If you use the symbols + and -, these will be translated into PLUS_ and MINUS_, respectively, in the the C enum. Thus, if we specify in the input file the following option option "myopt" ... ... values="+foo","-all","-foo" enum ... then the following C enum will be generated: enum enum_myopt { myopt__NULL = -1, myopt_arg_PLUS_foo = 0, myopt_arg_MINUS_all, myopt_arg_MINUS_foo }; An example using options with values (and enum options) is tests/test_values_cmd.ggo and tests/test_values.c. It is also possible to group options; options belonging to a group are considered in mutual exclusion. In order to use this feature, first the group has to be defined, and then a groupoption can be defined. A groupoption has basically the same syntax of a standard option, apart that the required flag must not be specified (it would not make sense, since the options of the same group are mutually exclusive) and the group to which the option belongs has to be specified. defgroup "<group name>" {groupdesc="<group description>"} {required} groupoption <long> <short> "<desc>" <argtype> group="<group name>" \ {argoptional} {multiple} If a group is defined as required, then one (but only one) option belonging to the group has to be specified. Here's an example (taken from the test test_group_cmd.ggo): defgroup "my grp2" defgroup "grp1" groupdesc="an option of this group is required" required groupoption "opta" a "string a" group="grp1" multiple groupoption "optA" A "string A" string group="grp1" argoptional groupoption "optAmul" M "string M" string group="grp1" argoptional multiple groupoption "optb" b "string b" group="grp1" groupoption "optc" - "string c" group="my grp2" groupoption "optd" d "string d" group="my grp2" The group grp1 is required, so either --opta or --optb has to be specified (but only one of them). Here's the output of some executions: $ ./test_groups test_groups: 0 options of group grp1 were given. One is required $ ./test_groups -a OK $ ./test_groups -a -a OK (the same option given twice) $ ./test_groups -a -b test_groups: 2 options of group grp1 were given. One is required $ ./test_groups -a -c OK $ ./test_groups -a --optc -d test_groups: 2 options of group my grp2 were given. At most one is required It is also possible to specify “mode options”; options belonging to a mode are considered in mutual exclusion with options of a different mode. Thus, you can specify more options belonging to the same mode, but you cannot specify, on the same command line, two options belonging to two different modes (thus, modes are different from groups, Group options). These sets of options are called modes, since they represent the different modes (modalities), in which a program can be run. In order to use this feature, first the mode has to be defined, and then a modeoption can be defined. A modeoption has basically the same syntax of a standard option, and it can be given the required flag must not be specified (with a slightly different semantics, see below) and the group to which the option belongs has to be specified. defmode "<mode name>" {modedesc="<mode description>"} modeoption <long> <short> "<desc>" <argtype> mode="<mode name>" \ {argoptional} {multiple} {required} If a mode option is specified as required, then it will be required only if other options of the same mode are specified; this makes it possible to specify options of different modes as required. Options not belonging to any mode are not in conflict with mode options. For instance, let us consider the file test_modes_cmd.ggo: package "test_modes" version "1.0" section "some non mode options" option "no-mode" N "a generic option not beloging to any mode" optional option "no-mode2" - "another generic option not beloging to any mode" string optional section "some modes just for testing" defmode "mode 2" defmode "my mode" defmode "mode1" modedesc="any option of this mode is in contrast with any \ option of the other mode\nNotice that this description is quite long so \ it may spawn many lines... \ fortunately gengetopt will wrap it for you :-)" modeoption "opta" a "string a" multiple mode="mode1" optional modeoption "optA" A "string A" string argoptional mode="mode1" required modeoption "optAmul" M "string M" argoptional string mode="mode1" multiple optional modeoption "optb" b "string b" mode="mode1" optional modeoption "optc" - "string c" mode="mode 2" optional modeoption "optd" d "string d" mode="mode 2" required modeoption "mopt" m "option of my mode" int optional mode="my mode" optional Now, we use the program test_modes (that uses the generated parser for the input file above) to demonstrate how the parser generated by gengetopt perform checks on mode options. test_modes -N This execution generates no errors (although there are required options which are not specified, these required options are part of modes and they are required only if that mode is used). test_modes -a ./test_modes: '--optA' ('-A') option required Since an option of a mode is specified, then required options of that mode must be provided, but, in this execution, we forgot to specify a required option of the mode that is being used. test_modes -a -A -N This execution is correct: we specified two options of the same mode, in particular we also specified the required option of that mode. Notice that we use also an option not belonging to any mode, which does not interfere with mode options. test_modes -a -A -N --optc test_modes: option --optc conflicts with option --opta test_modes: option --optc conflicts with option --optA test_modes: '--optd' ('-d') option required Here we see a conflict, (actually two), since the last option we specified belongs to a mode that is different from the one of the first two options. If you require gengetopt to generate --full-help (See --full-help.), the usage string will be generated so that it will show the modes of the program; for instance, this is the output of --help of the generated parser for the input file above: test_modes 1.0 Usage: test_modes [-h|--help] [-V|--version] [-N|--no-mode] [--no-mode2=STRING] or : test_modes -d|--optd [--optc] or : test_modes -ASTRING|--optA=STRING [-a|--opta] [-MSTRING|--optAmul=STRING] [-b|--optb] or : test_modes [-mINT|--mopt=INT] -h, --help Print help and exit -V, --version Print version and exit some non mode options: -N, --no-mode a generic option not beloging to any mode --no-mode2=STRING another generic option not beloging to any mode some modes just for testing: Mode: mode1 any option of this mode is in contrast with any option of the other mode Notice that this description is quite long so it may spawn many lines... fortunately gengetopt will wrap it for you :-) -a, --opta string a -A, --optA[=STRING] string A -M, --optAmul[=STRING] string M -b, --optb string b Mode: mode 2 --optc string c -d, --optd string d Mode: my mode -m, --mopt=INT option of my mode Besides the parser functions, in the generated header file, gengetopt also generates31 an additional structure <cmd_parser_name>_params that can be used to customize the invocation of the generated parsers (it is especially useful when using configuration file parsers, Configuration files, string parsers, String Parsers and Multiple Parsers, and, in general, multiple parsers). These are the fields of this structure (as usual, boolean options are represented as int and they are true if they are set to 1 and false if they are set to 0): int initialize (default = 1) int override (default = 0) int check_required (default = 1) int check_ambiguity (default = 0) int print_errors (default = 1) getopt_longmust print error messages to the standard error stream if it encounters an unknown option character or an option with a missing required argument. This is the default behavior. If you set this variable to zero, getopt_longdoes not print any messages, but the generated parser will still return with error. Gengetopt also generates an initialization function for such structures33, called <cmd_parser_name>_params_init, which takes as argument a pointer to such structure and initialize all its fields to their default values; it also generates a function called <cmd_parser_name>_params_create that returns a dynamically allocated structure with all fields initialized to their default values. We strongly advise to use such functions for creating and initializing such a structure, since this will make your code scalable to future releases of gengetopt where such structure might contain additional fields. Otherwise, you might risk to use a structure where some fields are not initialized, with unpredictable results. Furthermore, since the <cmd_parser_name>_params_create function returns a pointer to a dynamically allocated structure (with malloc), it is up to you to deallocate that structure when you no longer need it (with free). Some examples of usage of this parameters struct are shown in Configuration files. It is often useful to specify command line options directly in a configuration file, so that the value of some options are read from this file if they are not given as command line options. When the command line option -C|--conf-parser is given to gengetopt, apart from the standard command line option parser, also this additional parser is generated (its name is <cmd_parser_name>_config_file34): int <cmd_parser_name>_config_file(char * const filename, struct gengetopt_args_info *args_info, struct <cmd_parser_name>_params *params); The parameter structure <cmd_parser_name>_params is described in Parser function additional parameters. For instance, params->override tells whether the values read in the configuration file have to override those specified at the command line. IMPORTANT: you have to explicitly set params->initialize to 1 if you call the config file parser before the standard command line option parser, otherwise unpredictable results may show. If you call the config file parser before the standard command line option parser and then you want to call the standard command line parser you MUST use this second version of the parser function, with params->initialize set to 0, so that collected values from the config file are not lost35: int <cmd_parser_name>_ext (int argc, char **argv, struct gengetopt_args_info *args_info, struct <cmd_parser_name>_params *params); Notice, that with this version you can also specify whether the options passed at the command line must override the ones read from the config file. Moreover, you have to specify whether the check for missing required options must be performed or not. This concerns also options of a required group (Group options). If you decide not to request the check for required option, you can test it manually, after the command line parsing returns by using the following generated function: int <cmd_parser_name>_required (struct gengetopt_args_info *args_info, const char *program_name); where program_name is the name of your executable (usually you should pass argv[0] as argument). If the function returns a value different from 0, then some required options are missing. An error has already been printed by this function. This concerns also options of a required group (Group options). The config file has the following simple syntax: lines starting with # are considered comments and: <option_name> = {<option_val>} or simply (if the option does not take an argument): <option_name> which means that option_name is given, and if it accepts an argument, then its value is option_val. The = is not mandatory. Since version 2.19, it is possible to include other files (i.e., other configuration files) in a configuration file, by using the include syntax: include "filename" For instance here's a program that uses this feature (this is the test test_conf_parser): /* test_conf_parser.c test */ /* test all kinds of options and the conf file parser */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdlib.h> #include <stdio.h> #include "test_conf_parser_cmd.h" static struct my_args_info args_info; int main (int argc, char **argv) { unsigned int i; int result = 0; struct test_conf_parser_cmd_parser_params *params; /* initialize the parameters structure */ params = test_conf_parser_cmd_parser_params_create(); /* call the command line parser */ if (test_conf_parser_cmd_parser (argc, argv, &args_info) != 0) { result = 1; goto stop; } /* override command line options, but do not initialize args_info, check for required options. NOTICE: we must NOT skip the 0 assignment to initialize, since its default value is 1 and override defaults to 0 while check_required is already set to its default value, 1 */ params->initialize = 0; params->override = 1; /* call the config file parser */ if (test_conf_parser_cmd_parser_config_file (args_info.conf_file_arg, &args_info, params) != 0) { result = 1; goto stop; }); printf ("value of multi-string_given: %d\n", args_info.multi_string_given); for (i = 0; i < args_info.multi_string_given; i++) printf (" value of multi-string: %s\n", args_info.multi_string_arg [i]); printf ("value of multi-string-def_given: %d\n", args_info.multi_string_def_given); for (i = 0; i < args_info.multi_string_def_given; ++i) printf (" value of multi-string-def: %s\n", args_info.multi_string_def_arg [i]); if (!args_info.multi_string_def_given && args_info.multi_string_def_arg [0]) printf ("default value of multi-string-def: %s\n", args_info.multi_string_def_arg [0]); printf ("value of opta: %s\n", args_info.opta_arg); printf ("noarg given %d times\n", args_info.noarg_given); printf ("noarg_noshort given %d times\n", args_info.noarg_noshort_given); printf ("opt-arg given: %d\n", args_info.opt_arg_given); printf ("opt-arg value: %s\n", (args_info.opt_arg_arg ? args_info.opt_arg_arg : "not given")); if (args_info.file_save_given) { if (test_conf_parser_cmd_parser_file_save (args_info.file_save_arg, &args_info) == EXIT_FAILURE) result = 1; else printf ("saved configuration file %s\n", args_info.file_save_arg); } stop: /* deallocate structures */ test_conf_parser_cmd_parser_free (&args_info); free (params); return result; } So if we use the following config file # required option required "this is a test" float 3.14 no-short string another and we run test_conf_parser like that, we will have ./test_conf_parser -r bar -i 100 --float 2.14 --conf-file test_conf.conf value of required: this is a test value of string: another value of no-short: 1 value of int: 100 value of float: 3.140000 If, instead we call the test_conf_parser_cmd_parser_configfile with 0 for override argument, we get the following result value of required: bar value of string: another value of no-short: 1 value of int: 100 value of float: 2.140000 This second example use the second version of the command line parser: first call the configuration file parser and then the command line parser (the command line options will override the configuration file options): /* test_conf_parser_ov2.c test */ /* test all kinds of options and the conf file parser */ /* differently from test_conf_parser_ov.c, first scan the conf file and then the command line */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdlib.h> #include <stdio.h> #include "test_conf_parser_cmd.h" static struct my_args_info args_info; int main (int argc, char **argv) { struct test_conf_parser_cmd_parser_params *params; /* initialize the parameters structure */ params = test_conf_parser_cmd_parser_params_create(); /* initialize args_info, but don't check for required options NOTICE: the other fields are initialized to their default values */ params->check_required = 0; /* call the config file parser */ if (test_conf_parser_cmd_parser_config_file ("../../tests/test_conf2.conf", &args_info, params) != 0) exit(1); /* override config file options, do not initialize args_info, check for required options. */ params->initialize = 0; params->override = 1; params->check_required = 1; /* call the command line parser */ if (test_conf_parser_cmd_parser_ext (argc, argv, &args_info, params) != 0) exit(1) ;); /* release memory */ test_conf_parser_cmd_parser_free (&args_info); free (params); return 0; } This is an invocation and its results: ./test_conf_parser_ov2 -r "bar" --float 2.14 -i 100 value of required: bar value of string: another value of no-short: 1 value of int: 100 value of float: 2.140000 If on the above code you substitute params->override = 1 with params->check_ambiguity = 1 (see the test file test_conf_parser_ov4.c), then the following invocation will generate an error: ./test_conf_parser_ov4 -r "bar" -i 100 ./test_conf_parser_ov4: `--required' (`-r') option given more than once since the -r option is specified both in the configuration file and at the command line. The generated config file parser function uses the constant CONFIG_FILE_LINE_SIZE to read each line of the configuration file. By default this constant is set to 2048 that should be enough for most applications. If your application uses configuration files with lines that are longer, you can compile the generated C file by specifying an explicit value for this constant with the -D command line option of gcc. If an option is specified as multiple, then it can be specified multiple times at command line. In this case, say the option is called foo, the generated foo_given field in the args structure contains the number of times it was specified and the generated field foo_arg is an array containing all the values that were specified for this option. Notice that if a default value is specified for a multiple option, that value is assigned to the option only if no other value is specified on the command line, i.e., a default value IS NOT always part of the values of a multiple option. As in the case for standard options, if a multiple option has a default value, and this is set because no value was specified on the command line, then the corresponding <option>_given will still be initialized to 0. Thus, <option>_given will effectively inform you if the user has specified that command line option. If it is known that a multiple option has a default value, then it can be safely assumed that the first element of generated array <option>_arg is always set. For instance, if the gengetopt file is as follows # test options that can be given more than once option "string" s "string option" string optional multiple option "int" i "int option" int optional multiple Then the command line options can be collected like that Then if this program is called with the following command line options /* test options that can be given more than once */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdlib.h> #include <stdio.h> #include "test_multiple_cmd.h" static struct gengetopt_args_info args_info; int main (int argc, char **argv) { int i = 0; if (test_multiple_cmd_parser (argc, argv, &args_info) != 0) exit(1) ; for (i = 0; i < args_info.string_given; ++i) printf ("passed string: %s\n", args_info.string_arg[i]); for (i = 0; i < args_info.int_given; ++i) printf ("passed int: %d\n", args_info.int_arg[i]); return 0; } The output of the program will be passed string: world passed string: hello passed string: bar passed string: foo passed int: 200 passed int: 100 You can also pass arguments to a multiple option separated by commas (if you need to actually specify the comma operator as part of the argument you can escape it with \), as in the following: ./test_multiple -s"foo","bar","hello" -i100,200 -s "world" You can specify the number of occurrences of multiple options by using the following syntax (that must be given after the multiple keyword): (number) numbertimes (number1-number2) number1times and no more than number2times (number-) numbertimes (-number) numbertimes Here are some examples: option "string" s "string option" string optional multiple(4) option "string" s "string option" string optional multiple(1-4) option "string" s "string option" string optional multiple(-5) Notice that this is independent from the required flag. The parsers generated by gengetopt (indeed the C and header files) are self-contained and different parsers can be linked in the same program, without interferences. This is useful, e.g., in cases where a specific command line option argument has a complex syntax that accepts options itself according to terminology already defined, i.e., the one handled by getopt_long, see Terminology. Another case when multiple parsers can be useful is when your command behaves differently according to a specific command line option. Obviously there exists only one instance of command line arguments passed to the main function (namely the variables argc and argv) so passing the same arguments to different command line parsers is likely to generate errors: the different command line parsers are likely to have different syntaxes for accepted options. For this reason gengetopt can generate parser functions that take a string containing the further options to parse, instead of taking an array. This additional parser will have the parser name and the suffix _string. If you want these additional parsers to be generated you have to pass the command line option -S|--string-parser to gengetopt (see Invoking gengetopt). The two functions will be: int <parser_name>_string (const char *cmdline, struct test_first_cmdline_cmd_struct *args_info, const char *prog_name); int <parser_name>_string_ext (const char *cmdline, struct test_first_cmdline_cmd_struct *args_info, const char *prog_name, struct <cmd_parser_name>_params *params); The second version36 allows you to specify more details about the parsing, using the <cmd_parser_name>_params structure, shown in Parser function additional parameters (this is the same as for configuration files, thus we refer to that section for the details of the two functions and default values, see Configuration files). Of course, these functions can be used in general to simulate the invocation of a program with specific command line options (stored in the first string argument), or in general to parse options that are all stored in a string (instead of a vector). The first argument of these parsers is a string containing the options to parse (remember that this must respect the option format handled by getopt_long, see Terminology). The second one is the pointer to the struct that will be filled with passed options and arguments, as usual. The third option is the program name: this will be used when errors have to be printed. This last argument can be null: in this case, the first element of the first string argument is considered the program name. Let's show these functionalities with an example. Consider a program that accepts two command line options (required in this case): # test for multiple parsers, this is the main file # test_main_cmdline_cmd.ggo option "first-cmd" F "the first command line to parse" required \ typestr="first command" string multiple option "second-cmd" S "the second command line to parse" required \ typestr="second command" string multiple These two options accept strings as argument that in turn are considered command line arguments, according to specific syntaxes. The first one is: # test for multiple parsers, this is the first command line file # test_first_cmdline_cmd.ggostr option "option-a" a "option a of the first command line to parse" optional int option "multi" M \ "multiple option of the first command line to parse" \ optional string multiple and the second one is: # test for multiple parsers, this is the second command line file # test_second_cmdline_cmd.ggostr option "option-a" a "option a of the second command line to parse" \ optional string option "option-b" b "option a of the second command line to parse" \ optional string option "my-multi" M \ "multiple option of the second command line to parse" \ optional string multiple These last two files are processed with gengetopt using the --string-parser. Let's put everything together in this main file: #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdio.h> #include <stdlib.h> #include "test_main_cmdline_cmd.h" #include "test_first_cmdline_cmd.h" #include "test_second_cmdline_cmd.h" int main(int argc, char **argv) { struct gengetopt_args_info main_args_info; struct test_first_cmdline_cmd_struct first_args_info; struct test_second_cmdline_cmd_struct second_args_info; int exit_code = 0; unsigned int i, j; if (test_main_cmdline_cmd_parser (argc, argv, &main_args_info) != 0) { exit_code = 1; return exit_code; } for (j = 0; j < main_args_info.second_cmd_given; ++j) { printf("second cmdline: %s\n", main_args_info.second_cmd_arg[j]); if (test_second_cmdline_cmd_parser_string (main_args_info.second_cmd_arg[j], &second_args_info, argv[0]) == 0) { if (second_args_info.option_a_given) printf(" --option-a: %s\n", second_args_info.option_a_arg); if (second_args_info.option_b_given) printf(" --option-b: %s\n", second_args_info.option_b_arg); for (i = 0; i < second_args_info.my_multi_given; ++i) printf(" --my-multi: %s\n", second_args_info.my_multi_arg[i]); test_second_cmdline_cmd_parser_free (&second_args_info); } } for (j = 0; j < main_args_info.first_cmd_given; ++j) { printf("first cmdline: %s\n", main_args_info.first_cmd_arg[j]); if (test_first_cmdline_cmd_parser_string (main_args_info.first_cmd_arg[j], &first_args_info, argv[0]) == 0) { if (first_args_info.option_a_given) printf(" --option-a: %d\n", first_args_info.option_a_arg); for (i = 0; i < first_args_info.multi_given; ++i) printf(" --multi: %s\n", first_args_info.multi_arg[i]); test_first_cmdline_cmd_parser_free (&first_args_info); } } test_main_cmdline_cmd_parser_free (&main_args_info); return exit_code; } Notice that in the for loops we always free the elements of the argument structures in order to avoid memory leaks. Now if you can run this program as follows (notice that we use the comma separated arguments for multiple option arguments but we escape it with \ because otherwise, e.g., 200 and 300 would be intended as further arguments of --first-cmd instead of --multi, see Multiple Options): ./test_multiple_parsers \ --first-cmd="-M400 -a10 --multi 100\,200\,300" \ --second-cmd="-a20 -b10 --my-multi=a\,b\,c\,d\,e\,f" \ -F"-M500 -M600" -S"--my-multi g" second cmdline: -a20 -b10 --my-multi=a,b,c,d,e,f --option-a: 20 --option-b: 10 --my-multi: a --my-multi: b --my-multi: c --my-multi: d --my-multi: e --my-multi: f second cmdline: --my-multi g --my-multi: g first cmdline: -M400 -a10 --multi 100,200,300 --option-a: 10 --multi: 400 --multi: 100 --multi: 200 --multi: 300 first cmdline: -M500 -M600 --multi: 500 --multi: 600 If you use gengetopt to generate C functions for parsing command line arguments you have to know that these generated functions use getopt_long to actually read the command line and parsing it. This function is typically part of the standard C library, but some implementations may not include it. If you want your program to be portable on several systems, and be compilable with many C compilers, you can rely on one of the following solutions. getopt_longcode into the generated parser Since version 2.17, gengetopt can include into the generated C parser file the code of getopt_long, so that the include code will be used to actually parse the command line arguments, instead of that taken from the C library. This solution is actually quite easy, since you only need to specify the command line option --include-getopt (see Invoking gengetopt), but it has two main drawbacks: getopt_longof the C library It is up to you to choose between this and the automake/autoconf based solution. Actually, this solution has the advantage that your program won't behave strangely when used with another implementation of getopt_long. I prefer the automake/autoconf based solution, as described in Use automake/autoconf, in particular the one described in Use Gnulib, which is also the one I adopt for gengetopt itself. getopt_long Autoconf and Automake are great tools to generate a configure script that automatically checks for the configuration of your system and for possible missing functions required to compile your program. However, in case of detected missing functions, your program must be able to provide a replacement for such functions. In the next sections we describe two mechanisms for including the (possible) missing code for getopt_long and for checking its presence with automake/autoconf. Since version 2.19, gengetopt itself uses the first mechanism. Since version 2.19 I also started to use Gnulib - The GNU Portability Library37, “a central location for common GNU code, intended to be shared among GNU packages”. Gnulib provides an easy and smooth way to add to your package sources the sources of functions that you want to check during configure. It will also handle the checks for these functions in the configure script, and in case they're not in your system (or they're present but with some missing features) it compiles their sources into a library (that you will need to link your program to, as illustrated in the following). Once you retrieved gnulib (for the moment it is available only through git, see the home page), you can invoke ‘gnulib-tool --import’ that. In particular, you must specify the modules you want to import, and in our case, it is getopt: gnulib-tool --import getopt By default, the source code is copied into lib/ and the M4 macros in m4/. You can override these paths by using --source-base=DIRECTORY and --m4-base=DIRECTORY. For instance, gengetopt uses gl and gl/m4, respectively. We will use these directories in the rest of this section. You must ensure Autoconf can find the macro definitions in gnulib-comp.m4. Use the ACLOCAL_AMFLAGS specifier in your top-level Makefile.am file (and the first time you run aclocal you have to use the -I as well); for instance, in the case of gengetopt we have: ACLOCAL_AMFLAGS = -I gl ... The core part of the gnulib checks are done by the macro gl_INIT. Place it further down in the file, typically where you normally check for header files or functions. For example: ... # For gnulib. gl_INIT ... gl_INIT will in turn call the macros related with the gnulib functions, be it specific gnulib macros.(... gl/Makefile ...) You must also make sure that make will recurse into the gnulib directory. To achieve this, add the gnulib source base directory to a SUBDIRS Makefile.am statement, as in: SUBDIRS = gl Finally, you have to add compiler and linker flags in the appropriate source directories, so that you can make use of the gnulib library. Since the ‘getopt’ module copies files into the build directory, top_builddir/gl is needed as well as top_srcdir/gl. For example: ... AM_CPPFLAGS = -I$(top_srcdir)/gl -I$(top_builddir)/gl ... LDADD = gl/libgnu.a ... Don't forget to #include the various header files. In this example, you would need to make sure that ‘#include "getopt.h"’ is evaluated when compiling all source code files, that want to make use of getopt or getopt_long. If you simply use the files generated by gengetopt, you won't need include this header though, since it is already handled by the generated files. Every now and then, check whether there are updates in the Gnulib modules, and if the modules you use (e.g., getopt) are upgraded, please remember to also update your files, simply by running: gnulib-tool --update We refer to Gnulib documentation for further explanations and features. NOTICE: this was the procedure used by gengetopt itself up to version 2.18. We suggest now to use the procedure described in Use Gnulib, since the files described in the following might not be kept up-to-date. We provide C files that actually implement getopt_long function: getopt.c getopt1.c and gnugetopt.h. You'll find these files in the <install prefix>/share/gengetopt directory where <install prefix> is the one you specified during compilation. If no prefix had been specified, /usr/local is the default. If you downloaded gengetopt in binary form prefix will probably be /usr/local or /usr. You can rename gnugetopt.h to getopt.h and then simply compile these files and link them to the executable of you program. However, if you use automake and autoconf here's a more elegant solution: you should download the file adl_func_getopt_long.m4 you find at this site: and add its contents to your acinclude.m4. You can find this macro also in the acinclude.m4 in the sources of gengetopt. This macro checks if getopt_long function is in C library; if it is not then it adds getopt.o and getopt1.o to the objects files that will be linked to your executable ( LIBOBJS). Then in Makefile.am of your source directory you have to add the contents of LIBOBJS to the LDADD of the program that has to use getopt_long; e.g., if the program foo has to use getopt_long, you have to add the following line foo_LDADD = @LIBOBJS@ Now these files will be compiled and linked to your program only if necessary. Moreover you have to add getopt.c getopt1.c and gnugetopt.h to your distribution. Note that it is not necessary to put these file names among the foo_SOURCES contents), but you have to add gnugetopt.h to EXTRA_DIST: EXTRA_DIST = gnugetopt.h You may want to take a look at gengetopt's configure.in and src/Makefile.am: they both use the techniques described here. If you find a bug in gengetopt, please use the Savannah web interface Include the version number, which you can find by running ‘gengetopt --version’. Also include in your message the output that the program produced and the output you expected. If you have other questions, comments or suggestions about gengetopt, contact the author via electronic mail (find the address at). The author will try to help you out, although he may not have time to fix your problems. The list of to-dos in the TODO. It seems that getopt_long, at least the version in the GNU library, if invoked with different argv arrays, might access memory in a bad way leading to crashes or unexpected behaviors. This happens because it keeps pointers to locations of the previous arrays if not initialized each time by setting optind = 038. Unfortunately this initialization behavior seems to be part only of the implementation of GNU library and actually it is not documented (you can see it by taking a look into the source of getopt.c); other implementations of getopt_long might not be affected by this problem; alternatively, as reported by a user, optind = 0 leads some getopt_long implementations to consider the program name as a command line option (since it is in position 0), which is bad anyway! Probably this is usually not a problem since you usually parse only the command line, thus you only invoke the command line parser only once, and only with one instance of array (i.e., the argv passed to main). However, it can lead to problems when you use advanced features, as in the case of configuration file parsing (see Configuration files) and multiple parsers (see String Parsers and Multiple Parsers). The parser generated by gengetopt checks whether the program name was actually considered a command line option, and in that case it removes it from the collected command line options; thus, this optind issue should not come up anyway. In case you still don't feel comfortable, you can include a correct getopt_long implementation in the generated parser, so that you can be sure you will always use the same implementation of getopt_long (Include the getopt_long code into the parser). The following mailing lists are available: help-gengetopt at gnu dot org for generic discussions about the program and for asking for help about it (open mailing list), info-gengetopt on my blog, at this URL: --arg-struct-name: Invoking gengetopt --conf-parser: Invoking gengetopt --default-optional: Invoking gengetopt --default-optional: Basic Usage --detailed-help: Basic Usage --full-help: Basic Usage --func-name: Invoking gengetopt --gen-version: Invoking gengetopt --header-output-dir: Invoking gengetopt --include-getopt: Include the getopt_long code into the parser --include-getopt: Invoking gengetopt --long-help: Invoking gengetopt --no-handle-error: Invoking gengetopt --no-handle-help: Invoking gengetopt --no-handle-version: Invoking gengetopt --no-help: Invoking gengetopt --no-version: Invoking gengetopt --output-dir: Invoking gengetopt --show-full-help: Invoking gengetopt --show-help: Invoking gengetopt --show-required: Invoking gengetopt --show-version: Invoking gengetopt --src-output-dir: Invoking gengetopt --string-parser: Invoking gengetopt --unamed-opts: Invoking gengetopt -C,--conf-parser: Configuration files -h,--detailed-help: Basic Usage -h,--help: Basic Usage -S,--string-parser: String Parsers and Multiple Parsers -V,--version: Basic Usage [1] Since version 2.22.4 of Gengetopt the CVS repository was dismissed in favor of Git (). [2] [3] [4] [5] [10] Since version 2.22 the type can be specified [14] This is true since version 2.19. Before this version, strings were not allowed to spawn more than one line. [16] This holds since version 2.15: in previous versions the option specifications had to be given in a fixed order. [17] Before version 2.22 neither --help was added and you had to handle the help option manually [21] as it was up to version 2.22.2 of gengetopt. [22] This is taken from the comments in getopt.in.h of gnulib. [23] Since version 2.22 this field is of type unsigned int instead of int for uniformity with multiple options. [24] The <option>_orig was introduced in the release 2.14. [25] These strings and the <option>_help were introduced in the release 2.17. [26] This function was introduced in the release 2.14. [27] Introduced in version 2.22, thanks to Papp Gyozo. [29] Since version 2.22.3. [32] Introduced in version 2.22 [33] The <cmd_parser_name>_params_init was introduced in version 2.21, but it used to initialize all its fields to 0, which does not make much sense, since it's more helpful to have the fields initialized to their default values; in order not to silently break the semantics of previous code, the (void argument) creation function is now called <cmd_parser_name>_params_create and <cmd_parser_name>_params_init is now a procedure that initializes a passed pointer to the structure. This will make previous code not compilable, since the signature of <cmd_parser_name>_params_init has changed; hopefully, this will force the programmer to realize that something has changed. I'm sorry for the (hopefully little) problems this change might imply. [34] The previous function <cmd_parser_name>_configfile — notice the absence of the _ — is deprecated and should be no longer used, since it might be removed in the future releases. [35] The previous function <cmd_parser_name>2 — notice the 2 — is deprecated and should be no longer used, since it might be removed in the future releases. [36] The previous function <cmd_parser_name>_string2 — notice the 2 — is deprecated and should be no longer used, since it might be removed in the future releases. [37] [38] optind is the global variable in getopt implementation that is the index in ARGV of the next element to be scanned. This is used for communication to and from the caller and for communication between successive calls to getopt_long.
https://www.gnu.org/software/gengetopt/gengetopt.html
CC-MAIN-2015-11
refinedweb
13,611
52.39
Create Data Transfer Objects (DTOs) by Mike Wasson Download Completed Project Right now, our web API exposes the database entities to the client. The client receives data that maps directly to your database tables. However, that's not always a good idea. Sometimes you want to change the shape of the data that you send to client. For example, you might want to: - Remove circular references (see previous section). - Hide particular properties that clients are not supposed to view. - Omit some properties in order to reduce payload size. - Flatten object graphs that contain nested objects, to make them more convenient for clients. - Avoid "over-posting" vulnerabilities. (See Model Validation for a discussion of over-posting.) - Decouple your service layer from your database layer. To accomplish this, you can define a data transfer object (DTO). A DTO is an object that defines how the data will be sent over the network. Let's see how that works with the Book entity. In the Models folder, add two DTO classes: namespace BookService.Models { public class BookDto { public int Id { get; set; } public string Title { get; set; } public string AuthorName { get; set; } } } namespace BookService.Models { public class BookDetailDto { public int Id { get; set; } public string Title { get; set; } public int Year { get; set; } public decimal Price { get; set; } public string AuthorName { get; set; } public string Genre { get; set; } } } The BookDetailDto class includes all of the properties from the Book model, except that AuthorName is a string that will hold the author name. The BookDto class contains a subset of properties from BookDetailDto. Next, replace the two GET methods in the BooksController class, with versions that return DTOs. We'll use the LINQ Select statement to convert from Book entities into DTOs. // GET api/Books public IQueryable<BookDto> GetBooks() { var books = from b in db.Books select new BookDto() { Id = b.Id, Title = b.Title, AuthorName = b.Author.Name }; return books; } // GET api/Books/5 [ResponseType(typeof(BookDetailDto))] public async Task<IHttpActionResult> GetBook(int id) { var book = await db.Books.Include(b => b.Author).Select(b => new BookDetailDto() { Id = b.Id, Title = b.Title, Year = b.Year, Price = b.Price, AuthorName = b.Author.Name, Genre = b.Genre }).SingleOrDefaultAsync(b => b.Id == id); if (book == null) { return NotFound(); } return Ok(book); } Here is the SQL generated by the new GetBooks method. You can see that EF translates the LINQ Select into a SQL SELECT statement. SELECT [Extent1].[Id] AS [Id], [Extent1].[Title] AS [Title], [Extent2].[Name] AS [Name] FROM [dbo].[Books] AS [Extent1] INNER JOIN [dbo].[Authors] AS [Extent2] ON [Extent1].[AuthorId] = [Extent2].[Id] Finally, modify the PostBook method to return a DTO. [ResponseType(typeof(BookDto))] public async Task<IHttpActionResult> PostBook(Book book) { if (!ModelState.IsValid) { return BadRequest(ModelState); } db.Books.Add(book); await db.SaveChangesAsync(); // New code: // Load author name db.Entry(book).Reference(x => x.Author).Load(); var dto = new BookDto() { Id = book.Id, Title = book.Title, AuthorName = book.Author.Name }; return CreatedAtRoute("DefaultApi", new { id = book.Id }, dto); } Note In this tutorial, we're converting to DTOs manually in code. Another option is to use a library like AutoMapper that handles the conversion automatically.
https://docs.microsoft.com/en-us/aspnet/web-api/overview/data/using-web-api-with-entity-framework/part-5
CC-MAIN-2020-10
refinedweb
522
53.58
Discover why, when, and how to use WarpScript in Python, to glean the benefits of using the analytics engine of the most advanced time series platform. Pythonists can benefit from using WarpScript in Python. In this post, we explain why, when, and how to do that. Some of the contents in this article are taken from the talk I gave at a PyData meetup recently. The slides are available here. If it's the first time that you hear about WarpScript, I suggest you read this post first. Why and when do you need WarpScript? Python users already have the Pandas library to work with time-series, so when would they need WarpScript? - WarpScript supports pickle (using ->PICKLEand PICKLE->functions). This means that data can flow efficiently between Python and WarpScript. - WarpScript has built-in functions to manipulate data and meta-data coming from time-series databases. For example, multi-way grouping and computing the mean series in each group can be done with one line of code: [ $gts [ 'key1' 'key2' ] reducer.mean ] REDUCE ]. - WarpScript library is specialized in time-series (and geo time series) and contains more than 1000 functions which were written to answer common practical use cases, from time and geo manipulation to graphical content generation and more. Not reinventing the wheel will gain you time! - Some functions overlap between WarpScript and pandas. For example BUCKETIZEwith .resample()and MAPwith .rolling(), but they differ enough to justify using WarpScript version of the function in practical cases (for example when there are missing data). - The same WarpScript can be executed either on a single server, or can be distributed with PySpark. See the doc here. - WarpScript doesn't need a Warp 10 platform. You can use it for its library, or process any input source on-the-fly. For example, it can transform any Hadoop input format at loading time. - You can include WarpScript macros from a trusted remote repository easily. Just use the syntax @repo/my/macroin your WarpScript to use a remote macro. How to use WarpScript in Python Using WarpScript in Python can be done in just a few steps. Method 1: From a Jupyter notebook Just pip install the extension and load it in your notebook. %bash pip install warp10-jupyter %load_ext warpscript Now you are good to use the %%warpscript cell magic. The --local/l flag is used to tell that you are using the WarpScript library locally. If you want it to be connected to a Warp 10 platform, you can specify the --address and --port on which its Py4J gateway runs (see this post for more information). %%warpscript --local --stack stack 'Hello world of WarpScript!' top: 'Hello world of WarpScript!' The WarpScript execution environment is stored under the variable stack. It will be reused in subsequent %%warpscript cells, or you can also use it to directly execute WarpScript code stack.exec("some-warpscript-code"). Method 2: Not from a Jupyter notebook Note that the same package also provides functions to execute WarpScipt code outside of a notebook. import warpscript #pip install warp10-jupyter stack = warpscript.newLocalStack() # or newStack(adress, port, auth_token) stack.exec('Hello world of WarpScript!') ... Note that .exec() executes one-line statements and .execMulti() executes multi-line strings. Method 3: With the Py4J library If you want more control on your interaction with the stack and the JVM (for example for using a specific Warp 10 version, for using WarpScript extensions or simply other libraries from the Java world), you can do what precedes using the Py4J library directly. With this method, you need a Warp 10 jar first. You can download one from bintray, then untar it: wget tar xvzf warp10-X.Y.Z.tar.gz Now, launch a Py4J gateway. This gateway is responsible for creating a stack (the environment which executes WarpScript code). If you want to be connected to a Warp 10 platform, connect to its gateway rather than launching one. from py4j import launch_gateway, JavaGateway, GatewayParameters import warpscript # optional import (in warp10-jupyter package), this overrides methods for printing stack and GTS objects port, token = launch_gateway(enable_auth=True,die_on_exit=True,classpath='warp10-2.1.0/bin/warp10-2.1.0.jar') gateway = JavaGateway(gateway_parameters=GatewayParameters(port=port, auto_convert=True, auth_token=token)) Specify a WarpScript configuration and create the stack: default_conf = {} default_conf['warp.timeunits'] = 'us' default_conf['py4j.stack.nolimits'] = 'true' entry_point = gateway.jvm.io.warp10.Py4JEntryPoint(default_conf) stack = entry_point.newStack() You can now play with it! stack.exec('Hello world of WarpScript!') ... Conversions The gateway already automatically converts usual objects: numbers, lists, dicts, strings, bytes ... For larger objects, the principled way to transfer them between Python and WarpScript is to use the pickle representation. For example, in what follows we transfer some data to WarpScript: import pickle stack.push(pickle.dumps(ticks)) stack.push(pickle.dumps(values)) Now we use a WarpScript function (here it is TIMESPLIT): %%warpscript --local --stack stack --not-verbose [ 'ticks' 'values' ] STORE $ticks PICKLE-> [] [] [] $values PICKLE-> MAKEGTS 1 d 2 'piece' TIMESPLIT VALUES ->PICKLE ... and we retrieve data back in Python: result = pickle.loads(stack.pop()) Additional tips %%warpscript --local --stack stack NOOP Local gateway launched on port 40641 Creating a new WarpScript stack accessible under variable "stack". - You can load macros from any trusted remote repository. For example, we can set the list of trusted repository: trusted_repos = stack.getAttribute('warpfleet.repos') if trusted_repos is None: trusted_repos = [] trusted_repos.append('') stack.setAttribute('warpfleet.repos', trusted_repos) And then call a macro from this repo: %%warpscript --local --stack stack 2 @mc2/RANDNORMAL top: -0.9514475048807272 2: -0.6635116324344921 - You can use the --not-verbose/-vflag if your stack contains big pickle objects to avoid the notebook representing them below the executed cell - Stack objects have the same public methods as defined in WarpScript source code. Of notable use are .peek(), .pop(), .get(int), .push(), .getAttribute(key), setAttribute(key, value), .depth()... you can list them all with dir(stack). - The --stack/sflag uses stackas default, so --stack stackis in fact not needed. - The --local/lflag is only needed when the stack is initiated. After that, the stack variable given as argument (or default one) is reused. Conclusion In this post, we reviewed why and when to use WarpScript in Python and how to do it. Happy WarpScripting in Python! You may also be interested to read the previous post on the Py4J plugin for Warp 10, on the post that presented the notebook extension, and on the related page from the official documentation. Read more How to migrate data from a Warp 10 instance to another in 2 easy steps. Warp 10 2.0 introduced interactive mode which makes easier to explore WarpScript. In this tutorial we set up a WarpScript interpreter using this feature.
https://blog.senx.io/warpscript-for-pythonists/
CC-MAIN-2021-04
refinedweb
1,119
58.08
Simply put, Machine Learning (ML) is the process of employing algorithms to help computer systems progressively improve their performance for some specific task. Software-based ML can be traced back to the 1950’s, but the number and ubiquity of ML algorithms has exploded since the early 2000’s, mainly due to the rising popularity of the Python programming language, which continues to drive advances in ML. The reigning ML algorithm champ is arguably Python’s scikit-learn package, which offers simple and easy syntax paired with a treasure trove of multiple algorithms. While some algorithms are more appropriate for specific tasks, others are widely applicable to any project. In this article, I’ll show you the top 10 machine learning algorithms that always save my day! Before You Start: Install The Top 10 Algorithms Python Environment To follow along with the code in this article, you can download and install our pre-built Top 10 Algorithms environment, which contains a version of Python 3.9 and the packages used in this post. Top 10 Algorithms into a virtual environment: powershell -Command "& $([scriptblock]::Create((New-Object Net.WebClient).DownloadString(''))) -activate-default Pizza-Team/Top-Algorithms" For Linux users, run the following to automatically download and install our CLI, the State Tool along with the Top 10 Algorithms into a virtual environment: sh <(curl -q) --activate-default Pizza-Team/Top-Algorithms Choosing A Dataset To show how different algorithms work, we’ll apply them to a standard dataset. It has often been said that the results of an ML experiment are more dependent on the dataset you use than the algorithm you chose. With this in mind, we’ll choose a reputable classification dataset from Kaggle called “Titanic – Machine Learning from Disaster.” Exploring a Dataset By consulting the data dictionary on Kaggle, we can see that the dataset contains the following information: At this phase, you would typically perform an Exploratory Data Analysis on the dataset. If you’d like to deep-dive into this, you can pause this article and read my “Exploratory Data Analysis Using Python” blog and come right back. Cleaning & Preparing a Dataset Before we apply any algorithms against this data, it needs to be cleaned. This means weeding out missing values, transforming label data, normalizing values, and sometimes even dumping columns that we don’t need. In the interest of time (and length), I’m going to gloss over this portion. If you want to read a more detailed approach to this, you can explore another one of my blogs: “How To Clean Machine Learning Datasets Using Pandas” from where I’ve taken some of the concepts used in this article. Step 1: Drop Unnecessary Columns Several columns either have missing data or too much textual information that we can’t easily use. We can drop them like this: def drop_useless_columns(self): self.df.drop(['PassengerId'], axis=1, inplace=True) self.df.drop(['Name'], axis=1, inplace=True) self.df.drop(['Ticket'], axis=1, inplace=True) self.df.drop(['Cabin'], axis=1, inplace=True) It is important to note that many of these columns could be put to use to further strengthen the result. However, that would involve a lot of pre-processing. Step 2: Encode Labels This step converts labels into comparable numeric data: def one_hot_encode_columns(self): # Encode Pclass dummies = pd.get_dummies(self.df['Pclass'], prefix='route') self.df = pd.concat([self.df, dummies], axis=1) self.df.drop(['Pclass'], axis=1, inplace=True) # Encode Sex dummies = pd.get_dummies(self.df['Sex'], prefix='route') self.df = pd.concat([self.df, dummies], axis=1) self.df.drop(['Sex'], axis=1, inplace=True) # Encode Embarked dummies = pd.get_dummies(self.df['Embarked'], prefix='route') self.df = pd.concat([self.df, dummies], axis=1) self.df.drop(['Embarked'], axis=1, inplace=True) Step 3: Fill in Missing Values You can use self.df.isna().any() to find out if the dataset has missing or NaN columns: Survived False Age True SibSp False Parch False Fare False route_1 False route_2 False route_3 False route_female False route_male False route_C False route_Q False route_S False dtype: bool As you can see, the age variable has missing values. We can fill those in by getting the average age of the entire dataset: ef fill_in_nan(self): mean_age = self.df['Age'].mean() self.df['Age'].fillna(value=mean_age, inplace=True) Step 4 – Splitting The Dataset Now, let’s split the dataset into training and testing data using sklearn’s train_test_split: @staticmethod def clean_and_split(): base = Base() # clean base.drop_useless_columns() base.one_hot_encode_columns() base.fill_in_nan() # split return base.split() Perfect! Now that we’ve cleaned up the data and split it, it’s time to learn – or rather, for the machine to learn! Top ML Algorithms in Scikit-Learn Decision Tree Algorithm The Decision Tree algorithm is widely applicable to most scenarios, and can be surprisingly effective for such a simple algorithm. It requires minimal data preparation, and can even work with blank values. This algorithm focuses on learning simple decision rules inferred from the data. It then compiles them into a set of “if-then-else” decision rules: from sklearn.tree import DecisionTreeClassifier from base import Base Xtrain, Xtest, ytrain, ytest = Base.clean_and_split() model = DecisionTreeClassifier() model.fit(Xtrain, ytrain) ypred = model.predict(Xtest) print("\n\nDecision Tree Accuracy Score:", Base.accuracy_score(ytest, ypred), "%") And here’s the result: [Running] python -u "/top-10-machine-learning-algorithms-sklearn/decision_tree.py" Decision Tree Accuracy Score: 75.0 % [Done] exited with code=0 in 1.248 seconds Now, let’s chart a visualization of the tree itself. It’s quite easy to do since sklearn provides export_graphviz as part of its tree module: from sklearn.tree import export_graphviz dot_file = 'visualizations/decision_tree.dot' export_graphviz(model, out_file=dot_file, feature_names=Xtrain.columns.values) Now that you have the file, just convert it into a PNG image: dot -Tpng decision_tree.dot -o decision_tree.png You can also view a more detailed version here. Random Forest Classifier Algorithm If you think one decision tree is great, imagine what a forest of them could do! That’s essentially what a Random Forest Classifier does. The classification starts off by using multiple trees with slightly different training data. The predictions from all of the trees are then averaged out, resulting in better performance than any single tree in the model. Random Forests can be used to solve classification or regression problems. Let’s have a look at how it solves the following classification problem: from sklearn.ensemble import RandomForestClassifier from base import Base Xtrain, Xtest, ytrain, ytest = Base.clean_and_split() model = RandomForestClassifier() model.fit(Xtrain, ytrain) ypred = model.predict(Xtest) print("\n\nRandom Forest Classifier Accuracy Score:", Base.accuracy_score(ytest, ypred), "%") And now for the result: [Running] python -u "/top-10-machine-learning-algorithms-sklearn/random_forest.py" Random Forest Classifier Accuracy Score: 81.0 % [Done] exited with code=0 in 1.106 seconds K-Nearest Neighbor Algorithm The k-nearest neighbor (KNN) algorithm is a simple and efficient algorithm that can be used to solve both classification and regression problems. If you know the saying, “birds of a feather flock together” you have the essence of KNN in a nutshell. It assumes that similar “things” exist in close proximity to each other. Although you need to perform a certain amount of data cleansing before applying the algorithm, the benefits outweigh the burdens. Let’s have a look: from sklearn.neighbors import KNeighborsClassifier from base import Base Xtrain, Xtest, ytrain, ytest = Base.clean_and_split() model = KNeighborsClassifier(n_neighbors=7) model.fit(Xtrain, ytrain) ypred = model.predict(Xtest) print("\n\nK-Nearest Neighbor Accuracy Score:", Base.accuracy_score(ytest, ypred), "%") As you can see, you can tune the hyperparameters to achieve the highest accuracy. When the above code is executed with just 1 neighbor, the accuracy rate falls to 70%. [Running] python -u "/top-10-machine-learning-algorithms-sklearn/knn.py" K-Nearest Neighbor Accuracy Score: 74.0 % [Done] exited with code=0 in 0.775 seconds Now let’s visualize it. This part is a little tricky since we will need to reduce the model’s dimensions to be able to visualize the result on a scatter plot. You may want to read more about Principal Component Analysis (PCA), but for the purposes of this article, all you need to know is that PCA is used to reduce dimensionality while preserving the meaning of the data. # Transforming n-features into 2 pca = PCA(n_components=2).fit(X) pca_2d = pca.transform(X) for i in range(0, pca_2d.shape[0]): if y[i] == 1: c1 = pl.scatter(pca_2d[i,0], pca_2d[i,1], c='g', marker='o') elif y[i] == 0: c2 = pl.scatter(pca_2d[i,0], pca_2d[i,1], c='r', marker='+') pl.legend([c1, c2], ['Survived', 'Deceased']) pl.title('Titanic Survivors') plt.savefig('visualizations/knn.png') Now let’s plot our data. We’ll use green dots for passengers who survived and red ones for passengers who did not: Bagging Classifier Algorithm Before we look into Bagging Classifiers, we must understand ensemble learning. In the previous example of Random Forests and Decision Trees, we learned that the former is an averaging of the results of the latter. This is essentially what bagging is: it’s a paradigm in which multiple “weak” learners are trained in parallel to solve the same problem, and then combined to get better results. from sklearn.svm import SVC from sklearn.ensemble import BaggingClassifier from base import Base Xtrain, Xtest, ytrain, ytest = Base.clean_and_split() model = BaggingClassifier( base_estimator=SVC(), n_estimators=10, random_state=0 ) model.fit(Xtrain, ytrain) ypred = model.predict(Xtest) print("\n\nBagging Accuracy Score:", Base.accuracy_score(ytest, ypred), "%") In order to split up the data for multiple learners, we use a Linear Support Vector Classifier (SVC) to fit and divide the data as equally as possible. This means that no one set of data will lean on a column too much or have too much variability between the data. Let’s see what happens: [Running] python -u "/top-10-machine-learning-algorithms-sklearn/bagging.py" Bagging Accuracy Score: 72.0 % [Done] exited with code=0 in 1.302 seconds Boosting Classifier Algorithm Boosting is very similar to bagging in the sense that it averages out the results of multiple weak learners. However, in the case of boosting, these learners are executed in a sequential manner such that the latest model depends on the previous one. This leads to lower bias, meaning that it can handle a larger variance of data. from xgboost.sklearn import XGBClassifier from base import Base Xtrain, Xtest, ytrain, ytest = Base.clean_and_split() model = XGBClassifier() model.fit(Xtrain, ytrain) ypred = model.predict(Xtest) print("\n\nXG Boost Classifier Accuracy Score:", Base.accuracy_score(ytest, ypred), "%") And here is the result: [Running] python -u "/top-10-machine-learning-algorithms-sklearn/xgboost.py" Bagging Accuracy Score: 77.0 % [Done] exited with code=0 in 1.302 seconds Naive Bayes Algorithm It’s time to remember your high school course in probability. The Naive Bayes algorithm determines the probability of each feature set and uses that to determine the probability of the classification itself. Here’s a fantastic example from Naive Bayes for Dummies: “A fruit may be considered to be an apple if it is red, round, and about 3″ in diameter. A Naive Bayes classifier considers each of these “features” (red, round, 3” in diameter) to contribute independently to the probability that the fruit is an apple, regardless of any correlations between features.” Now let’s look at the code: from sklearn.naive_bayes import GaussianNB from base import Base Xtrain, Xtest, ytrain, ytest = Base.clean_and_split() model = GaussianNB() model.fit(Xtrain, ytrain) ypred = model.predict(Xtest) print("\n\nNaive Bayes Accuracy Score:", Base.accuracy_score(ytest, ypred), "%") And the result is pretty good: [Running] python -u "/top-10-machine-learning-algorithms-sklearn/naive_bayes.py" Naive Bayes Accuracy Score: 78.0 % [Done] exited with code=0 in 1.182 seconds What the accuracy score doesn’t show is the probability of false positives and false negatives. We can only capture “how right we are.” However, it is more important to know the extent of “how wrong we are” in many scenarios (including life!). We can plot this using a confusion matrix. This matrix shows the distribution of true positives, true negatives, false positives, and false negatives: mat = confusion_matrix(ytest, ypred) sns.heatmap(mat.T, square=True, annot=True, fmt='d', cbar=False) plt.xlabel('true label') plt.ylabel('predicted label'); plt.savefig("visualizations/naive_bayes_confusion_matrix.png") Now, we can see that the possibility of false positives is higher than false negatives. Support Vector Machines Support Vector Machines (SVMs) are robust, non-probabilistic models that can be used to predict both classification and regression problems. SVMs maximize space to widen the gap between categories and increase accuracy. Let’s have a look: from sklearn import svm from base import Base Xtrain, Xtest, ytrain, ytest = Base.clean_and_split() model = svm.LinearSVC(random_state=800) model.fit(Xtrain, ytrain) ypred = model.predict(Xtest) print("\n\nSVM Accuracy Score:", Base.accuracy_score(ytest, ypred), "%") As you can see, SVMs are generally more accurate than other methods. If even better data cleansing methods are applied, we can aim to reach higher accuracy. [Running] python -u "/top-10-machine-learning-algorithms-sklearn/svm.py" SVM Accuracy Score: 79.0 % [Done] exited with code=0 in 1.379 seconds Now, instead of visualizing model data, let’s look at model performance. We can look at the classification report using scikit learn’s metrics module: precision recall f1-score support 0 0.85 0.82 0.83 144 1 0.69 0.73 0.71 79 accuracy 0.79 223 macro avg 0.77 0.78 0.77 223 weighted avg 0.79 0.79 0.79 223 Stochastic Gradient Descent Classification Stochastic Gradient Descent (SGD) is popular in the neural network world, where it’s used to optimize the cost function. However, we can also use it to classify data. SGD is great for scenarios in which you have a large dataset with a very large feature set. It can help to reduce the complexities involved in learning from highly variable data. from sklearn.linear_model import SGDClassifier from base import Base Xtrain, Xtest, ytrain, ytest = Base.clean_and_split() model = SGDClassifier() model.fit(Xtrain, ytrain) ypred = model.predict(Xtest) print("\n\nStochastic Gradient Descent Classifier Accuracy Score:", Base.accuracy_score(ytest, ypred), "%") Let’s look at how accurate it is: [Running] python -u "/top-10-machine-learning-algorithms-sklearn/stochastic_gradient_descent_classifier.py" Stochastic Gradient Descent Classifier Accuracy Score: 76.0 % [Done] exited with code=0 in 0.779 seconds Logistic Regression This is a very basic model that still delivers decent results. It’s a statistical model that uses logistic (sigmoid) functions to accurately predict data. Before you use this model, you need to ensure that your training data is clean and has less noise. Significant variance could lower the accuracy of the model. from sklearn.linear_model import LogisticRegression from base import Base Xtrain, Xtest, ytrain, ytest = Base.clean_and_split() model = LogisticRegression() model.fit(Xtrain, ytrain) ypred = model.predict(Xtest) print("\n\nLogistic Regression Accuracy Score:", Base.accuracy_score(ytest, ypred), "%") => Logistic Regression Accuracy Score: 79.0 % Now, let’s plot the Receiver Operating Characteristics (ROC) curve for this model. This curve helps us visualize accuracy by plotting the true positive rate on the Y axis and the false positive rate on the X axis. The “larger” the area under the curve, the more accurate the model. Voting Classifier Voting Classifier is another ensemble method where instead of using the same type of “weak” learners, we choose very different models. The idea is to combine conceptually different ML algorithms and use a majority vote to predict the class labels. This is useful for a set of equally well-performing models since it can balance out individual weaknesses. For this ensemble, I will combine a Logistic Regression model, a Naive Bayes model, and a Random Forest model: from sklearn.ensemble import VotingClassifier from sklearn.linear_model import LogisticRegression from sklearn.naive_bayes import GaussianNB from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import cross_val_score from sklearn.model_selection import train_test_split from base import Base df = Base.clean() X = df.drop(['Survived'], axis=1) y = df['Survived'] Xtrain, Xtest, ytrain, ytest = train_test_split(X, y, random_state=0) model_1 = LogisticRegression() model_1.fit(Xtrain, ytrain) ypred = model_1.predict(Xtest) model_2 = GaussianNB() model_2.fit(Xtrain, ytrain) ypred = model_2.predict(Xtest) model_3 = RandomForestClassifier() model_3.fit(Xtrain, ytrain) ypred = model_3.predict(Xtest) eclf = VotingClassifier( estimators=[('lr', model_1), ('rf', model_2), ('gnb', model_3)], voting='hard' ) for clf, label in zip([model_1, model_2, model_3, eclf], ['Logistic Regression', 'Naive Bayes', 'Random Forest', 'Ensemble']): scores = cross_val_score(clf, X, y, scoring='accuracy', cv=5) print("Accuracy: %0.2f (+/- %0.2f) [%s]" % (scores.mean(), scores.std(), label)) Let’s see how it performs: [Running] python -u "/top-10-machine-learning-algorithms-sklearn/voting.py" Accuracy: 0.79 (+/- 0.02) [Logistic Regression] Accuracy: 0.78 (+/- 0.03) [Naive Bayes] Accuracy: 0.80 (+/- 0.03) [Random Forest] Accuracy: 0.80 (+/- 0.02) [Ensemble] [Done] exited with code=0 in 2.413 seconds As you can see, the Voting Ensemble learned from all three models and outperformed them all. Conclusions: Right Algorithm for the Right Job It is quite unfair to pit algorithms against each other. They’re all unique in their own way, and they all come with their own set of advantages and disadvantages. Before choosing which model works best for you, you should ensure that you understand the underlying dataset and feature set. Plot out variances and correlations before you try models out. If you’re still stuck after that, maybe the Voting Classifier can save your day. - You can check out all of this code on GitHub. - Download our Top 10 Algorithms Python environment, and try out the algorithms against your dataset to see how they perform. With the ActiveState Platform, you can create your Python environment in minutes, just like the one we built for this project. Try it out for yourself or learn more about how it helps Python developers be more productive. Recommended Reads How to Build an Algorithmic Trading Bot with Python Comparing Decision Tree Algorithms: Random Forest vs. XGBoost
https://www.activestate.com/blog/top-10-python-machine-learning-algorithms/
CC-MAIN-2022-05
refinedweb
3,021
50.94
Description The simple XML parser is a tiny parser for a subset of XML (everything except entities and namespaces). It uses a simple "one-handler per tag" interface and is suited for use with devices with limited resources. Simple XML Parser Web Site Categories License User Ratings User Reviews Very good for its purpose - in my case, operation in a memory-limited environment (3K heap). Be sure to apply the memory leak patch from the patches section. Read the listed limitations in the README file to determine if it is suitable for your use. This is the dumbest parser of all dumb parsers that I ever downloaded. Makefile doesn't work for compilation on linux. Visual Studio displayed that "entry point must be defined", you somehow wrote parser without int main( ) in *.c file. Compil and use your parser by himself. Simple and straight! I love every piece of it and probably wouldn't have had started my own "sxmlc" if I had seen yours before. Great work! :)
https://sourceforge.net/projects/simplexml/?source=directory
CC-MAIN-2016-36
refinedweb
168
64.81
Pre-requisite: an Eclipse version including Java Support (e.g. with the JDT : Java Development Tools, as in Eclipse For Java Developers, Eclipse For RCP/RAP developers, Eclipse for JavaEE developers, etc.) Update site : There is a central place for installation procedure of all clojure IDEs. You will find the counterclockwise's one here : As a bonus, you'll have the additional (optional) steps to install a clojure lab in counterclockwise (labrepl). Some people reported problems with the eclipse installer. The problem, as stated, is that eclipse can't manage to find the antlr required dependency. One quick option you have is to manually install the missing antlr jar in your eclipse's plugin directory, restart eclipse (maybe with -clean option, but not absolutely necessary in a first try), and then try reinstalling Counterclockwise from the update site, as mentioned above. For your convenience, we have placed the antlr plugin in the downloads section of Counterclockwise site : ( download page: ) (optional step, do this if you have any doubt) A clojure project is just a java project, with an added builder for clojure code. By default, creating/enabling a clojure project will also check if you have clojure in your classpath, and if not, will add a dependency on Counterclockwise plugin's own embedded clojure version. Everything you want as if you were in a classical java project. But you must of course always have clojure as a dependency of your project, but it can come in as many flavors as eclipse allows : Note: a REPL will also be installed. By default, if the selected file contains a (ns) call, the name of its namespace will be used. A preference can controller whether this feature is active or not. A console for the java process is started, and a REPL View is opened where you can type expressions for evaluation. YOU MUST HIT Ctrl+ENTER (CMD+ENTER ON A MAC) to send the expression for evaluation. Notes: The namespace browser will show you all symbols of all namespaces of the REPL you have launched, and allow you to jump to the source code defining them, if available (double clic on the symbol). It also allows you to search the symbol you want by typing regexps in the "Find :" text zone, and choosing to do the search only on symbols names, or also on symbols documentation. If you let the mouse hover a node in the browser, you will have the documentation, if available. When you have launched the REPL, Counterclockwise has embedded "server code" in the launched clojure environment. This server code is contacted by Counterclockwise to give information on the running clojure environment. The namespace browser uses this server to provide you with the most possible up to date info on the symbols. Clojure files must be located in normal java source directories. If you place files with the .clj extension outside of a java source directory, then Eclipse will not see it on the classpath of the project, and you will not be able to load it via the REPL, select it as an automatically loaded file in the launcher customization wizard ... Do as you would in a classic java project. Just remember to place all clojure files in a java source directory. 200 results are proposed, with a warning message at the bottom of the BE AWARE it is still a bit slow for java completion (due to the fact that there is no type to narrow the search, it is done for any class type in the classpath !) This will be enhanced in a future release by allowing gradually more time consuming code completions (first try completion only for those classes imported in the namespace as symbols, and then, on user demand - by pressing space a second time - broaden the search to the entire set of classpath visible class types) See this page: EditorKeyBindingsFeatures <!-- How does this work? Need more detailed description: how to define tests, how to see the run-tests result Currently I see only REPL background changed to yellow and "Tests failed" in statusbar. --> Once you have started a REPL for your project, eclipse will use a backdoor connection to this REPL to automatically compile and load the files you edit (if the eclipse Project > Build automatically option is selected, of course). It appears that someone created a useful Eclipse plugin to build executable jars from a java project. Once installed, it also works from a Counterclockwise project out of the box! Install the Fat Jar plugin To create the executable jar, open the contextual menu of the project, and select the Fat jar menu entry. Please refer to the Fat Jar plugin homepage for more detail N.B. : there is also out-of-the-box executable jar support in Eclipse, but we encountered problems with it when the main class is not located in the source folders of the project, as is the case when you generate the main class from a clojure namespace.
http://code.google.com/p/counterclockwise/wiki/Documentation#Syntax_higlighting
crawl-003
refinedweb
831
57
Using SWIG makes connecting libraries written in C/C++ to Python very simple. However you also need to compile the SWIG generated sources with all the right compiler flags (for finding the Python header files and libraries). We can use distutils to save us this work as well. Assume our C library is hello.c and our SWIG interface definition is in hello.i, write the following code in setup.py from distutils.core import setup, Extension setup( ext_modules = [ Extension("_hello", sources=["hello.c", "hello.i"]) ] ) Note the underscore in the module name, SWIG generated a hello.py which will call import _hello somewhere. To compile run python setup.py build_ext -i. For a long article on SWIG and Python see here. EDIT (3/2010): UnixReview is no longer with us, I'll try to locate the article.
http://pythonwise.blogspot.com/2006/06/using-distutils-to-build-swig-packages.html
CC-MAIN-2017-43
refinedweb
138
70.9
Details - Type: Improvement - Status: Closed - Priority: Major - Resolution: Fixed - Affects Version/s: None - - Component/s: modules/facet - Labels:None - Lucene Fields:New Description The new default DV format for binary fields has much more RAM-efficient encoding of the address for each document ... but it's also a bit slower at decode time, which affects facets because we decode for every collected docID. Activity - All - Work Log - History - Activity - Transitions should it really write a byte[]? i wonder how it would perform if it wrote and kept in ram packed ints, since it knows whats in the byte[]. it would just make a byte[] on the fly to satisfy merging etc but otherwise provide an int-based interface for facets? i wonder how it would perform if it wrote and kept in ram packed ints, since it knows whats in the byte[] We've tried that in the past. I don't remember on which issue we posted the results, but they were not compelling. I.e. what we tried is to keep the ints as int[] vs packed-ints. int[] performed (IIRC) 50% faster, while packed-int only ~6-10% faster. Also, their RAM footprint was very close. (that's 100 bytes/doc) x 6.6M documents – that's going to be ~660MB (offsets not included). I suspect that packed-ints will consume approximately the same size (at least, per past results) but won't yield significantly better performance. Therefore if we want to cache anything at the int level, we should do an int[] caching aggregator. Mike, correct me if I'm wrong. Right but i dont look at what its doing this way. Today the ords for the document are vint-deltas (or similar) within a byte[] right? So instead perhaps the codec could encode the "first ord" (minimum) for the doc in a simple int[] or whatever, but the additional deltas are all within a big packed stream or something like that. In all cases i like the idea of a specialized docvaluesformat for facets. it doesn't have to be one-sized-fits-all: it could have a number of strategies depending on whether someone had 5 ords/doc or 500 ords/doc for example, by examining the iterator once at index-time to decide. I think that it would actually be interesting to test only VInt, without dgap. Because the ords seem to be arbitrary, I'm not even sure what they buy us. Mike, can you try that? Index with a Sorting(Unique(VInt8)) and modify FastCountingFacetsAggregator to not do dgap? Would be interesting to see the effects on compression as well as speed. Dgap is something you want to do if you suspect that a document will have e.g. higher ordinals, that are close to each other in such a way that dgap would make them compress better ... Robert, if I understand your proposal correctly, what you suggest is to encode: int[] – pairs of highest/lowest ordinal in a document + length (#additional ords) byte[] – a packed-int of deltas for all documents (but deltas are computed off the absolute ord in the int[] Why would that be better than a single byte[] (packed-ints) + offsets? I think that 30% more RAM is ok .. i.e. either you will have enough RAM on the machine, or those 30% won't make a big difference (for really large indexes). What bothers me is that there's no way to do that out-of-the-box ... not with how facets are indexed today. E.g., if facets were in core, then we could modify IWC to detect when facets are used (e.g. isEnableFacets) and then create the optimized Codec for them... And the problem is that unlike with a caching decision yes/no, here the situation is that facets are loaded into RAM by default, we just offer a better way to load them. I think that if we can find a justification to a FacetsCodec in general, then we could stuff such optimizations in and would tell users that if they want to index facets, they should work with that Codec... Or .. we can just leave it as-is and document somewhere that you might want to consider that DV format, at the expense of more RAM but faster search. I think that 30% more RAM is ok .. i.e. either you will have enough RAM on the machine, or those 30% won't make a big difference (for really large indexes). This is misleading. Its not a constant 30%. The larger the index, the larger the cost. E.g., if facets were in core, then we could modify IWC to detect when facets are used (e.g. isEnableFacets) and then create the optimized Codec for them... I would be against this even if facets were in core. I think its ok to add this option, but i don't think its a good default. I think the benchmark being used here is easily misleading. And again by option: means users pick their codec the normal way (IndexWriterConfig.setCodec). We don't need to do any sneaky automatic codec-picking. I don't think if we chose the Codec it's sneaky. It's just like Lucene defaults to Lucene42Codec. If, hypothetically (I don't think facets go into core anytime soon), facets were in core, then the default Codec decision could take isFacetsEnabled into consideration. That's all I was saying. The 30% RAM overhead I measured was for the 7 dims per doc case. And the RAM overhead will vary greatly depending on the app: if you have fewer facet dims, and more docs, the overhead is higher. I think it should just be an optional DV Format that makes the obvious tradeoffs, and the javadocs should say "your mileage may vary", ie the time/space tradeoff will be app dependent. I think that it would actually be interesting to test only VInt, without dgap. Because the ords seem to be arbitrary, I'm not even sure what they buy us. Mike, can you try that? No dgap compression, 1M docs, 7 dims per doc. Looks like we lost a bit: Task QPS base StdDev QPS comp StdDev Pct diff MedTerm 258.50 (1.5%) 252.69 (1.6%) -2.2% ( -5% - 0%) OrHighLow 55.96 (2.4%) 54.73 (2.0%) -2.2% ( -6% - 2%) OrHighMed 57.47 (2.4%) 56.33 (2.1%) -2.0% ( -6% - 2%) HighPhrase 44.47 (10.9%) 43.63 (10.7%) -1.9% ( -21% - 22%) OrHighHigh 38.53 (2.6%) 37.88 (2.3%) -1.7% ( -6% - 3%) HighTerm 65.49 (1.2%) 64.70 (1.9%) -1.2% ( -4% - 1%) Prefix3 46.82 (1.5%) 46.30 (1.2%) -1.1% ( -3% - 1%) MedPhrase 149.78 (5.5%) 148.17 (5.3%) -1.1% ( -11% - 10%) AndHighHigh 93.50 (1.0%) 92.73 (0.8%) -0.8% ( -2% - 1%) HighSloppyPhrase 3.26 (6.8%) 3.24 (8.0%) -0.8% ( -14% - 15%) HighSpanNear 11.60 (1.7%) 11.51 (1.9%) -0.8% ( -4% - 2%) LowPhrase 73.57 (5.6%) 73.00 (5.0%) -0.8% ( -10% - 10%) LowSpanNear 43.68 (2.0%) 43.35 (2.3%) -0.8% ( -4% - 3%) MedSpanNear 90.77 (1.5%) 90.10 (1.4%) -0.7% ( -3% - 2%) LowSloppyPhrase 82.66 (1.9%) 82.13 (1.7%) -0.6% ( -4% - 2%) MedSloppyPhrase 92.12 (2.2%) 91.65 (2.2%) -0.5% ( -4% - 3%) LowTerm 466.62 (1.4%) 464.83 (1.9%) -0.4% ( -3% - 2%) AndHighMed 347.12 (1.7%) 348.61 (1.1%) 0.4% ( -2% - 3%) Wildcard 120.82 (1.2%) 121.50 (1.6%) 0.6% ( -2% - 3%) IntNRQ 23.40 (1.6%) 23.76 (1.4%) 1.5% ( -1% - 4%) Fuzzy1 80.87 (2.4%) 82.38 (2.6%) 1.9% ( -3% - 7%) Respell 71.83 (3.0%) 73.46 (3.2%) 2.3% ( -3% - 8%) AndHighLow 1159.47 (3.8%) 1189.72 (2.4%) 2.6% ( -3% - 9%) Fuzzy2 88.04 (3.0%) 91.48 (3.7%) 3.9% ( -2% - 10%) Trunk bytes for the DV facet field was 9219009, and no-dgap was 10163419 (~10% larger). So net/net dGap seems to help! I re-tested trunk vs this new DV format, with all 9 dims on the full 6.6M wikibig index. (The added 2 dims, username and categories, have many many unique values): Task QPS base StdDev QPS comp StdDev Pct diff HighPhrase 13.68 (8.1%) 13.64 (8.4%) -0.3% ( -15% - 17%) LowPhrase 15.05 (4.4%) 15.08 (4.4%) 0.1% ( -8% - 9%) LowSpanNear 7.12 (2.5%) 7.17 (2.3%) 0.6% ( -4% - 5%) AndHighLow 64.03 (1.3%) 64.55 (1.3%) 0.8% ( -1% - 3%) HighSloppyPhrase 0.82 (5.7%) 0.83 (4.8%) 1.1% ( -8% - 12%) Respell 44.90 (4.0%) 45.43 (4.3%) 1.2% ( -6% - 9%) LowSloppyPhrase 15.37 (2.1%) 15.57 (1.8%) 1.3% ( -2% - 5%) HighSpanNear 2.91 (1.8%) 2.95 (1.9%) 1.3% ( -2% - 5%) Fuzzy2 28.55 (2.0%) 29.02 (2.1%) 1.7% ( -2% - 5%) MedSloppyPhrase 16.56 (1.2%) 16.94 (1.2%) 2.3% ( 0% - 4%) AndHighMed 39.47 (0.8%) 40.40 (1.0%) 2.4% ( 0% - 4%) Fuzzy1 24.08 (1.3%) 24.73 (1.4%) 2.7% ( 0% - 5%) MedSpanNear 17.70 (1.6%) 18.19 (1.6%) 2.8% ( 0% - 6%) MedPhrase 41.06 (2.2%) 42.46 (2.6%) 3.4% ( -1% - 8%) LowTerm 34.19 (0.9%) 35.69 (1.0%) 4.4% ( 2% - 6%) AndHighHigh 11.92 (1.2%) 12.50 (1.1%) 4.9% ( 2% - 7%) Wildcard 13.13 (1.8%) 14.43 (1.5%) 9.9% ( 6% - 13%) OrHighMed 7.09 (2.7%) 7.85 (1.6%) 10.8% ( 6% - 15%) OrHighLow 7.16 (2.3%) 7.93 (1.6%) 10.8% ( 6% - 15%) HighTerm 7.59 (2.3%) 8.47 (1.6%) 11.5% ( 7% - 15%) MedTerm 20.14 (1.9%) 22.82 (1.1%) 13.3% ( 10% - 16%) Prefix3 5.78 (2.2%) 6.56 (1.5%) 13.4% ( 9% - 17%) OrHighHigh 4.03 (2.3%) 4.65 (2.0%) 15.4% ( 10% - 20%) IntNRQ 1.92 (2.2%) 2.45 (1.9%) 27.5% ( 22% - 32%) 145.3 MB for the new DV vs 129.0 MB for trunk = ~12.6% bigger.? I decided to test whether the specialization (checking if DV format is FacetDVFormat and "directly" accessing its address/bytes) helps: Base = new DV format; comp = new DV format + spec, 9 dims: Task QPS base StdDev QPS comp StdDev Pct diff LowSpanNear 7.15 (2.3%) 7.14 (2.0%) -0.1% ( -4% - 4%) Respell 45.60 (3.4%) 45.64 (3.3%) 0.1% ( -6% - 7%) Fuzzy1 24.79 (1.4%) 24.85 (1.3%) 0.3% ( -2% - 2%) MedSpanNear 18.07 (1.3%) 18.12 (1.6%) 0.3% ( -2% - 3%) AndHighMed 40.34 (0.8%) 40.47 (0.9%) 0.3% ( -1% - 2%) MedPhrase 42.25 (2.9%) 42.40 (2.7%) 0.4% ( -5% - 6%) LowTerm 35.62 (1.1%) 35.76 (1.3%) 0.4% ( -2% - 2%) AndHighLow 64.53 (1.7%) 64.78 (1.2%) 0.4% ( -2% - 3%) Fuzzy2 29.06 (1.6%) 29.19 (1.7%) 0.4% ( -2% - 3%) MedSloppyPhrase 16.88 (1.1%) 16.97 (1.5%) 0.5% ( -2% - 3%) LowPhrase 15.01 (4.7%) 15.09 (4.8%) 0.5% ( -8% - 10%) HighSpanNear 2.92 (1.9%) 2.94 (1.7%) 0.7% ( -2% - 4%) LowSloppyPhrase 15.48 (1.6%) 15.60 (2.1%) 0.7% ( -2% - 4%) HighPhrase 13.50 (8.8%) 13.60 (8.6%) 0.7% ( -15% - 19%) MedTerm 22.64 (1.1%) 22.91 (1.2%) 1.2% ( -1% - 3%) Wildcard 14.29 (0.9%) 14.47 (1.4%) 1.3% ( 0% - 3%) AndHighHigh 12.40 (0.9%) 12.56 (1.2%) 1.3% ( 0% - 3%) HighSloppyPhrase 0.82 (4.3%) 0.83 (5.2%) 1.9% ( -7% - 11%) OrHighMed 7.74 (1.3%) 7.90 (1.4%) 2.0% ( 0% - 4%) OrHighLow 7.82 (1.4%) 7.98 (1.7%) 2.0% ( 0% - 5%) HighTerm 8.35 (1.1%) 8.52 (1.5%) 2.1% ( 0% - 4%) Prefix3 6.48 (1.1%) 6.62 (1.1%) 2.3% ( 0% - 4%) OrHighHigh 4.58 (1.6%) 4.69 (1.5%) 2.3% ( 0% - 5%) IntNRQ 2.41 (1.6%) 2.48 (1.5%) 2.7% ( 0% - 5%) Same, but w/ 7 dims: Task QPS base StdDev QPS comp StdDev Pct diff MedSpanNear 28.73 (1.9%) 28.33 (2.7%) -1.4% ( -5% - 3%) Respell 45.08 (4.7%) 44.73 (4.0%) -0.8% ( -9% - 8%) LowSpanNear 8.38 (2.6%) 8.33 (2.5%) -0.6% ( -5% - 4%) Fuzzy2 52.13 (3.5%) 51.85 (3.5%) -0.5% ( -7% - 6%) HighSpanNear 3.53 (1.7%) 3.51 (1.9%) -0.5% ( -3% - 3%) Fuzzy1 46.42 (2.5%) 46.29 (2.3%) -0.3% ( -4% - 4%) MedPhrase 109.24 (5.5%) 109.16 (5.9%) -0.1% ( -10% - 11%) HighPhrase 17.28 (10.4%) 17.28 (10.6%) 0.0% ( -19% - 23%) HighSloppyPhrase 0.92 (8.0%) 0.92 (5.9%) 0.0% ( -12% - 15%) AndHighHigh 23.28 (1.2%) 23.29 (0.8%) 0.0% ( -1% - 2%) LowPhrase 21.08 (6.1%) 21.10 (6.6%) 0.1% ( -11% - 13%) AndHighLow 586.97 (2.5%) 587.46 (2.3%) 0.1% ( -4% - 5%) LowSloppyPhrase 20.38 (3.1%) 20.41 (2.6%) 0.1% ( -5% - 6%) LowTerm 110.38 (2.0%) 110.52 (1.4%) 0.1% ( -3% - 3%) AndHighMed 105.08 (1.0%) 105.31 (0.9%) 0.2% ( -1% - 2%) Wildcard 27.23 (2.5%) 27.30 (1.8%) 0.3% ( -3% - 4%) MedSloppyPhrase 25.94 (3.2%) 26.04 (2.1%) 0.4% ( -4% - 5%) IntNRQ 3.52 (3.6%) 3.54 (2.6%) 0.6% ( -5% - 7%) HighTerm 19.05 (3.3%) 19.18 (2.7%) 0.6% ( -5% - 6%) Prefix3 12.89 (3.3%) 12.97 (2.3%) 0.7% ( -4% - 6%) MedTerm 46.70 (3.0%) 47.06 (2.6%) 0.8% ( -4% - 6%) OrHighLow 17.06 (4.2%) 17.22 (3.5%) 1.0% ( -6% - 9%) OrHighMed 16.54 (4.2%) 16.71 (3.6%) 1.0% ( -6% - 9%) OrHighHigh 8.72 (4.4%) 8.83 (3.7%) 1.2% ( -6% - 9%) So net/net the specialization doesn't help much here... However, I realized later that this is not doable, since Codecs must have a default constructor, and b/c of how they are initialized, they cannot rely on stuff passed to them in the ctor (e.g. when they are initialized by a reader?). Actually this is a non-issue: the PerFieldDVFormat writes which format was used for which field, and uses that at read-time. The index is "self-contained" and you don't need any special logic at read-time ... Thanks for testing mike. So I guess FastCountingFA can go back to not specialize on this, and this remains a faster DV format only? And thanks for clarifying how those formats work. So I think that Facets42Codec can take a FIP in the ctor. So I guess FastCountingFA can go back to not specialize on this, and this remains a faster DV format only? We can do that, I'm fine with it: the gains are minor. Patch handles some nocommits. Now Facet42Codec takes a FacetIndexingParams and builds a HashSet over the fields returned by fip.getAllCLPs(), and uses it in getDVFForField. Also, this codec cannot support facet partitions, since the number of partitions is unknown in advance (each partition corresponds to a field). So I throw an IllegalArgEx. I renamed the package to o.a.l.facet.codecs.facet42 and moved everything under it. Facet42Codec and Facet42DVF are the only public classes. I also added a resources folder which declares the new DVF. Made FacetTestCase randomly select the new codec (30% of the times), all tests pass. Note though that only tests that use the default FacetIndexingParams actually test the new format. There are still few nocommits. I ran 'documetnation-lint' and it was happy. Oh, I see that the changes to FacetTestBase can be reverted, as now FacetTestCase picks that codec at random. I don't think that Facet42Codec should be final this way it can still be tweaked in the normal ways someone would tweak the default codec, overriding getPostings/DocValuesFormatForField, e.g.: @Override PostingsFormat getPostingsFormatForField(String field) { if (field.equals("id")) { return memory; } else { super.getPostingsFormatForField(field); } } You're right. I was just thinking ... until we need to do that, it can be final. But it can also be not final ... I'm still not sure what's the best (or common) way to work w/ Codecs. When do you create your own FilterCodec and override the relevant method, and when are you expected to extend another Codec? I guess that in this case, since getDVFForField is only on Lucene42Codec, you cannot really extend FilterCodec, so extending Lucene42 / Facet42 is the only option? In short, I don't mind if it's not final . I'm still not sure what's the best (or common) way to work w/ Codecs. When do you create your own FilterCodec and override the relevant method, and when are you expected to extend another Codec? The rule is that an index needs to be self-describing: basically I should be able to open any index if i have the right stuff in my classpath. This would be somewhat of a burden for users who just want to change their "id" field to use a different postings format (they would have to make a whole codec with their own unique name), and so on. So Lucene42Codec uses PerField[Postings/DocValuesFormat] (note this is final!), which separately record the name of the format used on a per-field basis. Because of this, its ok that it not final and exposes these hooks to custom postings/docvalues per-field, because it writes the name of those formats into the index for the field. I see, thanks for the clarification. So basically, if I'm happy w/ Lucene42Codec, but just was to override a per-field setting (DV or posting), it's simpler that I extend it. Would I also be able to extend FilterCodec, and delegate to Lucene42 the fields that are of not interest to me? Would it still use the PerField thingy for my fields too? Or in that case I'd need to use PerField myself? New patch, making acceptableOverheadRatio controllable (defaulting to PackedInts.DEFAULT), noting the 2GB limitation in the javadocs, making Facet42Codec un-final, and added CHANGES.txt entry. I think it's ready! [trunk commit] Michael McCandless LUCENE-4764: add more-ram-consuming-but-faster DV format for facets [branch_4x commit] Michael McCandless LUCENE-4764: add more-ram-consuming-but-faster DV format for facets Initial dirty patch (lots of nocommits still): I added a FacetDocValuesFormat, which goes back to the more-RAM-consuming-but-faster-for-facets 4.0 format, and also hacked the FastCountingFacetsAggregator to directly decode from the full byte[], saving overhead of method-call and filling a BytesRef. It gets faster results than default (Lucene42) DVFormat: This is wikibig all 6.6M, 7 facet dims: But it's also more Disk/RAM-consuming: trunk facet DVs take 61.2 MB while the patch takes 80.3 MB (31% more).
https://issues.apache.org/jira/browse/LUCENE-4764
CC-MAIN-2017-51
refinedweb
3,270
84.57
If your looking for the right approach to migrate your own developed Cognos reports from one environment to another, here is a bunch of links that cover the process involved. So lets use the scenario where you have developed some reports a in Development environment and now want to move them to a UAT or Production environment, how do you go about doing that? The recommended process is to create a deployment of the reports to be transferred, then import this deployment into the target environment. The process is covered in the following Cognos documentation ; Specific process and links: Deploying IBM Cognos Entries Deploying Selected Public Folders and Directory Content There is also a proven practices article on this at: IBM Cognos Proven Practices: IBM Cognos BI Deploy Content Between Environments As a support analyst, one of the first reports that you become familiar with is the Maintenance Cost Rollup report. In the past this report has been known as the Asset Cost Rollup and going way back to Maximo 4, DBRollup. The Cost Rollup report is actually 2 separate reports. Since this was introduced, the report acts basically the same. It's primary function is to update the the Asset Year to Date & Total Costs fields in the Asset Record. These costs include the following. Given that this report updates the YTD Total Charges in the Asset, one would think that this report would be run on a frequent basis.. (so that the YTD Totals reflect current values). Unfortunately, that is not what happens. I think that folks get busy with the day to day operations of the software and forget about this report. In the past, it is not uncommon for people to forget about this until they are performing their year end activities. By this time, they have accumulated a ton of transactions. With any database operation, the more data that needs to be searched & updated the longer it takes and the greater resource burden it becomes. Occasionally, you may find that the report will just not complete any more. If you in this situation, you will need to break the transactions down into smaller chunks. You can get the Rollup and Rollup Update reports to filter on the Asset Location in the Report Request page. You will need to to add the location parameter to both reports for this to work. You can run either report, but if you just want to rollup the transactions you need only run the update report. When setting up the Location parameter, set it to allow multiple values (so you can update multiple locations) and set it to Not Required. The idea here is to run the Update report against some of your larger locations first. Later you can run it against several smaller locations at a time, and finally run with no parameter to run on the balance of the locations. The following SQL will give you a rough idea of what locations have the most non rolled up transactions. Select siteid, location, loc_total from ( select siteid, location, count(*) as loc_total from matusetrans where rollup = 0 and assetnum is not null group by Orgid, siteid, location order by Orgid, Siteid ) order by loc_total desc Select siteid, location, assetnum, site_total from ( select siteid, location, assetnum, count(*) site_total from labtrans where rollup = 0 and assetnum is not null group by Orgid, siteid, location, assetnum order by Orgid, Siteid, location ) order by site_total DESC With Maximo 7.5 you can download reports as an Excel file. Normally, this means saving the file locally with an XLS extension. However sometimes users have later versions of Microsoft Office installed. This can cause Excel to display a Warning "The file you are trying to open, 'wotrack.xls', is in a different format than specified by the file extension. Verify that the file is not corrupted and is from a trusted source before opening the file. Do you want to open the file now ? Users can find this warning tiresome if they have to repeat this several times daily. The question is... Is there any way I can export Microsoft Excel files to *.xlsx format instead of *.xls format ? I gave this advice out recently and it worked like a charm. As this is really an Excel issue and not a Maximo problem, I googled 'excel warnings xls' and found the following. On that page, HansV suggests that this can be changed by tweaking the registry on the clients workstations. I certainly would not attempt this unless I was comfortable tweaking the registry. But if you are up to the task, I can say that this works. Not everyone will be comfortable with users changing the registry for this. For those folks Maximo will be providing xlsx downloads in the 7.6 release of Maximo. . One of the benefits of BIRT reporting in Maximo is that our users can generate all manner of reports that put the accumulated Maximo data in perspective. This ranges from transaction reports like the Work Order Detail report to high level reports (Asset Cost Rollup) that summarize vast swaths of Maximo Data.. Add to this, custom reports and the reporting possibilities are endless. However, this does come at a cost. The Work Order Detail report uses 17 different SQL statements (or more) and operates on a table that is typically huge. The Asset Cost Rollup report summarizes Labor, Materials, Services & Tool costs assigned to closed Work Orders. In the past it has not been uncommon for this report to run over several days. All this activity consumes server resources. If you have been using Maximo for some time, you will remember some of the lessons learned in the past. In Maximo 5, we found that users could run the Work Order Detail report against all the Workorders in the database. If you ran this a couple times in a row, you would be successful in overloading the UI server to the point that it crashed. In an effort to protect the UI server, we added some features.. There were some limitations (Direct Print reports still run on the UI Server), but generally, this approach was successful. Later we introduced AdHoc reporting. This allows users with limited technical ability to create reports. Unfortunately, only AdHoc reports that have been saved and are run from Select Actions / Run Reports run on the BROS. Previewing AdHoc Reports from the AdHoc Query Tool, runs on the UI server. This puts these non technical users in a position to seriously impact the UI server performance. This led to the introduction of the mxe.report.adhoc.previewLimit property. This property while configurable, defaults at 50 records. The best practice is to give your users enough data to develop their report. Once the report is saved, the Administrator can assign a specific record limit (or none at all) to the saved QBR report. This report, when run, will execute on the Birt Reporting Only Server. In summary, to protect your UI server from overload by reporting tasks, you want to do the following. Limit the reporting load on the UI server. This includes Direct Print reports and the number of records that can be run on Direct Print reports. This also includes the number of reports that can be run on a server. This can be limited by the system property mxe.report.birt.maxconcurrentrun. Limit the number of records that can be previewed on the UI server in the QBR (AdHoc) builder. This is the mxe.report.adhoc.previewLimit property. For more information see the QBR (AdHoc) Reporting and Report Object Structures Guide Page 68 Maximo There is known issue with AdHoc reports in a multilingual environment. It works like this. A user, who is not using the Maximo primary language, creates and saves an Ad Hoc report. In doing so, the user enters a report description. This is a required field and and is part of the search index for this report in the Select Actions / Run Reports window. The problem is that there is no Report Description entered for the Primary version of the report entry. If a user opens the Select Actions / Run Reports window in the primary language, they will see an error and be unable to search the report list. There are a couple ways to handle this. If you do not have a lot of users creating AdHoc reports, the Administrator can add the Report Descriptions in Report Administration. If this task becomes too much to handle, you can create an Automation Script that will automatically populate the Primary Language Report Description. Here are the values for creating this script. Script Language: jython Log Level: ERROR Source Code from psdi.mbo import MboConstants from psdi.security import UserInfo userLang = mbo.getUserInfo().getLangCode() # If the current user is not a base language user, set a value on the base language description if (userLang != baseLang): mbo.setMLValue("description", baseLang, mbo.getString("reportname"),MboConstants.NOACCESSCHECK) This Script is specifically targeted the AdHoc issue. It is only triggered when saving a new report (as specified by the Add Option in Launch Points) The Script uses the reportname as the default description. This could be modified if you prefer. How can I let my report developers create and publish reports and ensure that these reports do not have a negative performance impact on my production database & UI? We have created a couple methods to protect the UI from Report performance issues. To configure some reports, (This leaves the Out of Box reports, including update reports pointing at Production) (See Page 8 of the Guide) These users (or report developers) will have the Eclipse Report Designer installed locally. The Designer includes a properties file, mxreportdatasources.properties that points the report to the appropriate database. The default points to the Maximo primary db. This can be changed from the default, to a secondary database. maximoDataSource.url=jdbc:db2://localhost:50001/UDBPD to external.url=jdbc:db2://qadb04.usma.ibm.com:50000/db29winb See page 9 of the guide for the complete data source entry. After making the one time change in the properties file, each report will need to point to the new data source. Page 12. <script-data-source name=”maximoDataSource” becomes <script-data-source name=”external” Do my users have to make this change with every report? Yes, but if you edit the report templates to point to the correct datasource, each new report will automatically point to the correct Datasource. Finally, you will need to tell Maximo about the new secondary database and datasource. This is done under Report Admin, Configure Data Sources. So, all reports uploaded by these users will be loaded to the Production database, but will report from the secondary (external) database. You will need to provide these report writers with the following. Is there any way that these users can upload a report that points to the Production database? To upload a report that point to production, these users would have to upload an existing report that points to prod or modify a new report so that it points to ‘maximoDataSource’. So it remains possible that a user could point a report to Production, but this would have to be intentional. So, at this point, we have a strategy to create reports that will point to a secondary database. To take the remaining pressure off of the UI Server, you need to enable the BROS server. The BROS server is just another Maximo server pointing at the same primary database. Any immediate or scheduled reports will run on this server. The UI server will still host QBR report Previews and any Direct Print reports. In Summary. #1 moves the report overhead off of the UI server, but still points to the Prod db. #2 Points the custom reports at the secondary db, but leaves report processing on the UI. Using both #1 & #2 .. - Causes all reports to run on a BROS server ( with 7.5.0.x, Direct Print & QBR previews will still happen on the UI) - Points all the custom reports to the Secondary db, All OOB reports go to primary db... I. As a Maximo administrator you might notice the accumulation of temporary BIRT files on your TPAE/Maximo server. As this can consume the free diskspace on the server, this can be a serious issue. These temporary files are created by BIRT at the report execution time. Usually they are removed when the report completes. The resolution to this is to direct the output to a specific folder so that it does not interfere with the performance of the Maximo JVM. This can be done by adding a parameter to the Generic Java Parameters in either WebSphere or WebLogic. eg. Dmxe.report.birt.tempfolder=c:\tempReport\BIRTTEMP This process varies in WebLogic and Websphere, but in both cases, the Directory Path to this folder should contain no spaces, For detailed steps to setting this up in WAS, see page 25 in the V 7.5 Report Feature Guide mentioned at the link below. For further information see.
https://www.ibm.com/developerworks/mydeveloperworks/blogs/5d8025d9-0449-47fc-9872-55f3b98e0636?maxresults=15&sortby=4&lang=pt_br
CC-MAIN-2017-43
refinedweb
2,179
63.59
On Mon, 19 Feb 2001 14:49:35 -0800, Andrey Savochkin <saw@saw.sw.com.sg> wrote:> On Tue, Feb 20, 2001 at 09:21:06AM +1100, CaT wrote:>> >> It happened again. Same deal. Once was after a reboot and this time>> was after a resume. :/> > In my experiments wait_for_cmd timeouts almost always were related to> DumpStats command.> I think, we need to investigate what time constraints are related to this> command.Nothing documented...CaT, can you apply this debugging patch and let us know what you get in thelogs? It should allow us to pinpoint the error a bit more precisely.Thanks,Ion-- It is better to keep your mouth shut and be thought a fool, than to open it and remove all doubt.--------------------------------------------- /mnt/3/linux-2.2.19pre/drivers/net/eepro100.c Thu Feb 15 16:09:19 2001+++ linux-2.2.18/drivers/net/eepro100.c Mon Feb 19 16:13:45 2001@@ -368,9 +368,16 @@ #define outl writel #endif +static char *cmdwait_string = "wait_for_cmd_done timed out at %s:%d\n";+#define wait_for_cmd_done(ioaddr) \+ do { \+ if (do_wait_for_cmd_done(ioaddr)) \+ printk(cmdwait_string, __FUNCTION__, __LINE__); \+ } while (0)+ /* How to wait for the command unit to accept a command. Typically this takes 0 ticks. */-static inline void wait_for_cmd_done(long cmd_ioaddr)+static inline int do_wait_for_cmd_done(long cmd_ioaddr) { int wait = 20000; char cmd_reg1, cmd_reg2;@@ -383,10 +390,10 @@ if(cmd_reg2){ printk(KERN_ALERT "eepro100: cmd_wait for(%#2.2x) timedout with(%#2.2x)!\n", cmd_reg1, cmd_reg2);- + return 1; } }-+ return 0; } /* Offsets to the various registers.-To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgMore majordomo info at read the FAQ at
http://lkml.org/lkml/2001/2/19/145
CC-MAIN-2014-41
refinedweb
279
57.37
Introduction As of version 8.0, SAP Identity Management has a new redesigned java-based Lotus Notes Connector. It leverages completely the Lotus Domino’s server java API to greatly simplify the initial setup and to lower the cost of its consecutive usage by calling methods remotely using CORBA. This way it is no longer necessary to have the Lotus Notes Client installed locally on the Identity Management system nor to rely on Visual Basic or C components. Since the Domino API’s resetUserPassword method is only supported on the server and cannot be invoked remotely, the Identity Management’s connector has to call a dedicated Domino Agent for this task. In this blog post I am going to provide detailed instructions how to implement such Agent and how to use it with SAP Identity Management. Lotus Domino Agents So what exactly is a Lotus Domino agent? As we can read in the IBM’s documentation: “Agents are stand-alone programs that perform a specific task in one or more databases. Agents are the most flexible type of automation…”. These stand-alone programs run on the Domino server and can be invoked either directly, based on event, or scheduled to run periodically. In our case, we are going to call Agent’s methods directly from the Identity Management Java connector. Implementing Password Reset Agent To implement a Lotus Domino Agent, we will need the IBM Lotus Domino Designer which can be downloaded from here: After you have the Designer up and running, we can start with the implementation. Creating the Application - Create new application by clicking on File -> New -> Application. - In the dialog window, enter the details about the agent. - For server, select the server on which the agent will be running. This is where your ID Vault is. - For title, use “IDM Password Reset”. You can see that a file name is automatically generated. In my case, that is “IDMPassw.nsf”. Leave it as it is. - Click OK to create the application. The new application is created and automatically opened. You can see in the tree on the left hand side that an application can have many elements: Forms, views XPages, etc. For our use case we are only interested in the Code node where the agents are defined. - Expand it and right-click on the Agents node. - Select “New Agent…”. - In the new dialog window, enter the details of the agent. - For name, enter “IDMPasswordResetter”. - For alias “IDM Password Resetter”. - If you want, you can enter a comment in the next field. - Very important is to select the proper type of the agent. In our case, this is – “Java” and not “Imported Java”. Make sure that the agent will be created in the application we just created. You can check that in the last drop down. - Click OK to create the Agent. Putting the Password Reset Logic The new agent is created and automatically opened. You can see that in the Agent Contents tree there is a source folder with default package and Java class generated. Open the JavaAgent.java class. You can see that inside, we have a NotesMain() method which is the entry point of the agent. Now we have a placeholder for the resetUserPassword method which is part of the Session class. You can find its documentation here:. From the documentation, we can read that the method “…is only supported on the server.” And “This method is only supported in agents.” Also it takes three string arguments: servername, username and password. The server name is the “Canonical name of the server or servers to execute the agent”. The username is the one of the user we want to change the password for. The password is the new password for this user. As we saw earlier, the NotesMain() method which is the entry point of the agent does not have any parameters. So how do we send the servername, username and password from Identity Management? The Lotus Notes connector uses the runOnServer() method of the Domino API’s Agent class to run the password reset agent. This method comes in two flavors: the first one without any parameters, which just invokes the agent’s code (NotesMain()). The second one has one string argument which is the note id of a Notes document. Notes Document or Note is a central part of the Lotus Notes architecture. It is an object data store which “is a compound structure of mixed data types arranged in fields that can be arbitrarily modified and extended. A note may contain text, rich text, binary blobs (attachments, ActiveX or Java applets, for instance), encryption keys, doclinks, and so on. Each Notes database contains a collection of notes, and includes meta-organizing structures for display, security, retrieval and access rights to the notes.” In our case, we create a note document inside the Agent’s database and use this document to pass the parameters to the password reset method. So prior to invoke the agents code, the Identity Management connector creates a new Note and puts three key-value pairs: server, username and password with their respective values. Once the document is created, the connector gets its Note Id (or unique identifier) and passes it to the runOnServer() method. On the agent’s side we have to open that document and extract the parameters from it. This is done in the following way: First we need to acquire the current agent’s instance with the following code: Agent thisAgent = agentContext.getCurrentAgent(); You can see that we use the agentContext which is already available in the generated agent code. Next we have to acquire the note id of the document holding the parameters: String paramid = thisAgent.getParameterDocID(); Once we have the document id, we need to look up the agent’s database and from it to extract the document using its ID: Database db = agentContext.getCurrentDatabase(); Document doc = db.getDocumentByID(paramid); Now we have the document with our three parameters, but how to get their values? For this purpose we will use the getItemValue() method of the Document class. It has one parameter – the name of the item or in our case the parameter and returns a java.util.Vector of values. So to get the values of the three parameters, we can use these statements: Vector serverVector = doc.getItemValue("server"); String server = null; if (serverVector != null && serverVector.size() > 0) { server = (String) serverVector.get(0); } Vector usernameVector = doc.getItemValue("username"); String username = null; if (usernameVector != null && usernameVector.size() > 0) { username = (String) usernameVector.get(0); } Vector passwordVector = doc.getItemValue("password"); String password = null; if (passwordVector != null && passwordVector.size() > 0) { password = (String) passwordVector.get(0); } Now we have all we need to call the method that will actually reset the user’s password: session.resetUserPassword(server, username, password); It is important that the resetUserPassword method as well as most methods from the Notes API can throw a NotesException. This is a checked exception and you have to surround its invocation with try-catch block. Also it is peculiar that the NotesException class is not standard exception – if you try to get the exception’s message using getMessage() method or the stack trace using getStackTrace(), you will most likely get something useless. Instead, the NotesException class has three public fields: id, text and internal. The first two are the error’s code and text description and the third one is the stack trace of the exception. So if you want to print useful error message to the log, use the id and the text fields. To actually get a logging object with which to log the agent’s actions in a text file for example, you can use this snippet: Log log = session.createLog(thisAgent.getName()); log.openAgentLog(); log.openFileLog("path-to-log-file.log"); Then you can use the logAction() method to log events: log.logAction("Exception: " + e.id + “ – “ + e.text); To return value back to the Identity Management connector, we will use the same Notes document with which the input parameters were passed. We will use the replaceItemValue() method of the Document class to add new key-value pair holding the result: doc.replaceItemValue("result", Boolean.valueOf(isReset)); doc.save(true,true); It is important to call the save() method to actually commit the changes. Note: Unfortunately there is a weird quirk in the resetUserPassword() java method. It always returns false even if the password is reset successfully. For this reason the result handling is a little odd we have to check for NotesExceptions during password reset: if there are such, we return false otherwise we return true. Security Once the agent is implemented, we have to set the appropriate access rights so that it would be able to reset passwords. First double-click on the agent to open its content. You should see the Properties view. It has three tabs: Basics, Security and Document Selection. In the Basics tab, you have to set the Runtime area settings as follows: - Trigger: On event - Action menu selection - Target: None The rest should be with the default values. In the Security tab: - Uncheck the “Run as Web user” checkbox - Run on behalf of: should be empty - Runtime security level: 2. Allow restricted operations Next step is to make the user used to sign the agent to be a “Designated Password Re-setter”. First you have to check which username is used to sign the agent. In the Domino Designer, go to: “File -> Security -> User Security…”. In the “Who You Are” area you can see the Name value. In my case this is “Administrator/sap”. - Now go to the IBM Domino Administrator and select the Configuration tab. From the tree on the left, select Security -> ID Vaults node and select your ID Vault from the list. Then from the menu on the right-hand side, select Tools -> ID Vaults -> Manage… -> Add or remove password reset authorities. - From the Password reset authority by organization list, select the organization or organizational unit of users whose passwords will be reset. - From the Available users, groups and servers list, select the name of the user that has signed (or will sign) the application agent. - Click Add to give the selected agent signer password reset authority for the organization or organizational unit highlighted. - Keep the agent signer name highlighted and select Self-service password reset authority. - From the Available users, groups and servers list, select the name of a server or group of servers on which you will deploy the application. - Click Add to give the selected server or server group password reset authority for the organization or organizational unit highlighted. - Repeat the steps above if necessary For more details have a look at the IBM Domino Documentation: Wrap it up Source code: public class JavaAgent extends AgentBase { public void NotesMain() { Log log = null; Document parametersDocument = null; try { Session session = getSession(); AgentContext agentContext = session.getAgentContext(); Agent currentAgent = agentContext.getCurrentAgent(); Database currentDatabase = agentContext.getCurrentDatabase(); log = session.createLog(currentAgent.getName()); log.openAgentLog(); log.openFileLog("C:\\D\\agentlogBackend2.txt"); String parametersDocumentId = currentAgent.getParameterDocID(); parametersDocument = currentDatabase.getDocumentByID(parametersDocumentId); Vector serverVector = parametersDocument.getItemValue("server"); String server = null; if (serverVector != null && serverVector.size() > 0) { server = (String) serverVector.get(0); } Vector usernameVector = parametersDocument.getItemValue("username"); String username = null; if (usernameVector != null && usernameVector.size() > 0) { username = (String) usernameVector.get(0); } Vector passwordVector = parametersDocument.getItemValue("password"); String password = null; if (passwordVector != null && passwordVector.size() > 0) { password = (String) passwordVector.get(0); } log.logAction("Reseting password..."); session.resetUserPassword(server, username, password); parametersDocument.replaceItemValue("result", "true"); parametersDocument.save(true, true); log.logAction("Return value: true"); } catch (NotesException e) { try { log.logError(e.id, e.text); parametersDocument.replaceItemValue("result", "false"); parametersDocument.save(true, true); } catch (NotesException e1) { e1.printStackTrace(); } } } }
https://blogs.sap.com/2015/05/15/implementing-password-reset-agent-for-idm-lotus-notes-connector/
CC-MAIN-2017-47
refinedweb
1,942
57.67
: There is a common interaction pattern that all applications integrating with the ACS will follow. This is best depicted in the diagram below: Graphic is from the Azure App Fabric SDK .chm help file.. In order to request one of these tokens the client must be coded to follow one of these patterns:. Code Example of the Plain Text Request Pattern Code Example of the Plain Text Request Pattern // Step 1 Create web client object. WebClient client = new WebClient(); client.BaseAddress =); return Encoding.UTF8.GetString(serviceResponseBytes); // Step 1 Create web client object. client.BaseAddress = // Step 2 Create POST parameters // Step 2.1 wrap_name // Step 2.2 wrap_password // Step 2.3 wrap_scope // Step 3 & 4 // Step 5 // Reset Client target // Step 6 set Authentication header string headerValue = string.Format("WRAP access_token=\"{0}\"", HttpUtility.UrlDecode(token)); client.Headers.Add( values = values.Add( If you are going to take this route, I would highly recommend creating a TokenFactory that you can use to issues your self-signed tokens. The TokenFactory would look like this: (The code is pretty self-explanatory) using public { } builder.Append( builder.Append(signature); A signed token request only contains two parameters: wrap_scope wrap_assertion. wrap_token wrap_token_expires_in Before sending the token to the Web service, the service consumer must extract and URL-decode the token from the response. If the Web service requires the token to be presented in the HTTP Authorization header, then the token must be preceded by the scheme WRAPv0.9. Authorization WRAPv0.9 To do this, I recommend you create an SwtUnpacker that you can reuse to return a pre-built auth header value. It would look something like this: (again the code is self explanatory) namespace .Split( .Single(value => value.StartsWith( // Step 1: Create our own Signed SWT
http://blogs.msdn.com/b/rockyh/archive/2010/04/15/azure-access-control-service-client-patterns-part-1.aspx
CC-MAIN-2016-07
refinedweb
292
50.84
This Version: 26 October 2009 The namespace whose name is is bound by definition to the prefix xml: according to Namespaces in XML Specification (Fifth edition) (and also the XML 1.1 Specification Second edition) defines two attribute names in this namespace: xml:lang xml:space xml:base The XML Base specification (Second edition). All changes to the use of this namespace will be achieved by the publication of documents governed by the W3C Process. The XML specification reserves all names beginning with the letters 'x', 'm', 'l' in any combination of upper- and lower-case for use by the W3C. To date three such names have been given definitions—although these names are not in the XML namespace, they are listed here as a convenience to readers and users:.)
http://www.w3.org/XML/1998/namespace
CC-MAIN-2016-30
refinedweb
130
54.76
Django JsonResponse tutorial Django JsonResponse tutorial shows how to send JSON data with JsonResponse in Django. Django Django is a high-level Python web framework. It encourages rapid development and clean, pragmatic design. Django's primary goal is to ease the creation of complex, database-driven websites. Django is maintained by the Django Software Foundation. JSON JSON (JavaScript Object Notation) is a lightweight data-interchange format. The official Internet media type for JSON is application/json. The JSON filename extension is .json. It is easy for humans to read and write and for machines to parse and generate. Django JsonResponse JsonResponse is an HttpResponse subclass that helps to create a JSON-encoded response. Its default Content-Type header is set to application/json. The first parameter, data, should be a dict instance. If the safe parameter is set to False, any object can be passed for serialization; otherwise only dict instances are allowed. Django JsonResponse example In the following example, we create a Django application that sends a file to the client. The file is a JPEG image, which is located in the images directory in the project root directory. $ mkdir jsonresponse $ cd jsonresponse $ mkdir src $ cd src We create the project and the and src directories. Then we locate to the src directory. $ django-admin startproject jsonresponse . We create a new Django project in the src directory. Note: If the optional destination is provided, Django will use that existing directory as the project directory. If it is omitted, Django creates a new directory based on the project name. We use the dot (.) to create a project inside the current working directory. $ cd .. $ pwd /c/Users/Jano/Documents/pyprogs/django/jsonresponse We locate to the project directory. $ tree /f src │ manage.py │ └───jsonresponse settings.py urls.py views.py wsgi.py __init__.py These are the contents of the project directory. Note: The Django way is to put functionality into apps, which are created with django-admin startapp. In this tutorial, we do not use an app to make the example simpler. We focus on demonstrating how to send JSON response. from django.contrib import admin from django.urls import path from .views import send_json urlpatterns = [ path('admin/', admin.site.urls), path('sendjson/', send_json, name='send_json'), ] We add a new route page; it calls the send_json() function from the views.py module. from django.http import JsonResponse def send_json(request): data = [{'name': 'Peter', 'email': 'peter@example.org'}, {'name': 'Julia', 'email': 'julia@example.org'}] return JsonResponse(data, safe=False) Inside send_json(), we define a list of dictionaries. Since it is a list, we set safe to False. If we did not set this parameter, we would get a TypeError with the following message: In order to allow non-dict objects to be serialized set the safe parameter to False. By default, JsonResponse accepts only Python dictionaries. $ python manage.py runserver We run the server and navigate to. $ curl localhost:8000/sendjson/ [{"name": "Peter", "email": "peter@example.org"}, {"name": "Julia", "email": "julia@example.org"}] We use the curl tool to make the GET request. In this tutorial, we have demonstrated how to send JSON data in Django. You might also be interested in the following related tutorials: Django email tutorial, Django FileResponse tutorial, Python Jinja tutorial, and Python tutorial, or list all Python tutorials.
http://zetcode.com/django/jsonresponse/
CC-MAIN-2019-26
refinedweb
552
51.85
3. Library calls (functions within program libraries) WCRTOMBSection: Linux Programmer's Manual (3) Updated: 2017-09-15 Index | Return to Main Contents NAMEwcrtomb - convert a wide character to a multibyte sequence SYNOPSIS #include <wchar.h> size_t wcrtomb(char *s, wchar_t wc, mbstate_t *ps); DESCRIPTION VALUETheFor an explanation of the terms used in this section, see attributes(7). CONFORMING TOPOSIX.1-2001, POSIX.1-2008, C99. NOTESThe behavior of wcrtomb() depends on the LC_CTYPE category of the current locale. Passing NULL as ps is not multithread safe. SEE ALSOmbsinit(3), wcsrtombs(3) COLOPHONThis page is part of release 4.15 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at. Index Return to Main Contents
https://eandata.com/linux/?chap=3&cmd=wcrtomb
CC-MAIN-2020-16
refinedweb
130
56.76
Selecting a robust React grid is something a lot of us will eventually be required to do as enterprise-level developerс. In this article, I try to give some insight into what features I look for in a data grid. Finding a workhorse grid for tabular data in your applications is something you regularly need to do as a front-end developer building line-of-business applications in the enterprise or at a large company. Understanding what to look for and what features you will need is a good prerequisite to choosing a React data grid. When thinking about the must-have features of a solid data grid component, it's a matter of selecting one that fits all the criteria you have at the moment and anticipating where your project might go in the future. With this article, I've attempted to compile a list of key criteria most developers will need to consider when looking for a grid solution. I hope that you can take this guide as a foundation, expand on it with your own research and considerations and find the ideal grid for your project. Most components are going to appear to work fine in application demos and during your development phase. But you may run into performance issues once you start using real data and users start interacting with it in a test or production environment. For this reason, before making any final decisions on a particular component (or library), you should use the React Performance Tools to analyze its performance and try to replicate a real use case or scenario similar to how you will use it in production. The React.js Blog's Introducing the React Profiler is a great resource for measuring the performance of a React component. Just as you would profile components you build and release yourself to production, when looking for a component library to bring into your project you should be testing them with your own application-specific data. How do they perform under the situations you envision them working in? All React component libraries should give you the ability to install through npm or GitHub. Below is an example of importing and using a React Grid component into your project. The following list of features is largely based on my experience building line of business applications for a large auto manufacturer. We need to ensure that any grid that we decide to use has options for basic Sorting, Filtering and Paging. This is the absolute minimum requirement I would have needed for any grid we would have used for our inventory system. If the developer has to worry too much about the implementation details of how to do these tasks, they are not getting their money's worth in a grid. You can see a specific example with demos of what these features cover and how you can set them up to test their functionality in Carl Bergenhem's in-depth tutorial for the KendoReact Grid component. In React, we typically will have a wrapper around our component that will allow us to keep track of our component's state. We can utilize this local state to store information about our sorting, what field we want to sort on and the direction (ascending or descending), as well as default settings. We can pass these into our component using props. A StackBlitz demo I created shows a very basic setup where we want to sort our data based on a productName. The default is true, and as you would guess, if you pass a false value to this prop you turn off the sorting feature. true false As an aside, a great bonus in a UI library can offer is to help us query data. If the library you are looking at has something similar to the KendoReact Data Query package, it should help tremendously when applying the sorting, filtering, grouping, and other aggregate data operations. It makes methods like process(), orderBy(), and filterBy() available. These methods are helpful in areas outside your grid component as well. process() orderBy() filterBy() In React, we also have the concept of a container component. These container components can be utilized to wrap and store our state for the grid component. We can import orderBy() and use it to sort our data which we have imported from a json file, which in turn has a column called productName. This makes it easy to load our data with default sort already in place. Maybe we want to always start off in a state where the data is in reverse alphabetical order? We would have the following setup in our state object: json productName state = { sort: [ { field: 'ProductName', dir: 'desc' } ] } And now when we create our Data Grid component in React, we just need to pass the data into the grid using the data prop. The product of this value is an orderBy applied to the json data and as the second argument we can pass in our settings from our state object: data orderBy render() { return ( <Grid data={orderBy(products, this.state.sort)}> <Column field="ProductID" /> <Column field="ProductName" title="Product Name" /> <Column field="UnitPrice" title="Unit Price" /> </Grid> ); } Already, and with very minimal effort, we have sorted our products by productName in a descending fashion. In order to make the individual column sortable, we can use onSortChange(), an event that fires when the sorting of the Grid is changed. We handle this event ourselves and sort the data using a simple arrow function that updates our state using the setState() method in React. onSortChange() setState() By default, when filtering is enabled, the Grid renders a filter row in its header. Based on the type of data the columns contain, the filter row displays text boxes in each column header where the user can filter string, numeric, or date inputs. Most of the filtering that I want to do can be achieved with a Custom Filter Cell. This technique is easy to understand and it's powerful. Filtering can be accomplished similarly to our previous sorting example. Using a higher order component in conjunction with the process() Data Query method, we can manage local data. It has its own state and adds the filter, sort, total, and skip props to the Grid to handle an onDataStateChange() event. We can bind to more than one grid if needed using different sets of data, without the need for you to write any logic for the filtering, sorting or paging. Below is what this feature looks like in a grid: onDataStateChange() I prepared a StackBlitz Demo to show some basic filtering and paging as well. Sometimes we have a large amount of data in our grids. When we're working with large numbers of columns or rows, we want to implement virtual scrolling. While the user is scrolling the table, the Grid needs to display only the visible data. Column Virtualization ensures that columns outside of the currently visible area of the grid will not be rendered. The grid also has a special scrolling mode called Virtual Scrolling. It's this scrolling mode that is most useful with large data sets. You can set a prop on the grid called pageSize. If you like to see an example of this, you can check out a quick video demo I did of virtualization as implemented in the KendoReact Grid for our R2 2019 release webinar (starts at 18"20'). pageSize In this demo, if you open the grid in a new browser window and inspect the grid (as seen in the animated gif below) as you scroll, you will notice that the only rows getting rendered to the view at any one time are those that you see. Once you scroll past older records, they are removed and new records are rendered. Having this type of functionality can mean better grid performance. When looking for a good data grid, or a complete component library for that matter, you want to know that if you invest in using the library, it's going to continue growing and being supported. Some libraries have been short-lived, either because the main contributor started spending less time on the project or because the company building it was not able to continue supporting it. In most cases, active development on the project ensures future bug fixes and maintenance at the very least. Knowing that a library has been around for a while and that new flavors and products are being built to this day in React should give you confidence that it will be here for ten or more years, that it will grow and that bugs will get fixed quickly. These are things that you want in a library. Having these traits will ensure you can have longevity with the tools and that your skills can be transferable or exploited as a developer in another job. You only get this from the larger libraries that have longevity. Plain and simple, components that are not licensed rarely have any type of support outside of at-will community help. Most big web development shops and enterprise level businesses have tight deadlines and their developers push the technology to the edges. It's helpful to have someone to reach out to that is an expert on working with the component you're implementing. Those are some of the key criteria on which to evaluate the React data grid that you're selecting for your next big app. If there are any features that you think you can't live without, put them in the comments and let us know what your favorite grid features!
https://www.telerik.com/blogs/what-to-look-for-when-choosing-a-react-data-grid-component
CC-MAIN-2019-43
refinedweb
1,610
57.4
Technical Support On-Line Manuals RL-ARM User's Guide (MDK v4) #include <rtl.h> BOOL igmp_leave ( U8 *group_ip); /* IP Address of the Host Group. */ The igmp_leave function requests that this host gives up its membership in the host group identified by group_ip. After the upper-layer has requested to leave the host group, datagrams destined to a particular group can not be received, but are silently discarded by the IP-layer. The igmp_leave function is in the RL-TCPnet library. The prototype is defined in rtl.h. The igmp_leave function returns __TRUE when this host successfully left a host group. Otherwise, the function returns __FALSE. igmp_join, udp_mcast_ttl, udp_send U8 sgroup[4] = { 238, 0, 100, 1}; .. if (igmp_leave (sgroup) == __TRUE) { printf ("This Host has left the group: %d.%d.%d.%d\n", sgroup[0],sgroup[1],sgroup[2],sgroup[3]); } else { printf ("Failed to leave a group, this host is not a member..
http://www.keil.com/support/man/docs/rlarm/rlarm_igmp_leave.htm
CC-MAIN-2020-05
refinedweb
153
67.65
What I don't like on JavaFX A new version of JavaFX is out, and I want to say, what I don't like on JavaFX. 1. JavaFX 1.2 is binary incompatible to JavaFX 1.0 and 1.1 JavaFX 1.2 is completly different to the versions before. JavaFX can not run old JavaFX-compiled programs. In JavaFX 1.0 in all .class-files was a main-Method and Java starts the running Class-File direct. Now in JavaFX 1.2 in no generated .class-file is a main-Method. And Java starts at first its runtime as a Java-program and that starts then the JavaFX-program. Nothing is wrong with binary-incompatiblity, if it would be in Beta-phase or so. But at the moment it changed after the 1.0 release. Will the binary format after every new JavaFX version change? Who creates then jfx-binary-programs, when they can not run on newer versions? 2. The JavaFX license The license don't allow to copy JavaFX and its runtime or give it away. So, if you creates a JavaFX-program, the end-user have to download the JFX-runtime hinself. The EULA don't allow to give the runtime with iot away. 3. Is JavaFX OpenSource The binary license have the mistake I have mentioned in (2.). But how open is JavaFX ? OpenJDK is under the GPL + GNU Classpath exception. Ok, the Compiler IS OpenSource And Scenegraph is as a library under the GPL without GNU Classpath exception! And the last version on that side is 0.6 from March 2008! So, do you know, if the COMPLETE JavaFX is OpenSource or will be? 4. The syntax of JavaFX I don't like the Syntax of JavaFX so much. I think it would be better, if JavaFX becomes a XML-precompiler or something like that. For example, I have creates with ReportMill JFXBuilder a simple picture with a box, a star and so with color-gradients. If I save it, JFXBuilder creates a xml-file with the extension .rpt which looks this: <?xml version="1.0" encoding="UTF-8"?> And this is the generated JavaFX Code, which JFXBuilder creates from the same picture: import javafx.scene.*; import javafx.scene.shape.*; import javafx.scene.paint.*; import com.jfxbuilder.fx.*; // Scene Definition var scene = Scene { fill: Color.WHITE width: 600 height: 400 content: [ArcX { translateX: 146 translateY: 65 width: 227 height: 88 length: 360 stroke: Color.BLACK strokeWidth: 1 fill: LinearGradient { startX: -0.102 startY: 0.719 endX: 1.102 endY: 0.281 proportional: true stops: [Stop { offset: 0 color: Color {red: 1, green: 0.416, blue: 0.596} }, Stop { offset: 1 color: Color {red: 0, green: 0.067, blue: 0.318} }] } }, RectangleX { translateX: 109 translateY: 113 width: 120 height: 87 opacity: 0.8 stroke: Color.BLACK strokeWidth: 1 fill: Color {red: 0.008, green: 0.992, blue: 0.369} }, PathX { elements: [MoveTo {x: 195.233, y: 97.617}, LineTo {x: 127.782, y: 119.533}, LineTo {x: 127.782, y: 190.455}, LineTo {x: 86.094, y: 133.078}, LineTo {x: 18.643, y: 154.994}, LineTo {x: 60.33, y: 97.617}, LineTo {x: 18.643, y: 40.239}, LineTo {x: 86.094, y: 62.155}, LineTo {x: 127.782, y: 4.778}, LineTo {x: 127.782, y: 75.7}, ClosePath { }, MoveTo {x: 0, y: 0}, MoveTo {x: 195.233, y: 195.233}] translateX: 155.383 translateY: 83.383 width: 195.233 height: 195.233 rotate: 37.926 opacity: 0.7 stroke: Color.BLACK strokeWidth: 1 fill: LinearGradient { startX: -0.065 startY: 0.911 endX: 1.065 endY: 0.089 proportional: true stops: [Stop { offset: 0 color: Color {red: 0.392, green: 0.996, blue: 0.996} }, Stop { offset: 1 color: Color {red: 1, green: 0.98, blue: 0.498} }] } }, PathX { elements: [MoveTo {x: 0, y: 26}, LineTo {x: 104, y: 0}] translateX: 302 translateY: 65 width: 104 height: 26 stroke: Color.BLACK strokeWidth: 1 fill: null }] }; What is easyier to read? What code can you see on one monitor-side without scrolling? Greatings theuserbl Wait a minute, is this even a fair comparison? You have a "star" tag already defined in the XML file, while in the JFX code you are drawing the star manually. Of course the jfx code is going to be longer, you already defined the star elsewhere ... you could have done the same with the JFX code if you defined a "star" class. Also in JFX you could specify the colors using the hex value too instead of the longer way you have used here. > For example, I have creates with ReportMill > > document> > > > > > > JFXBuilder a simple picture with a box, a star and so > with color-gradients. > If I save it, JFXBuilder creates a xml-file with the > extension .rpt which looks this: > > > > > > > > > > > > > > > > > > > > /line> > Is it possible to use functions, loops, define new classes for this xml file?
https://www.java.net/node/693751/atom/feed
CC-MAIN-2015-27
refinedweb
819
80.88
#include <deal.II/lac/solver_control.h> Class to be thrown upon failing convergence of an iterative solver, when either the number of iterations exceeds the limit or the residual fails to reach the desired limit, e.g. in the case of a break-down. The residual in the last iteration, as well as the iteration number of the last step are stored in this object and can be recovered upon catching an exception of this class. Definition at line 94 of file solver_control.h. Definition at line 97 of file solver_control.h. Print more specific information about the exception which occurred. Overload this function in your own exception classes. Reimplemented from ExceptionBase. Definition at line 105 of file solver_control.h. Set the file name and line of where the exception appeared as well as the violated condition and the name of the exception as a char pointer. This function also populates the stacktrace. Definition at line 128 of file exceptions.cc. Override the standard function that returns the description of the error. Definition at line 151 of file exceptions.cc. Get exception name. Definition at line 174 of file exceptions.cc. Print out the general part of the error information. Definition at line 182 of file exceptions.cc. Print a stacktrace, if one has been recorded previously, to the given stream. Definition at line 222 of file exceptions.cc. Iteration number of the last step. Definition at line 129 of file solver_control.h. Residual in the last step. Definition at line 134 of file solver_control.h.. A backtrace to the position where the problem happened, if the system supports this. Definition at line 148 of file exceptions.h. The number of stacktrace frames that are stored in the previous variable. Zero if the system does not support stack traces. Definition at line 154 of file exceptions.h. array of pointers that contains the raw stack trace Definition at line 160 of file exceptions.h.
https://dealii.org/developer/doxygen/deal.II/classSolverControl_1_1NoConvergence.html
CC-MAIN-2021-10
refinedweb
324
61.12
Hi everyone. I’m trying to SUM the places of the first 5 finishers in a Cross Country running event. In a Cross Country race the team score is based upon the sum of the top 5 runners on your team. The lowest team score at the competition wins. I have EVENTS(the race), PARTICIPANTS(the runner), and EVENT_PARTICIPANTS(a runner in a race). Within event_participant I have this code, which doesn’t work as it adds places beyond the 5th runner. def self.score_5 self.calculate(:sum, :finish_place, :order => :finish_place, :limit => 5) end It appears that the LIMIT is ignored or is applied after the summation. Any suggestions?
https://www.ruby-forum.com/t/sum-enumeration-with-limit/155091
CC-MAIN-2022-40
refinedweb
109
54.42
OpacityMask doesn't work for me ... what am I missing? I downloaded the images & used the QML code from the OpacityMask documentation page (qt-project.org/doc/qt-5/qml-qtgraphicaleffects-opacitymask.html) but it isn't doing what I expect. I though I would end up with a mostly red screen with a butterfly-shaped picture of a bug, but what I get instead is a boring square picture of a bug (on a red screen). There are no warnings in the console that would indicate the problem. Am I just mis-understanding the purpose of OpacityMask? Thanks, Chris @ import QtQuick 2.2 import QtQuick.Controls 1.2 import QtGraphicalEffects 1.0 Item { id: screen anchors.fill: parent Rectangle { anchors.fill: parent color: "red" } Item { id: hole anchors.fill: parent Image { id: bug source:"qrc:/Bug.png" sourceSize: Qt.size(parent.width, parent.height) smooth: true visible: false } Image { id: mask source:"qrc:/Butterfly.png" sourceSize: Qt.size(parent.width, parent.height) smooth: true visible: false } OpacityMask { anchors.fill: bug source: bug maskSource: mask } } } @ [edit: added missing coding tags @ SGaist] - p3c0 Moderators Hi, Make sure the image source files are in the resources. QtCreator must have shown the error in the console when you run the application. I figured out the problem, I downloaded the Butterfly.png from the OpacityMask documentation page and it looked like it had the properly transparent background, but it didn't. When I modified the image to actually have transparency, everything worked.
https://forum.qt.io/topic/43751/opacitymask-doesn-t-work-for-me-what-am-i-missing/1
CC-MAIN-2019-04
refinedweb
248
53.68
May 29, 2018 10:02 AM|davidmichaeli|LINK I have a issue with my script (powershell) that is monitored my nlb cluster that have only 2 nodes. my script is checks the state of the iis (for each a node), and check the state of the node, if the iis is down, so i perform stop-NlbClusterNode on the certain node, but it perform stop all nodes.. i try few options: Stop-NlbClusterNode -InputObject (Get-NlbClusterNode -NodeName "node1") Stop-NlbClusterNode -HostName "node1" -Drain -Timout 10 but always all nodes are stopped. any idea? Microsoft May 30, 2018 05:55 AM|deepakpanchal10|LINK Hi Davidmichael, I can see that you did not posted the full script. So it is possible that you try to stop all nodes in it. You can try to refer the example below and try to put your code in else part of both if conditions to stop the specific node as per condition. CLS #Define Nodes $node1 = "Server1" $node2 = "Server2" #get NLB status on NLB Nodes $Node1status = Get-WmiObject -Class MicrosoftNLB_Node -computername $node1 -namespace root\MicrosoftNLB | Select-Object __Server, statuscode $Node2status = Get-WmiObject -Class MicrosoftNLB_Node -computername $node2 -namespace root\MicrosoftNLB | Select-Object __Server, statuscode IF ($node1.statuscode -eq "1008" -or $node1.statuscode -eq "1007") { write-host "NLB Status of $node1 is: Converged" } else { write-host "NLB Status of $node1 is: Error" } IF ($node2.statuscode -eq "1008" -or $node2.statuscode -eq "1007") { write-host "NLB Status of $node2 is: Converged" } else { write-host "NLB Status of $node2 is: Error" } Reference: Check NLB status on nodes Regards Deepak 1 reply Last post May 30, 2018 05:55 AM by deepakpanchal10
https://forums.iis.net/p/1238692/2141186.aspx?Re+Stop+NlbClusterNode+perform+stop+all+nodes
CC-MAIN-2018-39
refinedweb
272
57.1
Hello, I am trying to insert a point process to a postsynaptic cell using the .loc() fn, for some reason the point process is also inserted into the presynaptic cell (i found this out using neuron.h.psection() ). Could you please tell me what i did wrong (see code): pre = preCell() post = postCell() ampa = neuron.h.gluR() <-point process ampa.loc(0.5, post) thank you, inserting point process When Python is the interpreter, what is a good design for the interface to the basic NEURON concepts. design for the interface to the basic NEURON concepts. Post Reply 2 posts • Page 1 of 1 Re: inserting point process Pre is still the currently accessed section. Try: Try: Code: Select all from neuron import h ampa=h.gluR(post(0.5)) h.psection(sec=post) Post Reply 2 posts • Page 1 of 1
https://www.neuron.yale.edu/phpBB/viewtopic.php?f=2&t=2135&p=8108
CC-MAIN-2020-34
refinedweb
142
65.62
digitalmars.D.bugs - static interface function - Chris Newton (22/22) Dec 26 2004 Hello all, Hello all, It seems to me that a static function within an interface is not correct. But with DMD v0.109 you can create an interface with a static function. Then when that interface is implemented, you can include that same function in the implementing class. That function can be called from the namespace of the class and it all works. If you try to call that function from the namespace of the interface, it will compile but fail to link and find that interface static function. You can even not put that function in the class, but have it in the interface, and call the function from the namespace of the class. Once again it will compile (without an undefined property error), but fail to link. This leads me to a thought though. It would be pretty damn cool if you could have a 'singleton' static interface function. For interfaces that follow the singleton model. For example, have an interface that is shared between two different binaries, but each binary has its own implementation. And having the standard 'getInstance' style function to get a reference to a static instance variable (the variable would deffinitely not be part of the interface, but part of the implementation). It would require making sure that that symbol is only found once for the link of a binary. Otherwise you could choose between multiples. Perhaps this was intended with D for the 'static' keyword? :) Thanks, Chris Newton Dec 26 2004
http://www.digitalmars.com/d/archives/digitalmars/D/bugs/2612.html
CC-MAIN-2016-44
refinedweb
261
64.61
. In a world of limited resources, Design Patterns help us achieve the most results with the least amount of used resources. It is also important to note that Design Patterns do not apply to all situations and it is crucial to assess the problem at hand in order to choose the best approach for that particular scenario. Design Patterns are divided into a few broad categories, though mainly into Creational Patterns, Structural Patterns, and Behavioral Patterns. The Factory Method pattern is a Creational Design Pattern. The Factory Method Design Pattern Definition The Factory Method is used in object-oriented programming as a means to provide factory interfaces for creating objects. These interfaces define the generic structure, but don't initialize objects. The initialization is left to more specific subclasses. The parent class/interface houses all the standard and generic behaviour that can be shared across subclasses of different types. The subclass is in turn responsible for the definition and instantiation of the object based on the superclass. Motivation The main motivation behind the Factory Method Design Pattern is to enhance loose coupling in code through the creation of an abstract class that will be used to create different types of objects that share some common attributes and functionality. This results in increased flexibility and reuse of code because the shared functionality will not be rewritten having been inherited from the same class. This design pattern is also known as a Virtual Constructor. The Factory Method design pattern is commonly used in libraries by allowing clients to choose what subclass or type of object to create through an abstract class. A Factory Method will receive information about a required object, instantiate it and return the object of the specified type. This gives our application or library a single point of interaction with other programs or pieces of code, thereby encapsulating our object creation functionality. Factory Method Implementation Our program is going to be a library used for handling shape objects in terms of creation and other operations such as adding color and calculating the area of the shape. Users should be able to use our library to create new objects. We can start by creating single individual shapes and availing them as is but that would mean that a lot of shared logic will have to be rewritten for each and every shape we have available. The first step to solving this repetition would be to create a parent shape class that has methods such as calculate_area() and calculate_perimeter(), and properties such as dimensions. The specific shape objects will then inherit from our base class. To create a shape, we will need to identify what kind of shape is required and create the subclass for it. We will start by creating an abstract class to represent a generic shape: import abc class Shape(metaclass=abc.ABCMeta): @abc.abstractmethod def calculate_area(self): pass @abc.abstractmethod def calculate_perimeter(self): pass This is the base class for all of our shapes. Let's go ahead and create several concrete, more specific shapes: class Rectangle(Shape): def __init__(self, height, width): self.height = height self.width = width def calculate_area(self): return self.height * self.width def calculate_perimeter(self): return 2 * (self.height + self.width) class Square(Shape): def __init__(self, width): self.width = width def calculate_area(self): return self.width ** 2 def calculate_perimeter(self): return 4 * self.width class Circle(Shape): def __init__(self, radius): self.radius = radius def calculate_area(self): return 3.14 * self.radius * self.radius def calculate_perimeter(self): return 2 * 3.14 * self.radius So far, we have created an abstract class and extended it to suit different shapes that will be available in our library. In order to create the different shape objects, clients will have to know the names and details of our shapes and separately perform the creation. This is where the Factory Method comes into play. The Factory Method design pattern will help us abstract the available shapes from the client, i.e. the client does not have to know all the shapes available, but rather only create what they need during runtime. It will also allow us to centralize and encapsulate the object creation. Let us achieve this by creating a ShapeFactory that will be used to create the specific shape classes based on the client's input: class ShapeFactory: def create_shape(self, name): if name == 'circle': radius = input("Enter the radius of the circle: ") return Circle(float(radius)) elif name == 'rectangle': height = input("Enter the height of the rectangle: ") width = input("Enter the width of the rectangle: ") return Rectangle(int(height), int(width)) elif name == 'square': width = input("Enter the width of the square: ") return Square(int(width)) This is our interface for creation. We don't call the constructors of concrete classes, we call the Factory and ask it to create a shape. Our ShapeFactory works by receiving information about a shape such as a name and the required dimensions. Our factory method create_shape() will then be used to create and return ready objects of the desired shapes. The client doesn't have to know anything about the object creation or specifics. Using the factory object, they can create objects with minimal knowledge of how they work: def shapes_client(): shape_factory = ShapeFactory() shape_name = input("Enter the name of the shape: ") shape = shape_factory.create_shape(shape_name) print(f"The type of object created: {type(shape)}") print(f"The area of the {shape_name} is: {shape.calculate_area()}") print(f"The perimeter of the {shape_name} is: {shape.calculate_perimeter()}") Running this code will result in: Enter the name of the shape: circle Enter the radius of the circle: 7 The type of object created: <class '__main__.Circle'> The area of the circle is: 153.86 The perimeter of the circle is: 43.96 Or, we could build another shape: Enter the name of the shape: square Enter the width of the square: 5 The type of object created: <class '__main__.Square'> The area of the square is: 25 The perimeter of the square is: 20 What's worth noting is that besides the client not having to know much about the creation process - when we'd like to instantiate an object, we don't call the constructor of the class. We ask the factory to do this for us based on the info we pass to the create_shape() function. Pros and Cons Pros One of the major advantages of using the Factory Method design pattern is that our code becomes loosely coupled in that the majority of the components of our code are unaware of other components of the same codebase. This results in code that is easy to understand and test and add more functionality to specific components without affecting or breaking the entire program. The Factory Method design pattern also helps uphold the Single Responsibility Principle where classes and objects that handle specific functionality resulting in better code. Cons Creation of more classes eventually leads to less readability. If combined with an Abstract Factory (factory of factories), the code will soon become verbose, though, maintainable. Conclusion.
https://stackabuse.com/the-factory-method-design-pattern-in-python/
CC-MAIN-2021-17
refinedweb
1,176
52.49
allocate memory like other languages? It turns out, CPython, the most popular Python runtime is written in human-readable C and Python code. This tutorial will walk you through the CPython source code. You’ll cover all the concepts behind the internals of CPython, how they work and visual explanations as you go. You’ll learn how to: - Read and navigate the source code - Compile CPython from source code - Navigate and comprehend the inner workings of concepts like lists, dictionaries, and generators - Run the test suite - Modify or upgrade components of the CPython library to contribute them to future versions Yes, this is a very long article. If you just made yourself a fresh cup of tea, coffee or your favorite beverage, it’s going to be cold by the end of Part 1. This tutorial is split into five parts. Take your time for each part and make sure you try out the demos and the interactive components. You can feel a sense of achievement that you grasp the core concepts of Python that can make you a better Python programmer. Free Download: Get a sample chapter from CPython Internals: Your Guide to the Python 3 Interpreter showing you how to unlock the inner workings of the Python language, compile the Python interpreter from source code, and participate in the development of CPython. Part 1: Introduction to CPython# When you type python at the console or install a Python distribution from python.org, you are running CPython. CPython is one of the many Python runtimes, maintained and written by different teams of developers. Some other runtimes you may have heard are PyPy, Cython, and Jython. The unique thing about CPython is that it contains both a runtime and the shared language specification that all Python runtimes use. CPython is the “official,” or reference implementation of Python. The Python language specification is the document that the description of the Python language. For example, it says that assert is a reserved keyword, and that [] is used for indexing, slicing, and creating empty lists. Think about what you expect to be inside the Python distribution on your computer: - When you type pythonwithout a file or module, it gives an interactive prompt. - You can import built-in modules from the standard library like json. - You can install packages from the internet using pip. - You can test your applications using the built-in unittestlibrary. These are all part of the CPython distribution. There’s a lot more than just a compiler. What’s in the Source Code?# The CPython source distribution comes with a whole range of tools, libraries, and components. We’ll explore those in this article. First we are going to focus on the compiler. To download a copy of the CPython source code, you can use git to pull the latest version to a working copy locally: $ git clone $ cd cpython $ git checkout v3.8.0b4 Note: If you don’t have Git available, you can download the source in a ZIP file directly from the GitHub website. Inside of the newly downloaded cpython directory, you will find the following subdirectories: Next, we’ll compile CPython from the source code. This step requires a C compiler, and some build tools, which depend on the operating system you’re using. Compiling CPython (macOS)# Compiling CPython on macOS is straightforward. You will first need the essential C compiler toolkit. The Command Line Development Tools is an app that you can update in macOS through the App Store. You need to perform the initial installation on the terminal. To open up a terminal in macOS, go to the Launchpad, then Other then choose the Terminal app. You will want to save this app to your Dock, so right-click the Icon and select Keep in Dock. Now, within the terminal, install the C compiler and toolkit by running the following: $ xcode-select --install This command will pop up with a prompt to download and install a set of tools, including Git, Make, and the GNU C compiler. You will also need a working copy of OpenSSL to use for fetching packages from the PyPi.org website. If you later plan on using this build to install additional packages, SSL validation is required. The simplest way to install OpenSSL on macOS is by using HomeBrew. If you already have HomeBrew installed, you can install the dependencies for CPython with the brew install command: $ brew install openssl xz zlib Now that you have the dependencies, you can run the configure script, enabling SSL support by discovering the location that HomeBrew installed to and enabling the debug hooks --with-pydebug: $ CPPFLAGS="-I$(brew --prefix zlib)/include" \ LDFLAGS="-L$(brew --prefix zlib)/lib" \ ./configure --with-openssl=$(brew --prefix openssl) --with-pydebug This will generate a Makefile in the root of the repository that you can use to automate the build process. The ./configure step only needs to be run once. You can build the CPython binary by running: $ make -j2 -s The -j2 flag allows make to run 2 jobs simultaneously. If you have 4 cores, you can change this to 4. The -s flag stops the Makefile from printing every command it runs to the console. You can remove this, but the output is very verbose. During the build, you may receive some errors, and in the summary, it will notify you that not all packages could be built. For example, _dbm, _sqlite3, _uuid, nis, ossaudiodev, spwd, and _tkinter would fail to build with this set of instructions. That’s okay if you aren’t planning on developing against those packages. If you are, then check out the dev guide website for more information. The build will take a few minutes and generate a binary called python.exe. Every time you make changes to the source code, you will need to re-run make with the same flags. The python.exe binary is the debug binary of CPython. Execute python.exe to see a working REPL: $ ./python.exe Python 3.8.0b4 (tags/v3.8.0b4:d93605de72, Aug 30 2019, 10:00:03) [Clang 10.0.1 (clang-1001.0.46.4)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> Note: Yes, that’s right, the macOS build has a file extension for .exe. This is not because it’s a Windows binary. Because macOS has a case-insensitive filesystem and when working with the binary, the developers didn’t want people to accidentally refer to the directory Python/ so .exe was appended to avoid ambiguity. If you later run make install or make altinstall, it will rename the file back to python. Compiling CPython (Linux)# For Linux, the first step is to download and install make, gcc, configure, and pkgconfig. For Fedora Core, RHEL, CentOS, or other yum-based systems: $ sudo yum install yum-utils For Debian, Ubuntu, or other apt-based systems: $ sudo apt install build-essential Then install the required packages, for Fedora Core, RHEL, CentOS or other yum-based systems: $ sudo yum-builddep python3 For Debian, Ubuntu, or other apt-based systems: $ sudo apt install libssl-dev zlib1g-dev libncurses5-dev \ libncursesw5-dev libreadline-dev libsqlite3-dev libgdbm-dev \ libdb5.3-dev libbz2-dev libexpat1-dev liblzma-dev libffi-dev Now that you have the dependencies, you can run the configure script, enabling the debug hooks --with-pydebug: $ ./configure --with-pydebug Review the output to ensure that OpenSSL support was marked as YES. Otherwise, check with your distribution for instructions on installing the headers for OpenSSL. Next, you can build the CPython binary by running the generated Makefile: $ make -j2 -s During the build, you may receive some errors, and in the summary, it will notify you that not all packages could be built. That’s okay if you aren’t planning on developing against those packages. If you are, then check out the dev guide website for more information. The build will take a few minutes and generate a binary called python. This is the debug binary of CPython. Execute ./python to see a working REPL: $ ./python Python 3.8.0b4 (tags/v3.8.0b4:d93605de72, Aug 30 2019, 10:00:03) [Clang 10.0.1 (clang-1001.0.46.4)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> Compiling CPython (Windows)# Inside the PC folder is a Visual Studio project file for building and exploring CPython. To use this, you need to have Visual Studio installed on your PC. The newest version of Visual Studio, Visual Studio 2019, makes it easier to work with Python and the CPython source code, so it is recommended for use in this tutorial. If you already have Visual Studio 2017 installed, that would also work fine. None of the paid features are required for compiling CPython or this tutorial. You can use the Community edition of Visual Studio, which is available for free from Microsoft’s Visual Studio website. Once you’ve downloaded the installer, you’ll be asked to select which components you want to install. The bare minimum for this tutorial is: - The Python Development workload - The optional Python native development tools - Python 3 64-bit (3.7.2) (can be deselected if you already have Python 3.7 installed) Any other optional features can be deselected if you want to be more conscientious with disk space: The installer will then download and install all of the required components. The installation could take an hour, so you may want to read on and come back to this section. Once the installer has completed, click the Launch button to start Visual Studio. You will be prompted to sign in. If you have a Microsoft account you can log in, or skip that step. Once Visual Studio starts, you will be prompted to Open a Project. A shortcut to getting started with the Git configuration and cloning CPython is to choose the Clone or check out code option: For the project URL, type to clone: Visual Studio will then download a copy of CPython from GitHub using the version of Git bundled with Visual Studio. This step also saves you the hassle of having to install Git on Windows. The download may take 10 minutes. Once the project has downloaded, you need to point it to the pcbuild Solution file, by clicking on Solutions and Projects and selecting pcbuild.sln: When the solution is loaded, it will prompt you to retarget the project’s inside the solution to the version of the C/C++ compiler you have installed. Visual Studio will also target the version of the Windows SDK you have installed. Ensure that you change the Windows SDK version to the newest installed version and the platform toolset to the latest version. If you missed this window, you can right-click on the Solution in the Solutions and Projects window and click Retarget Solution. Once this is complete, you need to download some source files to be able to build the whole CPython package. Inside the PCBuild folder there is a .bat file that automates this for you. Open up a command-line prompt inside the downloaded PCBuild and run get_externals.bat: > get_externals.bat Using py -3.7 (found 3.7 with py.exe) Fetching external libraries... Fetching bzip2-1.0.6... Fetching sqlite-3.21.0.0... Fetching xz-5.2.2... Fetching zlib-1.2.11... Fetching external binaries... Fetching openssl-bin-1.1.0j... Fetching tcltk-8.6.9.0... Finished. Next, back within Visual Studio, build CPython by pressing Ctrl+Shift+B, or choosing Build Solution from the top menu. If you receive any errors about the Windows SDK being missing, make sure you set the right targeting settings in the Retarget Solution window. You should also see Windows Kits inside your Start Menu, and Windows Software Development Kit inside of that menu. The build stage could take 10 minutes or more for the first time. Once the build is completed, you may see a few warnings that you can ignore and eventual completion. To start the debug version of CPython, press F5 and CPython will start in Debug mode straight into the REPL: Once this is completed, you can run the Release build by changing the build configuration from Debug to Release on the top menu bar and rerunning Build Solution again. You now have both Debug and Release versions of the CPython binary within PCBuild\win32\. You can set up Visual Studio to be able to open a REPL with either the Release or Debug build by choosing Tools-> Python-> Python Environments from the top menu: Then click Add Environment and then target the Debug or Release binary. The Debug binary will end in _d.exe, for example, python_d.exe and pythonw_d.exe. You will most likely want to use the debug binary as it comes with Debugging support in Visual Studio and will be useful for this tutorial. In the Add Environment window, target the python_d.exe file as the interpreter inside the PCBuild/win32 and the pythonw_d.exe as the windowed interpreter: Now, you can start a REPL session by clicking Open Interactive Window in the Python Environments window and you will see the REPL for the compiled version of Python: During this tutorial there will be REPL sessions with example commands. I encourage you to use the Debug binary to run these REPL sessions in case you want to put in any breakpoints within the code. Lastly, to make it easier to navigate the code, in the Solution View, click on the toggle button next to the Home icon to switch to Folder view: Now you have a version of CPython compiled and ready to go, let’s find out how the CPython compiler works. What Does a Compiler Do?# The purpose of a compiler is to convert one language into another. Think of a compiler like a translator. You would hire a translator to listen to you speaking in English and then speak in Japanese: Some compilers will compile into a low-level machine code which can be executed directly on a system. Other compilers will compile into an intermediary language, to be executed by a virtual machine. One important decision to make when choosing a compiler is the system portability requirements. Java and .NET CLR will compile into an Intermediary Language so that the compiled code is portable across multiple systems architectures. C, Go, C++, and Pascal will compile into a low-level executable that will only work on systems similar to the one it was compiled. Because Python applications are typically distributed as source code, the role of the Python runtime is to convert the Python source code and execute it in one step. Internally, the CPython runtime does compile your code. A popular misconception is that Python is an interpreted language. It is actually compiled. Python code is not compiled into machine-code. It is compiled into a special low-level intermediary language called bytecode that only CPython understands. This code is stored in .pyc files in a hidden directory and cached for execution. If you run the same Python application twice without changing the source code, it’ll always be much faster the second time. This is because it loads the compiled bytecode and executes it directly. Why Is CPython Written in C and Not Python?# The C in CPython is a reference to the C programming language, implying that this Python distribution is written in the C language. This statement is largely true: the compiler in CPython is written in pure C. However, many of the standard library modules are written in pure Python or a combination of C and Python. So why is CPython written in C and not Python? The answer is located in how compilers work. There are two types of compiler: - Self-hosted compilers are compilers written in the language they compile, such as the Go compiler. - Source-to-source compilers are compilers written in another language that already have a compiler. If you’re writing a new programming language from scratch, you need an executable application to compile your compiler! You need a compiler to execute anything, so when new languages are developed, they’re often written first in an older, more established language. A good example would be the Go programming language. The first Go compiler was written in C, then once Go could be compiled, the compiler was rewritten in Go. CPython kept its C heritage: many of the standard library modules, like the ssl module or the sockets module, are written in C to access low-level operating system APIs. The APIs in the Windows and Linux kernels for creating network sockets, working with the filesystem or interacting with the display are all written in C. It made sense for Python’s extensibility layer to be focused on the C language. Later in this article, we will cover the Python Standard Library and the C modules. There is a Python compiler written in Python called PyPy. PyPy’s logo is an Ouroboros to represent the self-hosting nature of the compiler. Another example of a cross-compiler for Python is Jython. Jython is written in Java and compiles from Python source code into Java bytecode. In the same way that CPython makes it easy to import C libraries and use them from Python, Jython makes it easy to import and reference Java modules and classes. The Python Language Specification# Contained within the CPython source code is the definition of the Python language. This is the reference specification used by all the Python interpreters. The specification is in both human-readable and machine-readable format. Inside the documentation is a detailed explanation of the Python language, what is allowed, and how each statement should behave. Documentation# Located inside the Doc/reference directory are reStructuredText explanations of each of the features in the Python language. This forms the official Python reference guide on docs.python.org. Inside the directory are the files you need to understand the whole language, structure, and keywords: cpython/Doc/reference | ├── compound_stmts.rst ├── datamodel.rst ├── executionmodel.rst ├── expressions.rst ├── grammar.rst ├── import.rst ├── index.rst ├── introduction.rst ├── lexical_analysis.rst ├── simple_stmts.rst └── toplevel_components.rst Inside compound_stmts.rst, the documentation for compound statements, you can see a simple example defining the with statement. The with statement can be used in multiple ways in Python, the simplest being the instantiation of a context-manager and a nested block of code: with x(): ... You can assign the result to a variable using the as keyword: with x() as y: ... You can also chain context managers together with a comma: with x() as y, z() as jk: ... Next, we’ll explore the computer-readable documentation of the Python language. Grammar# The documentation contains the human-readable specification of the language, and the machine-readable specification is housed in a single file, Grammar/Grammar. The Grammar file is written in a context-notation called Backus-Naur Form (BNF). BNF is not specific to Python and is often used as the notation for grammars in many other languages. The concept of grammatical structure in a programming language is inspired by Noam Chomsky’s work on Syntactic Structures in the 1950s! Python’s grammar file uses the Extended-BNF (EBNF) specification with regular-expression syntax. So, in the grammar file you can use: *for repetition +for at-least-once repetition []for optional parts |for alternatives ()for grouping If you search for the with statement in the grammar file, at around line 80 you’ll see the definitions for the with statement: with_stmt: 'with' with_item (',' with_item)* ':' suite with_item: test ['as' expr] Anything in quotes is a string literal, which is how keywords are defined. So the with_stmt is specified as: - Starting with the word with - Followed by a with_item, which is a testand (optionally), the word as, and an expression - Following one or many items, each separated by a comma - Ending with a : - Followed by a suite There are references to some other definitions in these two lines: suiterefers to a block of code with one or multiple statements testrefers to a simple statement that is evaluated exprrefers to a simple expression If you want to explore those in detail, the whole of the Python grammar is defined in this single file. If you want to see a recent example of how grammar is used, in PEP 572 the colon equals operator was added to the grammar file in this Git commit. Using pgen# The grammar file itself is never used by the Python compiler. Instead, a parser table created by a tool called pgen is used. pgen reads the grammar file and converts it into a parser table. If you make changes to the grammar file, you must regenerate the parser table and recompile Python. Note: The pgen application was rewritten in Python 3.8 from C to pure Python. To see pgen in action, let’s change part of the Python grammar. Around line 51 you will see the definition of a pass statement: pass_stmt: 'pass' Change that line to accept the keyword 'pass' or 'proceed' as keywords: pass_stmt: 'pass' | 'proceed' Now you need to rebuild the grammar files. On macOS and Linux, run make regen-grammar to run pgen over the altered grammar file. For Windows, there is no officially supported way of running pgen. However, you can clone my fork and run build.bat --regen from within the PCBuild directory. You should see an output similar to this, showing that the new Include/graminit.h and Python/graminit.c files have been generated: # Regenerate Doc/library/token-list.inc from Grammar/Tokens # using Tools/scripts/generate_token.py ... python3 ./Tools/scripts/update_file.py ./Include/graminit.h ./Include/graminit.h.new python3 ./Tools/scripts/update_file.py ./Python/graminit.c ./Python/graminit.c.new Note: pgen works by converting the EBNF statements into a Non-deterministic Finite Automaton (NFA), which is then turned into a Deterministic Finite Automaton (DFA). The DFAs are used by the parser as parsing tables in a special way that’s unique to CPython. This technique was formed at Stanford University and developed in the 1980s, just before the advent of Python. With the regenerated parser tables, you need to recompile CPython to see the new syntax. Use the same compilation steps you used earlier for your operating system. If the code compiled successfully, you can execute your new CPython binary and start a REPL. In the REPL, you can now try defining a function and instead of using the pass statement, use the proceed keyword alternative that you compiled into the Python grammar: Python 3.8.0b4 (tags/v3.8.0b4:d93605de72, Aug 30 2019, 10:00:03) [Clang 10.0.1 (clang-1001.0.46.4)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> def example(): ... proceed ... >>> example() Well done! You’ve changed the CPython syntax and compiled your own version of CPython. Ship it! Next, we’ll explore tokens and their relationship to grammar. Tokens# Alongside the grammar file in the Grammar folder is a Tokens file, which contains each of the unique types found as a leaf node in a parse tree. We will cover parser trees in depth later. Each token also has a name and a generated unique ID. The names are used to make it simpler to refer to in the tokenizer. Note: The Tokens file is a new feature in Python 3.8. For example, the left parenthesis is called LPAR, and semicolons are called SEMI. You’ll see these tokens later in the article: LPAR '(' RPAR ')' LSQB '[' RSQB ']' COLON ':' COMMA ',' SEMI ';' As with the Grammar file, if you change the Tokens file, you need to run pgen again. To see tokens in action, you can use the tokenize module in CPython. Create a simple Python script called test_tokens.py: # Hello world! def my_function(): proceed For the rest of this tutorial, ./python.exe will refer to the compiled version of CPython. However, the actual command will depend on your system. For Windows: > python.exe For Linux: > ./python For macOS: > ./python.exe Then pass this file through a module built into the standard library called tokenize. You will see the list of tokens, by line and character. Use the -e flag to output the exact token name: $ ./python.exe -m tokenize -e test_tokens.py 0,0-0,0: ENCODING 'utf-8' 1,0-1,14: COMMENT '# Hello world!' 1,14-1,15: NL '\n' 2,0-2,3: NAME 'def' 2,4-2,15: NAME 'my_function' 2,15-2,16: LPAR '(' 2,16-2,17: RPAR ')' 2,17-2,18: COLON ':' 2,18-2,19: NEWLINE '\n' 3,0-3,3: INDENT ' ' 3,3-3,7: NAME 'proceed' 3,7-3,8: NEWLINE '\n' 4,0-4,0: DEDENT '' 4,0-4,0: ENDMARKER '' In the output, the first column is the range of the line/column coordinates, the second column is the name of the token, and the final column is the value of the token. In the output, the tokenize module has implied some tokens that were not in the file. The ENCODING token for utf-8, and a blank line at the end, giving DEDENT to close the function declaration and an ENDMARKER to end the file. It is best practice to have a blank line at the end of your Python source files. If you omit it, CPython adds it for you, with a tiny performance penalty. The tokenize module is written in pure Python and is located in Lib/tokenize.py within the CPython source code. Important: There are two tokenizers in the CPython source code: one written in Python, demonstrated here, and another written in C. The tokenizer written in Python is meant as a utility, and the one written in C is used by the Python compiler. They have identical output and behavior. The version written in C is designed for performance and the module in Python is designed for debugging. To see a verbose readout of the C tokenizer, you can run Python with the -d flag. Using the test_tokens.py script you created earlier, run it with the following: $ ./python.exe -d test_tokens.py Token NAME/'def' ... It's a keyword DFA 'file_input', state 0: Push 'stmt' DFA 'stmt', state 0: Push 'compound_stmt' DFA 'compound_stmt', state 0: Push 'funcdef' DFA 'funcdef', state 0: Shift. Token NAME/'my_function' ... It's a token we know DFA 'funcdef', state 1: Shift. Token LPAR/'(' ... It's a token we know DFA 'funcdef', state 2: Push 'parameters' DFA 'parameters', state 0: Shift. Token RPAR/')' ... It's a token we know DFA 'parameters', state 1: Shift. DFA 'parameters', state 2: Direct pop. Token COLON/':' ... It's a token we know DFA 'funcdef', state 3: Shift. Token NEWLINE/'' ... It's a token we know DFA 'funcdef', state 5: [switch func_body_suite to suite] Push 'suite' DFA 'suite', state 0: Shift. Token INDENT/'' ... It's a token we know DFA 'suite', state 1: Shift. Token NAME/'proceed' ... It's a keyword DFA 'suite', state 3: Push 'stmt' ... ACCEPT. In the output, you can see that it highlighted proceed as a keyword. In the next chapter, we’ll see how executing the Python binary gets to the tokenizer and what happens from there to execute your code. Now that you have an overview of the Python grammar and the relationship between tokens and statements, there is a way to convert the pgen output into an interactive graph. Here is a screenshot of the Python 3.8a2 grammar: The Python package used to generate this graph, instaviz, will be covered in a later chapter. Memory Management in CPython# Throughout this article, you will see references to a PyArena object. The arena is one of CPython’s memory management structures. The code is within Python/pyarena.c and contains a wrapper around C’s memory allocation and deallocation functions. In a traditionally written C program, the developer should allocate memory for data structures before writing into that data. This allocation marks the memory as belonging to the process with the operating system. It is also up to the developer to deallocate, or “free,” the allocated memory when its no longer being used and return it to the operating system’s block table of free memory. If a process allocates memory for a variable, say within a function or loop, when that function has completed, the memory is not automatically given back to the operating system in C. So if it hasn’t been explicitly deallocated in the C code, it causes a memory leak. The process will continue to take more memory each time that function runs until eventually, the system runs out of memory, and crashes! Python takes that responsibility away from the programmer and uses two algorithms: a reference counter and a garbage collector. Whenever an interpreter is instantiated, a PyArena is created and attached one of the fields in the interpreter. During the lifecycle of a CPython interpreter, many arenas could be allocated. They are connected with a linked list. The arena stores a list of pointers to Python Objects as a PyListObject. Whenever a new Python object is created, a pointer to it is added using PyArena_AddPyObject(). This function call stores a pointer in the arena’s list, a_objects. Even though Python doesn’t have pointers, there are some interesting techniques to simulate the behavior of pointers. The PyArena serves a second function, which is to allocate and reference a list of raw memory blocks. For example, a PyList would need extra memory if you added thousands of additional values. The PyList object’s C code does not allocate memory directly. The object gets raw blocks of memory from the PyArena by calling PyArena_Malloc() from the PyObject with the required memory size. This task is completed by another abstraction in Objects/obmalloc.c. In the object allocation module, memory can be allocated, freed, and reallocated for a Python Object. A linked list of allocated blocks is stored inside the arena, so that when an interpreter is stopped, all managed memory blocks can be deallocated in one go using PyArena_Free(). Take the PyListObject example. If you were to .append() an object to the end of a Python list, you don’t need to reallocate the memory used in the existing list beforehand. The .append() method calls list_resize() which handles memory allocation for lists. Each list object keeps a list of the amount of memory allocated. If the item you’re appending will fit inside the existing free memory, it is simply added. If the list needs more memory space, it is expanded. Lists are expanded in length as 0, 4, 8, 16, 25, 35, 46, 58, 72, 88. PyMem_Realloc() is called to expand the memory allocated in a list. PyMem_Realloc() is an API wrapper for pymalloc_realloc(). Python also has a special wrapper for the C call malloc(), which sets the max size of the memory allocation to help prevent buffer overflow errors (See PyMem_RawMalloc()). In summary: - Allocation of raw memory blocks is done via PyMem_RawAlloc(). - The pointers to Python objects are stored within the PyArena. PyArenaalso stores a linked-list of allocated memory blocks. More information on the API is detailed on the CPython documentation. Reference Counting# To create a variable in Python, you have to assign a value to a uniquely named variable: my_variable = 180392 Whenever a value is assigned to a variable in Python, the name of the variable is checked within the locals and globals scope to see if it already exists. Because my_variable is not already within the locals() or globals() dictionary, this new object is created, and the value is assigned as being the numeric constant 180392. There is now one reference to my_variable, so the reference counter for my_variable is incremented by 1. You will see function calls Py_INCREF() and Py_DECREF() throughout the C source code for CPython. These functions increment and decrement the count of references to that object. References to an object are decremented when a variable falls outside of the scope in which it was declared. Scope in Python can refer to a function or method, a comprehension, or a lambda function. These are some of the more literal scopes, but there are many other implicit scopes, like passing variables to a function call. The handling of incrementing and decrementing references based on the language is built into the CPython compiler and the core execution loop, ceval.c, which we will cover in detail later in this article. Whenever Py_DECREF() is called, and the counter becomes 0, the PyObject_Free() function is called. For that object PyArena_Free() is called for all of the memory that was allocated. Garbage Collection# How often does your garbage get collected? Weekly, or fortnightly? When you’re finished with something, you discard it and throw it in the trash. But that trash won’t get collected straight away. You need to wait for the garbage trucks to come and pick it up. CPython has the same principle, using a garbage collection algorithm. CPython’s garbage collector is enabled by default, happens in the background and works to deallocate memory that’s been used for objects which are no longer in use. Because the garbage collection algorithm is a lot more complex than the reference counter, it doesn’t happen all the time, otherwise, it would consume a huge amount of CPU resources. It happens periodically, after a set number of operations. CPython’s standard library comes with a Python module to interface with the arena and the garbage collector, the gc module. Here’s how to use the gc module in debug mode: >>> import gc >>> gc.set_debug(gc.DEBUG_STATS) This will print the statistics whenever the garbage collector is run. You can get the threshold after which the garbage collector is run by calling get_threshold(): >>> gc.get_threshold() (700, 10, 10) You can also get the current threshold counts: >>> gc.get_count() (688, 1, 1) Lastly, you can run the collection algorithm manually: >>> gc.collect() 24 This will call collect() inside the Modules/gcmodule.c file which contains the implementation of the garbage collector algorithm. Conclusion# In Part 1, you covered the structure of the source code repository, how to compile from source, and the Python language specification. These core concepts will be critical in Part 2 as you dive deeper into the Python interpreter process. Part 2: The Python Interpreter Process# Now that you’ve seen the Python grammar and memory management, you can follow the process from typing python to the part where your code is executed. There are five ways the python binary can be called: - To run a single command with -cand a Python command - To start a module with -mand the name of a module - To run a file with the filename - To run the stdininput using a shell pipe - To start the REPL and execute commands one at a time Python has so many ways to execute scripts, it can be a little overwhelming. Darren Jones has put together a great course on running Python scripts if you want to learn more. The three source files you need to inspect to see this process are: Programs/python.cis a simple entry point. Modules/main.ccontains the code to bring together the whole process, loading configuration, executing code and clearing up memory. Python/initconfig.cloads the configuration from the system environment and merges it with any command-line flags. This diagram shows how each of those functions is called: The execution mode is determined from the configuration. The CPython source code style: Similar to the PEP8 style guide for Python code, there is an official style guide for the CPython C code, designed originally in 2001 and updated for modern versions. There are some naming standards which help when navigating the source code: Use a Pyprefix for public functions, never for static functions. The Py_prefix is reserved for global service routines like Py_FatalError. Specific groups of routines (like specific object type APIs) use a longer prefix, such as PyString_for string functions. Public functions and variables use MixedCase with underscores, like this: PyObject_GetAttr, Py_BuildValue, PyExc_TypeError. Occasionally an “internal” function has to be visible to the loader. We use the _Pyprefix for this, for example, _PyObject_Dump. Macros should have a MixedCase prefix and then use upper case, for example PyString_AS_STRING, Py_PRINT_RAW. Establishing Runtime Configuration# In the swimlanes, you can see that before any Python code is executed, the runtime first establishes the configuration. The configuration of the runtime is a data structure defined in Include/cpython/initconfig.h named PyConfig. The configuration data structure includes things like: - Runtime flags for various modes like debug and optimized mode - The execution mode, such as whether a filename was passed, stdinwas provided or a module name - Extended option, specified by -X <option> - Environment variables for runtime settings The configuration data is primarily used by the CPython runtime to enable and disable various features. Python also comes with several Command Line Interface Options. In Python you can enable verbose mode with the -v flag. In verbose mode, Python will print messages to the screen when modules are loaded: $ ./python.exe -v -c "print('hello world')" # installing zipimport hook import zipimport # builtin # installed zipimport hook ... You will see a hundred lines or more with all the imports of your user site-packages and anything else in the system environment. You can see the definition of this flag within Include/cpython/initconfig.h inside the struct for PyConfig: /* --- PyConfig ---------------------------------------------- */ typedef struct { int _config_version; /* Internal configuration version, used for ABI compatibility */ int _config_init; /* _PyConfigInitEnum value */ ... /* If greater than 0, enable the verbose mode:. Incremented by the -v option. Set by the PYTHONVERBOSE environment variable. If set to -1 (default), inherit Py_VerboseFlag value. */ int verbose; In Python/initconfig.c, the logic for reading settings from environment variables and runtime command-line flags is established. In the config_read_env_vars function, the environment variables are read and used to assign the values for the configuration settings: static PyStatus config_read_env_vars(PyConfig *config) { PyStatus status; int use_env = config->use_environment; /* Get environment variables */ _Py_get_env_flag(use_env, &config->parser_debug, "PYTHONDEBUG"); _Py_get_env_flag(use_env, &config->verbose, "PYTHONVERBOSE"); _Py_get_env_flag(use_env, &config->optimization_level, "PYTHONOPTIMIZE"); _Py_get_env_flag(use_env, &config->inspect, "PYTHONINSPECT"); For the verbose setting, you can see that the value of PYTHONVERBOSE is used to set the value of &config->verbose, if PYTHONVERBOSE is found. If the environment variable does not exist, then the default value of -1 will remain. Then in config_parse_cmdline within initconfig.c again, the command-line flag is used to set the value, if provided: static PyStatus config_parse_cmdline(PyConfig *config, PyWideStringList *warnoptions, Py_ssize_t *opt_index) { ... switch (c) { ... case 'v': config->verbose++; break; ... /* This space reserved for other options */ default: /* unknown argument: parsing failed */ config_usage(1, program); return _PyStatus_EXIT(2); } } while (1); This value is later copied to a global variable Py_VerboseFlag by the _Py_GetGlobalVariablesAsDict function. Within a Python session, you can access the runtime flags, like verbose mode, quiet mode, using the sys.flags named tuple. The -X flags are all available inside the sys._xoptions dictionary: $ ./python.exe -X dev -q >>> import sys >>> sys.flags sys.flags(debug=0, inspect=0, interactive=0, optimize=0, dont_write_bytecode=0, no_user_site=0, no_site=0, ignore_environment=0, verbose=0, bytes_warning=0, quiet=1, hash_randomization=1, isolated=0, dev_mode=True, utf8_mode=0) >>> sys._xoptions {'dev': True} As well as the runtime configuration in initconfig.h, there is also the build configuration, which is located inside pyconfig.h in the root folder. This file is created dynamically in the configure step in the build process, or by Visual Studio for Windows systems. You can see the build configuration by running: $ ./python.exe -m sysconfig Reading Files/Input# Once CPython has the runtime configuration and the command-line arguments, it can establish what it needs to execute. This task is handled by the pymain_main function inside Modules/main.c. Depending on the newly created config instance, CPython will now execute code provided via several options. Input via -c# The simplest is providing CPython a command with the -c option and a Python program inside quotes. For example: $ ./python.exe -c "print('hi')" hi Here is the full flowchart of how this happens: First, the pymain_run_command() function is executed inside Modules/main.c taking the command passed in -c as an argument in the C type wchar_t*. The wchar_t* type is often used as a low-level storage type for Unicode data across CPython as the size of the type can store UTF8 characters. When converting the wchar_t* to a Python string, the Objects/unicodeobject.c file has a helper function PyUnicode_FromWideChar() that returns a PyObject, of type str. The encoding to UTF8 is then done by PyUnicode_AsUTF8String() on the Python str object to convert it to a Python bytes object. Once this is complete, pymain_run_command() will then pass the Python bytes object to PyRun_SimpleStringFlags() for execution, but first converting the bytes to a str type again: static int pymain_run_command(wchar_t *command, PyCompilerFlags *cf) { PyObject *unicode, *bytes; int ret; unicode = PyUnicode_FromWideChar(command, -1); if (unicode == NULL) { goto error; } if (PySys_Audit("cpython.run_command", "O", unicode) < 0) { return pymain_exit_err_print(); } bytes = PyUnicode_AsUTF8String(unicode); Py_DECREF(unicode); if (bytes == NULL) { goto error; } ret = PyRun_SimpleStringFlags(PyBytes_AsString(bytes), cf); Py_DECREF(bytes); return (ret != 0); error: PySys_WriteStderr("Unable to decode the command from the command line:\n"); return pymain_exit_err_print(); } The conversion of wchar_t* to Unicode, bytes, and then a string is roughly equivalent to the following: unicode = str(command) bytes_ = bytes(unicode.encode('utf8')) # call PyRun_SimpleStringFlags with bytes_ The PyRun_SimpleStringFlags() function is part of Python/pythonrun.c. It’s purpose is to turn this simple command into a Python module and then send it on to be executed. Since a Python module needs to have __main__ to be executed as a standalone module, it creates that automatically: int PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags) { PyObject *m, *d, *v; m = PyImport_AddModule("__main__"); if (m == NULL) return -1; d = PyModule_GetDict(m); v = PyRun_StringFlags(command, Py_file_input, d, d, flags); if (v == NULL) { PyErr_Print(); return -1; } Py_DECREF(v); return 0; } Once PyRun_SimpleStringFlags() has created a module and a dictionary, it calls PyRun_StringFlags(), which creates a fake filename and then calls the Python parser to create an AST from the string and return a module, mod: PyObject * PyRun_StringFlags(const char *str, int start, PyObject *globals, PyObject *locals, PyCompilerFlags *flags) { ... mod = PyParser_ASTFromStringObject(str, filename, start, flags, arena); if (mod != NULL) ret = run_mod(mod, filename, globals, locals, flags, arena); PyArena_Free(arena); return ret; You’ll dive into the AST and Parser code in the next section. Input via -m# Another way to execute Python commands is by using the -m option with the name of a module. A typical example is python -m unittest to run the unittest module in the standard library. Being able to execute modules as scripts were initially proposed in PEP 338 and then the standard for explicit relative imports defined in PEP366. The use of the -m flag implies that within the module package, you want to execute whatever is inside __main__. It also implies that you want to search sys.path for the named module. This search mechanism is why you don’t need to remember where the unittest module is stored on your filesystem. Inside Modules/main.c there is a function called when the command-line is run with the -m flag. The name of the module is passed as the modname argument. CPython will then import a standard library module, runpy and execute it using PyObject_Call(). The import is done using the C API function PyImport_ImportModule(), found within the Python/import.c file: static int pymain_run_module(const wchar_t *modname, int set_argv0) { PyObject *module, *runpy, *runmodule, *runargs, *result; runpy = PyImport_ImportModule("runpy"); ... runmodule = PyObject_GetAttrString(runpy, "_run_module_as_main"); ... module = PyUnicode_FromWideChar(modname, wcslen(modname)); ... runargs = Py_BuildValue("(Oi)", module, set_argv0); ... result = PyObject_Call(runmodule, runargs, NULL); ... if (result == NULL) { return pymain_exit_err_print(); } Py_DECREF(result); return 0; } In this function you’ll also see 2 other C API functions: PyObject_Call() and PyObject_GetAttrString(). Because PyImport_ImportModule() returns a PyObject*, the core object type, you need to call special functions to get attributes and to call it. In Python, if you had an object and wanted to get an attribute, then you could call getattr(). In the C API, this call is PyObject_GetAttrString(), which is found in Objects/object.c. If you wanted to run a callable, you would give it parentheses, or you can run the __call__() property on any Python object. The __call__() method is implemented inside Objects/object.c: hi = "hi!" hi.upper() == hi.upper.__call__() # this is the same The runpy module is written in pure Python and located in Lib/runpy.py. Executing python -m <module> is equivalent to running python -m runpy <module>. The runpy module was created to abstract the process of locating and executing modules on an operating system. runpy does a few things to run the target module: - Calls __import__()for the module name you provided - Sets __name__(the module name) to a namespace called __main__ - Executes the module within the __main__namespace The runpy module also supports executing directories and zip files. Input via Filename# If the first argument to python was a filename, such as python test.py, then CPython will open a file handle, similar to using open() in Python and pass the handle to PyRun_SimpleFileExFlags() inside Python/pythonrun.c. There are 3 paths this function can take: - If the file path is a .pycfile, it will call run_pyc_file(). - If the file path is a script file ( .py) it will run PyRun_FileExFlags(). - If the filepath is stdinbecause the user ran command | pythonthen treat stdinas a file handle and run PyRun_FileExFlags(). int PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit, PyCompilerFlags *flags) { ... m = PyImport_AddModule("__main__"); ... if (maybe_pyc_file(fp, filename, ext, closeit)) { ... v = run_pyc_file(pyc_fp, filename, d, d, flags); } else { /* When running from stdin, leave __main__.__loader__ alone */ if (strcmp(filename, "<stdin>") != 0 && set_main_loader(d, filename, "SourceFileLoader") < 0) { fprintf(stderr, "python: failed to set __main__.__loader__\n"); ret = -1; goto done; } v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d, closeit, flags); } ... return ret; } Input via File With PyRun_FileExFlags()# For stdin and basic script files, CPython will pass the file handle to PyRun_FileExFlags() located in the pythonrun.c file. The purpose of PyRun_FileExFlags() is similar to PyRun_SimpleStringFlags() used for the -c input. CPython will load the file handle into PyParser_ASTFromFileObject(). We’ll cover the Parser and AST modules in the next section. Because this is a full script, it doesn’t need the PyImport_AddModule("__main__"); step used by -c: PyObject * PyRun_FileExFlags(FILE *fp, const char *filename_str, int start, PyObject *globals, PyObject *locals, int closeit, PyCompilerFlags *flags) { ... mod = PyParser_ASTFromFileObject(fp, filename, NULL, start, 0, 0, flags, NULL, arena); ... ret = run_mod(mod, filename, globals, locals, flags, arena); } Identical to PyRun_SimpleStringFlags(), once PyRun_FileExFlags() has created a Python module from the file, it sent it to run_mod() to be executed. run_mod() is found within Python/pythonrun.c, and sends the module to the AST to be compiled into a code object. Code objects are a format used to store the bytecode operations and the format kept in .pyc files:; } We will cover the CPython compiler and bytecodes in the next section. The call to run_eval_code_obj() is a simple wrapper function that calls PyEval_EvalCode() in the Python/eval.c file. The PyEval_EvalCode() function is the main evaluation loop for CPython, it iterates over each bytecode statement and executes it on your local machine. Input via Compiled Bytecode With run_pyc_file()# In the PyRun_SimpleFileExFlags() there was a clause for the user providing a file path to a .pyc file. If the file path ended in .pyc then instead of loading the file as a plain text file and parsing it, it will assume that the .pyc file contains a code object written to disk. The run_pyc_file() function inside Python/pythonrun.c then marshals the code object from the .pyc file by using the file handle. Marshaling is a technical term for copying the contents of a file into memory and converting them to a specific data structure. The code object data structure on the disk is the CPython compiler’s way to caching compiled code so that it doesn’t need to parse it every time the script is called: static PyObject * run_pyc_file(FILE *fp, const char *filename, PyObject *globals, PyObject *locals, PyCompilerFlags *flags) { PyCodeObject *co; PyObject *v; ... v = PyMarshal_ReadLastObjectFromFile(fp); ... if (v == NULL || !PyCode_Check(v)) { Py_XDECREF(v); PyErr_SetString(PyExc_RuntimeError, "Bad code object in .pyc file"); goto error; } fclose(fp); co = (PyCodeObject *)v; v = run_eval_code_obj(co, globals, locals); if (v && flags) flags->cf_flags |= (co->co_flags & PyCF_MASK); Py_DECREF(co); return v; } Once the code object has been marshaled to memory, it is sent to run_eval_code_obj(), which calls Python/ceval.c to execute the code. Lexing and Parsing# In the exploration of reading and executing Python files, we dived as deep as the parser and AST modules, with function calls to PyParser_ASTFromFileObject(). Sticking within Python/pythonrun.c, the PyParser_ASTFromFileObject() function will take a file handle, compiler flags and a PyArena instance and convert the file object into a node object using PyParser_ParseFileObject(). With the node object, it will then convert that into a module using the AST function PyAST_FromNodeObject(): mod_ty PyParser_ASTFromFileObject(FILE *fp, PyObject *filename, const char* enc, int start, const char *ps1, const char *ps2, PyCompilerFlags *flags, int *errcode, PyArena *arena) { ... node *n = PyParser_ParseFileObject(fp, filename, enc, &_PyParser_Grammar, start, ps1, ps2, &err, &iflags); ... if (n) { flags->cf_flags |= iflags & PyCF_MASK; mod = PyAST_FromNodeObject(n, flags, filename, arena); PyNode_Free(n); ... return mod; } For PyParser_ParseFileObject() we switch to Parser/parsetok.c and the parser-tokenizer stage of the CPython interpreter. This function has two important tasks: - Instantiate a tokenizer state tok_stateusing PyTokenizer_FromFile()in Parser/tokenizer.c - Convert the tokens into a concrete parse tree (a list of node) using parsetok()in Parser/parsetok.c node * PyParser_ParseFileObject(FILE *fp, PyObject *filename, const char *enc, grammar *g, int start, const char *ps1, const char *ps2, perrdetail *err_ret, int *flags) { struct tok_state *tok; ... if ((tok = PyTokenizer_FromFile(fp, enc, ps1, ps2)) == NULL) { err_ret->error = E_NOMEM; return NULL; } ... return parsetok(tok, g, start, err_ret, flags); } tok_state (defined in Parser/tokenizer.h) is the data structure to store all temporary data generated by the tokenizer. It is returned to the parser-tokenizer as the data structure is required by parsetok() to develop the concrete syntax tree. Inside parsetok(), it will use the tok_state structure and make calls to tok_get() in a loop until the file is exhausted and no more tokens can be found. tok_get(), defined in Parser/tokenizer.c behaves like an iterator. It will keep returning the next token in the parse tree. tok_get() is one of the most complex functions in the whole CPython codebase. It has over 640 lines and includes decades of heritage with edge cases, new language features, and syntax. One of the simpler examples would be the part that converts a newline break into a NEWLINE token: static int tok_get(struct tok_state *tok, char **p_start, char **p_end) { ... /* Newline */ if (c == '\n') { tok->atbol = 1; if (blankline || tok->level > 0) { goto nextline; } *p_start = tok->start; *p_end = tok->cur - 1; /* Leave '\n' out of the string */ tok->cont_line = 0; if (tok->async_def) { /* We're somewhere inside an 'async def' function, and we've encountered a NEWLINE after its signature. */ tok->async_def_nl = 1; } return NEWLINE; } ... } In this case, NEWLINE is a token, with a value defined in Include/token.h. All tokens are constant int values, and the Include/token.h file was generated earlier when we ran make regen-grammar. The node type returned by PyParser_ParseFileObject() is going to be essential for the next stage, converting a parse tree into an Abstract-Syntax-Tree (AST): typedef struct _node { short n_type; char *n_str; int n_lineno; int n_col_offset; int n_nchildren; struct _node *n_child; int n_end_lineno; int n_end_col_offset; } node; Since the CST is a tree of syntax, token IDs, and symbols, it would be difficult for the compiler to make quick decisions based on the Python language. That is why the next stage is to convert the CST into an AST, a much higher-level structure. This task is performed by the Python/ast.c module, which has both a C and Python API. Before you jump into the AST, there is a way to access the output from the parser stage. CPython has a standard library module parser, which exposes the C functions with a Python API. The module is documented as an implementation detail of CPython so that you won’t see it in other Python interpreters. Also the output from the functions is not that easy to read. The output will be in the numeric form, using the token and symbol numbers generated by the make regen-grammar stage, stored in Include/token.h: >>> from pprint import pprint >>> import parser >>> st = parser.expr('a + 1') >>> pprint(parser.st2list(st)) [258, [332, [306, [310, [311, [312, [313, [316, [317, [318, [319, [320, [321, [322, [323, [324, [325, [1, 'a']]]]]], [14, '+'], [321, [322, [323, [324, [325, [2, '1']]]]]]]]]]]]]]]]], [4, ''], [0, '']] To make it easier to understand, you can take all the numbers in the symbol and token modules, put them into a dictionary and recursively replace the values in the output of parser.st2list() with the names: import symbol import token import parser def lex(expression): symbols = {v: k for k, v in symbol.__dict__.items() if isinstance(v, int)} tokens = {v: k for k, v in token.__dict__.items() if isinstance(v, int)} lexicon = {**symbols, **tokens} st = parser.expr(expression) st_list = parser.st2list(st) def replace(l: list): r = [] for i in l: if isinstance(i, list): r.append(replace(i)) else: if i in lexicon: r.append(lexicon[i]) else: r.append(i) return r return replace(st_list) You can run lex() with a simple expression, like a + 1 to see how this is represented as a parser-tree: >>> from pprint import pprint >>> pprint(lex('a + 1')) ['eval_input', ['testlist', ['test', ['or_test', ['and_test', ['not_test', ['comparison', ['expr', ['xor_expr', ['and_expr', ['shift_expr', ['arith_expr', ['term', ['factor', ['power', ['atom_expr', ['atom', ['NAME', 'a']]]]]], ['PLUS', '+'], ['term', ['factor', ['power', ['atom_expr', ['atom', ['NUMBER', '1']]]]]]]]]]]]]]]]], ['NEWLINE', ''], ['ENDMARKER', '']] In the output, you can see the symbols in lowercase, such as 'test' and the tokens in uppercase, such as 'NUMBER'. Abstract Syntax Trees# The next stage in the CPython interpreter is to convert the CST generated by the parser into something more logical that can be executed. The structure is a higher-level representation of the code, called an Abstract Syntax Tree (AST). ASTs are produced inline with the CPython interpreter process, but you can also generate them in both Python using the ast module in the Standard Library as well as through the C API. Before diving into the C implementation of the AST, it would be useful to understand what an AST looks like for a simple piece of Python code. To do this, here’s a simple app called instaviz for this tutorial. It displays the AST and bytecode instructions (which we’ll cover later) in a Web UI. To install instaviz: $ pip install instaviz Then, open up a REPL by running python at the command line with no arguments: >>> import instaviz >>> def example(): a = 1 b = a + 1 return b >>> instaviz.show(example) You’ll see a notification on the command-line that a web server has started on port 8080. If you were using that port for something else, you can change it by calling instaviz.show(example, port=9090) or another port number. In the web browser, you can see the detailed breakdown of your function: The bottom left graph is the function you declared in REPL, represented as an Abstract Syntax Tree. Each node in the tree is an AST type. They are found in the ast module, and all inherit from _ast.AST. Some of the nodes have properties which link them to child nodes, unlike the CST, which has a generic child node property. For example, if you click on the Assign node in the center, this links to the line b = a + 1: It has two properties: targetsis a list of names to assign. It is a list because you can assign to multiple variables with a single expression using unpacking valueis the value to assign, which in this case is a BinOpstatement, a + 1. If you click on the BinOp statement, it shows the properties of relevance: left: the node to the left of the operator op: the operator, in this case, an Addnode ( +) for addition right: the node to the right of the operator Compiling an AST in C is not a straightforward task, so the Python/ast.c module is over 5000 lines of code. There are a few entry points, forming part of the AST’s public API. In the last section on the lexer and parser, you stopped when you’d reached the call to PyAST_FromNodeObject(). By this stage, the Python interpreter process had created a CST in the format of node * tree. Jumping then into PyAST_FromNodeObject() inside Python/ast.c, you can see it receives the node * tree, the filename, compiler flags, and the PyArena. The return type from this function is mod_ty, defined in Include/Python-ast.h. mod_ty is a container structure for one of the 5 module types in Python: Module Interactive Expression FunctionType Suite In Include/Python-ast.h you can see that an Expression type requires a field body, which is an expr_ty type. The expr_ty type is also defined in Include/Python-ast.h: enum _mod_kind {Module_kind=1, Interactive_kind=2, Expression_kind=3, FunctionType_kind=4, Suite_kind=5}; struct _mod { enum _mod_kind kind; union { struct { asdl_seq *body; asdl_seq *type_ignores; } Module; struct { asdl_seq *body; } Interactive; struct { expr_ty body; } Expression; struct { asdl_seq *argtypes; expr_ty returns; } FunctionType; struct { asdl_seq *body; } Suite; } v; }; The AST types are all listed in Parser/Python.asdl. You will see the module types, statement types, expression types, operators, and comprehensions all listed. The names of the types in this document relate to the classes generated by the AST and the same classes named in the ast standard module library. The parameters and names in Include/Python-ast.h correlate directly to those specified in Parser/Python.asdl: -- ASDL's 5 builtin types are: -- identifier, int, string, object, constant module Python { mod = Module(stmt* body, type_ignore *type_ignores) | Interactive(stmt* body) | Expression(expr body) | FunctionType(expr* argtypes, expr returns) The C header file and structures are there so that the Python/ast.c program can quickly generate the structures with pointers to the relevant data. Looking at PyAST_FromNodeObject() you can see that it is essentially a switch statement around the result from TYPE(n). TYPE() is one of the core functions used by the AST to determine what type a node in the concrete syntax tree is. In the case of PyAST_FromNodeObject() it’s just looking at the first node, so it can only be one of the module types defined as Module, Interactive, Expression, FunctionType. The result of TYPE() will be either a symbol or token type, which we’re very familiar with by this stage. For file_input, the results should be a Module. Modules are a series of statements, of which there are a few types. The logic to traverse the children of n and create statement nodes is within ast_for_stmt(). This function is called either once, if there is only 1 statement in the module, or in a loop if there are many. The resulting Module is then returned with the PyArena. For eval_input, the result should be an Expression. The result from CHILD(n ,0), which is the first child of n is passed to ast_for_testlist() which returns an expr_ty type. This expr_ty is sent to Expression() with the PyArena to create an expression node, and then passed back as a result: mod_ty PyAST_FromNodeObject(const node *n, PyCompilerFlags *flags, PyObject *filename, PyArena *arena) { ... switch (TYPE(n)) { case file_input: stmts = _Py_asdl_seq_new(num_stmts(n), arena); if (!stmts) goto out;); } } } /* Type ignores are stored under the ENDMARKER in file_input. */ ... res = Module(stmts, type_ignores, arena); break; case eval_input: { expr_ty testlist_ast; /* XXX Why not comp_for here? */ testlist_ast = ast_for_testlist(&c, CHILD(n, 0)); if (!testlist_ast) goto out; res = Expression(testlist_ast, arena); break; } case single_input: ... break; case func_type_input: ... ... return res; } Inside the ast_for_stmt() function, there is another switch statement for each possible statement type ( simple_stmt, compound_stmt, and so on) and the code to determine the arguments to the node class. One of the simpler functions is for the power expression, i.e., 2**4 is 2 to the power of 4. This function starts by getting the ast_for_atom_expr(), which is the number 2 in our example, then if that has one child, it returns the atomic expression. If it has more than one child, it will get the right-hand (the number 4) and return a BinOp (binary operation) with the operator as Pow (power), the left hand of e (2), and the right hand of f (4): static expr_ty ast_for_power(struct compiling *c, const node *n) { /* power: atom trailer* ('**' factor)* */ expr_ty e; REQ(n, power); e = ast_for_atom_expr(c, CHILD(n, 0)); if (!e) return NULL; if (NCH(n) == 1) return e; if (TYPE(CHILD(n, NCH(n) - 1)) == factor) { expr_ty f = ast_for_expr(c, CHILD(n, NCH(n) - 1)); if (!f) return NULL; e = BinOp(e, Pow, f, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); } return e; } You can see the result of this if you send a short function to the instaviz module: >>> def foo(): 2**4 >>> import instaviz >>> instaviz.show(foo) In the UI you can also see the corresponding properties: In summary, each statement type and expression has a corresponding ast_for_*() function to create it. The arguments are defined in Parser/Python.asdl and exposed via the ast module in the standard library. If an expression or statement has children, then it will call the corresponding ast_for_* child function in a depth-first traversal. Conclusion# CPython’s versatility and low-level execution API make it the ideal candidate for an embedded scripting engine. You will see CPython used in many UI applications, such as Game Design, 3D graphics and system automation. The interpreter process is flexible and efficient, and now you have an understanding of how it works you’re ready to understand the compiler. Part 3: The CPython Compiler and Execution Loop# In Part 2, you saw how the CPython interpreter takes an input, such as a file or string, and converts it into a logical Abstract Syntax Tree. We’re still not at the stage where this code can be executed. Next, we have to go deeper to convert the Abstract Syntax Tree into a set of sequential commands that the CPU can understand. Compiling# Now the interpreter has an AST with the properties required for each of the operations, functions, classes, and namespaces. It is the job of the compiler to turn the AST into something the CPU can understand. This compilation task is split into 2 parts: - Traverse the tree and create a control-flow-graph, which represents the logical sequence for execution - Convert the nodes in the CFG to smaller, executable statements, known as byte-code Earlier, we were looking at how files are executed, and the PyRun_FileExFlags() function in Python/pythonrun.c. Inside this function, we converted the FILE handle into a mod, of type mod_ty. This task was completed by PyParser_ASTFromFileObject(), which in turns calls the tokenizer, parser-tokenizer and then the AST: PyObject * PyRun_FileExFlags(FILE *fp, const char *filename_str, int start, PyObject *globals, PyObject *locals, int closeit, PyCompilerFlags *flags) { ... mod = PyParser_ASTFromFileObject(fp, filename, NULL, start, 0, 0, ... ret = run_mod(mod, filename, globals, locals, flags, arena); } The resulting module from the call to is sent to run_mod() still in Python/pythonrun.c. This is a small function that gets a PyCodeObject from PyAST_CompileObject() and sends it on to run_eval_code_obj(). You will tackle run_eval_code_obj() in the next section:; } The PyAST_CompileObject() function is the main entry point to the CPython compiler. It takes a Python module as its primary argument, along with the name of the file, the globals, locals, and the PyArena all created earlier in the interpreter process. We’re starting to get into the guts of the CPython compiler now, with decades of development and Computer Science theory behind it. Don’t be put off by the language. Once we break down the compiler into logical steps, it’ll make sense. Before the compiler starts, a global compiler state is created. This type, compiler is defined in Python/compile.c and contains properties used by the compiler to remember the compiler flags, the stack, and the PyArena: struct compiler { PyObject *c_filename; struct symtable *c_st; PyFutureFeatures *c_future; /* pointer to module's __future__ */ PyCompilerFlags *c_flags; int c_optimize; /* optimization level */ int c_interactive; /* true if in interactive mode */ int c_nestlevel; int c_do_not_emit_bytecode; /* The compiler won't emit any bytecode if this value is different from zero. This can be used to temporarily visit nodes without emitting bytecode to check only errors. */ PyObject *c_const_cache; /* Python dict holding all constants, including names tuple */ struct compiler_unit *u; /* compiler state for current block */ PyObject *c_stack; /* Python list holding compiler_unit ptrs */ PyArena *c_arena; /* pointer to memory allocation arena */ }; Inside PyAST_CompileObject(), there are 11 main steps happening: - Create an empty __doc__property to the module if it doesn’t exist. - Create an empty __annotations__property to the module if it doesn’t exist. - Set the filename of the global compiler state to the filename argument. - Set the memory allocation arena for the compiler to the one used by the interpreter. - Copy any __future__flags in the module to the future flags in the compiler. - Merge runtime flags provided by the command-line or environment variables. - Enable any __future__features in the compiler. - Set the optimization level to the provided argument, or default. - Build a symbol table from the module object. - Run the compiler with the compiler state and return the code object. - Free any allocated memory by the compiler. PyCodeObject * PyAST_CompileObject(mod_ty mod, PyObject *filename, PyCompilerFlags *flags, int optimize, PyArena *arena) { struct compiler c; PyCodeObject *co = NULL; PyCompilerFlags local_flags = _PyCompilerFlags_INIT; int merged; PyConfig *config = &_PyInterpreterState_GET_UNSAFE()->config; if (!__doc__) { __doc__ = PyUnicode_InternFromString("__doc__"); if (!__doc__) return NULL; } if (!__annotations__) { __annotations__ = PyUnicode_InternFromString("__annotations__"); if (!__annotations__) return NULL; } if (!compiler_init(&c)) return NULL; Py_INCREF(filename); c.c_filename = filename; c.c_arena = arena; c.c_future = PyFuture_FromASTObject(mod, filename); if (c.c_future == NULL) goto finally; if (!flags) { flags = &local_flags; } merged = c.c_future->ff_features | flags->cf_flags; c.c_future->ff_features = merged; flags->cf_flags = merged; c.c_flags = flags; c.c_optimize = (optimize == -1) ? config->optimization_level : optimize; c.c_nestlevel = 0; c.c_do_not_emit_bytecode = 0; if (!_PyAST_Optimize(mod, arena, c.c_optimize)) { goto finally; } c.c_st = PySymtable_BuildObject(mod, filename, c.c_future); if (c.c_st == NULL) { if (!PyErr_Occurred()) PyErr_SetString(PyExc_SystemError, "no symtable"); goto finally; } co = compiler_mod(&c, mod); finally: compiler_free(&c); assert(co || PyErr_Occurred()); return co; } Future Flags and Compiler Flags# Before the compiler runs, there are two types of flags to toggle the features inside the compiler. These come from two places: - The interpreter state, which may have been command-line options, set in pyconfig.hor via environment variables - The use of __future__statements inside the actual source code of the module To distinguish the two types of flags, think that the __future__ flags are required because of the syntax or features in that specific module. For example, Python 3.7 introduced delayed evaluation of type hints through the annotations future flag: from __future__ import annotations The code after this statement might use unresolved type hints, so the __future__ statement is required. Otherwise, the module wouldn’t import. It would be unmaintainable to manually request that the person importing the module enable this specific compiler flag. The other compiler flags are specific to the environment, so they might change the way the code executes or the way the compiler runs, but they shouldn’t link to the source in the same way that __future__ statements do. One example of a compiler flag would be the -O flag for optimizing the use of assert statements. This flag disables any assert statements, which may have been put in the code for debugging purposes. It can also be enabled with the PYTHONOPTIMIZE=1 environment variable setting. Symbol Tables# In PyAST_CompileObject() there was a reference to a symtable and a call to PySymtable_BuildObject() with the module to be executed. The purpose of the symbol table is to provide a list of namespaces, globals, and locals for the compiler to use for referencing and resolving scopes. The symtable structure in Include/symtable.h is well documented, so it’s clear what each of the fields is for. There should be one symtable instance for the compiler, so namespacing becomes essential. If you create a function called resolve_names() in one module and declare another function with the same name in another module, you want to be sure which one is called. The symtable serves this purpose, as well as ensuring that variables declared within a narrow scope don’t automatically become globals (after all, this isn’t JavaScript): */ }; Some of the symbol table API is exposed via the symtable module in the standard library. You can provide an expression or a module an receive a symtable.SymbolTable instance. You can provide a string with a Python expression and the compile_type of "eval", or a module, function or class, and the compile_mode of "exec" to get a symbol table. Looping over the elements in the table we can see some of the public and private fields and their types: >>> import symtable >>> s = symtable.symtable('b + 1', filename='test.py', compile_type='eval') >>> [symbol.__dict__ for symbol in s.get_symbols()] [{'_Symbol__name': 'b', '_Symbol__flags': 6160, '_Symbol__scope': 3, '_Symbol__namespaces': ()}] The C code behind this is all within Python/symtable.c and the primary interface is the PySymtable_BuildObject() function. Similar to the top-level AST function we covered earlier, the PySymtable_BuildObject() function switches between the mod_ty possible types (Module, Expression, Interactive, Suite, FunctionType), and visits each of the statements inside them. Remember, mod_ty is an AST instance, so the will now recursively explore the nodes and branches of the tree and add entries to the symtable: struct symtable * PySymtable_BuildObject(mod_ty mod, PyObject *filename, PyFutureFeatures *future) { struct symtable *st = symtable_new(); asdl_seq *seq; int i; PyThreadState *tstate; int recursion_limit = Py_GetRecursionLimit(); ... st->st_top = st->st_cur; switch (mod->kind) { case Module_kind: seq = mod->v.Module.body; for (i = 0; i < asdl_seq_LEN(seq); i++) if (!symtable_visit_stmt(st, (stmt_ty)asdl_seq_GET(seq, i))) goto error; break; case Expression_kind: ... case Interactive_kind: ... case Suite_kind: ... case FunctionType_kind: ... } ... } So for a module, PySymtable_BuildObject() will loop through each statement in the module and call symtable_visit_stmt(). The symtable_visit_stmt() is a huge switch statement with a case for each statement type (defined in Parser/Python.asdl). For each statement type, there is specific logic to that statement type. For example, a function definition has particular logic for: - If the recursion depth is beyond the limit, raise a recursion depth error - The name of the function to be added as a local variable - The default values for sequential arguments to be resolved - The default values for keyword arguments to be resolved - Any annotations for the arguments or the return type are resolved - Any function decorators are resolved - The code block with the contents of the function is visited in symtable_enter_block() - The arguments are visited - The body of the function is visited Note: If you’ve ever wondered why Python’s default arguments are mutable, the reason is in this function. You can see they are a pointer to the variable in the symtable. No extra work is done to copy any values to an immutable type. static int symtable_visit_stmt(struct symtable *st, stmt_ty s) { if (++st->recursion_depth > st->recursion_limit) { // 1. PyErr_SetString(PyExc_RecursionError, "maximum recursion depth exceeded during compilation"); VISIT_QUIT(st, 0); } switch (s->kind) { case FunctionDef_kind: if (!symtable_add_def(st, s->v.FunctionDef.name, DEF_LOCAL)) // 2. VISIT_QUIT(st, 0); if (s->v.FunctionDef.args->defaults) // 3. VISIT_SEQ(st, expr, s->v.FunctionDef.args->defaults); if (s->v.FunctionDef.args->kw_defaults) // 4. VISIT_SEQ_WITH_NULL(st, expr, s->v.FunctionDef.args->kw_defaults); if (!symtable_visit_annotations(st, s, s->v.FunctionDef.args, // 5. s->v.FunctionDef.returns)) VISIT_QUIT(st, 0); if (s->v.FunctionDef.decorator_list) // 6. VISIT_SEQ(st, expr, s->v.FunctionDef.decorator_list); if (!symtable_enter_block(st, s->v.FunctionDef.name, // 7. FunctionBlock, (void *)s, s->lineno, s->col_offset)) VISIT_QUIT(st, 0); VISIT(st, arguments, s->v.FunctionDef.args); // 8. VISIT_SEQ(st, stmt, s->v.FunctionDef.body); // 9. if (!symtable_exit_block(st, s)) VISIT_QUIT(st, 0); break; case ClassDef_kind: { ... } case Return_kind: ... case Delete_kind: ... case Assign_kind: ... case AnnAssign_kind: ... Once the resulting symtable has been created, it is sent back to be used for the compiler. Core Compilation Process# Now that the PyAST_CompileObject() has a compiler state, a symtable, and a module in the form of the AST, the actual compilation can begin. The purpose of the core compiler is to: - Convert the state, symtable, and AST into a Control-Flow-Graph (CFG) - Protect the execution stage from runtime exceptions by catching any logic and code errors and raising them here You can call the CPython compiler in Python code by calling the built-in function compile(). It returns a code object instance: >>> compile('b+1', 'test.py', mode='eval') <code object <module> at 0x10f222780, file "test.py", line 1> The same as with the symtable() function, a simple expression should have a mode of 'eval' and a module, function, or class should have a mode of 'exec'. The compiled code can be found in the co_code property of the code object: >>> co.co_code b'e\x00d\x00\x17\x00S\x00' There is also a dis module in the standard library, which disassembles the bytecode instructions and can print them on the screen or give you a list of Instruction instances. If you import dis and give the dis() function the code object’s co_code property it disassembles it and prints the instructions on the REPL: >>> import dis >>> dis.dis(co.co_code) 0 LOAD_NAME 0 (0) 2 LOAD_CONST 0 (0) 4 BINARY_ADD 6 RETURN_VALUE LOAD_NAME, LOAD_CONST, BINARY_ADD, and RETURN_VALUE are all bytecode instructions. They’re called bytecode because, in binary form, they were a byte long. However, since Python 3.6 the storage format was changed to a word, so now they’re technically wordcode, not bytecode. The full list of bytecode instructions is available for each version of Python, and it does change between versions. For example, in Python 3.7, some new bytecode instructions were introduced to speed up execution of specific method calls. In an earlier section, we explored the instaviz package. This included a visualization of the code object type by running the compiler. It also displays the Bytecode operations inside the code objects. Execute instaviz again to see the code object and bytecode for a function defined on the REPL: >>> import instaviz >>> def example(): a = 1 b = a + 1 return b >>> instaviz.show(example) If we now jump into compiler_mod(), a function used to switch to different compiler functions depending on the module type. We’ll assume that mod is a Module. The module is compiled into the compiler state and then assemble() is run to create a PyCodeObject. The new code object is returned back to PyAST_CompileObject() and sent on for execution: static PyCodeObject * compiler_mod(struct compiler *c, mod_ty mod) { PyCodeObject *co; int addNone = 1; static PyObject *module; ... switch (mod->kind) { case Module_kind: if (!compiler_body(c, mod->v.Module.body)) { compiler_exit_scope(c); return 0; } break; case Interactive_kind: ... case Expression_kind: ... case Suite_kind: ... ... co = assemble(c, addNone); compiler_exit_scope(c); return co; } The compiler_body() function has some optimization flags and then loops over each statement in the module and visits it, similar to how the symtable functions worked: static int compiler_body(struct compiler *c, asdl_seq *stmts) { int i = 0; stmt_ty st; PyObject *docstring; ... for (; i < asdl_seq_LEN(stmts); i++) VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i)); return 1; } The statement type is determined through a call to the asdl_seq_GET() function, which looks at the AST node’s type. Through some smart macros, VISIT calls a function in Python/compile.c for each statement type: #define VISIT(C, TYPE, V) {\ if (!compiler_visit_ ## TYPE((C), (V))) \ return 0; \ } For a stmt (the category for a statement) the compiler will then drop into compiler_visit_stmt() and switch through all of the potential statement types found in Parser/Python.asdl: static int compiler_visit_stmt(struct compiler *c, stmt_ty s) { Py_ssize_t i, n; /* Always assign a lineno to the next instruction for a stmt. */ c->u->u_lineno = s->lineno; c->u->u_col_offset = s->col_offset; c->u->u_lineno_set = 0; switch (s->kind) { case FunctionDef_kind: return compiler_function(c, s, 0); case ClassDef_kind: return compiler_class(c, s); ... case For_kind: return compiler_for(c, s); ... } return 1; } As an example, let’s focus on the For statement, in Python is the: for i in iterable: # block else: # optional if iterable is False # block If the statement is a For type, it calls compiler_for(). There is an equivalent compiler_*() function for all of the statement and expression types. The more straightforward types create the bytecode instructions inline, some of the more complex statement types call other functions. Many of the statements can have sub-statements. A for loop has a body, but you can also have complex expressions in the assignment and the iterator. The compiler’s compiler_ statements sends blocks to the compiler state. These blocks contain instructions, the instruction data structure in Python/compile.c has the opcode, any arguments, and the target block (if this is a jump instruction), it also contains the line number. For jump statements, they can either be absolute or relative jump statements. Jump statements are used to “jump” from one operation to another. Absolute jump statements specify the exact operation number in the compiled code object, whereas relative jump statements specify the jump target relative to another operation: struct instr { unsigned i_jabs : 1; unsigned i_jrel : 1; unsigned char i_opcode; int i_oparg; struct basicblock_ *i_target; /* target block (if jump instruction) */ int i_lineno; }; So a frame block (of type basicblock), contains the following fields: - A b_listpointer, the link to a list of blocks for the compiler state - A list of instructions b_instr, with both the allocated list size b_ialloc, and the number used b_iused - The next block after this one b_next - Whether the block has been “seen” by the assembler when traversing depth-first - If this block has a RETURN_VALUEopcode ( b_return) - The depth of the stack when this block was entered ( b_startdepth) - The instruction offset for the assembler typedef struct basicblock_ { /* Each basicblock in a compilation unit is linked via b_list in the reverse order that the block are allocated. b_list points to the next block, not to be confused with b_next, which is next by control flow. */ struct basicblock_ *b_list; /* number of instructions used */ int b_iused; /* length of instruction array (b_instr) */ int b_ialloc; /* pointer to an array of instructions, initially NULL */ struct instr *b_instr; /* If b_next is non-NULL, it is a pointer to the next block reached by normal control flow. */ struct basicblock_ *b_next; /* b_seen is used to perform a DFS of basicblocks. */ unsigned b_seen : 1; /* b_return is true if a RETURN_VALUE opcode is inserted. */ unsigned b_return : 1; /* depth of stack upon entry of block, computed by stackdepth() */ int b_startdepth; /* instruction offset for block, computed by assemble_jump_offsets() */ int b_offset; } basicblock; The For statement is somewhere in the middle in terms of complexity. There are 15 steps in the compilation of a For statement with the for <target> in <iterator>: syntax: - Create a new code block called start, this allocates memory and creates a basicblockpointer - Create a new code block called cleanup - Create a new code block called end - Push a frame block of type FOR_LOOPto the stack with startas the entry block and endas the exit block - Visit the iterator expression, which adds any operations for the iterator - Add the GET_ITERoperation to the compiler state - Switch to the startblock - Call ADDOP_JRELwhich calls compiler_addop_j()to add the FOR_ITERoperation with an argument of the cleanupblock - Visit the targetand add any special code, like tuple unpacking, to the startblock - Visit each statement in the body of the for loop - Call ADDOP_JABSwhich calls compiler_addop_j()to add the JUMP_ABSOLUTEoperation which indicates after the body is executed, jumps back to the start of the loop - Move to the cleanupblock - Pop the FOR_LOOPframe block off the stack - Visit the statements inside the elsesection of the for loop - Use the endblock Referring back to the basicblock structure. You can see how in the compilation of the for statement, the various blocks are created and pushed into the compiler’s frame block and stack: static int compiler_for(struct compiler *c, stmt_ty s) { basicblock *start, *cleanup, *end; start = compiler_new_block(c); // 1. cleanup = compiler_new_block(c); // 2. end = compiler_new_block(c); // 3. if (start == NULL || end == NULL || cleanup == NULL) return 0; if (!compiler_push_fblock(c, FOR_LOOP, start, end)) // 4. return 0; VISIT(c, expr, s->v.For.iter); // 5. ADDOP(c, GET_ITER); // 6. compiler_use_next_block(c, start); // 7. ADDOP_JREL(c, FOR_ITER, cleanup); // 8. VISIT(c, expr, s->v.For.target); // 9. VISIT_SEQ(c, stmt, s->v.For.body); // 10. ADDOP_JABS(c, JUMP_ABSOLUTE, start); // 11. compiler_use_next_block(c, cleanup); // 12. compiler_pop_fblock(c, FOR_LOOP, start); // 13. VISIT_SEQ(c, stmt, s->v.For.orelse); // 14. compiler_use_next_block(c, end); // 15. return 1; } Depending on the type of operation, there are different arguments required. For example, we used ADDOP_JABS and ADDOP_JREL here, which refer to “ADD Operation with Jump to a RELative position” and “ADD Operation with Jump to an ABSolute position”. This is referring to the APPOP_JREL and ADDOP_JABS macros which call compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute) and set the absolute argument to 0 and 1 respectively. There are some other macros, like ADDOP_I calls compiler_addop_i() which add an operation with an integer argument, or ADDOP_O calls compiler_addop_o() which adds an operation with a PyObject argument. Once these stages have completed, the compiler has a list of frame blocks, each containing a list of instructions and a pointer to the next block. Assembly# With the compiler state, the assembler performs a “depth-first-search” of the blocks and merge the instructions into a single bytecode sequence. The assembler state is declared in Python/compile.c: struct assembler { PyObject *a_bytecode; /* string containing bytecode */ int a_offset; /* offset into bytecode */ int a_nblocks; /* number of reachable blocks */ basicblock **a_postorder; /* list of blocks in dfs postorder */ PyObject *a_lnotab; /* string containing lnotab */ int a_lnotab_off; /* offset into lnotab */ int a_lineno; /* last lineno of emitted instruction */ int a_lineno_off; /* bytecode offset of last lineno */ }; The assemble() function has a few tasks: - Calculate the number of blocks for memory allocation - Ensure that every block that falls off the end returns None, this is why every function returns None, whether or not a returnstatement exists - Resolve any jump statements offsets that were marked as relative - Call dfs()to perform a depth-first-search of the blocks - Emit all the instructions to the compiler - Call makecode()with the compiler state to generate the PyCodeObject static PyCodeObject * assemble(struct compiler *c, int addNone) { basicblock *b, *entryblock; struct assembler a; int i, j, nblocks; PyCodeObject *co = NULL; /* Make sure every block that falls off the end returns None. XXX NEXT_BLOCK() isn't quite right, because if the last block ends with a jump or return b_next shouldn't set. */ if (!c->u->u_curblock->b_return) { NEXT_BLOCK(c); if (addNone) ADDOP_LOAD_CONST(c, Py_None); ADDOP(c, RETURN_VALUE); } ... dfs(c, entryblock, &a, nblocks); /* Can't modify the bytecode after computing jump offsets. */ assemble_jump_offsets(&a, c); /* Emit code in reverse postorder from dfs. */ for (i = a.a_nblocks - 1; i >= 0; i--) { b = a.a_postorder[i]; for (j = 0; j < b->b_iused; j++) if (!assemble_emit(&a, &b->b_instr[j])) goto error; } ... co = makecode(c, &a); error: assemble_free(&a); return co; } The depth-first-search is performed by the dfs() function in Python/compile.c, which follows the the b_next pointers in each of the blocks, marks them as seen by toggling b_seen and then adds them to the assemblers **a_postorder list in reverse order. The function loops back over the assembler’s post-order list and for each block, if it has a jump operation, recursively call dfs() for that jump: static void dfs(struct compiler *c, basicblock *b, struct assembler *a, int end) { int i, j; /* Get rid of recursion for normal control flow. Since the number of blocks is limited, unused space in a_postorder (from a_nblocks to end) can be used as a stack for still not ordered blocks. */ for (j = end; b && !b->b_seen; b = b->b_next) { b->b_seen = 1; assert(a->a_nblocks < j); a->a_postorder[--j] = b; } while (j < end) { b = a->a_postorder[j++]; for (i = 0; i < b->b_iused; i++) { struct instr *instr = &b->b_instr[i]; if (instr->i_jrel || instr->i_jabs) dfs(c, instr->i_target, a, j); } assert(a->a_nblocks < j); a->a_postorder[a->a_nblocks++] = b; } } Creating a Code Object# The task of makecode() is to go through the compiler state, some of the assembler’s properties and to put these into a PyCodeObject by calling PyCode_New(): The variable names, constants are put as properties to the code object: static PyCodeObject * makecode(struct compiler *c, struct assembler *a) { ... consts = consts_dict_keys_inorder(c->u->u_consts); names = dict_keys_inorder(c->u->u_names, 0); varnames = dict_keys_inorder(c->u->u_varnames, 0); ... cellvars = dict_keys_inorder(c->u->u_cellvars, 0); ... freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_GET_SIZE(cellvars)); ... flags = compute_code_flags(c); if (flags < 0) goto error; bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab); ... co = PyCode_NewWithPosOnlyArgs(posonlyargcount+posorkeywordargcount, posonlyargcount, kwonlyargcount, nlocals_int, maxdepth, flags, bytecode, consts, names, varnames, freevars, cellvars, c->c_filename, c->u->u_name, c->u->u_firstlineno, a->a_lnotab); ... return co; } You may also notice that the bytecode is sent to PyCode_Optimize() before it is sent to PyCode_NewWithPosOnlyArgs(). This function is part of the bytecode optimization process in Python/peephole.c. The peephole optimizer goes through the bytecode instructions and in certain scenarios, replace them with other instructions. For example, there is an optimizer called “constant unfolding”, so if you put the following statement into your script: a = 1 + 5 It optimizes that to: a = 6 Because 1 and 5 are constant values, so the result should always be the same. Conclusion# We can pull together all of these stages with the instaviz module: import instaviz def foo(): a = 2**4 b = 1 + 5 c = [1, 4, 6] for i in c: print(i) else: print(a) return c instaviz.show(foo) Will produce an AST graph: With bytecode instructions in sequence: Also, the code object with the variable names, constants, and binary co_code: Execution# In Python/pythonrun.c we broke out just before the call to run_eval_code_obj(). This call takes a code object, either fetched from the marshaled .pyc file, or compiled through the AST and compiler stages. run_eval_code_obj() will pass the globals, locals, PyArena, and compiled PyCodeObject to PyEval_EvalCode() in Python/ceval.c. This stage forms the execution component of CPython. Each of the bytecode operations is taken and executed using a “Stack Frame” based system. What is a Stack Frame? Stack Frames are a data type used by many runtimes, not just Python, that allows functions to be called and variables to be returned between functions. Stack Frames also contain arguments, local variables, and other state information. Typically, a Stack Frame exists for every function call, and they are stacked in sequence. You can see CPython’s frame stack anytime an exception is unhandled and the stack is printed on the screen. PyEval_EvalCode() is the public API for evaluating a code object. The logic for evaluation is split between _PyEval_EvalCodeWithName() and _PyEval_EvalFrameDefault(), which are both in ceval.c. The public API PyEval_EvalCode() will construct an execution frame from the top of the stack by calling _PyEval_EvalCodeWithName(). The construction of the first execution frame has many steps: - Keyword and positional arguments are resolved. - The use of *argsand **kwargsin function definitions are resolved. - Arguments are added as local variables to the scope. - Co-routines and Generators are created, including the Asynchronous Generators. The frame object looks like this: Let’s step through those sequences. 1. Constructing Thread State# Before a frame can be executed, it needs to be referenced from a thread. CPython can have many threads running at any one time within a single interpreter. An Interpreter state includes a list of those threads as a linked list. The thread structure is called PyThreadState, and there are many references throughout ceval.c. Here is the structure of the thread state object: 2. Constructing Frames# The input to PyEval_EvalCode() and therefore _PyEval_EvalCodeWithName() has arguments for: _co: a PyCodeObject globals: a PyDictwith variable names as keys and their values locals: a PyDictwith variable names as keys and their values The other arguments are optional, and not used for the basic API: args: a PyTuplewith positional argument values in order, and argcountfor the number of values kwnames: a list of keyword argument names kwargs: a list of keyword argument values, and kwcountfor the number of them defs: a list of default values for positional arguments, and defcountfor the length kwdefs: a dictionary with the default values for keyword arguments closure: a tuple with strings to merge into the code objects co_freevarsfield name: the name for this evaluation statement as a string qualname: the qualified name for this evaluation statement as a string PyObject * _PyEval_EvalCodeWithName(PyObject *_co, PyObject *globals, PyObject *locals, PyObject *const *args, Py_ssize_t argcount, PyObject *const *kwnames, PyObject *const *kwargs, Py_ssize_t kwcount, int kwstep, PyObject *const *defs, Py_ssize_t defcount, PyObject *kwdefs, PyObject *closure, PyObject *name, PyObject *qualname) { ... PyThreadState *tstate = _PyThreadState_GET(); assert(tstate != NULL); if (globals == NULL) { _PyErr_SetString(tstate, PyExc_SystemError, "PyEval_EvalCodeEx: NULL globals"); return NULL; } /* Create the frame */ f = _PyFrame_New_NoTrack(tstate, co, globals, locals); if (f == NULL) { return NULL; } fastlocals = f->f_localsplus; freevars = f->f_localsplus + co->co_nlocals; 3. Converting Keyword Parameters to a Dictionary# If the function definition contained a **kwargs style catch-all for keyword arguments, then a new dictionary is created, and the values are copied across. The kwargs name is then set as a variable, like in this example: def example(arg, arg2=None, **kwargs): print(kwargs['extra']) # this would resolve to a dictionary key The logic for creating a keyword argument dictionary is in the next part of _PyEval_EvalCodeWithName(): /* Create a dictionary for keyword parameters (**kwargs) */ if (co->co_flags & CO_VARKEYWORDS) { kwdict = PyDict_New(); if (kwdict == NULL) goto fail; i = total_args; if (co->co_flags & CO_VARARGS) { i++; } SETLOCAL(i, kwdict); } else { kwdict = NULL; } The kwdict variable will reference a PyDictObject if any keyword arguments were found. 4. Converting Positional Arguments Into Variables# Next, each of the positional arguments (if provided) are set as local variables: /* Copy all positional arguments into local variables */ if (argcount > co->co_argcount) { n = co->co_argcount; } else { n = argcount; } for (j = 0; j < n; j++) { x = args[j]; Py_INCREF(x); SETLOCAL(j, x); } At the end of the loop, you’ll see a call to SETLOCAL() with the value, so if a positional argument is defined with a value, that is available within this scope: def example(arg1, arg2): print(arg1, arg2) # both args are already local variables. Also, the reference counter for those variables is incremented, so the garbage collector won’t remove them until the frame has evaluated. 5. Packing Positional Arguments Into *args# Similar to **kwargs, a function argument prepended with a * can be set to catch all remaining positional arguments. This argument is a tuple and the *args name is set as a local variable: /* Pack other positional arguments into the *args argument */ if (co->co_flags & CO_VARARGS) { u = _PyTuple_FromArray(args + n, argcount - n); if (u == NULL) { goto fail; } SETLOCAL(total_args, u); } 6. Loading Keyword Arguments# If the function was called with keyword arguments and values, the kwdict dictionary created in step 4 is now filled with any remaining keyword arguments passed by the caller that doesn’t resolve to named arguments or positional arguments. For example, the e argument was neither positional or named, so it is added to **remaining: >>> def my_function(a, b, c=None, d=None, **remaining): print(a, b, c, d, remaining) >>> my_function(a=1, b=2, c=3, d=4, e=5) (1, 2, 3, 4, {'e': 5}) Positional-only arguments is a new feature in Python 3.8. Introduced in PEP570, positional-only arguments are a way of stopping users of your API from using positional arguments with a keyword syntax. For example, this simple function converts Farenheit to Celcius. Note, the use of / as a special argument seperates positional-only arguments from the other arguments. def to_celcius(farenheit, /, options=None): return (farenheit-31)*5/9 All arguments to the left of / must be called only as a positional argument, and arguments to the right can be called as either positional or keyword arguments: >>> to_celcius(110) Calling the function using a keyword argument to a positional-only argument will raise a TypeError: >>> to_celcius(farenheit=110) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: to_celcius() got some positional-only arguments passed as keyword arguments: 'farenheit' The resolution of the keyword argument dictionary values comes after the unpacking of all other arguments. The PEP570 positional-only arguments are shown by starting the keyword-argument loop at co_posonlyargcount. If the / symbol was used on the 3rd argument, the value of co_posonlyargcount would be 2. PyDict_SetItem() is called for each remaining argument to add it to the locals dictionary, so when executing, each of the keyword arguments are scoped local variables: for (i = 0; i < kwcount; i += kwstep) { PyObject **co_varnames; PyObject *keyword = kwnames[i]; PyObject *value = kwargs[i]; ... /* Speed hack: do raw pointer compares. As names are normally interned this should almost always hit. */ co_varnames = ((PyTupleObject *)(co->co_varnames))->ob_item; for (j = co->co_posonlyargcount; j < total_args; j++) { PyObject *name = co_varnames[j]; if (name == keyword) { goto kw_found; } } if (kwdict == NULL) { if (co->co_posonlyargcount && positional_only_passed_as_keyword(tstate, co, kwcount, kwnames)) { goto fail; } _PyErr_Format(tstate, PyExc_TypeError, "%U() got an unexpected keyword argument '%S'", co->co_name, keyword); goto fail; } if (PyDict_SetItem(kwdict, keyword, value) == -1) { goto fail; } continue; kw_found: ... Py_INCREF(value); SETLOCAL(j, value); } ... At the end of the loop, you’ll see a call to SETLOCAL() with the value. If a keyword argument is defined with a value, that is available within this scope: def example(arg1, arg2, example_kwarg=None): print(example_kwarg) # example_kwarg is already a local variable. 7. Adding Missing Positional Arguments# Any positional arguments provided to a function call that are not in the list of positional arguments are added to a *args tuple if this tuple does not exist, a failure is raised: /* Add missing positional arguments (copy default values from defs) */ if (argcount < co->co_argcount) { Py_ssize_t m = co->co_argcount - defcount; Py_ssize_t missing = 0; for (i = argcount; i < m; i++) { if (GETLOCAL(i) == NULL) { missing++; } } if (missing) { missing_arguments(co, missing, defcount, fastlocals); goto fail; } if (n > m) i = n - m; else i = 0; for (; i < defcount; i++) { if (GETLOCAL(m+i) == NULL) { PyObject *def = defs[i]; Py_INCREF(def); SETLOCAL(m+i, def); } } } 8. Adding Missing Keyword Arguments# Any keyword arguments provided to a function call that are not in the list of named keyword arguments are added to a **kwargs dictionary if this dictionary does not exist, a failure is raised: /* Add missing keyword arguments (copy default values from kwdefs) */ if (co->co_kwonlyargcount > 0) { Py_ssize_t missing = 0; for (i = co->co_argcount; i < total_args; i++) { PyObject *name; if (GETLOCAL(i) != NULL) continue; name = PyTuple_GET_ITEM(co->co_varnames, i); if (kwdefs != NULL) { PyObject *def = PyDict_GetItemWithError(kwdefs, name); ... } missing++; } ... } 9. Collapsing Closures# Any closure names are added to the code object’s list of free variable names: /* Copy closure variables to free variables */ for (i = 0; i < PyTuple_GET_SIZE(co->co_freevars); ++i) { PyObject *o = PyTuple_GET_ITEM(closure, i); Py_INCREF(o); freevars[PyTuple_GET_SIZE(co->co_cellvars) + i] = o; } 10. Creating Generators, Coroutines, and Asynchronous Generators# If the evaluated code object has a flag that it is a generator, coroutine or async generator, then a new frame is created using one of the unique methods in the Generator, Coroutine or Async libraries and the current frame is added as a property. The new frame is then returned, and the original frame is not evaluated. The frame is only evaluated when the generator/coroutine/async method is called on to execute its target: /* Handle generator/coroutine/asynchronous generator */ if (co->co_flags & (CO_GENERATOR | CO_COROUTINE | CO_ASYNC_GENERATOR)) { ... /*; } Lastly, PyEval_EvalFrameEx() is called with the new frame: retval = PyEval_EvalFrameEx(f,0); ... } Frame Execution# As covered earlier in the compiler and AST chapters, the code object contains a binary encoding of the bytecode to be executed. It also contains a list of variables and a symbol table. The local and global variables are determined at runtime based on how that function, module, or block was called. This information is added to the frame by the _PyEval_EvalCodeWithName() function. There are other usages of frames, like the coroutine decorator, which dynamically generates a frame with the target as a variable. The public API, PyEval_EvalFrameEx() calls the interpreter’s configured frame evaluation function in the eval_frame property. Frame evaluation was made pluggable in Python 3.7 with PEP 523. _PyEval_EvalFrameDefault() is the default function, and it is unusual to use anything other than this. Frames are executed in the main execution loop inside _PyEval_EvalFrameDefault(). This function is central function that brings everything together and brings your code to life. It contains decades of optimization since even a single line of code can have a significant impact on performance for the whole of CPython. Everything that gets executed in CPython goes through this function. Note: Something you might notice when reading ceval.c, is how many times C macros have been used. C Macros are a way of having DRY-compliant code without the overhead of making function calls. The compiler converts the macros into C code and then compile the generated code. If you want to see the expanded code, you can run gcc -E on Linux and macOS: $ gcc -E Python/ceval.c Alternatively, Visual Studio Code can do inline macro expansion once you have installed the official C/C++ extension: We can step through frame execution in Python 3.7 and beyond by enabling the tracing attribute on the current thread. This code example sets the global tracing function to a function called trace() that gets the stack from the current frame, prints the disassembled opcodes to the screen, and some extra information for debugging: import sys import dis import traceback import io def trace(frame, event, args): frame.f_trace_opcodes = True stack = traceback.extract_stack(frame) pad = " "*len(stack) + "|" if event == 'opcode': with io.StringIO() as out: dis.disco(frame.f_code, frame.f_lasti, file=out) lines = out.getvalue().split('\n') [print(f"{pad}{l}") for l in lines] elif event == 'call': print(f"{pad}Calling {frame.f_code}") elif event == 'return': print(f"{pad}Returning {args}") elif event == 'line': print(f"{pad}Changing line to {frame.f_lineno}") else: print(f"{pad}{frame} ({event} - {args})") print(f"{pad}----------------------------------") return trace sys.settrace(trace) # Run some code for a demo eval('"-".join([letter for letter in "hello"])') This prints the code within each stack and point to the next operation before it is executed. When a frame returns a value, the return statement is printed: The full list of instructions is available on the dis module documentation. The Value Stack# Inside the core evaluation loop, a value stack is created. This stack is a list of pointers to sequential PyObject instances. One way to think of the value stack is like a wooden peg on which you can stack cylinders. You would only add or remove one item at a time. This is done using the PUSH(a) macro, where a is a pointer to a PyObject. For example, if you created a PyLong with the value 10 and pushed it onto the value stack: PyObject *a = PyLong_FromLong(10); PUSH(a); This action would have the following effect: In the next operation, to fetch that value, you would use the POP() macro to take the top value from the stack: PyObject *a = POP(); // a is PyLongObject with a value of 10 This action would return the top value and end up with an empty value stack: If you were to add 2 values to the stack: PyObject *a = PyLong_FromLong(10); PyObject *b = PyLong_FromLong(20); PUSH(a); PUSH(b); They would end up in the order in which they were added, so a would be pushed to the second position in the stack: If you were to fetch the top value in the stack, you would get a pointer to b because it is at the top: If you need to fetch the pointer to the top value in the stack without popping it, you can use the PEEK(v) operation, where v is the stack position: PyObject *first = PEEK(0); 0 represents the top of the stack, 1 would be the second position: To clone the value at the top of the stack, the DUP_TWO() macro can be used, or by using the DUP_TWO opcode: DUP_TOP(); This action would copy the value at the top to form 2 pointers to the same object: There is a rotation macro ROT_TWO that swaps the first and second values: Each of the opcodes have a predefined “stack effect,” calculated by the stack_effect() function inside Python/compile.c. This function returns the delta in the number of values inside the stack for each opcode. Example: Adding an Item to a List# In Python, when you create a list, the .append() method is available on the list object: my_list = [] my_list.append(obj) Where obj is an object, you want to append to the end of the list. There are 2 operations involved in this operation. LOAD_FAST, to load the object obj to the top of the value stack from the list of locals in the frame, and LIST_APPEND to add the object. First exploring LOAD_FAST, there are 5 steps: The pointer to objis loaded from GETLOCAL(), where the variable to load is the operation argument. The list of variable pointers is stored in fastlocals, which is a copy of the PyFrame attribute f_localsplus. The operation argument is a number, pointing to the index in the fastlocalsarray pointer. This means that the loading of a local is simply a copy of the pointer instead of having to look up the variable name. If variable no longer exists, an unbound local variable error is raised. The reference counter for value(in our case, obj) is increased by 1. The pointer to objis pushed to the top of the value stack. The FAST_DISPATCHmacro is called, if tracing is enabled, the loop goes over again (with all the tracing), if tracing is not enabled, a gotois called to fast_next_opcode, which jumps back to the top of the loop for the next instruction. ... case TARGET(LOAD_FAST): { PyObject *value = GETLOCAL(oparg); // 1. if (value == NULL) { format_exc_check_arg( PyExc_UnboundLocalError, UNBOUNDLOCAL_ERROR_MSG, PyTuple_GetItem(co->co_varnames, oparg)); goto error; // 2. } Py_INCREF(value); // 3. PUSH(value); // 4. FAST_DISPATCH(); // 5. } ... Now the pointer to obj is at the top of the value stack. The next instruction LIST_APPEND is run. Many of the bytecode operations are referencing the base types, like PyUnicode, PyNumber. For example, LIST_APPEND appends an object to the end of a list. To achieve this, it pops the pointer from the value stack and returns the pointer to the last object in the stack. The macro is a shortcut for: PyObject *v = (*--stack_pointer); Now the pointer to obj is stored as v. The list pointer is loaded from PEEK(oparg). Then the C API for Python lists is called for list and v. The code for this is inside Objects/listobject.c, which we go into in the next chapter. A call to PREDICT is made, which guesses that the next operation will be JUMP_ABSOLUTE. The PREDICT macro has compiler-generated goto statements for each of the potential operations’ case statements. This means the CPU can jump to that instruction and not have to go through the loop again: ... case TARGET(LIST_APPEND): { PyObject *v = POP(); PyObject *list = PEEK(oparg); int err; err = PyList_Append(list, v); Py_DECREF(v); if (err != 0) goto error; PREDICT(JUMP_ABSOLUTE); DISPATCH(); } ... Opcode predictions: Some opcodes tend to come in pairs thus making it possible to predict the second code when the first is run. For example, COMPARE_OP is often followed by POP_JUMP_IF_FALSE or POP_JUMP_IF_TRUE. “Verifying the prediction costs a single high-speed test of a register variable against a constant. If the pairing was good, then the processor’s own internal branch predication has a high likelihood of success, resulting in a nearly zero-overhead transition to the next opcode. A successful prediction saves a trip through the eval-loop including its unpredictable switch-case branch. Combined with the processor’s internal branch prediction, a successful PREDICT has the effect of making the two opcodes run as if they were a single new opcode with the bodies combined.” If collecting opcode statistics, you have two choices: - Keep the predictions turned-on and interpret the results as if some opcodes had been combined - Turn off predictions so that the opcode frequency counter updates for both opcodes Opcode prediction is disabled with threaded code since the latter allows the CPU to record separate branch prediction information for each opcode. Some of the operations, such as CALL_FUNCTION, CALL_METHOD, have an operation argument referencing another compiled function. In these cases, another frame is pushed to the frame stack in the thread, and the evaluation loop is run for that function until the function completes. Each time a new frame is created and pushed onto the stack, the value of the frame’s f_back is set to the current frame before the new one is created. This nesting of frames is clear when you see a stack trace, take this example script: def function2(): raise RuntimeError def function1(): function2() if __name__ == '__main__': function1() Calling this on the command line will give you: $ ./python.exe example_stack.py Traceback (most recent call last): File "example_stack.py", line 8, in <module> function1() File "example_stack.py", line 5, in function1 function2() File "example_stack.py", line 2, in function2 raise RuntimeError RuntimeError In traceback.py, the walk_stack() function used to print trace backs: def walk_stack(f): """Walk a stack yielding the frame and line number for each frame. This will follow f.f_back from the given frame. If no frame is given, the current stack is used. Usually used with StackSummary.extract. """ if f is None: f = sys._getframe().f_back.f_back while f is not None: yield f, f.f_lineno f = f.f_back Here you can see that the current frame, fetched by calling sys._getframe() and the parent’s parent is set as the frame, because you don’t want to see the call to walk_stack() or print_trace() in the trace back, so those function frames are skipped. Then the f_back pointer is followed to the top. sys._getframe() is the Python API to get the frame attribute of the current thread. Here is how that frame stack would look visually, with 3 frames each with its code object and a thread state pointing to the current frame: Conclusion# In this Part, you explored the most complex element of CPython: the compiler. The original author of Python, Guido van Rossum, made the statement that CPython’s compiler should be “dumb” so that people can understand it. By breaking down the compilation process into small, logical steps, it is far easier to understand. In the next chapter, we connect the compilation process with the basis of all Python code, the object. Part 4: Objects in CPython# CPython comes with a collection of basic types like strings, lists, tuples, dictionaries, and objects. All of these types are built-in. You don’t need to import any libraries, even from the standard library. Also, the instantiation of these built-in types has some handy shortcuts. For example, to create a new list, you can call: lst = list() Or, you can use square brackets: lst = [] Strings can be instantiated from a string-literal by using either double or single quotes. We explored the grammar definitions earlier that cause the compiler to interpret double quotes as a string literal. All types in Python inherit from object, a built-in base type. Even strings, tuples, and list inherit from object. During the walk-through of the C code, you have read lots of references to PyObject*, the C-API structure for an object. Because C is not object-oriented like Python, objects in C don’t inherit from one another. PyObject is the data structure for the beginning of the Python object’s memory. Much of the base object API is declared in Objects/object.c, like the function PyObject_Repr, which the built-in repr() function. You will also find PyObject_Hash() and other APIs. All of these functions can be overridden in a custom object by implementing “dunder” methods on a Python object: class MyObject(object): def __init__(self, id, name): self.id = id self.name = name def __repr__(self): return "<{0} id={1}>".format(self.name, self.id) This code is implemented in PyObject_Repr(), inside Objects/object.c. The type of the target object, v will be inferred through a call to Py_TYPE() and if the tp_repr field is set, then the function pointer is called. If the tp_repr field is not set, i.e. the object doesn’t declare a custom __repr__ method, then the default behavior is run, which is to return "<%s object at %p>" with the type name and the ID: PyObject * PyObject_Repr(PyObject *v) { PyObject *res; if (PyErr_CheckSignals()) return NULL; ... if (v == NULL) return PyUnicode_FromString("<NULL>"); if (Py_TYPE(v)->tp_repr == NULL) return PyUnicode_FromFormat("<%s object at %p>", v->ob_type->tp_name, v); ... } The ob_type field for a given PyObject* will point to the data structure PyTypeObject, defined in Include/cpython/object.h. This data-structure lists all the built-in functions, as fields and the arguments they should receive. Take tp_repr as an example: typedef struct _typeobject { PyObject_VAR_HEAD const char *tp_name; /* For printing, in format "<module>.<name>" */ Py_ssize_t tp_basicsize, tp_itemsize; /* For allocation */ /* Methods to implement standard operations */ ... reprfunc tp_repr; Where reprfunc is a typedef for PyObject *(*reprfunc)(PyObject *);, a function that takes 1 pointer to PyObject ( self). Some of the dunder APIs are optional, because they only apply to certain types, like numbers: /* Method suites for standard classes */ PyNumberMethods *tp_as_number; PySequenceMethods *tp_as_sequence; PyMappingMethods *tp_as_mapping; A sequence, like a list would implement the following methods: typedef struct { lenfunc sq_length; // len(v) binaryfunc sq_concat; // v + x ssizeargfunc sq_repeat; // for x in v ssizeargfunc sq_item; // v[x] void *was_sq_slice; // v[x:y:z] ssizeobjargproc sq_ass_item; // v[x] = z void *was_sq_ass_slice; // v[x:y] = z objobjproc sq_contains; // x in v binaryfunc sq_inplace_concat; ssizeargfunc sq_inplace_repeat; } PySequenceMethods; All of these built-in functions are called the Python Data Model. One of the great resources for the Python Data Model is “Fluent Python” by Luciano Ramalho. Base Object Type# In Objects/object.c, the base implementation of object type is written as pure C code. There are some concrete implementations of basic logic, like shallow comparisons. Not all methods in a Python object are part of the Data Model, so that a Python object can contain attributes (either class or instance attributes) and methods. A simple way to think of a Python object is consisting of 2 things: - The core data model, with pointers to compiled functions - A dictionary with any custom attributes and methods The core data model is defined in the PyTypeObject, and the functions are defined in: Objects/object.cfor the built-in methods Objects/boolobject.cfor the booltype Objects/bytearrayobject.cfor the byte[]type Objects/bytesobjects.cfor the bytestype Objects/cellobject.cfor the celltype Objects/classobject.cfor the abstract classtype, used in meta-programming Objects/codeobject.cused for the built-in codeobject type Objects/complexobject.cfor a complex numeric type Objects/iterobject.cfor an iterator Objects/listobject.cfor the listtype Objects/longobject.cfor the longnumeric type Objects/memoryobject.cfor the base memory type Objects/methodobject.cfor the class method type Objects/moduleobject.cfor a module type Objects/namespaceobject.cfor a namespace type Objects/odictobject.cfor an ordered dictionary type Objects/rangeobject.cfor a range generator Objects/setobject.cfor a settype Objects/sliceobject.cfor a slice reference type Objects/structseq.cfor a struct.Structtype Objects/tupleobject.cfor a tupletype Objects/typeobject.cfor a typetype Objects/unicodeobject.cfor a strtype Objects/weakrefobject.cfor a weakrefobject We’re going to dive into 3 of these types: - Booleans - Integers - Generators Booleans and Integers have a lot in common, so we’ll cover those first. The Bool and Long Integer Type# The bool type is the most straightforward implementation of the built-in types. It inherits from long and has the predefined constants, Py_True and Py_False. These constants are immutable instances, created on the instantiation of the Python interpreter. Inside Objects/boolobject.c, you can see the helper function to create a bool instance from a number: PyObject *PyBool_FromLong(long ok) { PyObject *result; if (ok) result = Py_True; else result = Py_False; Py_INCREF(result); return result; } This function uses the C evaluation of a numeric type to assign Py_True or Py_False to a result and increment the reference counters. The numeric functions for and, xor, and or are implemented, but addition, subtraction, and division are dereferenced from the base long type since it would make no sense to divide two boolean values. The implementation of and for a bool value checks if a and b are booleans, then check their references to Py_True, otherwise, are cast as numbers, and the and operation is run on the two numbers: static PyObject * bool_and(PyObject *a, PyObject *b) { if (!PyBool_Check(a) || !PyBool_Check(b)) return PyLong_Type.tp_as_number->nb_and(a, b); return PyBool_FromLong((a == Py_True) & (b == Py_True)); } The long type is a bit more complex, as the memory requirements are expansive. In the transition from Python 2 to 3, CPython dropped support for the int type and instead used the long type as the primary integer type. Python’s long type is quite special in that it can store a variable-length number. The maximum length is set in the compiled binary. The data structure of a Python long consists of the PyObject header and a list of digits. The list of digits, ob_digit is initially set to have one digit, but it later expanded to a longer length when initialized: struct _longobject { PyObject_VAR_HEAD digit ob_digit[1]; }; Memory is allocated to a new long through _PyLong_New(). This function takes a fixed length and makes sure it is smaller than MAX_LONG_DIGITS. Then it reallocates the memory for ob_digit to match the length. To convert a C long type to a Python long type, the long is converted to a list of digits, the memory for the Python long is assigned, and then each of the digits is set. Because long is initialized with ob_digit already being at a length of 1, if the number is less than 10, then the value is set without the memory being allocated: PyObject * PyLong_FromLong(long ival) { PyLongObject *v; unsigned long abs_ival; unsigned long t; /* unsigned so >> doesn't propagate sign bit */ int ndigits = 0; int sign; CHECK_SMALL_INT(ival); ... /* Fast path for single-digit ints */ if (!(abs_ival >> PyLong_SHIFT)) { v = _PyLong_New(1); if (v) { Py_SIZE(v) = sign; v->ob_digit[0] = Py_SAFE_DOWNCAST( abs_ival, unsigned long, digit); } return (PyObject*)v; } ... /* Larger numbers: loop to determine number of digits */ t = abs_ival; while (t) { ++ndigits; t >>= PyLong_SHIFT; } v = _PyLong_New(ndigits); if (v != NULL) { digit *p = v->ob_digit; Py_SIZE(v) = ndigits*sign; t = abs_ival; while (t) { *p++ = Py_SAFE_DOWNCAST( t & PyLong_MASK, unsigned long, digit); t >>= PyLong_SHIFT; } } return (PyObject *)v; } To convert a double-point floating point to a Python long, PyLong_FromDouble() does the math for you: PyObject * PyLong_FromDouble(double dval) { PyLongObject *v; double frac; int i, ndig, expo, neg; neg = 0; if (Py_IS_INFINITY(dval)) { PyErr_SetString(PyExc_OverflowError, "cannot convert float infinity to integer"); return NULL; } if (Py_IS_NAN(dval)) { PyErr_SetString(PyExc_ValueError, "cannot convert float NaN to integer"); return NULL; } if (dval < 0.0) { neg = 1; dval = -dval; } frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */ if (expo <= 0) return PyLong_FromLong(0L); ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */ v = _PyLong_New(ndig); if (v == NULL) return NULL; frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1); for (i = ndig; --i >= 0; ) { digit bits = (digit)frac; v->ob_digit[i] = bits; frac = frac - (double)bits; frac = ldexp(frac, PyLong_SHIFT); } if (neg) Py_SIZE(v) = -(Py_SIZE(v)); return (PyObject *)v; } The remainder of the implementation functions in longobject.c have utilities, such as converting a Unicode string into a number with PyLong_FromUnicodeObject(). A Review of the Generator Type# Python Generators are functions which return a yield statement and can be called continually to generate further values. Commonly they are used as a more memory efficient way of looping through values in a large block of data, like a file, a database or over a network. Generator objects are returned in place of a value when yield is used instead of return. The generator object is created from the yield statement and returned to the caller. Let’s create a simple generator with a list of 4 constant values: >>> def example(): ... lst = [1,2,3,4] ... for i in lst: ... yield i ... >>> gen = example() >>> gen <generator object example at 0x100bcc480> If you explore the contents of the generator object, you can see some of the fields starting with gi_: >>> dir(gen) [ ... 'close', 'gi_code', 'gi_frame', 'gi_running', 'gi_yieldfrom', 'send', 'throw'] The PyGenObject type is defined in Include/genobject.h and there are 3 flavors: - Generator objects - Coroutine objects - Async generator objects All 3 share the same subset of fields used in generators, and have similar behaviors: Focusing first on generators, you can see the fields: gi_framelinking to a PyFrameObjectfor the generator, earlier in the execution chapter, we explored the use of locals and globals inside a frame’s value stack. This is how generators remember the last value of local variables since the frame is persistent between calls gi_runningset to 0 or 1 if the generator is currently running gi_codelinking to a PyCodeObjectwith the compiled function that yielded the generator so that it can be called again gi_weakreflistlinking to a list of weak references to objects inside the generator function gi_nameas the name of the generator gi_qualnameas the qualified name of the generator gi_exc_stateas a tuple of exception data if the generator call raises an exception The coroutine and async generators have the same fields but prepended with cr and ag respectively. If you call __next__() on the generator object, the next value is yielded until eventually a StopIteration is raised: >>> gen.__next__() 1 >>> gen.__next__() 2 >>> gen.__next__() 3 >>> gen.__next__() 4 >>> gen.__next__() Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration Each time __next__() is called, the code object inside the generators gi_code field is executed as a new frame and the return value is pushed to the value stack. You can also see that gi_code is the compiled code object for the generator function by importing the dis module and disassembling the bytecode inside: >>> gen = example() >>> import dis >>> dis.disco(gen.gi_code) 2 0 LOAD_CONST 1 (1) 2 LOAD_CONST 2 (2) 4 LOAD_CONST 3 (3) 6 LOAD_CONST 4 (4) 8 BUILD_LIST 4 10 STORE_FAST 0 (l) 3 12 SETUP_LOOP 18 (to 32) 14 LOAD_FAST 0 (l) 16 GET_ITER >> 18 FOR_ITER 10 (to 30) 20 STORE_FAST 1 (i) 4 22 LOAD_FAST 1 (i) 24 YIELD_VALUE 26 POP_TOP 28 JUMP_ABSOLUTE 18 >> 30 POP_BLOCK >> 32 LOAD_CONST 0 (None) 34 RETURN_VALUE Whenever __next__() is called on a generator object, gen_iternext() is called with the generator instance, which immediately calls gen_send_ex() inside Objects/genobject.c. gen_send_ex() is the function that converts a generator object into the next yielded result. You’ll see many similarities with the way frames are constructed in Python/ceval.c from a code object as these functions have similar tasks. The gen_send_ex() function is shared with generators, coroutines, and async generators and has the following steps: The current thread state is fetched The frame object from the generator object is fetched If the generator is running when __next__()was called, raise a ValueError If the frame inside the generator is at the top of the stack: - In the case of a coroutine, if the coroutine is not already marked as closing, a RuntimeErroris raised - If this is an async generator, raise a StopAsyncIteration - For a standard generator, a StopIterationis raised. If the last instruction in the frame ( f->f_lasti) is still -1 because it has just been started, and this is a coroutine or async generator, then a non-None value can’t be passed as an argument, so an exception is raised Else, this is the first time it’s being called, and arguments are allowed. The value of the argument is pushed to the frame’s value stack The f_backfield of the frame is the caller to which return values are sent, so this is set to the current frame in the thread. This means that the return value is sent to the caller, not the creator of the generator The generator is marked as running The last exception in the generator’s exception info is copied from the last exception in the thread state The thread state exception info is set to the address of the generator’s exception info. This means that if the caller enters a breakpoint around the execution of a generator, the stack trace goes through the generator and the offending code is clear The frame inside the generator is executed within the Python/ceval.cmain execution loop, and the value returned The thread state last exception is reset to the value before the frame was called The generator is marked as not running The following cases then match the return value and any exceptions thrown by the call to the generator. Remember that generators should raise a StopIterationwhen they are exhausted, either manually, or by not yielding a value. Coroutines and async generators should not: - If no result was returned from the frame, raise a StopIterationfor generators and StopAsyncIterationfor async generators - If a StopIterationwas explicitly raised, but this is a coroutine or an async generator, raise a RuntimeErroras this is not allowed - If a StopAsyncIterationwas explicitly raised and this is an async generator, raise a RuntimeError, as this is not allowed Lastly, the result is returned back to the caller of static PyObject * gen_send_ex(PyGenObject *gen, PyObject *arg, int exc, int closing) { PyThreadState *tstate = _PyThreadState_GET(); // 1. PyFrameObject *f = gen->gi_frame; // 2. PyObject *result; if (gen->gi_running) { // 3. const char *msg = "generator already executing"; if (PyCoro_CheckExact(gen)) { msg = "coroutine already executing"; } else if (PyAsyncGen_CheckExact(gen)) { msg = "async generator already executing"; } PyErr_SetString(PyExc_ValueError, msg); return NULL; } if (f == NULL || f->f_stacktop == NULL) { // 4. if (PyCoro_CheckExact(gen) && !closing) { /* `gen` is an exhausted coroutine: raise an error, except when called from gen_close(), which should always be a silent method. */ PyErr_SetString( PyExc_RuntimeError, "cannot reuse already awaited coroutine"); // 4a. } else if (arg && !exc) { /* `gen` is an exhausted generator: only set exception if called from send(). */ if (PyAsyncGen_CheckExact(gen)) { PyErr_SetNone(PyExc_StopAsyncIteration); // 4b. } else { PyErr_SetNone(PyExc_StopIteration); // 4c. } } return NULL; } if (f->f_lasti == -1) { if (arg && arg != Py_None) { // 5. const char *msg = "can't send non-None value to a " "just-started generator"; if (PyCoro_CheckExact(gen)) { msg = NON_INIT_CORO_MSG; } else if (PyAsyncGen_CheckExact(gen)) { msg = "can't send non-None value to a " "just-started async generator"; } PyErr_SetString(PyExc_TypeError, msg); return NULL; } } else { // 6. /* Push arg onto the frame's value stack */ result = arg ? arg : Py_None; Py_INCREF(result); *(f->f_stacktop++) = result; } /* Generators always return to their most recent caller, not * necessarily their creator. */ Py_XINCREF(tstate->frame); assert(f->f_back == NULL); f->f_back = tstate->frame; // 7. gen->gi_running = 1; // 8. gen->gi_exc_state.previous_item = tstate->exc_info; // 9. tstate->exc_info = &gen->gi_exc_state; // 10. result = PyEval_EvalFrameEx(f, exc); // 11. tstate->exc_info = gen->gi_exc_state.previous_item; // 12. gen->gi_exc_state.previous_item = NULL; gen->gi_running = 0; // 13. /* Don't keep the reference to f_back any longer than necessary. It * may keep a chain of frames alive or it could create a reference * cycle. */ assert(f->f_back == tstate->frame); Py_CLEAR(f->f_back); /* If the generator just returned (as opposed to yielding), signal * that the generator is exhausted. */ if (result && f->f_stacktop == NULL) { // 14a. if (result == Py_None) { /* Delay exception instantiation if we can */ if (PyAsyncGen_CheckExact(gen)) { PyErr_SetNone(PyExc_StopAsyncIteration); } else { PyErr_SetNone(PyExc_StopIteration); } } else { /* Async generators cannot return anything but None */ assert(!PyAsyncGen_CheckExact(gen)); _PyGen_SetStopIterationValue(result); } Py_CLEAR(result); } else if (!result && PyErr_ExceptionMatches(PyExc_StopIteration)) { // 14b. const char *msg = "generator raised StopIteration"; if (PyCoro_CheckExact(gen)) { msg = "coroutine raised StopIteration"; } else if PyAsyncGen_CheckExact(gen) { msg = "async generator raised StopIteration"; } _PyErr_FormatFromCause(PyExc_RuntimeError, "%s", msg); } else if (!result && PyAsyncGen_CheckExact(gen) && PyErr_ExceptionMatches(PyExc_StopAsyncIteration)) // 14c. { /* code in `gen` raised a StopAsyncIteration error: raise a RuntimeError. */ const char *msg = "async generator raised StopAsyncIteration"; _PyErr_FormatFromCause(PyExc_RuntimeError, "%s", msg); } ... return result; // 15. } Going back to the evaluation of code objects whenever a function or module is called, there was a special case for generators, coroutines, and async generators in _PyEval_EvalCodeWithName(). This function checks for the CO_GENERATOR, CO_COROUTINE, and CO_ASYNC_GENERATOR flags on the code object. When a new coroutine is created using PyCoro_New(), a new async generator is created with PyAsyncGen_New() or a generator with PyGen_NewWithQualName(). These objects are returned early instead of returning an evaluated frame, which is why you get a generator object after calling a function with a yield statement: PyObject * _PyEval_EvalCodeWithName(PyObject *_co, PyObject *globals, PyObject *locals, ... ... /* Handle generator/coroutine/asynchronous generator */ if (co->co_flags & (CO_GENERATOR | CO_COROUTINE | CO_ASYNC_GENERATOR)) { PyObject *gen; PyObject *coro_wrapper = tstate->coroutine_wrapper; int is_coro = co->co_flags & CO_COROUTINE; ... /*; } ... The flags in the code object were injected by the compiler after traversing the AST and seeing the yield or yield from statements or seeing the coroutine decorator. PyGen_NewWithQualName() will call gen_new_with_qualname() with the generated frame and then create the PyGenObject with NULL values and the compiled code object: static PyObject * gen_new_with_qualname(PyTypeObject *type, PyFrameObject *f, PyObject *name, PyObject *qualname) { PyGenObject *gen = PyObject_GC_New(PyGenObject, type); if (gen == NULL) { Py_DECREF(f); return NULL; } gen->gi_frame = f; f->f_gen = (PyObject *) gen; Py_INCREF(f->f_code); gen->gi_code = (PyObject *)(f->f_code); gen->gi_running = 0; gen->gi_weakreflist = NULL; gen->gi_exc_state.exc_type = NULL; gen->gi_exc_state.exc_value = NULL; gen->gi_exc_state.exc_traceback = NULL; gen->gi_exc_state.previous_item = NULL; if (name != NULL) gen->gi_name = name; else gen->gi_name = ((PyCodeObject *)gen->gi_code)->co_name; Py_INCREF(gen->gi_name); if (qualname != NULL) gen->gi_qualname = qualname; else gen->gi_qualname = gen->gi_name; Py_INCREF(gen->gi_qualname); _PyObject_GC_TRACK(gen); return (PyObject *)gen; } Bringing this all together you can see how the generator expression is a powerful syntax where a single keyword, yield triggers a whole flow to create a unique object, copy a compiled code object as a property, set a frame, and store a list of variables in the local scope. To the user of the generator expression, this all seems like magic, but under the covers it’s not that complex. Conclusion# Now that you understand how some built-in types, you can explore other types. When exploring Python classes, it is important to remember there are built-in types, written in C and classes inheriting from those types, written in Python or C. Some libraries have types written in C instead of inheriting from the built-in types. One example is numpy, a library for numeric arrays. The nparray type is written in C, is highly efficient and performant. In the next Part, we will explore the classes and functions defined in the standard library. Part 5: The CPython Standard Library# Python has always come “batteries included.” This statement means that with a standard CPython distribution, there are libraries for working with files, threads, networks, web sites, music, keyboards, screens, text, and a whole manner of utilities. Some of the batteries that come with CPython are more like AA batteries. They’re useful for everything, like the collections module and the sys module. Some of them are a bit more obscure, like a small watch battery that you never know when it might come in useful. There are 2 types of modules in the CPython standard library: - Those written in pure Python that provides a utility - Those written in C with Python wrappers We will explore both types. Python Modules# The modules written in pure Python are all located in the Lib/ directory in the source code. Some of the larger modules have submodules in subfolders, like the An easy module to look at would be the colorsys module. It’s only a few hundred lines of Python code. You may not have come across it before. The colorsys module has some utility functions for converting color scales. When you install a Python distribution from source, standard library modules are copied from the Lib folder into the distribution folder. This folder is always part of your path when you start Python, so you can import the modules without having to worry about where they’re located. For example: >>> import colorsys >>> colorsys <module 'colorsys' from '/usr/shared/lib/python3.7/colorsys.py'> >>> colorsys.rgb_to_hls(255,0,0) (0.0, 127.5, -1.007905138339921) We can see the source code of rgb_to_hls() inside Lib/colorsys.py: # HLS: Hue, Luminance, Saturation # H: position in the spectrum # L: color lightness # S: color saturation def rgb_to_hls(r, g, b): maxc = max(r, g, b) minc = min(r, g, b) # XXX Can optimize (maxc+minc) and (maxc-minc) l = (minc+maxc)/2.0 if minc == maxc: return 0.0, l, 0.0 if l <= 0.5: s = (maxc-minc) / (maxc+minc) else: s = (maxc-minc) / (2.0-maxc-min, l, s There’s nothing special about this function, it’s just standard Python. You’ll find similar things with all of the pure Python standard library modules. They’re just written in plain Python, well laid out and easy to understand. You may even spot improvements or bugs, so you can make changes to them and contribute it to the Python distribution. We’ll cover that toward the end of this article. Python and C Modules# The remainder of modules are written in C, or a combination or Python and C. The source code for these is in Lib/ for the Python component, and Modules/ for the C component. There are two exceptions to this rule, the sys module, found in Python/sysmodule.c and the __builtins__ module, found in Python/bltinmodule.c. Python will import * from __builtins__ when an interpreter is instantiated, so all of the functions like print(), chr(), format(), etc. are found within Python/bltinmodule.c. Because the sys module is so specific to the interpreter and the internals of CPython, that is found inside the Python directly. It is also marked as an “implementation detail” of CPython and not found in other distributions. The built-in print() function was probably the first thing you learned to do in Python. So what happens when you type print("hello world!")? - The argument "hello world"was converted from a string constant to a PyUnicodeObjectby the compiler builtin_print()was executed with 1 argument, and NULL kwnames - The filevariable is set to PyId_stdout, the system’s stdouthandle - Each argument is sent to file - A line break, \nis sent to file static PyObject * builtin_print(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames) { ... if (file == NULL || file == Py_None) { file = _PySys_GetObjectId(&PyId_stdout); ... } ... for (i = 0; i < nargs; i++) { if (i > 0) { if (sep == NULL) err = PyFile_WriteString(" ", file); else err = PyFile_WriteObject(sep, file, Py_PRINT_RAW); if (err) return NULL; } err = PyFile_WriteObject(args[i], file, Py_PRINT_RAW); if (err) return NULL; } if (end == NULL) err = PyFile_WriteString("\n", file); else err = PyFile_WriteObject(end, file, Py_PRINT_RAW); ... Py_RETURN_NONE; } The contents of some modules written in C expose operating system functions. Because the CPython source code needs to compile to macOS, Windows, Linux, and other *nix-based operating systems, there are some special cases. The time module is a good example. The way that Windows keeps and stores time in the Operating System is fundamentally different than Linux and macOS. This is one of the reasons why the accuracy of the clock functions differs between operating systems. In Modules/timemodule.c, the operating system time functions for Unix-based systems are imported from <sys/times.h>: #ifdef HAVE_SYS_TIMES_H #include <sys/times.h> #endif ... #ifdef MS_WINDOWS #define WIN32_LEAN_AND_MEAN #include <windows.h> #include "pythread.h" #endif /* MS_WINDOWS */ ... Later in the file, time_process_time_ns() is defined as a wrapper for _PyTime_GetProcessTimeWithInfo(): static PyObject * time_process_time_ns(PyObject *self, PyObject *unused) { _PyTime_t t; if (_PyTime_GetProcessTimeWithInfo(&t, NULL) < 0) { return NULL; } return _PyTime_AsNanosecondsObject(t); } _PyTime_GetProcessTimeWithInfo() is implemented multiple different ways in the source code, but only certain parts are compiled into the binary for the module, depending on the operating system. Windows systems will call GetProcessTimes() and Unix systems will call clock_gettime(). Other modules that have multiple implementations for the same API are the threading module, the file system module, and the networking modules. Because the Operating Systems behave differently, the CPython source code implements the same behavior as best as it can and exposes it using a consistent, abstracted API. The CPython Regression Test Suite# CPython has a robust and extensive test suite covering the core interpreter, the standard library, the tooling and distribution for both Windows and Linux/macOS. The test suite is located in Lib/test and written almost entirely in Python. The full test suite is a Python package, so can be run using the Python interpreter that you’ve compiled. Change directory to the Lib directory and run python -m test -j2, where j2 means to use 2 CPUs. On Windows use the rt.bat script inside the PCBuild folder, ensuring that you have built the Release configuration from Visual Studio in advance: $ cd PCbuild $ rt.bat -q C:\repos\cpython\PCbuild>"C:\repos\cpython\PCbuild\win32\python.exe" -u -Wd -E -bb -m test == CPython 3.8.0b4 == Windows-10-10.0.17134-SP0 little-endian == cwd: C:\repos\cpython\build\test_python_2784 == CPU count: 2 == encodings: locale=cp1252, FS=utf-8 Run tests sequentially 0:00:00 [ 1/420] test_grammar 0:00:00 [ 2/420] test_opcodes 0:00:00 [ 3/420] test_dict 0:00:00 [ 4/420] test_builtin ... On Linux: $ cd Lib $ ../python ... On macOS: $ cd Lib $ ../python.exe ... Some tests require certain flags; otherwise they are skipped. For example, many of the IDLE tests require a GUI. To see a list of test suites in the configuration, use the --list-tests flag: $ ../python.exe -m test --list-tests test_grammar test_opcodes test_dict test_builtin test_exceptions ... You can run specific tests by providing the test suite as the first argument: $ ../python.exe -m test test_webbrowser Run tests sequentially 0:00:00 load avg: 2.74 [1/1] test_webbrowser == Tests result: SUCCESS == 1 test OK. Total duration: 117 ms Tests result: SUCCESS You can also see a detailed list of tests that were executed with the result using the -v argument: $ ../python.exe -m test test_webbrowser -v == CPython 3.8.0b4 == macOS-10.14.3-x86_64-i386-64bit little-endian == cwd: /Users/anthonyshaw/cpython/build/test_python_24562 == CPU count: 4 == encodings: locale=UTF-8, FS=utf-8 Run tests sequentially 0:00:00 load avg: 2.36 [1/1] test_webbrowser test_open (test.test_webbrowser.BackgroundBrowserCommandTest) ... ok test_register (test.test_webbrowser.BrowserRegistrationTest) ... ok test_register_default (test.test_webbrowser.BrowserRegistrationTest) ... ok test_register_preferred (test.test_webbrowser.BrowserRegistrationTest) ... ok test_open (test.test_webbrowser.ChromeCommandTest) ... ok test_open_new (test.test_webbrowser.ChromeCommandTest) ... ok ... test_open_with_autoraise_false (test.test_webbrowser.OperaCommandTest) ... ok ---------------------------------------------------------------------- Ran 34 tests in 0.056s OK (skipped=2) == Tests result: SUCCESS == 1 test OK. Total duration: 134 ms Tests result: SUCCESS Understanding how to use the test suite and checking the state of the version you have compiled is very important if you wish to make changes to CPython. Before you start making changes, you should run the whole test suite and make sure everything is passing. Installing a Custom Version# From your source repository, if you’re happy with your changes and want to use them inside your system, you can install it as a custom version. For macOS and Linux, you can use the altinstall command, which won’t create symlinks for python3 and install a standalone version: $ make altinstall For Windows, you have to change the build configuration from Debug to Release, then copy the packaged binaries to a directory on your computer which is part of the system path. The CPython Source Code: Conclusion# Congratulations, you made it! Did your tea get cold? Make yourself another cup. You’ve earned it. Now that you’ve seen the CPython source code, the modules, the compiler, and the tooling, you may wish to make some changes and contribute them back to the Python ecosystem. The official dev guide contains plenty of resources for beginners. You’ve already taken the first step, to understand the source, knowing how to change, compile, and test the CPython applications. Think back to all the things you’ve learned about CPython over this article. All the pieces of magic to which you’ve learned the secrets. The journey doesn’t stop here. This might be a good time to learn more about Python and C. Who knows: you could be contributing more and more to the CPython project! Also be sure to check out the new CPython Internals book available here on Real Python: Free Download: Get a sample chapter from CPython Internals: Your Guide to the Python 3 Interpreter showing you how to unlock the inner workings of the Python language, compile the Python interpreter from source code, and participate in the development of CPython.
https://realpython.com/cpython-source-code-guide/
CC-MAIN-2020-40
refinedweb
22,815
53.71
In this post, we are going to explore arrays is created by the numpy package in Python. Understanding how arrays are created and manipulated is useful when you need to perform complex coding and or analysis. In particular, we will address the following, - Creating and exploring arrays - Math with arrays - Manipulating arrays Creating and Exploring an Array Creating an array is simple. You need to import the numpy package and then use the np.array function to create the array. Below is the code. import numpy as np example=np.array([[1,2,3,4,5],[6,7,8,9,10]]) Making an array requires the use of square brackets. If you want multiple dimensions or columns than you must use inner square brackets. In the example above I made an array with two dimensions and each dimension has it’s own set of brackets. Also, notice that we imported numpy as np. This is a shorthand so that we do not have to type the word numpy but only np. In addition, we now created an array with ten data points spread in two dimensions. There are several functions you can use to get an idea of the size of a data set. Below is a list with the function and explanation. - .ndim = number of dimensions - .shape = Shares the number of rows and columns - .size = Counts the number of individual data points - .dtype.name = Tells you the data structure type Below is code that uses all four of these functions with our array. example.ndim Out[78]: 2 example.shape Out[79]: (2, 5) example.size Out[80]: 10 example.dtype.name Out[81]: 'int64' You can see we have 2 dimensions. The .shape function tells us we have 2 dimensions and 5 examples in each one. The .size function tells us we have 10 total examples (5 * 2). Lastly, the .dtype.name function tells us that this is an integer data type. Math with Arrays All mathematical operations can be performed on arrays. Below are examples of addition, subtraction, multiplication, and conditionals. example=np.array([[1,2,3,4,5],[6,7,8,9,10]]) example+2 Out[83]: array([[ 3, 4, 5, 6, 7], [ 8, 9, 10, 11, 12]]) example-2 Out[84]: array([[-1, 0, 1, 2, 3], [ 4, 5, 6, 7, 8]]) example*2 Out[85]: array([[ 2, 4, 6, 8, 10], [12, 14, 16, 18, 20]]) example<3 Out[86]: array([[ True, True, False, False, False], [False, False, False, False, False]], dtype=bool) Each number inside the example array was manipulated as indicated. For example, if we typed example + 2 all the values in the array increased by 2. Lastly, the example < 3 tells python to look inside the array and find all the values in the array that are less than 3. Manipulating Arrays There are also several ways you can manipulate or access data inside an array. For example, you can pull a particular element in an array by doing the following. example[0,0] Out[92]: 1 The information in the brackets tells python to access the first bracket and the first number in the bracket. Recall that python starts from 0. You can also access a range of values using the colon as shown below example=np.array([[1,2,3,4,5],[6,7,8,9,10]]) example[:,2:4] Out[96]: array([[3, 4], [8, 9]]) In this example, the colon means take all values or dimension possible for finding numbers. This means to take columns 1 & 2. After the comma we have 2:4, this means take the 3rd and 4th value but not the 5th. It is also possible to turn a multidimensional array into a single dimension with the .ravel() function and also to transpose with the transpose() function. Below is the code for each. example=np.array([[1,2,3,4,5],[6,7,8,9,10]]) example.ravel() Out[97]: array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) example.transpose() Out[98]: array([[ 1, 6], [ 2, 7], [ 3, 8], [ 4, 9], [ 5, 10]]) You can see the .ravel function made a one-dimensional array. The .transpose broke the array into several more dimensions with two numbers each. Conclusion We now have a basic understanding of how numpy array work using python. As mention before, this is valuable information to understand when trying to wrestling with different data science questions.
https://educationalresearchtechniques.com/2018/09/28/numpy-arrays-in-python/?shared=email&msg=fail
CC-MAIN-2019-51
refinedweb
739
57.67
Take3DScreenshot Description This editor script lets you take "3D Screenshots" of a specified object using the Game View. A 3D Screenshot is special type of movie that gives a "bullet-time" type camera rotation effect around a paused scene. Useful for the creation of QuicktimeVR. Usage - Place this script in YourProject/Assets/Editor and a menu item will automatically appear in the Custom menu after it is compiled. - If capturing an action scene, pause your game at the exact moment you want to capture. Make sure the camera is the distance you want it to be from the object during capture. If it isn't, you can usually just move it into position while paused. - Select Custom -> Take 3D Screenshot of Game View from the Custom menu. - In the wizard, change the folder name to match your system (make sure the folder exists). - Next, select the camera you want to use with useCamera, and the object to rotate the camera around with rotateAround. - The everyXdegrees parameter let's you choose how many screenshots you'll take and the fluidity of the final sequence. A lower number here means more images will be created; for example a value of 1 means 360 images will be created, 1 for each degree in a circle, default of 30 means 12 images will be made, and so on. More images result in a more fluid or smooth sequence. - The captureDelayMs value is the time in milliseconds that will be delayed between each screenshot (to allow the script to save the image to your hard disk). Best to leave captureDelayMs as is, but if you have a slower system and/or a low everyXdegrees number and are finding that some images in the sequence are missing, then you might increase this value. - Click Create and sit back and wait until the process has finished. Now you will have a series of images. "What you do from here is up to you" as the tools to create QTVR are currently pretty bad (especially on OS X, ironically). The exact procedure for making an object movie depends on the tool you choose. You generally specify the number of rows, the degrees of rotation and number of images per row, the initial view, and the folder that contains the images, and then the software creates the movie. Reluctantly, I recommend a windows program to do this: Pano2QTVR Microsoft ICE also works well: ICE Special thanks to NCarter for helping with the threading. Examples C# - Take3DScreenshot.cs using UnityEngine; using UnityEditor; using System.Threading; using System.Collections; public class Take3DScreenshot : ScriptableWizard { public static string fileName = "Unity 3D Screenshot _"; public static string folder = "/Users/Casemon/Desktop/Screens/"; public GameObject useCamera; public GameObject rotateAround; public int everyXdegrees = 30; public int captureDelayMs = 500; [MenuItem ("Custom/Take 3D Screenshot of Game View")] static void DoSet () { ScriptableWizard.DisplayWizard("Set params for 3D Screenshot", typeof(Take3DScreenshot), "Create"); } void OnWizardUpdate () { helpString = "Set the parameters to create a series of pictures in a circle... \n\nThese settings will create: " + (360 / everyXdegrees) + " images"; } void OnWizardCreate () { Thread thread = new Thread (TakeScreenshot); thread.Start (); } void TakeScreenshot () { for (int number = 0; number < (360 / everyXdegrees); number++) { Application.CaptureScreenshot(folder +fileName +number+"_"+number.ToString("d4") +".png"); if (rotateAround) useCamera.transform.RotateAround(rotateAround.transform.position, Vector3.up, everyXdegrees); else useCamera.transform.Rotate(Vector3.up, everyXdegrees); Debug.Log ("Saving " +folder +fileName +number.ToString("d4") +".png... DO NOT use the Unity Editor!!"); Thread.Sleep (captureDelayMs); } Debug.Log ("All Done! We now return you to your previously scheduled Unity work..."); } }
http://wiki.unity3d.com/index.php?title=Take3DScreenshot&oldid=13126
CC-MAIN-2013-48
refinedweb
585
56.55
Today I made an authentication flow using React, React Router, and Firebase. I adapted the structure from an earlier project for something new with a new UI here, but the main principles are the same. This will just be a short post highlighting the main functionalities here and how they're implemented. We just have four components- the App component, Login and GlobalNavbar. I have other components in the repo but they're not being used so feel free to ignore them. All of the magic happens in the App component where we import react-router-dom for our routing functionality. # App.js import React,{useState} from 'react'; import {auth} from './firebase'; import { BrowserRouter as Router, Route, Switch, Link } from 'react-router-dom'; import SignUp from './pages/SignUp'; import SignIn from './pages/SignIn'; import GlobalNavbar from './components/GlobalNavbar'; As you can see we also import a custom {auth} object that we created in a local firebase file. That's just a js file we store in the src folder that imports the relevant firebase node modules and initializes them, and their connection to Firebase: # firebase.js import firebase from "firebase/app"; import "firebase/analytics"; import "firebase/auth"; import "firebase/firestore";, measurementId: process.env.REACT_APP_FIREBASE_MEASUREMENT_ID }; // Initialize Firebase firebase.initializeApp(firebaseConfig); firebase.analytics(); export const auth = firebase.auth(); export default firebase; As you can see I am storing that sensitive Firebase API information in environment variables. The node package nodenv allows us to create environment variables that can easily be left out of git commits by creating a .env file in the root of the project folder and putting our React App variables there with the following format: REACT_APP_API_KEY=123123123123 You can then access those variables (after a server restart) by calling process.env.REACT_APP_API_KEY in your src folder files. Make sure those variables start with REACT_APP_ or CRA won't pick them up. Anyway, the firebase.js file above initializes the connection to Firebase and imports the relevant methods for Firebase auth, analytics, and firestore. We export firebase.auth() just for convenience and brevity. I trust you know how to make a form in React using text inputs- so I won't go over those. You just need an email and password text inputs plus a button to make this work. I'll just go over the Firebase methods used here: To sign up a user with an email simply use firebase.auth().createUserWithEmailAndPassword(email,password) where email and password are text strings. I do this in the following function (after some basic validation): const handleSignUp = () => { if (handleConfirmPassword()) { // password and confirm password match! auth.createUser); }); clearFields() } } This function will alert the user whether or not the submission was successful and tell the user why if there was an error. In the SignIn page we have a similar setup. A simple form that takes an email and password. For that the functionality is very similar and we use the firebase.auth().ignInWithEmailAndPassword(email, password) method like so: const logUserIn = () => { auth.signIn); }) } These two methods are the heart are sign in and sign up with Firebase, which takes a lot of pain out of your authentication flow. After we've imported the pages into App.js we put them into a React Router Switch like so (with the GlobalNavbar component on top of everything so it is present regardless of the page we're on): return ( <div className="App"> <Router> <GlobalNavbar /> <Switch> <Route path='/login'> <SignIn /> </Route> <Route> <SignUp path='/' /> </Route> </Switch> </Router> </div> ); I haven't done anything with it yet in this application, but the Firebase method to check if there is a logged in user or not is the following: const [userExists,setUserExists] = useState(false); auth.onAuthStateChanged((user) => { if (user) { setUserExists(true); console.log('Signed in as '+user.email); } else { setUserExists(false); } }); If you get creative you can imagine using that piece of userExists state to automatically route a user to a main dashboard or other authenticated page if they're logged in. Lastly, I just want to tell you about what you need to do to make an app like this work on Netlify. This app really relies on React Router working, but React Router and Netlify don't necessarily play well together. In fact, if you just upload a project with React Router to Netlify it won't work, and when you try to follow a redirect Netlify will show you a "Page does not exist" error. So, to deal with this, before we build the project we've got to add a file called _redirects to the public folder. This tells Netlify that any redirects will come back to the index.html page that is the root of your project. I followed this and this to get it going. Ultimately- it's just a matter of putting the following single line of code into that _redirects file: /* /index.html 200 That's it! Sorry it's not as detailed today- but check the code in the repo and I'm sure you can follow along. As usual if you get stuck don't be afraid to ping me in the comments :) Discussion (2) Man this is gem. Thanks just been looking for this. Thank you very much Subhakant! Let me know what you build with it :)
https://dev.to/jwhubert91/project-50-of-100-firebase-sign-up-and-login-with-react-router-5fbn
CC-MAIN-2021-10
refinedweb
879
64.61
STDARG(3) BSD Programmer's Manual STDARG(3) va_start, va_arg, va_copy, va_end - variable argument lists #include <stdarg.h> void va_start(va_list ap, last); type va_arg(va_list ap, type); void va_copy(va_list dst, va_list src);, nor as a function, nor an array type. The va_start() macro returns no value. The va_arg() macro expands to an expression that has the type and value of the next argument in the call. The parameter ap is the va_list ap ini- tialized, see below), random errors will occur. If the type in question is one that would normally be promoted, the pro- moted type should be used as the argument to va_arg(). The following describes which types should be promoted (and to what): - short is promoted to int - float is promoted to double - char is promoted to int The same rules apply to unsigned versions of the above types, as well as their bit-type equivalents (e.g. int8_t and int16_t). The first use of the va_arg() macro after that of the va_start() macro returns the argument after last. Successive invocations return the values of the remaining arguments. The va_copy() macro makes dst); } These macros are not compatible with the historic macros they replace. A backward compatible version can be found in the include file <varargs.h>. The va_start(), va_arg() and va_end() macros conform to ANSI/ISO/IEC 9899-1999 ("ANSI C99"). The va_start(), va_arg() and va_end() macros were introduced in ANSI X3.159-1989 ("ANSI C"). The va_copy() macro was introduced in ANSI/ISO/IEC 9899-1999 ("ANSI C99").). MirOS BSD #10-current October 24,.
http://mirbsd.mirsolutions.de/htman/sparc/man3/stdarg.htm
crawl-003
refinedweb
261
65.52
This action might not be possible to undo. Are you sure you want to continue? the .NET interview, I had downloaded all the material from the Internet from various websites and collected to form a single film, u will find few repeated questions also, all the material are from the various websites, so I had just bind it into a single file. So for any mistake I am not responsible, this is just for the view purpose. My view was only to collect a material to a single file. Please, if u find any mistake in this file, please contact me to my email address satishcm@gmail.com, so that I can able to correct it. Thanks Satish ALL THE BEST J Satish Marwat Dot Net Web Resources satishcm@gmail.com 1 Page .NET FRAME WORK Introduction Form s), database access (ADO.NET), web development (ASP.NET), web services, XML etc... Satish Marwat Dot Net Web Resources satishcm@gmail.com 2 Page 1.5 What tools can I use to develop .NET applications? There are a number of tools, described here in ascending order of cost: • • • • The .NET Framework SDK is free and includes command-line compilers for C++, C#, and VB.NET and various other utilities to aid development. ASP.NET Web Matrix. Microsoft Visual C# .NET Standard 2003. At the top end of the price spectrum are the Visual Studio.NET 2003 Enterprise and Enterprise Architect editions. These offer extra features such as Visual Sourcesafe (version control), and performance and analysis tools. Check out the Visual Studio.NET Feature Comparison at Terminology 2.1 What is the CLI? Is it the same as the CLR? The CLI (Common Language Infrastructure) is the definition. Satish Marwat Dot Net Web Resources satishcm@gmail.com 3 Page object oriented.NET runtime understands. 2.3 What is IL? IL = Intermediate Language. CLS = Common Language Specification. and you'll see that the statement still works pretty well :-). 2.for example a VB.4 What is C#? C# is a new language designed by Microsoft to work with the . The IL is then converted to machine code at the point where the software is installed. Not all . Such code is called managed code.NET source code (of any language) is compiled to IL during development. C# (pronounced “C sharp”) is firmly planted in the C and C++ family tree of languages. the code must provide a minimum level of information to the runtime.NET runtime's garbage collector.NET framework provides several core run-time services to the programs that run within it .NET context? The term 'managed' is the cause of much confusion.com 4 Page .NET languages are expected to support.NET framework. In their "Introduction to C#" whitepaper.NET class can inherit from a C# class. Also known as MSIL (Microsoft Intermediate Language) or CIL (Common Intermediate Language).2 What is the CTS. meaning slightly different things. Satish Marwat Dot Net Web Resources satishcm@gmail. This interop is very fine-grained . modern." Substitute 'Java' for 'C#' in the quote above. For these services to work.2. This is a subset of the CTS which all .for example exception handling and security. and will immediately be familiar to C and C++ programmers. 2. and type-safe programming language derived from C and C++. This is the full range of types that the . All . C# aims to combine the high productivity of Visual Basic and the raw power of C++.NET program written in any language. The idea is that any program which uses CLS-compliant types can interoperate with any .NET languages support all the types in the CTS. and how does it relate to the CLS? CTS = Common Type System. or (more commonly) at run-time by a Just-In-Time (JIT) compiler. Managed code: The .NET. Microsoft describe C# as follows: "C# is a simple. Managed data: This is data that is allocated and freed by the . It is used in various places within .5 What does 'managed' mean in the . NET compilers produce metadata about the types defined in the modules they produce.NET community with the benefits and restrictions that brings.Reflection. and it is used for similar purposes . It's the Satish Marwat Dot Net Web Resources satishcm@gmail. exes. An assembly consists of one or more files (dlls.g. To the runtime. 2. and represents a group of resources. Using reflection to access .com 5 Page . 3. As the name suggests. determining data type sizes for marshaling data across context/process/machine boundaries. but it also means more than that. html files etc).e. for example.Reflection namespace contains classes that can be used to interrogate the types for a module/assembly. Furthermore. regardless of whether namespaces are used to organise the names. An example of a restriction is that a managed class can only inherit from one base class. and implementations of those types. Assemblies 3.DLL.EXE or . don't get confused between assemblies and namespaces . This means.Type. types and references are described in a block of data called a manifest.1 What is an assembly? An assembly is sometimes described as a logical . thus making the assembly self-describing. Reflection can also be used to dynamically invoke methods (see System.Emit. type definitions.Managed classes: This is usually referred to in the context of Managed Extensions (ME) for C++. type names are type names. and can be an application (with a main entry point) or a library.6 What is reflection? All .namespaces are merely a hierarchical way of organising type names.NET metadata is very similar to using ITypeLib/ITypeInfo to access type library data in COM.for example. An important aspect of assemblies is that they are part of the identity of a type. This metadata is packaged along with the module (modules in turn are packaged together in assemblies). and assembly B exports a type called T.InvokeMember). An example of a benefit is proper interop with classes written in other languages . The class becomes a fully paid-up member of the . When using ME C++.NET runtime sees these as two completely different types. These resources. An assembly may also contain references to other assemblies. The manifest is part of the assembly. a class can be marked with the __gc keyword. and can be accessed by a mechanism called reflection. that if assembly A exports a type called T.TypeBuilder). The System. The identity of a type is the assembly that houses it combined with the type name. a managed C++ class can inherit from a VB class. the . or even create types dynamically at run-time (see System. this means that the memory for instances of the class is managed by the garbage collector. For example. Assemblies are also important in .3 What is the difference between a private assembly and a shared assembly? • • Location and visibility: A private assembly is normally used by a single application.many of the security restrictions are enforced at the assembly boundary. A shared assembly is normally stored in the global assembly cache.NET SDK.exe). but for private assemblies the search path is normally the application's directory and its sub-directories. Finally.WriteLine( "Hello from CTest" ). not on private assemblies. the /target:module switch is used to generate a module instead of an assembly. Shared assemblies are usually libraries of code which many applications will find useful. Alternatively you can compile your source into modules. the search path is normally same as the private assembly path plus the shared assembly cache.assembly plus the typename (regardless of whether the type name belongs to a namespace) that uniquely indentifies a type to the runtime. There are several factors which can affect the path (such as the AppDomain host. or a subdirectory beneath.NET .cs You can then view the contents of the assembly by running the "IL Disassembler" tool that comes with the .NET with respect to security . and application configuration files). For shared assemblies. For the C# compiler.g.more on this below.Console.4 How do assemblies find each other? By searching directory paths. and is stored in the application's directory. assemblies are the unit of versioning in . Versioning: The runtime enforces versioning constraints only on shared assemblies. and then combine the modules into an assembly using the assembly linker (al. } } can be compiled into a library assembly (dll) like this: csc /t:library ctest. 3. 3.com 6 Page . which is a repository of assemblies maintained by the .NET runtime.NET framework classes. the following C# program: public class CTest { public CTest() { System. Satish Marwat Dot Net Web Resources satishcm@gmail. 3.2 How can I produce an assembly? The simplest way to produce an assembly is directly from a . e.NET compiler. the . Currently the only way to unload a . 5. but expensive. Assemblies with either of the first two parts different are normally viewed as incompatible. Application Domains 4. so the runtime can ensure that AppDomains do not access each other's memory. Remember: versioning is only applied to shared assemblies.it is the version policy that decides to what extent these rules are enforced.g.1 What is an application domain? An AppDomain can be thought of as a lightweight process.5 How does assembly versioning work? Each assembly has a version number called the compatibility version. 3. not private assemblies. the assemblies are deemed compatible. The version number has four numeric parts (e. If only the fourth part is different. The primary purpose of the AppDomain is to isolate applications from each other.33).all memory in the AppDomain is managed by the .6 How can I develop an application that automatically updates itself from the web? 4. One non-obvious use of AppDomains is for unloading types. this is just the default guideline . However.2. The .NET type is to destroy the AppDomain it is loaded into. This is effective.NET runtime. Also each reference to an assembly (from another assembly) includes both the name and version of the referenced assembly.NET runtime enforces AppDomain isolation by keeping control over the use of memory . Win32 processes provide isolation by having distinct memory address spaces. but the third is different. This is particularly useful if you create and destroy types on-the-fly via reflection.5.com 7 Page . Satish Marwat Dot Net Web Resources satishcm@gmail. The version policy can be specified via the application configuration file.3. If the first two parts are the same. An AppDomain can be destroyed by the host without affecting other AppDomains in the process.NET. and so it is particularly useful in hosting scenarios such as ASP. Multiple AppDomains can exist inside a Win32 process. the assemblies are deemed as 'maybe compatible'. return 0. Garbage Collection 5.CurrentDomain. "CAppDomainInfo" ). using System. ASP. For an example of how to do this.Remoting. There is also a code sample in the . Satish Marwat Dot Net Web Resources satishcm@gmail. creates an instance of an object inside it.GetName() ).GetCallingAssembly(). the host is the Shell.net moniker developed by Jason Whittington and Don Box.GetName().Java and many other languages/runtimes have used garbage collection for some time. using System. CAppDomainInfo adInfo = (CAppDomainInfo)ad.NET and IE. The Shell creates a new AppDomain for every application.NET host? Yes.CreateInstanceAndUnwrap( Assembly. public class CAppDomainInfo : MarshalByRefObject { public string GetName() { return AppDomain.NET applications.FriendlyName.Runtime.1 What is garbage collection? Garbage collection is a heap-management strategy where a run-time component takes responsibility for managing the lifetime of the memory used by objects. Here is a C# sample which creates an AppDomain.3 Can I write my own . AppDomains can also be explicitly created by .NET SDK called CorHost. 5.4.NET application from the command-line.Name. } } 4. } } public class App { public static int Main() { AppDomain ad = AppDomain.2 How does an AppDomain get created? AppDomains are usually created by hosts.WriteLine( "Created AppDomain name = " + adInfo. Examples of hosts are the Windows Shell. This concept is not new to .CreateDomain( "Andy's new domain" ).com 8 Page .NET .Reflection. Console. When you run a . take a look at the source for the dm. and then executes one of the object's methods: using System. An example of the second category is a class with a System.g. Microsoft recommend that you provide a method called Dispose() for this purpose. started by Chris Sells. 5. There are really two categories of class that require deterministic destruction .the first category manipulate unmanaged types directly. Chris Sells' response to Brian's posting is here. database locks).NET garbage collector works by periodically running through a list of all the objects that are currently being referenced by an application. this type of algorithm works best by performing the garbage collection sweep as rarely as possible.IO. Normally heap exhaustion is the trigger for a collection sweep. Futhermore. The implication of this algorithm is that the runtime doesn't get notified immediately when the final reference on an object goes away .NET a problem? It's certainly an issue that affects component design.2 Is it true that objects don't always get immediately when the last reference goes away? destroyed Yes.5. 5. An example of the first category is a class with an IntPtr member representing an OS file handle.4 Is the lack of deterministic destruction in .com 9 Page . Satish Marwat Dot Net Web Resources satishcm@gmail.5 Should I implement Finalize on my class? Should I implement IDisposable? This issue is a little more complex than it first appears. this causes problems for distributed objects .NET runtime offer deterministic destruction? Because of the garbage collection algorithm.it only finds out during the next 'sweep' of the heap. 5. There was an interesting thread on the DOTNET list. Microsoft's Brian Harry posted a lengthy analysis of the problem. The .FileStream member. The garbage collector offers no guarantees about the time when an object will be destroyed and its memory reclaimed. about the implications of non-deterministic destruction of objects in C#. whereas the second category manipulate managed types that require deterministic destruction.3 Why doesn't the .in a distributed system who calls the Dispose() method? Some form of referencecounting or ownership-management mechanism is needed to handle distributed objects . you need to provide some way to tell the object to release the resource when it is done.unfortunately the runtime offers no help with this. If you have objects that maintain expensive or scarce resources (e. In October 2000. All the objects that it doesn't find during this search are ready to be destroyed and the memory reclaimed. However. 8 What is the lapsed listener problem? The lapsed listener problem is one of the primary causes of leaks in . it doesn't really make sense to call Dispose on member objects from a Finalizer anyway. This specifies whether or not the garbage collector performs some of its collection activities on a separate thread. Note that some developers argue that implementing a Finalizer is always a bad idea. as managed member objects cannot be accessed in the Finalizer. This allows the object user to 'do the right thing' by calling Dispose. but also provides a fallback of freeing the unmanaged resource in the Finalizer. but fails to unsubscribe. Satish Marwat Dot Net Web Resources satishcm@gmail. see Microsoft's documented pattern. The setting only applies on multi-processor machines.For the first category. and defaults to true. It occurs when a subscriber (or 'listener') signs up for a publisher's event.7 How can I find out what the garbage collector is doing? Lots of interesting statistics are exported from the . 5.GC class exposes a Collect method. In this case implementing Finalize is pointless. this may be the duration of the application. 5. as it hides a bug in your code (i. Use Performance Monitor to view them.e.) For classes that need to implement IDisposable and override Finalize.NET applications. However this logic does not apply to the second category of class. A less radical approach is to implement Finalize but include a Debug.NET CLR xxx' performance counters. with only managed resources. Also there is a gcConcurrent setting that can be specified via the application configuration file. So only the Dispose method should be implemented. 5. thus signalling the problem in developer builds but allowing the cleanup to occur in release builds.Assert at the start. This is because there is no guarantee about the ordering of Finalizer execution. The failure to unsubscribe means that the publisher maintains a reference to the subscriber as long as the publisher is alive.NET runtime via the '.6 Do I have any control over the garbage collection algorithm? A little. For example the System. should the calling code fail in its duty. it makes sense to implement IDisposable and override Finalize. as the member object's Finalizer will do the required cleanup. the lack of a Dispose call). which forces the garbage collector to collect all unreferenced objects immediately. For some publishers.com 10 Page . (If you think about it. class Win32 { [DllImport("kernel32. } class EventUser { public EventUser() { hEvent = Win32. is to change the publisher to use weak references in its subscriber list.CreateEvent( IntPtr. but the runtime can decide that an object is garbage much sooner than you expect. } static void UseEventInStatic( IntPtr hEvent ) Satish Marwat Dot Net Web Resources satishcm@gmail.WriteLine("EventUser finalized"). More specifically. [DllImport("kernel32.CloseHandle( hEvent ). Console. bool bManualReset. which is contrary to most developers' expectations. null ). The other problem is the performance degredation due to the publisher sending redundant notifications to 'zombie' subscribers. an object can become garbage while a method is executing on the object.bool bInitialState.dll".9 When do I need to use GC. false. typically by adding an Unsubscribe() method to the subscriber.com 11 Page . string lpName). } ~EventUser() { Win32.dll")] public static extern bool SetEvent(IntPtr hEvent).InteropServices.hEvent ). false. SetLastError=true)] public static extern bool CloseHandle(IntPtr hObject).KeepAlive? It's very unintuitive. 5. [DllImport("kernel32. Another solution. Chris Brumme explains the issue on his blog. documented here by Shawn Van Ness. I've taken Chris's code and expanded it into a full app that you can play with if you want to prove to yourself that this is a real problem: using System. } public void UseEvent() { UseEventInStatic( this.This situation causes two problems.Zero. The obvious problem is the leakage of the subscriber object. There are at least a couple of solutions to the problem.dll")] public static extern IntPtr CreateEvent( IntPtr lpEventAttributes. using System.Runtime. The simplest is to make sure the subscriber is unsubscribed from the publisher. during remoting). creating an object from a stream of bytes. to a file or database).KeepAlive(this) to the end of the UseEvent method.WriteLine( "SetEvent " + (bSuccess ? "succeeded" : "FAILED!") ). } IntPtr hEvent.g. so you'll get away with it.) So what's happening here? Well.1 What is serialization? Serialization is the process of converting an object into a stream of bytes. eventUser. i. if you uncomment the GC. Deserialization is the opposite process. A solution to this problem is to add a call to GC. } } If you run this code. as Chris explains. and you'll get the following output: SetEvent succeeded EventDemo finalized However. Serialization/Deserialization is mostly used to transport objects (e. or to persist objects (e. Normally of course the collection won't happen immediately. 6. Console.e. but sooner or later a collection will occur at the wrong time.{ //GC. Satish Marwat Dot Net Web Resources satishcm@gmail. Serialization 6. at the point where UseEvent() calls UseEventInStatic(). the EventUser object is garbage and can be collected.com 12 Page .Collect() call in the UseEventInStatic() method. a copy is taken of the hEvent field.SetEvent( hEvent ).g. and your app will fail. bool bSuccess = Win32. So as far as the runtime is concerned.UseEvent(). } class App { static void Main(string[] args) { EventUser eventUser = new EventUser(). it'll probably work fine.Collect(). and there are no further references to the EventUser object anywhere in the code. you'll get this output: EventDemo finalized SetEvent FAILED! (Note that you need to use a release build to reproduce this problem. and SoapFormatter/BinaryFormatter for remoting. 6. Satish Marwat Dot Net Web Resources satishcm@gmail. the [NonSerialized] attribute is the equivalent of XmlSerializer's [XmlIgnore] attribute. They can serialize private fields.NET platform and where performance is important. and only public read/write properties and fields can be serialized. XmlSerializer's features mean that it is most suitable for cross-platform work. However. for ease of debugging if nothing else. or for constructing objects from existing XML documents. Should I use XmlSerializer. The choice between SoapFormatter and BinaryFormatter depends on the application. for example. Both are available for use in your own code.NET Framework have in-built support for serialization? There are two separate mechanisms provided by the .NET class library XmlSerializer and SoapFormatter/BinaryFormatter. SoapFormatter generally makes more sense in all other cases. 6. Another example is the [XmlElement] attribute. which can be used to specify the XML element name to be used for a particular property or field. Ultimate control of the serialization process can be acheived by implementing the the ISerializable interface on the class whose instances are to be serialized. BinaryFormatter makes sense where both serialization and deserialization will be performed on the . SoapFormatter or BinaryFormatter? It depends.for example on deserialization the constructor of the new object is not invoked. For example. However they both require that the target class be marked with the [Serializable] attribute.2 Does the . For example. on the plus side. XmlSerializer has severe limitations such as the requirement that the target class has a parameterless constructor.6. SoapFormatter and BinaryFormatter have fewer limitations than XmlSerializer. XmlSerializer has good support for customising the XML document that is produced or consumed.3 I want to serialize instances of my class.4 Can I customise the serialization process? Yes. so like XmlSerializer the class needs to be written with serialization in mind.com 13 Page . XmlSerializer supports a range of attributes that can be used to configure serialization for a particular class. Serialization via SoapFormatter/BinaryFormatter can also be controlled to some extent by attributes. Also there are some quirks to watch out for . Microsoft uses XmlSerializer for Web Services. a field or property can be marked with the [XmlIgnore] attribute to exclude it from serialization.; } Satish Marwat Dot Net Web Resources satishcm@gmail.com 14 Page similar syntax to metadata Context attributes provide activation and method calls encountered Keith Brown's idea. is a context attribute. Context attributes use a attributes but they are fundamentally different. an interception mechanism whereby instance can be pre- and/or post-processed. If you have universal delegator you'll be familiar with this ); } } Satish Marwat Dot Net Web Resources satishcm@gmail.com 15 Page 7.3 Can I create my own context attributes?.) 8.334 8 465E08 07AC11EC1DCC7D054E807A43336DDE408A5393A48556123272CEEEE72F1660B71927D3856 1AABF5C AC1DF1734633C602F8F2D5: Everything Satish Marwat Dot Net Web Resources satishcm@gmail.com 16 Page To achieve this.com and you want it have full access to your system.4 How do I define my own code group? Use caspol.1) is just a caspol invention to make the code groups easy to manipulate from the command-line.Note the hierarchy of code groups . Note that the numeric label (1.3.com FullTrust Now if you run caspol -lg you will see that the new group has been added as group 1.1.com 17 Page . For example. which is then sub-divided into several groups. Satish Marwat Dot Net Web Resources satishcm@gmail. Also note that (somewhat counterintuitively) a sub-group can be associated with a more permissive permission set than its parent. you should only do this at the machine level .com: FullTrust .1: . but you want to keep the default restrictions for all other internet sites..the top of the hierarchy is the most general ('All code').3. to allow intranet code to do what it likes you might do this: caspol -cg 1.mydomain.mydomain.. If you are a normal (non-admin) user you can still modify the permissions. 8. 1.3 -site www.. like this: caspol -ag 1. suppose you trust code from www. The underlying runtime never sees it.which means not only that the changes you make become the default for the machine.2 FullTrust Note that because this is more permissive than the default policy (on a standard system). For example. but also that users cannot change the permissions to be more permissive.3.. you can operate at the 'machine' level . each of which in turn can be sub-divided. you would add a new code group as a sub-group of the 'Zone . Site .Internet' group. but only to make them more restrictive.Internet: Internet 1.. Zone . If you are the machine administrator.5 How do I change the permission set for a code group? Use caspol.doing it at the user level will have no effect. 8.mydomain. 1812.10. mscorlib.1812.<Permission class="System.FileDialogPermission.8.<Permission class="System.<Permission class="System. Ver=2000.NamedPermissionSet" version="1"> . SN=03689116d3a4ae33" version="1"> <Unrestricted /> </Permission> .Permissions.xml <PermissionSet class="System.Security.SecurityPermission.Permissions.<Permission class="System.Security.Security. mscorlib.6 Can I create my own permission set? Yes.14.10.<Permission class="System.1812.com 18 Page . specifying an XML file containing the permissions in the permission set. SN=03689116d3a4ae33" version="1"> <Assertion /> <UnmanagedCode /> <Execution /> <ControlThread /> <ControlEvidence /> <ControlPolicy /> <SerializationFormatter /> <ControlDomainPolicy /> <ControlPrincipal /> </Permission> .1812. here is a sample file corresponding to the 'Everything' permission set .just edit to suit your needs. SN=03689116d3a4ae33" version="1"> <Unrestricted /> </Permission> . Ver=2000. SN=03689116d3a4ae33" version="1"> <Unrestricted /> </Permission> Satish Marwat Dot Net Web Resources satishcm@gmail. Use caspol -ap.<Permission class="System.Security.1812.10.Permissions.14.14.Security.10. SN=03689116d3a4ae33" version="1"> <Unrestricted /> </Permission> . Ver=2000. Ver=2000. mscorlib. Ver=2000.Permissions.Permissions. mscorlib.Security.14.EnvironmentPermission.10. When you have edited the sample.Security.1812. Ver=2000.RegistryPermission.Security.IsolatedStorageFilePermission. SN=03689116d3a4ae33" version="1"> <Unrestricted /> </Permission> .14.Permissions.10.<Permission class="System.14.Permissions. mscorlib.ReflectionPermission. SN=03689116d3a4ae33" version="1"> <Unrestricted /> </Permission> .14. add it to the range of available permission sets like this: caspol -ap samplepermset. mscorlib.FileIOPermission.1812. To save you some time. Ver=2000. mscorlib.10. Permissions.UIPermission.1 Can I look at the IL for an assembly? Yes.1812.14. 1. How can I troubleshoot the problem? Caspol has a couple of options that might help. Ver=2000.com 19 Page .. Intermediate Language (IL) 9.just edit to suit your needs. Can I turn it off? Yes. Just run: caspol -s off 9. First. using caspol -rsg.3 is the 'Internet' code group) 8. MS supply a tool called Ildasm that can be used to view the metadata and IL for an assembly.Security. you can ask caspol to tell you what code group an assembly belongs to.<Permission class="System.10. mscorlib. to apply the permission set to a code group. Similarly. 8. you can ask what permissions are being applied to a particular assembly using caspol -rsp.3 SamplePermSet (By default. as long as you are an administrator.8 I can't be bothered with CAS.7 I'm having some trouble with CAS. Satish Marwat Dot Net Web Resources satishcm@gmail. SN=03689116d3a4ae33" version="1"> <Unrestricted /> </Permission> <Name>SamplePermSet</Name> <Description>By default this sample permission set is the same as the standard 'Everything' permission set .</Description> </PermissionSet> Then. do something like this: caspol -cg 1. 3 How can I stop my code being reverse-engineered from IL? You can buy an IL obfuscation tool.Object) ret } } Just put this into a file called hello.assembly MyAssembly {} . 10.com/archives/wa. as you'll see if you read the mailing list archives.develop.class MyApp { .il. These tools work by 'optimising' the IL in such a way that reverse-engineering becomes much more difficult. Lutz Roeder's Reflector does a very good job of turning IL into C# or VB. 9.exe?A2=ind0007&L=DOTNET&D=0& P=68241. 9. it is often relatively straightforward to regenerate high-level source from IL.4 Can I write IL programs directly? Yes. and then run ilasm hello. 9. Peter Drayton posted this simple example to the DOTNET mailing list: . IL!" call void System.NET. Take a look at the following two threads: 20 Page . Of course if you are writing web services then reverse-engineering is not a problem as clients do not have access to your IL. A couple of simple examples are that you can throw exceptions that are not derived from System.Exception.1 Does .9.il. and you can have non-zero-based arrays.entrypoint ldstr "Hello.5 Can I do things in IL that I can't do in C#? Yes.2 Can source code be reverse-engineered from IL? Yes.Console::WriteLine(class System. An exe assembly will be generated.method static void Main() { .NET replace COM? This subject causes a lot of controversy. Implications for COM 10.exe?A2=ind0007&L=DOTNET&P=R6 0761 Satish Marwat Dot Net Web Resources satishcm@gmail. As is always the case. and it looks like you have avoided that trap. this shouldn't seem so radical. I am personally glad that the same technology I use for loading cross-component types is used for intra-component types. enables tons of goodness from both MS and third parties. The former makes it impossible to perform dependency analysis for deployment. Personally. In classic COM.COM is about introducing type into components. so I am willing to be proven wrong. period. Your comment. which until not that long ago was called "COM+" (run REGASM. etc. Rather. This solves tons of the old VB "New vs.that is. The context architecture of MTS made this loader extensible. CreateObject" bugs that today's COM programmers still battle. In CLR. This was a big advance from the days when we loaded code based on files (LoadLibrary) and resolved entry points based on flat symbolic names (GetProcAddress). Focusing on things like GC or IL/JIT performance is really a red herring. As far as I can tell. In classic COM. Nothing in CLR changes that. attributes. but I see (but don't necessarily agree with) the arguments in favor of the approach. your aren't that far off from passing structs. Satish Marwat Dot Net Web Resources satishcm@gmail. class definitions that are immutable. really cuts to the chase in terms of the "soul of COM" . IMPORTED types are opaque. Thankfully. as most of today's COM components use class-based references internally (most ATL programmers work this way. the TLB describes the EXPORTED types only. Where classic COM has always fallen short was in the area of runtime type information. For inter-component sharing of class-based references. however.-)). CLR provides the system with "perfect" type information.com 21 Page . none of the ideas worth keeping from the IUnknown era have been dropped. classes and interfaces) simply have a better supporting implementation called CLR. the role of the interface. In the intra-component case where incremental deployment is a non-issue. all object references were interface-based. The latter makes it impossible for certain classes of services to do anything useful without massive programmer intervention. the water is more murky. which as you well know. On the one hand. the community at large figures our which parts of a programming model make sense and which don't. as are INTERNAL types used within the component boundary. and as long as you stick to sealed. In fact. object references can be either interface-based or class-based. versioning. MBV. Yes. this should be pretty easy to swallow. I am still skeptical about this one. I know I do). the big four concepts of COM (contexts. if you look at passing class-based references as parameters. many of the folks at MS now advocate using classes in many of the scenarios where interfaces were used in the past.exe and look up your code in the registry . The primary theme of COM was that we loaded code based on types (CoCreateInstance) and that we resolved entry points based on types (QueryInterface). allowing aspects of your implementation to be expressed via declarative attributes as well as executable statements. The more problematic case is where abstract classes are used in lieu of interfaces. 4 Can I use COM components from . . Here's a simple example for those familiar with ATL. First. create an ATL component which implements the following IDL: Satish Marwat Dot Net Web Resources satishcm@gmail. For oleautomation interfaces. search for postings by Joe Long in the archives .0 was to provide access to the existing COM+ services (through an interop layer) rather than replace the services with native . This wrapper turns the COM interfaces exposed by the COM component into .com/archives/wa. the RCW can be generated automatically from a type library. then the answer is yes.NET ones. attributes and context. no registrybased activation.NET-compatible interfaces.NET allows you to package and use components in a similar way to COM. once firewalls became widespread and Microsoft got SOAP fever. COM components are accessed from the .develop. Generally speaking. The . then the answer is no*.NET programs? Yes.2 Is DCOM dead? Pretty much.NET has its own mechanisms for type interaction.NETcompatible types. no IDL.Joe is the MS group manager for COM+. Over time it is expected that interop will become more seamless .So.exe?A2=ind0007&L=DOTNET&P=R6 8370 10.NET Framework has a new remoting model which is not based on DCOM.NET developers. For more on this topic. no typelibs. 10. as a lot of COM was ugly. so to me. Of course DCOM will still be used in interop scenarios. 10. If you think COM is a programming model based on typed components. Start with this message:. CLR is just better plumbing for the same programming model I've spent years working with.NET 1.NET runtime via a Runtime Callable Wrapper (RCW).this may mean that some services become a core part of the CLR. is CLR COM? If you think COM is IUnknown and a set of APIs. This is mostly good. No IUnknown. and/or it may mean that some services will be rewritten as managed code which runs on top of the CLR. interfaces. The approach for . but makes the whole thing a bit easier. DCOM was pretty much dead anyway. The bottom line is that . Various tools and attributes were provided to make this as painless as possible.3 Is COM+ dead? Not immediately. for . and they don't use COM. it may be necessary to develop a custom RCW which manually maps the types exposed by the COM interface to . For non-oleautomation interfaces.com 22 Page . I fall firmly in the latter camp. uuid(EA013F93-487A-4403-86EC-FD9FEE5E6206). import "ocidl. helpstring("CppName Class") ] coclass CppName { [default] interface ICppName.tlb"). you will get a message like this: Typelib imported successfully to CPPCOMSERVERLib.retval] BSTR *pName ).NET client .tlb").0 Type Library") ] library CPPCOMSERVERLib { importlib("stdole32. pointer_default(unique).0).idl". version(1. importlib("stdole2. oleautomation ] interface ICppName : IUnknown { [helpstring("method SetName")] HRESULT SetName([in] BSTR name). helpstring("ICppName Interface"). [ object.dll You now need a . }.idl". }. Create a .cs file containing the following code: Satish Marwat Dot Net Web Resources satishcm@gmail.com 23 Page . When you've built the component. helpstring("cppcomserver 1.let's use C#. like this: tlbimp cppcomserver.import "oaidl. [ uuid(600CE6D9-5ED7-4B4D-BB49-E8D5D5096F70). Run the TLBIMP utility on the typelibary.tlb If successful. [ uuid(F5E4C61D-D93A-4295-A4B4-2453D4A4484D). }. you should get a typelibrary. [helpstring("method GetName")] HRESULT GetName([out. com 24 Page . .dll csharpcomclient. namespace AndyMc { [ClassInterface(ClassInterfaceType.Runtime. Again.cs and put the following in it: using System. using System.using System.WriteLine( "Name is " + cppname.InteropServices.NET development tools. Also.NET component.exe. Console. } private string m_name. public class MainApp { static public void Main() { CppName cppname = new CppName(). cppname. the .SetName( "bob" ). } } Then compile the . a custom CCW can be developed.cs Note that the compiler is being told to reference the DLL we previously generated from the typelibrary using TLBIMP.cs Satish Marwat Dot Net Web Resources satishcm@gmail. using CPPCOMSERVERLib.5 Can I use . or if the automatic behaviour is not desirable.NET components from COM programs? Yes. and get the following output on the console: Name is bob 10. } } Compile the C# code like this: csc /r:cppcomserverlib.GetName() ). Create a C# file called testcomserver. for COM to 'see' the . if the wrapper cannot be automatically generated by the . You should now be able to run csharpcomclient. Here's a simple example.AutoDual)] public class CSharpCOMServer { public CSharpCOMServer() {} public void SetName( string name ) { m_name = name. but works in the opposite direction.NET components are accessed from COM via a COM Callable Wrapper (CCW).cs file as follows: csc /target:library testcomserver. } public string GetName() { return m_name. This is similar to a RCW (see previous question).NET component must be registered in the registry. but it has no place in the .tlb /codebase Now you need to create a client to test your .1 How does . Support is provided for multiple message serializarion formats. An alternative to the approach above it to use the dm.NET remoting work? .com 25 Page .You should get a dll. The object is thrown away when the request has finished.NET runtime Serialization Binary Formatter).NET runtime Serialization SOAP Formatter). But either channel can use either serialization format.put the following in a file called comclient. 10.vbs And hey presto you should get a message box displayed with the text "Name is bob". VBScript will do . the HTTP channel uses SOAP (via the . Singleton. There are a number of styles of remote access: • • SingleCall.6 Is ATL redundant in the . and the TCP channel uses binary (via the . All incoming requests from clients are processed by a single server object.CSharpCOMServer") dotNetObj. Each incoming request from a client is serviced by a new object.NET remoting involves sending messages along channels. Examples are SOAP (XML-based) and binary. which you register like this: regasm testcomserver.dll /tlb:testcomserver.SetName ("bob") MsgBox "Name is " & dotNetObj.NET world? Yes. 11. TCP is intended for LANs only . Satish Marwat Dot Net Web Resources satishcm@gmail.NET COM component.net moniker developed by Jason Whittington and Don Box.NET world. Two of the standard channels are HTTP and TCP.vbs: Dim dotNetObj Set dotNetObj = CreateObject("AndyMc.HTTP can be used for LANs or WANs (internet).GetName() and run the script like this: wscript comclient. By default. Miscellaneous 11. ATL will continue to be valuable for writing COM components for some time. Auto)] public static extern int MessageBox(int hWnd. SetLastError=true. String strMessage.2 How can I get at the Win32 API from a .. class MainApp { [DllImport("user32.Runtime.. it is has the same name as the executable with . This uses similar technology to COM Interop.that way I can just post a link next time. public static void Main() { MessageBox( 0. In web apps.dll". 11. Each object has a lease time.NET". 0 ). the file is called web. Objects have a default renew time . this is PInvoke in operation!". "Hello. For a normal Windows or console application.net is a great resource for off-the-shelf P/Invoke signatures. String strCaption.Net.• Client-activated object. EntryPoint="MessageBox".NET runtime remoting infrastructure.config. and when that time expires the object is disconnected from the . take a look at Charles Cook's XML-RPC.NET Application Configuration Files Is a Bad Idea I seem to write about this often enough in news groups and mailing lists that I thought I'd put it up here .3 How do I write to the application configuration file at runtime? Why Writing Into .NET program? Use P/Invoke. using System. This is the old stateful (D)COM model whereby the client receives a reference to the remote object and holds that reference (thus keeping the remote object alive) until it is finished with it. } } Pinvoke. The client can also explicitly renew the lease.NET applications can have a configuration file associated with them. uint uiType). . ".com 26 Page .the lease is renewed when a successful call is made from the client to the object. but is used to access static DLL entry points instead of COM objects. If you're interested in using XML-RPC as an alternative to SOAP. Distributed garbage collection of objects is managed by a system called 'leased based lifetime'.InteropServices.config tacked on Satish Marwat Dot Net Web Resources satishcm@gmail. CharSet=CharSet. 11. Here is an example of C# calling the Win32 MessageBox function: using System. " The slightly more informative but still fairly succinct answer is: "You quite often can't. This is a shame as it means they are throwing away a lot of the protection Windows can offer them. Indeed that's just common sense and good practice .NET projects.NET itself looks for certain settings inside this file. So if your app is called Foo.VS. For example. you would put the configuration file in the same directory and call it Foo. Because of this.config.com 27 Page . Don't try and write into the directory where your application is installed.exe. and you are unlikely to be able to modify it.ensuring that the user doesn't have permission to write into directories where executables are stored prevents a lot of viruses." Here's the long answer. the assembly resolver can be configured this way. If your application is deployed via HTTP. This is why the Program Files directory is configured not to allow normal users to write to it.config .lots of people run as administrators on their Windows machines. your program won't run properly unless the user is an administrator. It can also be used to store some application-specific settings in its <appSettings> element. and other malware from wreaking havoc. In Visual Studio . the configuration file will live on the web server. the file will be called App. Of course one of the reasons so many people run as administrators is because of crappy applications that attempt to write into their installation directories. Unfortunately. Why the Config File Might Not Be Writable The configuration file is stored in the same directory as the executable itself. .NET copies it into your build output directory and changes the name appropriately. not everyone runs as a normal user . Don't make your application one of those crappy applications. Satish Marwat Dot Net Web Resources satishcm@gmail. Of course there may be other reasons that the file isn't writable. spyware.exe. a frequently asked question emerges: How do I write settings into the application configuration file at runtime? The short answer is: "Don't do that. because if you do that. It's pretty common for users not to have permission to write to this directory.the end. and even when you can you don't want to. Why You Wouldn't Want to Write Into It Even If You Could Let's suppose you've ignored the above.all my home machines have multiple users because I'm not the only person who logs into them. because I'd have to keep reconfiguring them. They don't tend to have multiple simultaneous users.NET makes that very easy.com 28 Page . the user's settings will then follow them around the network as they log into various machines.GetFolderPath(Environment. (And there's no need to put application-wide settings there either. What's not to like? So how do you locate this directory? . and have decided to write a crappy application that writes into the directory it runs from. And if they back up their Documents and Settings directory. but that's not the point.Environment class: Environment. All of the fonts are configured to be extra large and legible.) You still don't want to be writing user settings in there. But you'd be mad to build such a thing when there's already a perfectly good system for doing this built into Windows! Where Should I Put This Information Then? The user's profile directory is the appropriate place for user settings. Moreover. I have a separate login I use on my laptop for doing presentations.ApplicationData) That will return a string. It would be hugely annoying if these things were configured on a per-machine basis. And not just terminal servers .SpecialFolder. (Welcome to Keith Brown's Hall of Shame by the way. and it really bugs me.) If you store user settings in the application configuration file. Of course you could fix that by rolling your own mechanism to keep each user's settings isolated. (Actually ILDASM stores font settings in a machine-wide way. (If you want to store data that does not Satish Marwat Dot Net Web Resources satishcm@gmail. Since there is a profile directory for each user. For example. containing the path of the Application Data subdirectory of the user's profile. if the profile is configured as a roaming profile. your application's settings will be backed up as a part of that operation. this keeps the settings separate. The resolution is set for a projector rather than the laptop's own screen. you will be storing one load of settings that apply to all users on the machine. thanks to the System. rather than simply being able to switch user accounts.) Lots of machines have multiple users. I don't want someone else's configuration choices to affect my account. but does not make the invocation mechanism public.) You may also choose to put a version-specific subdirectory underneath the application name directory. use LocalApplicationData instead. so be careful.CommonApplicationData) That returns a path for machine-wide settings. But they have the considerable advantage of working in partial trust scenarios. These are 4 bytes each on a 32-bit system. So.NET components. and create some funny-looking paths. Obviously the instance data for the type must be added to this to get the overall size of the object. and in both cases the publisher object can send notifications to the subscribers.) Note that even if you want to store application-wide settings.become part of the roaming profile. (If you look inside your profile's Application Data directory. These are a bit more cumbersome than just creating files in the right directory. Not all users will have write access to this by the way. subscriber objects can register for notifications. you'll see that this is the structure applications usually use.5 What size is a .an event adds public methods to the containing class to add and remove receivers.4 What is the difference between an event and a delegate? An event is just a wrapper for a multicast delegate. instances of the following class are 12 bytes each: Satish Marwat Dot Net Web Resources satishcm@gmail. (If your code might need to run with partial trust. making a total of 8 bytes per object overhead. Adding a public event to a class is almost the same as adding a public multicast delegate field.SpecialFolder.) You should create a subdirectory named after your company. In both cases.GetFolderPath(Environment. Hence events .NET object? Each instance of a reference type has two fields maintained by the runtime a method table pointer and a sync block. something we'd normally want to restrict to the publisher. look at the Isolated Storage APIs. a public multicast delegate has the undesirable property that external objects can invoke the delegate. for example. and inside that a subdirectory named after your program. So What Exactly Is The Configuration File For Then? The configuration file is really only for settings configured at deployment time. but this is not something you'd normally change in production once the application is deployed.it's useful to be able to deploy an application to connect to a test or staging server. you still don't have to write into the application installation directory. 11. Just do this: Environment. And it's often used for connections strings . It can be used to deal with versioning issues with . However.com 29 Page . 11.: Satish Marwat Dot Net Web Resources satishcm@gmail.com 30. 12 Satish Marwat Dot Net Web Resources satishcm@gmail.com 31(); } } 12.4 What's new in the .NET 2.0 class library? Here is a selection of new features in the .NET 2.0 class library (beta 1): • • • • • • Generic collections in the System.Collections.Generic namespace. The System.Nullable<T> type. (Note that C# has special syntax for this type, e.g. int? is equivalent to Nullable<int>) The GZipStream and DeflateStream classes in the System.IO.Compression namespace. The Semaphore class in the System.Threading namespace. Wrappers for DPAPI in the form of the ProtectedData and ProtectedMemory classes in the System.Security.Cryptography namespace. The IPC remoting channel in the System.Runtime.Remoting.Channels.Ipc namespace, for optimised intra-machine communication. 1) The C# keyword .int. maps to which .NET type? 1. 2. 3. 4. System.Int16 System.Int32 System.Int64 System.Int128 2) Which of these string definitions will prevent escaping on backslashes in C#? 1. 2. 3. 4. string s = #.n Test string.; string s = ..n Test string.; string s = @.n Test string.; string s = .n Test string.; Satish Marwat Dot Net Web Resources satishcm@gmail.com 32 Page 2. 2. d) Encapsulating a copy of a value type in an object. int[][] myArray. 4. and classes derived from the declaring class. Any DLL file used by an EXE file. 4.] myArray.com 33 Page . System. c) Encapsulating a value type in an object. An assembly containing localized resources for another assembly. Internal methods can be only be called using reflection. 3. 3. Classes within the same assembly.Array[2] myArray. int[. /text /doc /xml /help 7) What is a satellite Assembly? 1. 4. 3. 6) What compiler switch creates an xml file from the xml comments in the files in an assembly? 1. b) Encapsulating a copy of an object in a value type. int[2] myArray. 4. 2. A peripheral assembly designed to monitor permissions requests from an application. 5) What is boxing? a) Encapsulating an object in a value type. 4) If a method is marked as protected internal who can access it? 1. Only methods that are in the same class as the method in question. An assembly designed to alter the appearance or . 3. Satish Marwat Dot Net Web Resources satishcm@gmail.3) Which of these statements correctly declares a two-dimensional array in C#? 1. of an application. Classes that are both in the same assembly and derived from the declaring class.skin. 2. 4. private A() { } public static A Instance { get { if ( A == null ) A = new A(). Factory Abstract Factory Singleton Builder 11) In the NUnit test framework. It doesn. TestAttribute TestClassAttribute TestFixtureAttribute NUnitTestClassAttribute Satish Marwat Dot Net Web Resources satishcm@gmail. 9) How does assembly versioning in . A light weight thread or process that can call a single method.t. 2.8) What is a delegate? 1. An inter-process message channel. which attribute must adorn a test class in order for it to be picked up by the NUnit GUI? 1. } } } 1. . 10) Which . design pattern is shown below? public class A { private A instance. 3. 3. A strongly typed function pointer. 3.NET prevent DLL Hell? 1. 2. return instance.com 34 Page . The runtime checks to see that only one version of an assembly is on the machine at any one time. The compiler offers compile time checking for backward compatibility. 2. 4. 3.NET allows assemblies to specify the name AND the version of any assemblies they need to run. 4. A reference to an object in a different process. 4. 2.Gang of Four. NET assembly? With the help of Strong Name tool (sn. serviced components. 2. 4. A DataSet can be synchronised with the database. bin\debug” /> should do the trick.NET application. The exposition of data. Where are shared assemblies stored? Global assembly cache. 6. You can infer the schema from a DataSet.NET assemblies? Assemblies are the smallest units of versioning and deployment in the . Can you have two files with the same file name in GAC? Yes. and a public key token. 13) In Object Oriented Programming. 2. The separation of interface and implementation.12) Which of the following operations can you NOT perform on an ADO.exe) to find out the paths searched.com 35 Page . A DataSet can be synchronised with a RecordSet. How can you tell the application to look for assemblies at the locations other than its own install? Use the directive in the XML . <probing privatePath=”c:\mylibs.NET DataSet? 1.exe). remember that GAC is a very special folder. 4. and while normally you Satish Marwat Dot Net Web Resources satishcm@gmail. How can you debug failed assembly binds? Use the Assembly Binding Log Viewer (fuslogvw. how would you describe encapsulation? 1. Where’s global assembly cache located on the system? Usually C:\winnt\assembly or C:\windows\assembly. culture identity.config file for a given application. version number. 4. How can you create a strong name for a . 2. and . 3. Windows services. What do you know about . 9. A DataSet can be converted to XML. . Shared assembly can be used by multiple applications and has to have a strong name. Assemblies are also the building blocks for programs such as Web services. 8. 3.NET remoting applications. The conversion of one type of object to another. What’s the difference between private and shared assembly? Private assembly is used inside an application only and does not have to be identified by a strong name. 3. The runtime resolution of method calls. 5. What’s a strong name? A strong name includes the name of the assembly. Or you can add additional search paths in the Properties box of the deployed application.NET deployment questions 1. 7. private void ThreadMain() { Console. m_thread = new Thread( new ThreadStart(ThreadMain) ). 10.1 Threads 13. This process enables developers to work with shared assemblies as if they were strongly named.0.dll to co-exist in GAC if the first one is version 1. and I publish the patch. This allows the assembly to be signed with the private key at a later stage. Class Library 13. a publisher policy file needs to be compiled into an assembly and placed in the GAC.0.0.would not be able to place two files with the same name into a Windows folder.0. passing it an instance of a ThreadStart delegate that will be executed on the new thread.config file.0.dll and MyApp. There is a security bug in that assembly. } // ThreadMain() is executed on the new thread.com 36 Page .dll 1.Join(). GAC differentiates by version number as well. when the development process is complete and the component or assembly is ready to be deployed.0. version 1.What is delay signing? Delay signing allows you to place a shared assembly in the GAC by signing the assembly with just the public key. and it secures the private key of the signature from being accessed at different stages of development. use the publisher policy configuration file.Threading. m_thread. 11. 13.0.dll assembly.0 and the second one is 1. But unlike the app .0.WriteLine( m_data ).0.dll? Use publisher policy.So let’s say I have an application that uses MyApp.Start(). To configure a publisher policy. For example: class MyThread { public MyThread( string initData ) { m_data = initData.1. } Satish Marwat Dot Net Web Resources satishcm@gmail.1.1. } public void WaitUntilFinished() { m_thread. so it’s possible for MyApp.1 How do I spawn a thread? Create an instance of a System. How do I tell the client applications that are already installed to start using this new MyApp. which uses a format similar app .config file.Thread object. issuing it under name MyApp. Sleep( 1000 ).Abort() throws a ThreadAbortException regardless of what the thread is doing." ). 13. t. Thread. In other words.3 How do I use the thread pool? By passing an instance of a WaitCallback delegate to the ThreadPool. the ThreadAbortException cannot normally be caught (though the ThreadStart's finally method will be executed).1. you can use your own communication mechanism to tell the ThreadStart method to finish. The former will cause a ThreadInterruptedException to be thrown on the thread when it next goes into a WaitJoinSleep state. world. // Give time for work item to be executed // DoWork is executed on a thread from the thread pool.WriteLine( state ). The two principle methods are Thread.QueueUserWorkItem() method class CApp { static void Main(){ string s = "Hello. s ).com 37 Page .1.2 How do I stop a thread? There are several options.Interrupt is a polite way of asking the thread to stop when it is no longer doing any useful work.Interrupt() and Thread. ThreadPool. 13. Furthermore.Abort() is a heavy-handed mechanism which should not normally be required. static void DoWork( object state ){ Console.QueueUserWorkItem( new WaitCallback( DoWork ). Thread.WaitUntilFinished(). World". First. Alternatively the Thread class has in-built support for instructing the thread to stop.private Thread m_thread. private string m_data. } In this case creating an instance of the MyThread class is sufficient to spawn the thread and execute the MyThread.ThreadMain() method: MyThread t = new MyThread( "Hello. } Thread. } } Satish Marwat Dot Net Web Resources satishcm@gmail. Thread. In contrast.Abort(). . Satish Marwat Dot Net Web Resources satishcm@gmail. } } } C# has a 'lock' keyword which provides a convenient shorthand for the code above: class C{ public void f(){ lock(this){ . You must put code into the WaitCallback method to signal that it has completed. 13. The System.4 How do I know when my thread pool work item has completed? There is no way to query the thread pool for this information.Threading...com 38 Page .Enter(this).Monitor.Exit(o) is called.Exit(this)..5 How do I prevent concurrent access to my data? Each object has a concurrency lock (critical section) associated with it.Enter(myObject) does NOT mean that all access to myObject is serialized. In other words.Enter/Exit methods are used to acquire and release this lock.. Events are useful for this. instances of the following class only allow one thread at a time to enter method f(): class C{ public void f(){ try{ Monitor. and no other thread can acquire that lock until Monitor. this class is functionally equivalent to the classes above: class C{ public void f(){ lock( m_object ){ . } } } Note that calling Monitor. } } } private m_object = new object(). For example. It means that the synchronisation lock associated with myObject has been acquired.13. } finally{ Monitor.1.1. .. The Debug and Trace classes both have a Listeners property.Diagnostics. and System.Diagnostics namespace.WriteLine respectively.Create.Enter/Exit? Maybe. the TextWriterTraceListener class is provided for this purpose.Debug. while still granting exclusive access to a single writer thread.Enter/Exit. This sends output to the Win32 OutputDebugString() function and also the System.WriteLine for tracing that you want to work only in debug builds.Write ). but if you're trying to trace a problem at a customer site. but be careful. First. which is an instance of the DefaultTraceListener class. Trace. Here's how to use the TextWriterTraceListener class to redirect Trace output to a file: Trace. They both work in a similar way . which offsets some of the benefits.2 Can I redirect tracing to a file? Yes.6 Should I use ReaderWriterLock instead of Monitor. Second.txt". Typically this means that you should use System.Listeners. Satish Marwat Dot Net Web Resources satishcm@gmail.WriteLine and Trace. Fortunately.Diagnostics.1. redirecting the output to a file is more appropriate. it could be argued that this version of the code is superior. By default the Listeners collection contains a single sink.2. as the lock is totally encapsulated within the class. whereas tracing from the Trace class only works in builds that have the TRACE symbol defined. you need to be very sure that the data structures you are accessing fully support multithreaded read access. which is a collection of sinks that receive the tracing that you send via Debug. This makes sense for data access that is mostly read-only.Listeners. 13.1 ReaderWriterLock that can cause starvation for writers when there are a large number of readers. in the System.2 Tracing 13.2. This is useful when debugging. ReaderWriterLock is relatively poor performing compared to Monitor.com 39 Page . There are two main classes that deal with tracing . there is apparently a bug in the v1. ReaderWriterLock is used to allow multiple threads to read from a data source. Finally.Add( new TextWriterTraceListener( fs ) ). FileStream fs = new FileStream( @"c:\log.Debug and Trace.Actually.Log() method. FileAccess.Trace. and not accessible to the user of the object. 13.the difference is that tracing from the Debug class only works in builds that have the DEBUG symbol defined. but there are some caveats.Clear().1 Is there built-in support for tracing/logging? Yes.Diagnostics. FileMode. 13.WriteLine for tracing that you want to work in debug and release builds.Debugger. WriteLine() go through MyListener.2. all calls to Trace.) The beauty of this approach is that when an instance of MyListener is added to the Trace.Trace.TickCount . } (Note that this implementation is not complete . Trace.m_startTickCount. AppDomain. including calls made by referenced assemblies that know nothing about the MyListener class.TickCount.the TraceListener.NET runtime. If you don't do this. } protected int m_startTickCount = Environment.Write method is not overridden for example.txt!" ). the output will go to the file and OutputDebugString(). Note the use of Trace.WriteLine( "{0:D8} [{1:D4}] {2}".com 40 Page .GetCurrentThreadId().4 Are there any third party logging components available? Log4net is a port of the established log4j Java logging component.Flush().2. Typically this is not what you want. because OutputDebugString() imposes a big performance hit.WriteLine( @"This will be writen to c:\log. Environment. You can write your own TraceListener-derived class.Listeners collection. log4net is a tool to help the programmer output log statements to a variety of output targets.Clear() to remove the default listener. which derives from TextWriterTraceListener (and therefore has in-built support for writing to files. 13. Satish Marwat Dot Net Web Resources satishcm@gmail.NET runtime. For more information on log4net see the features document. and direct all output through it. log4net is a port of the excellent log4j framework to the .3 Can I customise the trace output? Yes. as shown above) and adds timing information and the thread ID for each trace line: class MyListener : TextWriterTraceListener { public MyListener( Stream s ) : base(s) { } public override void WriteLine( string s ) { Writer.Listeners. s ). Here's a simple example. 13. We have kept the framework similar in spirit to the original log4j while taking advantage of new features in the . Config file ? Its a base configuration file for all . list of all files. 5. culture information. properties and their parameters etc. The main advantage of public assemblies is code reusability.cs or assembelyinfo. 2.web). like classes. base class. outside this application there is no scope of privaet assembely. scope. the .NET framework is System. memory allocation. What is an Assembly ? Assemblies are the fundamental buildung block of .NET libraries. Assembly enables code reuse. 1. The Logging Services project is intended to provide cross-language logging services for purposes of application debugging and auditing. Explain dotnet framework ? The dot net Framework has two main components CLR and .vb file within an application. 3. version number. code reuability etc. Type metadata. security and deployment. Apart from CLR. interfaces. What is the difference between Metadata and Menifest ? Menifest descriubes the assembely itself. While the Metadata describes the contents within the assembely. 6. garbage collection. namespaces. An assembely can have four parts : Menifest.windows) are generated which can be further have their namespaces. MSIL and Resource file 5. version control. An application must have one private assembely.NET framework contains . type reference and reference assembely. The root namespace of . What is GAC ? GAC (global assembelu cache) Its an space (directory C:\winnt\assembely) on the server where all the shared assemblies are registrered and that can be used in the application for code reuse. data (system.data). These are also called as shared assemblies.NET assemblies running on the Satish Marwat Dot Net Web Resources satishcm@gmail.NET framework. windows (system. What do you know about Machine. Assembely name.com 41 Page . thread management etc. with this namespace many namespaces like web (system.log4net is part of the Apache Logging Services project. They contains the type and resources that are useful to make an application. What are public and private assemblies ? differences and scope ? Public assembly are the dll/exe file that can be used in different application.NET Libraries. The classes and namespaces are kept in a systematic way and can be used in making any application. which are collection of namespaces and classes. strong name. that actually runs the code manages so many things for example code execution. CLR (common language runtimes). Private assembly is the assembelyinfo. These can be used in different machine on different computers. com 42 Page . 13.g c:\winnt\assembely or c:\windows\assembely 10. It may be connected that once the Satish Marwat Dot Net Web Resources satishcm@gmail. It specifies a settings that are global to a perticular machine. A strong name incudes information about Assembely version. Different types of authentication modes in . Passport and None. what is connected and diconnected database ? Connected and Disconneted database basicallythe approch that how you handle the database connection. What is Strong name ? Strong name ensures the uniqueness of assembely on the server. COM is used to create reusable software components COM+ : COM+ is an extension of Component Object Model (COM). DCOM an extension of the Component Object Model (COM) that allows COM components to communicate across network boundaries. What are different types that a variable can be defined and their scopes ? Public.server. 8. Forms. DCOM uses the RPC mechanism to transparently send and receive information between COM components (i. clients and servers) on the same network.. 7. What is COM. Traditional COM components can only perform interprocess communication across process boundaries on the same machine. Public/Private Key token. Where does the GAC exist ? By defauit C:\\assembely e.Members of the class within the assembely Protected friend.anywhere in the same class Protected -winthin the class and the class that inherites this class Friend. 9. but the dlls are of different versions. Culture information and ASsembely name. COM+ and DCOM ? COM (Component Object Model) A standard that is used to for communication between OS and the softwares. for example integer to object type conversion. This is known as dll hell.e. COM+ is both an OOP architecture and a set of operating system services. Conversion of Boxed type variable back to value type is called as UnBoxing.NET Framework ? Windows.member of assembely or inheriting class 11. What is boxing and unboxing ? Implicit (manual) conversion of value type to reference type of a variable is known as BOXING.Can be accessed anywhere Private. 14. What is DLL HELL ? Previously (when using VB) we can have a situation that we have to put same name dll file in a single directory . for example.0 SDK and runtime was made publicly available around 6pm PST on 15-Jan-2002. The Mono project is attempting to implement the . Windows 2000. NT4 SP6a and Windows ME/98. 2000. When was .application starts you have to open the connection only for a single time and then performs many transactions and close the connection just before exit the application.NET framework. When a variable is defined. regardless of programming language.NET was made available to MSDN subscribers.com 43 Page . exception handling. What is the CLR? CLR = Common Language Runtime. polymorphism.NET base classes Many . The July 2000 PDC had a number of sessions on . 15. and so cannot be used to host ASP. IIS is not supported on Windows XP Home Edition. debugging.NET announced? Bill Gates delivered a keynote at Forum 2000. This approch will be generally used in windows based application. It manages the memory allocated to the .NET. and delegates were given CDs containing a pre-release version of the .NET program can take advantage of. On other hand disconnected architecter refere to open and close the connection for each time while performing a transactio.NET released? The final version of the 1.NET is only supported on Windows XP and Windows 2000. CLR takes cares about . the ASP.NET Web Matrix web server does run on XP Home. When was the first version of .NET framework classes Development. Windows 98/ME cannot be used for development. ASP.NET 'vision'.NET framework. The CLR is a set of standard resources that (in theory) any . However.NET framework on Linux. What is garbage collection and how it works ? Garbage Collection is Automatic Memory Manager for the dotnet framework. Its gets a space in the memory and when the program control comes out of that function the scope of variable gets ended. garbage collection) Security model Type system All . Robert Schmidt (Microsoft) lists the following CLR resources in his MSDN PDC# article: Object-oriented programming model (inheritance. Some parts of the framework do not work on all platforms . and profiling tools Execution and code management Satish Marwat Dot Net Web Resources satishcm@gmail. At the same time.NET framework/SDK and Visual Studio.NET Framework run on? The runtime supports Windows XP. Windows 95 is not supported.NET technology. outlining the . What platforms does the . so the garbage collection acts on and memory will releases.NET. held June 22. the final version of Visual Studio. Such code is called managed code. although clearly not all languages will support all CLR services.Managed code: The .for example exception handling and security.NET code is managed by default. In theory this allows very tight interop between different .NET languages will support all the types in the CTS.NET languages for example allowing a C# class to inherit from a VB class. a managed Satish Marwat Dot Net Web Resources satishcm@gmail. The IL is then converted to machine code at the point where the software is installed.NET languages are expected to support. For these services to work. a class can be marked with the __gc keyword.for example. What is IL? IL = Intermediate Language. This is a subset of the CTS which all .NET community with the benefits and restrictions that brings. but it also means more than that.NET source code (of any language) is compiled to IL.NET context? The term 'managed' is the cause of much confusion. different programming languages will be more equal in capability than they have ever been before. but the compiler can produce managed code by specifying a command-line switch (/com+). All C# and Visual Basic.NET applications can use. However note that not all . This is the range of types that the . The CTS is a superset of the CLS. VS7 C++ code is not managed by default. An example of a benefit is proper interop with classes written in other languages .NET program written in any language. but it can be marked as managed using the __gc keyword. even when using the /com+ switch. What is the CTS? CTS = Common Type System. this means that the memory for instances of the class is managed by the garbage collector. VS7 C++ data is unmanaged by default. All . C# and VB.com 44 Page .NET runtime understands. It is used in various places within .IL-to-native translators and optimizers What this means is that in the . As the name suggests.NET framework provides several core run-time services to the programs that run within it .NET data is always managed. When using ME C++.NET. What is the CLS? CLS = Common Language Specification. the code must provide a minimum level of information to the runtime. The idea is that any program which uses CLS-compliant types can interoperate with any . and therefore that . Also known as MSIL (Microsoft Intermediate Language) or CIL (Common Intermediate Language).NET world. or at run-time by a Just-In-Time (JIT) compiler.Managed classes: This is usually referred to in the context of Managed Extensions (ME) for C++. The class becomes a fully paid-up member of the . What does 'managed' mean in the . meaning slightly different things. Managed data: This is data that is allocated and de-allocated by the .NET runtime's garbage collector. Reflection. To provide explicit control. The consumer of the object should call this method when it is done using the object. What is the difference between Finalize and Dispose (Garbage collection) ? Class instances often encapsulate control over resources that are not managed by the runtime. such as window handles (HWND). and so on.g. Using reflection to access .Emit. The garbage collector calls this method at some point after there are no longer any valid references to the object. If an external resource is scarce or expensive. you should provide implicit cleanup using the Finalize method.Type.Reflection namespace contains classes that can be used to interrogate the types for a module/assembly. An example of a restriction is that a managed class can only inherit from one base class.TypeBuilder).InvokeMember ) . determining data type sizes for marshaling data across context/process/machine boundaries. Therefore. and can be accessed by a mechanism called reflection. implement the Dispose method provided by the IDisposable Interface.C++ class can inherit from a VB class.e.NET metadata is very similar to using ITypeLib/ITypeInfo to access type library data in COM. Reflection can also be used to dynamically invoke methods (see System. you should provide both an explicit and an implicit way to free those resources. Note that even when you provide explicit control by way of Dispose.com 45 Page . or even create types dynamically at runtime (see System. Provide implicit control by implementing the protected Finalize Method on an object (destructor syntax in C# and the Managed Extensions for C++). This metadata is packaged along with the module (modules in turn are packaged together in assemblies). better performance can be achieved if the programmer explicitly releases resources when they are no longer being used. Finalize provides a backup to prevent resources from permanently leaking if the programmer fails to call Dispose. you might want to provide programmers using an object with the ability to explicitly release these external resources before the garbage collector frees the object. In some cases. Satish Marwat Dot Net Web Resources satishcm@gmail. and it is used for similar purposes . What is reflection? All . database connections. Dispose can be called even if other references to the object are alive.NET compilers produce metadata about the types defined in the modules they produce. The System. Assembly. Changes to the revision number are typically reserved for an incremental build needed to fix a particular bug. and public key token (if the assembly has a strong name). the runtime looks for the assembly only in the application directory.What is Partial Assembly References? Full Assembly reference: A full assembly reference includes the assembly's text name. The Build number is typically used to distinguish between daily builds or smaller compatible releases. culture. Under this convention then. You can have multiple versions of the common language runtime. Partial Assembly reference: We can dynamically reference an assembly by providing only partial information. Build.0. on the same computer at the same time. and not to private assemblies. Changes to the major or minor portion of the version number indicate an incompatible change. When you specify a partial assembly reference.0 would be considered incompatible with version 1.LoadWithPartialName method and specify only a partial reference. version.0. The runtime checks for the assembly in the application directory and in the global assembly cache Changes to which portion of version number indicates an incompatible change? Major or minor. Since versioning is only applied to shared assemblies. two application one using private assembly and one using shared assembly cannot be stated as side-by-side executables. A full assembly reference is required if you reference any assembly that is part of the common language runtime or any assembly located in the global assembly cache.Assembly. The runtime checks for the assembly in the application directory. version 2.0. and multiple versions of applications and components that use a version of the runtime..Reflection.0.Reflection. Satish Marwat Dot Net Web Resources satishcm@gmail. -> Use the System. We can make partial references to an assembly in your code one of the following ways: -> Use a method such as System. Revision. Examples of an incompatible change would be a change to the types of some method parameters or the removal of a type or method altogether.0.com 46 Page . such as specifying only the assembly name.Load and specify only a partial reference. the assemblies are deemed as 'maybe compatible'.5. How does assembly versioning work? Each assembly has a version number called the compatibility version. However. but for private assemblies the search path is normally the application's directory and its sub-directories. What does assert() method do? In debug compilation. allowing you to fine-tune the tracing activities. How do assemblies find each other? By searching directory paths.The version number has four numeric parts (e. The program proceeds without any interruption if the condition is true. the assemblies are deemed compatible. Use Debug class for debug builds. Satish Marwat Dot Net Web Resources satishcm@gmail.TraceSwitcher? The tracing dumps can be quite verbose.it is the version policy that decides to what extent these rules are enforced. the search path is normally same as the private assembly path plus the shared assembly cache. There are several factors which can affect the path (such as the AppDomain host. Why are there five tracing levels in System. this is just the default guideline . For shared assemblies. If only the fourth part is different.g. The version policy can be specified via the application configuration file. and shows the error dialog if the condition is false.33). and application configuration files). Five levels range from None to Verbose. but the third is different. Thus keeping the Old string in Memory for Garbage Collector to be disposed. Where is the output of TextWriterTraceListener redirected? To the Console or a text file depending on the parameter passed to the constructor.com 47 Page .Diagnostics. If the first two parts are the same. What's the difference between the Debug class and Trace class? Documentation looks the same.Why string are called Immutable data Type ? The memory representation of string is an Array of Characters. Assemblies with either of the first two parts different are normally viewed as incompatible. assert takes in a Boolean condition as a parameter. So on reassigning the new array of Char is formed & the start address is changed . use Trace class for both debug and release builds. Also each reference to an assembly (from another assembly) includes both the name and version of the referenced assembly.2. 5. For applications that are constantly running you run the risk of overloading the machine and the hard drive. g. or to persist objects (e.unfortunately the runtime offers no help with this. The .Java and many other languages/runtimes have used garbage collection for some time. Normally heap exhaustion is the trigger for a collection sweep.What is garbage collection? Garbage collection is a system whereby a run-time component takes responsibility for managing the lifetime of objects and the heap memory that they occupy. All the objects that it doesn't find during this search are ready to be destroyed and the memory reclaimed. Microsoft uses XmlSerializer for Web Services. Is the lack of deterministic destruction in . this causes problems for distributed objects .it only finds out during the next sweep of the heap. Why doesn't the . What is serialization? Serialization is the process of converting an object into a stream of bytes. The implication of this algorithm is that the runtime doesn't get notified immediately when the final reference on an object goes away . Futhermore.NET runtime offer deterministic destruction? Because of the garbage collection algorithm. a field or property can be marked with the [XmlIgnore] attribute to exclude it from serialization. Another example is the [XmlElement] Satish Marwat Dot Net Web Resources satishcm@gmail. For example.NET a problem? It's certainly an issue that affects component design. This concept is not new to .NET Framework have in-built support for serialization? There are two separate mechanisms provided by the . and uses SoapFormatter/BinaryFormatter for remoting.NET garbage collector works by periodically running through a list of all the objects that are currently being referenced by an application. Microsoft recommend that you provide a method called Dispose() for this purpose. database locks). However. Deserialization is the opposite process of creating an object from a stream of bytes. during remoting). Does the . you need to provide some way for the client to tell the object to release the resource when it is done.com 48 Page .NET . to a file or database). Serialization / Deserialization is mostly used to transport objects (e. XmlSerializer supports a range of attributes that can be used to configure serialization for a particular class. Can I customise the serialization process? Yes. Both are available for use in your own code.g.g.NET class library XmlSerializer and SoapFormatter/BinaryFormatter.in a distributed system who calls the Dispose() method? Some form of reference-counting or ownership-management mechanism is needed to handle distributed objects . If you have objects that maintain expensive or scarce resources (e. this type of algorithm works best by performing the garbage collection sweep as rarely as possible. Why is XmlSerializer so slow? There is a once-per-process-per-type overhead with XmlSerializer. To see the code groups defined on your system. For example. Hashtable.code groups and permissions.and/or post-processed. e.Internet' code group. run 'caspol -lg' from the command-line. there is a significant delay. Each . Context attributes use a similar syntax to metadata attributes but they are fundamentally different. The first type I will refer to as a metadata attribute . Context attributes provide an interception mechanism whereby instance activation and method calls can be pre. How does CAS work? The CAS security policy revolves around two key concepts . The other type of attribute is a context attribute. Serialization via SoapFormatter/BinaryFormatter can also be controlled to some extent by attributes. which adheres to the permissions defined by the 'Internet' named permission set.NET assembly is a member of a particular code group. using the default security policy. (Naturally the 'Internet' named permission set represents a very restrictive range of permissions. for example. SoapFormatter and BinaryFormatter do not have this restriction. Ultimate control of the serialization process can be acheived by implementing the the ISerializable interface on the class whose instances are to be serialized. and (like other class metadata) can be accessed via reflection. Why do I get errors when I try to serialize a Hashtable? XmlSerializer will refuse to serialize instances of any class that implements IDictionary.) Who defines the CAS code groups? Microsoft defines some default ones.it allows some data to be attached to a class or method. that XmlSerializer is a poor choice for loading configuration settings during startup of a GUI application. but it may mean.g. This normally doesn't matter. and each code group is granted the permissions specified in a named permission set. On my system it looks like this: Level = Machine Code Groups: Satish Marwat Dot Net Web Resources satishcm@gmail. the [NonSerialized] attribute is the equivalent of XmlSerializer's [XmlIgnore] attribute.com 49 Page .attribute. So the first time you serialize or deserialize an object of a given type in an application. What are attributes? There are at least two types of . For example. a control downloaded from a web site belongs to the 'Zone . This data becomes part of the metadata for the class. but you can modify these and even create your own.NET attribute. which can be used to specify the XML element name to be used for a particular property or field. Zone . to allow intranet code to do what it likes you might do this: caspol -cg 1. each of which in turn can be sub-divided.3 -site: Internet 1. which is then sub-divided into several groups.3.the top of the hierarchy is the most general ('All code').2 FullTrust Note that because this is more permissive than the default policy (on a Satish Marwat Dot Net Web Resources satishcm@gmail.1. you would add a new code group as a sub-group of the 'Zone . 30 D69CED0FC8F83B465E08 07AC11EC1DCC7D054E807A43336DDE408A5393A48556123272CEEEE72F16 60B71927D38561AABF5C AC1DF1734633C602F8F2D5: Note the hierarchy of code groups . Site . Zone .Untrusted: Nothing 1. you can operate at the 'machine' level .mydomain.mydomain.Intranet: LocalIntranet 1.5.com 50 Page .which means not only that the changes you make become the default for the machine.3.Trusted: Internet 1. All code: Nothing 1.Internet: Internet 1. but also that users cannot change the permissions to be more permissive.com and you want it have full access to your system. Zone .1) is just a caspol invention to make the code groups easy to manipulate from the command-line. but only to make them more restrictive.1.1.com: FullTrust Note that the numeric label (1.2.1. like this: caspol -ag 1.3.com FullTrust Now if you run caspol -lg you will see that the new group has been added as group 1.4.6.1: 1. Zone . For example. If you are the machine administrator.Internet' group. How do I change the permission set for a code group? Use caspol. The underlying runtime never sees it. suppose you trust code from www. but you want to keep the default restrictions for all other internet sites. Zone .3.MyComputer: FullTrust 1. To achieve this. How do I define my own code group? Use caspol.mydomain. For example. Honor SkipVerification requests: SkipVerification 1. Also note that (somewhat counter-intuitively) a sub-group can be associated with a more permissive permission set than its parent.www. If you are a normal (non-admin) user you can still modify the permissions.3. Zone .1. Debug and Trace. which contains assembly metadata. They both work in a similar way . the TextWriterTraceListener class is provided for this purpose. Is there built-in support for tracing/logging? Yes. you should only do this at the machine level . Satish Marwat Dot Net Web Resources satishcm@gmail. as long as you are an administrator.Debug. but if you're trying to trace a problem at a customer site.Diagnostics. it is often relatively straightforward to regenerate high-level source (e. in the System. Fortunately. This is useful when debugging.Log() method.WriteLine and Trace.Diagnostics namespace. whereas tracing from the Trace class only works in builds that have the TRACE symbol defined. which is a collection of sinks that receive the tracing that you send via Debug.standard system). and System. redirecting the output to a file is more appropriate.WriteLine for tracing that you want to work in debug and release builds.WriteLine for tracing that you want to work only in debug builds. The Debug and Trace classes both have a Listeners property. Type metadata. C#) from IL. Can I turn it off? Yes.WriteLine respectively. How can I stop my code being reverse-engineered from IL? There is currently no simple way to stop code being reverse-engineered from IL.Debugger. There are two main classes that deal with tracing . Typically this means that you should use System.com 51 Page . These tools work by 'optimising' the IL in such a way that reverse-engineering becomes much more difficult.Trace.doing it at the user level will have no effect.g. MS supply a tool called Ildasm which can be used to view the metadata and IL for an assembly. a static assembly can consist of four elements: The assembly manifest. This sends output to the Win32 OutputDebugString() function and also the System. I can't be bothered with all this CAS stuff. Of course if you are writing web services then reverse-engineering is not a problem as clients do not have access to your IL. In future it is likely that IL obfuscation tools will become available.Diagnostics. either from MS or from third parties. which is an instance of the DefaultTraceListener class. Can I redirect tracing to a file? Yes. What are the contents of assembly? In general.Diagnostics. By default the Listeners collection contains a single sink. Can source code be reverse-engineered from IL? Yes.the difference is that tracing from the Debug class only works in builds that have the DEBUG symbol defined. Just run: caspol -s off Can I look at the IL for an assembly? Yes. The common language runtime garbage collector also compacts the memory that is in use to reduce the working space needed for the heap. Unmanaged code executes in the common language runtime environment with minimal services (for example. direct memory access. Managed code must supply the metadata necessary for the runtime to provide services such as memory management. no garbage collection. control flow. MSIL includes instructions for loading. storing. CLR ? MSIL: (Microsoft intermediate language) When compiling to managed code. CTS and. IL. the compiler translates your source code into Microsoft intermediate language (MSIL). usually by a just-in-time (JIT) compiler. MSIL must be converted to CPU-specific code. What is MSIL. A set of resources. Differnce between Managed code and unmanaged code ? Managed Code: Code that runs under a "contract of cooperation" with the common language runtime. and calling methods on objects. since the GC is always running. the same set of MSIL can be JIT-compiled and executed on any supported Satish Marwat Dot Net Web Resources satishcm@gmail. cross-language integration. What is GC (Garbage Collection) and how it works One of the good features of the CLR is Garbage Collection. which runs in the background collecting unused object references.] Heap: A portion of memory reserved for a program to use for the temporary storage of data structures whose existence or size cannot be determined until the program is running. which is a CPU-independent set of instructions that can be efficiently converted to native code. Because the common language runtime supplies one or more JIT compilers for each computer architecture it supports. Un-Managed Code: Code that is created without regard for the conventions and requirements of the common language runtime.Microsoft intermediate language (MSIL) code that implements the types.com 52 Page . as well as instructions for arithmetic and logical operations. and then arranging to reuse any heap memory that was not found during this trace. limited debugging. exception handling. freeing us from having to ensure we always destroy them. and automatic lifetime control of objects. All code based on Microsoft intermediate language (MSIL) executes as managed code. initializing. Before code can be executed. and so on). code access security. and other operations. [The process of transitively tracing through all pointers to actively used objects in order to locate all objects that can be referenced. In reality the time difference between you releasing the object instance and it being garbage collected is likely to be very small. The presence of metadata in the file along with the MSIL enables your code to describe itself. Satish Marwat Dot Net Web Resources satishcm@gmail. The value of a reference type is the location of the sequence of bits that represent the type's data. it also produces metadata. uses. This file format. Reference types can be self-describing types. Metadata describes the types in your code. What is Reference type and value type ? Reference Type: Reference types are allocated on the managed CLR heap. just like object types. CTS: (Common Type System) The specification that determines how the common language runtime defines. Value types are not instantiated using new go out of scope when the function they are defined within returns. including the definition of each type. When a compiler produces MSIL. and other data that the runtime uses at execution time. which means that there is no need for type libraries or Interface Definition Language (IDL).valueType. or interface types Value Type: Value types are allocated on the stack just like primitive types in VBScript. VB6 and C/C++.architecture. A data type that is stored as a reference to the value's location. Value types in the CLR are defined as types that derive from system.com 53 Page . the members that your code references. the signatures of each type's members. The runtime supplies managed code with services such as cross-language integration. code access security. pointer types. The runtime locates and extracts the metadata from the file as needed during execution. The common language runtime includes a JIT compiler for converting MSIL to native code. The MSIL and metadata are contained in a portable executable (PE) file that is based on and extends the published Microsoft PE and Common Object File Format (COFF) used historically for executable content. and debugging and profiling support. IL: (Intermediate Language) A language used as the output of a number of compilers and as the input to a just-in-time (JIT) compiler. and manages types CLR: (Common Language Runtime) The engine at the core of managed code execution. object lifetime management. enables the operating system to recognize common language runtime images. which accommodates MSIL or native code as well as metadata. Satish Marwat Dot Net Web Resources satishcm@gmail. What is JIT and how is works ? An acronym for "just-in-time. Assemblies with the same strong name are expected to be identical What is global assembly cache? A machine-wide code cache that stores assemblies specifically installed to be shared by many applications on the computer. and culture information (if provided)—strengthened by a public key and a digital signature generated over the assembly. Static: Value can be initialized once. static ? Constants: The value can’t be changed Read-only: The value will be initialized only once from the constructor of the class. it is sufficient to generate the digital signature over just the one file in the assembly that contains the assembly manifest. What is Boxing and unboxing ? Boxing: The conversion of a value type instance to an object. which implies that the instance will carry full type information at run time and will be allocated in the heap." a phrase that describes an action that is taken only when it becomes necessary. version number.A data type that fully describes a value by specifying the sequence of bits that constitutes the value's representation. Un-Boxing: The conversion of an object instance to a value type. Because the assembly manifest contains file hashes for all the files that constitute the assembly implementation. Type information for a value type instance is not stored with the instance at run time. such as just-in-time compilation or just-intime object activation What is portable executable (PE) ? The file format used for executable programs and for files to be linked together to form executable programs What is strong name? A name that consists of an assembly's identity—its simple text name. What is difference between constants. readonly and. but it is available in metadata. Value type instances can be treated as objects using boxing. Applications deployed in the global assembly cache must have a strong name. The Microsoft intermediate language (MSIL) instruction set's box instruction converts a value type to an object by making a copy of the value type and embedding it in a newly allocated object.com 54 Page . com 55 Page . What's the access level of the visibility type internal? Current application. Windows authentication 3. How big is the datatype int in . the struct is less expensive. A default constructor is always provided to initialize the struct members to their default values.net? We have three types of authentication: 1. the fields will remain unassigned and the object cannot be used until all of the fields are initialized. and it does that exactly as classes do. A struct cannot inherit from another struct or class. When you create a struct object using the new operator. There is no inheritance for structs as there is for classes. and Color.Reflection What are the types of authentication in . A struct can implement interfaces. If you do not use new. if you declare an array of 1000 Point objects. Structs. inherit from the base class Object.What is difference between shared and public? An assembly that can be referenced by more than one application.config file. An assembly must be explicitly built to be shared by giving it a cryptographically strong name. A struct is a value type. Rectangle. Satish Marwat Dot Net Web Resources satishcm@gmail. a struct is more efficient in some scenarios. Unlike classes. you will allocate additional memory for referencing each object.NET? 32 bits. It is an error to declare a default (parameterless) constructor for a struct. Although it is possible to represent a point as a class. How big is the char? 16 bits (Unicode). Form authentication 2. Passport This has to be declared in web. and it cannot be the base of a class. it gets created and the appropriate constructor is called. however. It is an error to initialize an instance field in a struct. structs can be instantiated without using the new operator. while a class is a reference type. For example. What is the difference between a Struct and a Class ? The struct type is suitable for representing lightweight objects such as Point. What is namespace used for loading assemblies at run time and name the methods? System. In this case. How do you initiate a string without escaping each backslash? Put an @ sign in front of the double-quoted string. depending on whose JRE you're using.Collect(). What's different about namespace declaration when comparing that to package declaration in Java? No semicolon. what's different between C# and C/C++? There's no conversion between 0 and false.com 56 Page . pass an object.NET? System. they just fall off the stack when they fall out of scope. Speaking of Boolean data types. What is the difference between the value-type variables and reference-type variables in terms of garbage collection? The value-type variables are not garbage-collected.NET? Int32.Parse(string) How do you box a primitive data type variable? Assign it to the object. Why do you need to box a primitive variable? To pass it by reference. Where do the reference-type variables go in the RAM? The references go on the stack. What's the difference between Java and . as well as any other number and true. the interface is exposed.NET garbage collectors? Sun left the implementation of a specific garbage collector up to the JRE developer. like in C/C++. How do you enforce garbage collection in .GC. while the objects themselves go on the heap.Explain encapsulation ? The implementation is hidden. What data type should you use if you want an 8-bit value that's signed? sbyte. How do you convert a string into an integer in . Microsoft standardized on their garbage collection. the reference-type objects are picked up by GC when their references go null. Satish Marwat Dot Net Web Resources satishcm@gmail. Where are the value-type variables allocated in the computer RAM? Stack. so their performance varies widely. where a lot of manipulation is done to the text.Array. then why not write the proper code to handle that error instead of passing a new Exception object to the catch block? Throwing your own exceptions signifies some design flaws in the project. What's the . Strings are immutable. Can you store multiple data types in System.ToString().StringBuilder over System.NET datatype that allows the retrieval of data by a unique key? HashTable.Text.What's the difference between const and readonly? You can initialize readonly variables to some runtime values.com 57 Page . This way you declare public readonly string DateT = new DateTime(). Satish Marwat Dot Net Web Resources satishcm@gmail. Will finally block get executed if the exception had not occurred? Yes. Can multiple catch blocks be executed? No. a new instance is created. the control is transferred back to the beginning of the loop. How can you sort the elements of the array in descending order? By calling Sort() and then Reverse() methods. What's the difference between the System. What's class SortedList underneath? A sorted HashTable.String? StringBuilder is more efficient in the cases. once the proper catch code fires off. the second one is shallow.Array? No. Let's say your program uses current date and time as one of the values that won't change.Array.Clone()? The first one performs a deep copy of the array.CopyTo() and System. the control is transferred to the finally block (if there are any). if at that point you know that an error has occurred. and then whatever follows the finally block. so each time it's being operated on. Why is it a bad idea to throw your own exceptions? Well. What's the advantage of using System. What happens when you encounter a continue statement inside the for loop? The code for the rest of the loop is ignored. Where is the output of TextWriterTraceListener redirected? To the Console or a text file depending on the parameter passed to the constructor.Globalization. assert takes in a Boolean condition as a parameter. System. Five levels range from None to Verbose.Resources. System. What's a satellite assembly? When you write a multilingual or multi-cultural application in . What namespaces are necessary to create a localized application? System. In C++ they were referred to as function pointers. but also the version of the assembly. The program proceeds without any interruption if the condition is true. What's a multicast delegate? It's a delegate that points to and eventually fires off several methods. allowing to fine-tune the tracing activities.Resources What does assert() do? In debug compilation. and shows the error dialog if the condition is false. a CAB archive. What are the ways to deploy an assembly? An MSI installer.NET? Assembly versioning allows the application to specify not only the library it needs to run (which was available under Win32). and want to distribute the core application separately from the localized modules.What's a delegate? A delegate object encapsulates a reference to a method.TraceSwitcher? The tracing dumps can be quite verbose and for some applications that are constantly running you run the risk of overloading the machine and the hard drive there. and XCOPY command. the localized assemblies that modify the core application are called satellite assemblies. What namespaces are necessary to create a localized application? System.Globalization. Why are there five tracing levels in System. What's the difference between the Debug class and Trace class? Documentation looks the same. Satish Marwat Dot Net Web Resources satishcm@gmail. How's the DLL Hell problem solved in .com 58 Page . Use Debug class for debug builds.Diagnostics. use Trace class for both debug and release builds.NET. if you are debugging via Visual Studio. you can't. only the keyword virtual is changed to keyword override. you cannot access private methods in inherited classes. Can you change the value of a variable while debugging a C# application? Yes. just go to Immediate window.NET class that everything is derived from? System. Can you override private virtual methods? No. What's the implicit name of the parameter that gets passed into the class' set method? Value. and it's datatype depends on whatever variable we're changing. moreover. use interfaces instead.com 59 Page . Does C# support multiple inheritance? No. How do you inherit from a class in C#? Place a colon and then the name of the base class. Can you declare the override method static while the original method is non-static? No. proper handling). the signature of the virtual method must remain the same.What are three test cases you should go through in unit testing? Positive test cases (correct data.NET. have to be protected in the base class to allow any sort of access. Satish Marwat Dot Net Web Resources satishcm@gmail. What's the top . What does the keyword virtual mean in the method definition? The method can be over-ridden. exception test cases (exceptions are thrown and caught properly). Overloading simply involves having a method with the same name within the class. who is it available to? Derived Classes. Notice that it's double colon in C++. you change the method behavior for a derived class. When you inherit a protected class-level variable. correct output).Object. negative test cases (broken or missing data. How's method overriding different from overloading? When overriding. If a base class has a bunch of overloaded constructors. and an inherited class has another bunch of overloaded constructors. to prevent you from getting the false impression that you have any freedom of choice. and then keyword base (parameter list to invoke the appropriate constructor) in the overloaded constructor definition inside the inherited class. that's what keyword sealed in the class definition is for. can you enforce a call from an inherited constructor to an arbitrary base constructor? Yes. This might cause a problem on a higher-level scale if similarly named methods from different interfaces expect different data. but prevent the method from being over-ridden? Yes. How can you overload a method? Different parameter data types. just place a colon. Can you inherit multiple interfaces? Yes. different number of parameters. but as far as compiler cares you're okay. Therefore. It's the same concept as final class in Java. just leave the class public and make the method sealed. What's the difference between an interface and abstract class? In the interface all methods must be abstract. Satish Marwat Dot Net Web Resources satishcm@gmail.Can you prevent your class from being inherited and becoming a base class for some other classes? Yes. In the interface no accessibility modifiers are allowed.com 60 Page . you are not allowed to specify any accessibility. And if they have conflicting method names? It's up to you to implement the method inside your own class. different order of parameters. so implementation is left entirely up to you. Why can't you specify the accessibility modifier for methods inside the interface? They all must be public. which is ok in abstract classes. why not. The developer trying to derive from your class will get a message: cannot inherit from Sealed class WhateverBaseClassName. Can you allow class to be inherited. it's public by default. in the abstract class some methods can be concrete. NET class that everything is derived from? System. What's the top . Describe the accessibility modifier "protected internal".String? StringBuilder is more efficient in cases where there is a large amount of string manipulation. but they are not accessible. What's the advantage of using System. An abstract class is a class that must be inherited and have the methods overridden. a new instance is created.String is immutable. When you inherit a protected class-level variable.StringBuilder over System. who is it available to? The derived class.Text.com 61 Page .String and System. so each time it's being operated on. they are inherited. Can you store multiple data types in System. Strings are immutable.Array? No. An abstract class is essentially a blueprint for a class without any implementation. Satish Marwat Dot Net Web Resources satishcm@gmail.What's the difference between System. System. It is available to derived classes and classes within the same Assembly (and naturally from the base class it's declared in). Does C# support multiple-inheritance? No. What's an abstract class? A class that cannot be instantiated.NET class that allows the retrieval of a data element using a unique key? HashTable.StringBuilder classes? System.Object. Will the finally block get executed if an exception has not occurred? Yes. use interfaces instead. What's the .StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed. Although they are not visible or accessible via the class interface. Are private class-level variables inherited? Yes. For commercial products. you can. and deserializing and decoding messages into data on the other end. all methods must be abstract. Why can't you specify the accessibility modifier for methods inside the interface? They all must be public. but not all base abstract methods have been overridden. which is ok in an abstract class. Overloading a method simply involves having another method with the same name within the class. Can you override private virtual methods? No. What's an interface? It's an abstract class with public abstract methods all of which must be implemented in the inherited classes. The signature of the virtual method must remain the same. you are not allowed to specify any accessibility.com 62 Page . Private methods are not accessible outside the class. In an abstract class some methods can be concrete. to prevent you from getting the false impression that you have any freedom of choice. Therefore. Can you write a class without specifying namespace? Which namespace does it belong to by default? Yes. only the keyword virtual is changed to keyword override. Satish Marwat Dot Net Web Resources satishcm@gmail.When do you absolutely have to declare a class as abstract? 1. you wouldn't want global namespace What is a formatter? A formatter is an object that is responsible for encoding and serializing data into messages on one end. What's the difference between an interface and abstract class? In an interface class. How is method overriding different from method overloading? When overriding a method. naturally. In an interface class. Can you declare an override method to be static if the original method is non-static? No. you change the behavior of the method for the derived class. it's public by default. no accessibility modifiers are allowed. 2. then the class belongs to global namespace which has no name. When at least one of the methods in the class is abstract. When the class itself is inherited from an abstract class. all of which meet the requirements of this specification.NET & J2EE ? Differences between J2EE and the . as I have discussed at length. along with IBM and Ariba.NET platform eCollaboration model is.com/j2ee/) Overall Maturity Given that the . and we see UDDI as an important project to establish a registry framework for business-to-business e-commerce But while Sun publicly says it believes in the UDDI standards. are the leaders in this area. Whereas we have high volume highly reliable web sites using . it is tied to the Microsoft operating systems. it should be no surprise to learn that the . Sun is a member of the UDDI consortium and recognizes the importance of the UDDI standards. (ref : Java 2 Platform Enterprise Edition Specification. Sun has done nothing whatsoever to incorporate any of the UDDI standards into J2EE. A portable J2EE application will function correctly when successfully deployed in any of these products. v1. These standards are widely supported by more than 100 companies. in reality. In a recent press release.NET platform is far more mature than the J2EE platform.NET technologies (NASDAQ and Dell being among many examples) Interoperability and Web Services The . But neither are any of the J2EE implementations Many companies buy into J2EE believing that it will give them vendor neutrality.3. page 2-7 available at. Vice President for the Java Community Development.NET Platform Vendor Neutrality The . And.t Systems and their costs Satish Marwat Dot Net Web Resources satishcm@gmail. in fact.Different b/w .NET platform is not vendor neutral. Scalability Typical Comparision w. this is a stated goal of Sun's vision: A wide variety of J2EE product configurations and implementations.r. Sun's George Paolini. standards-based technologies that facilitate the growth of network-based applications.sun.com 63 Page . Microsoft. based on the UDDI and SOAP standards.NET platform has a three year lead over J2EE. are possible. says: "Sun has always worked to help establish and support open. 097.826 Total Sys.626 IBM $443.720 179.305.785 $1.463 Compaq $3.179 IBM RS/6000 Enterprise Server F80 16.594 .272 Compaq $3.375 $3.546.571 Compaq $5.NET platform includes such an eCommerce framework called Commerce Server.563.785 $2.499 IBM RS/6000 Enterprise Server M80 33.375 $3.037.003.231 32. there is no equivalent vendor-neutral framework in the J2EE space.914 262.658 229.J2EE Company System Total Sys. you should assume that you will be building your new eCommerce solution from scratch Satish Marwat Dot Net Web Resources satishcm@gmail.263 IBM IBM eServer pSeries 680 Model 7017-S85 110.055 Bull Escala EPC2450 110.305.244 505.681 Bull Escala EPC810 c/s 33.026.582 Compaq $5.717 Dell $334. PowerEdge 4400 ProLiant ML-570-6/700-3P PowerEdge 6400 Netfinity 7600 c/s ProLiant 8500-X550-64P ProLiant 8500-X700-64P ProLiant 8500-X550-96P ProLiant 8500-X700-96P ProLiant 8500-700-192P Cost 16.com 64 Page .487 Compaq $201. With J2EE.377 161.980.534.303 Framework Support The .403 $9.560.NET platform systems Company System Dell $273. Cost Bull Escala T610 c/s 16.571 Compaq $10. At this point.403 $9.207 30.263 20. particularly when the J2EE platform itself can be bundled with the ISV's product as an integrated offering. As Sun's Distinguished Scientist and Java Architect Rick Cattell said in a recent interview. the group that standardizes JavaScript. Although both IBM's WebSphere and BEA's WebLogic support other languages. you are in for a frustrating experience Language In the language arena. It will provide much better performance at a much lower cost. In fact.NET platform. it is likely that any language that comes out in the near future will include support for the . moving from one operating system to another should be possible. neither does it through their J2EE technology. It is worth noting. It will not support any other language in the foreseeable future. J2EE offers an acceptable solution to ISVs when the product must be marketed to non-Windows customers. no matter what [J2EE] vendor you choose.com 65 Page . Satish Marwat Dot Net Web Resources satishcm@gmail. The . This is probably the single most important benefit in favor of J2EE over the .NET platform supports every language except Java (although it does support a language that is syntactically and functionally equivalent to Java. There are only two official ways in the J2EE platform to access other languages.NET platform should be chosen. then the . Portability The reason that operating system portability is a possibility with J2EE is not so much because of any inherent portability of J2EE.NET Framework (called the common language infrastructure) to ECMA.Moreover. and only Java. one through the Java Native Interface and the other through CORBA interoperability. as it is that most of the J2EE vendors support multiple operating systems. however. which is limited to the Windows operating system. Some companies are under the impression that J2EE supports other languages. if you expect a component framework that will allow you to quickly field complete e-business applications. Therefore as long as one sticks with a given J2EE vendor and a given database vendor. the choice is about as simple as it gets. that Microsoft has submitted the specifications for C# and a subset of the .NET platform as a language independent vehicle. Sun recommends the later approach. C#).NET platform. J2EE supports Java. given the importance of the . If the primary customer base for the ISV is Windows customers. The . not the programmer.com 66 Page . It is open in the sense that any company can license and implement the technology.NET platform vision is a family of products rather than specifications. Their are several important advantages to the . with the proved ability to support at least ten times the number of clients any J2EE platform has shown itself able to support.NET Framework approach is to write device independent code that interacts with visual controls. One of J2EE's major advantages is that most of the J2EE vendors do offer operating system portability. * The cost of running applications is much lower.NET control. and with .NET platform: * The cost of developing applications is much lower. This Java approach has three problems. it is very difficult to add new thin clients to an existing application. Third. it is very difficult to test the code with every possible thin client system. since to do so involves searching through.Client device independence The major difference being that with Java. It is the control. and modifying a tremendous amount of presentation tier logic. it is the presentation tier programmer that determines the ultimate HTML that will be delivered to the client. it requires a lot of code on the presentation tier. Second. one can forget that such a thing as HTML even exists! Sun's J2EE vision is based on a family of specifications that can be implemented by many vendors.. based on the capabilities of the client device. since commodity hardware platforms (at 1/5 the cost of their Unix counterparts) can be used. since every possible thin client system requires a different code path. The major disadvantage of this approach is that if is limited to the Windows platform.NET platforms. * The ability to scale up is much greater. First.NET Framework model. since standard business languages can be used and device independent presentation tier logic can be written. it is a Visual Studio. One of J2EE's major disadvantages is that the choice of the platform dictates the use of a single programming language. In the . and a programming language that is not well suited for most businesses. Satish Marwat Dot Net Web Resources satishcm@gmail.NET. so applications written for the . but closed in the sense that it is controlled by a single vendor. with specifications used primarily to define points of interoperability. and a self contained architectural island with very limited ability to interact outside of itself. Microsoft's .NET platform can only be run on . that is responsible for determining what HTML to deliver. Metadata and Self-Describing Components Explains how the . into all modules and assemblies. which are collections of types and resources that form logical units of functionality.NET.NET Framework simplifies component interoperation by allowing compilers to emit additional declarative information. and security permissions.com 67 Page . . and shell executables.NET Platform are :Common Language Runtime Explains the features and benefits of the common language runtime. version control. or metadata. reuse.NET Framework. . Cross-Language Interoperability Explains how managed objects created in different programming languages can interact with one another. Application Domains Explains how to use application domains to provide isolation between applications.NET Framework. a runtime environment that manages the execution of code and provides services that simplify the development process. including ASP. Satish Marwat Dot Net Web Resources satishcm@gmail. Runtime Hosts Describes the runtime hosts supported by the . Common Type System Identifies the types supported by the common language runtime.* Interoperability is much stronger. What are the Main Features of .NET Framework Class Library Introduces the library of types provided by the . which expedites and optimizes the development process and gives you access to system functionality. Assemblies Defines the concept of assemblies. with industry standard eCollaboration built into the platform.NET platform? Features of . Internet Explorer.NET Framework Security Describes mechanisms for protecting resources and code from unauthorized code and unauthorized users. Assemblies are the fundamental units of deployment. activation scoping. JIT compilation takes into account the fact that some code might never get called during execution. the stub passes control to the JIT compiler. developers can write a set of MSIL that can be JIT-compiled and run on computers with different architectures. All managed types and resources are marked either as accessible only within their implementation unit. Subsequent calls of the JIT-compiled method proceed directly to the native code that was previously generated. C:\winnt\Assembly in explore.Time) is a compiler which converts MSIL code to Native Code (ie. or a platform-specific class library.In . We can register the assembly to global assembly cache by using gacutil command. which converts the MSIL for that method into native code and modifies the stub to direct execution to the location of the native code. The loader creates and attaches a stub to each of a type's methods when the type is loaded. In the tools menu select the cache properties. We can Navigate to the GAC directory. or as accessible by code outside that unit. your managed code will run only on a specific operating system if it calls platform-specific native APIs.An assembly is the primary building block of a . it converts the MSIL as needed during execution and stores the resulting native code so that it is accessible for subsequent calls. versioned. GAC is a machine wide a local cache of assemblies maintained by the . Assembly :-. On the initial call to the method.Assemblies can be shared among multiple applications on the machine by registering them in global Assembly cache(GAC).NET based application.NET Framework.The . Because the common language runtime supplies a JIT compiler for each supported CPU architecture. and deployed as a single implementation unit (as one or more files). It overcomes the problem of 'dll Hell'. This Manifest contains Metadata information of the Module/Assembly as well as it contains detailed Metadata Satish Marwat Dot Net Web Resources satishcm@gmail. It is a collection of functionality that is built. Rather than using time and memory to convert all the MSIL in a portable executable (PE) file to native code. in the windows displayed you can set the memory limit in MB used by the GAC MetaData :--Assemblies have Manifests. What meant of assembly & global assembly cache (gac) & Meta data.NET Framework uses assemblies as the fundamental unit for several purposes: • • • • • Security Type Identity Reference Scope Versioning Deployment Global Assembly Cache :-..com 68 Page .What is the use of JIT ? JIT (Just . However. reducing the time it takes to JIT-compile and run the code. CPU-specific code that runs on the same computer architecture). The easiest way to develop and test a Smart Device Application is to use an emulator. For instance. What is GUID .).e..g.com 69 Page .GUID is Short form of Globally Unique Identifier. network MAC address. clock date/time. a Web site may generate a GUID and assign it to a user's browser to record and track the session.NET supports two modes of page development: Page logic code that is written inside blocks within an .of other assemblies/modules references (exported). and/or user. its physical location. It's the Assembly Manifest which differentiates between an Assembly and a Module. A GUID is also used in a Windows registry to identify COM DLLs. an IP address. etc. These devices are divided into two main divisions: 1) Those that are directly supported by . information in the type library. application. i-Mode phones. why we use it and where? GUID :-. What are the mobile devices supported by . GUIDs can be created in a number of ways.aspx file at run time. etc. and WAP devices) 2) Those that are not (Palm OS and J2ME-powered devices). Some database administrators even will use GUIDs as primary key values in databases. Personal Digital Assistants (PDAs).net platform The Microsoft .. Describe the difference between inline and code behind . a unique 128-bit number that is produced by the Windows OS or by some Windows applications to identify a particular component.NET Compact Framework is designed to run on mobile devices such as mobile phones. Satish Marwat Dot Net Web Resources satishcm@gmail. but usually they are a combination of a few unique settings based on specific point in time (e. database entry.aspx file and dynamically compiled the first time the page is requested on the server. Windows also identifies user accounts by a username (computer/domain and username) and assigns it a GUID. Page logic code that is written within an external class that is compiled prior to deployment on a server and linked ""behind"" the .which is best in a loosely coupled solution ASP. file. Knowing where to look in the registry and having the correct GUID yields a lot information about a COM object (i. and embedded devices.).NET (Pocket PCs. An assembly is a collection of types and resources that are built to work together and form a logical unit of functionality. version control. An assembly provides the common language runtime with the information it needs to be aware of type implementations. It converts the MSIL as needed whilst executing. format.NET DLL contain? One What type of code (server or client) is found in a Code-Behind class? Server Whats an assembly? Assemblies are the building blocks of . must be converted by the . or other characteristics of a data source. Microsoft intermediate language (MSIL) is a translation used as the output of a number of compilers. In . reuse. activation scoping."" Such information might include details on content. version information. This is CPU-specific code that runs on the same computer architecture as the JIT compiler. then caches the resulting native code so its accessible for any subsequent calls How many . external assembly references.NET.Whats MSIL. It is the input to a just-in-time (JIT) compiler.com 70 Page . This is a CPUindependent set of instructions that can efficiently be converted to native code.NET DLL contain? Unlimited. and other standardized information.NET Framework applications. Satish Marwat Dot Net Web Resources satishcm@gmail. metadata includes type definitions. What is metadata? Metadata is machine-readable information about a resource. Rather than using time and memory to convert all of the MSIL in a portable executable (PE) file to native code. size. What is the difference between string and String ? No difference What is manifest? It is the metadata that describes the assemblies. The Common Language Runtime includes a JIT compiler for the conversion of MSIL to native code. How many classes can a single . To the runtime.NET Framework just-in-time (JIT) compiler to native code. they form the fundamental unit of deployment.NET languages can a single . the compiler translates the source into Microsoft intermediate language (MSIL). and security permissions. or ""data about data. and why should my developers need an appreciation of it if at all? When compiling the source code to managed code. a type does not exist outside the context of an assembly. Before Microsoft Intermediate Language (MSIL) can be executed it. NET: Static assemblies These are the . When do you use virutal keyword?. which means that their implementation can be overridden in derived classes.NET PE files that you create at compile time. Public or shared assemblies These are static assemblies that must have a unique shared name and can be used by any application. While the CLR doesn't enforce versioning policies-checking whether the correct version is used-for private assemblies. an application uses a specific shared assembly by referring to the specific shared assembly.What are the types of assemblies? There are four types of assemblies in . When we need to override a method of the base class in the sub class. then we give the virtual keyword in the base class method. Thus.NET. an assembly is the smallest unit to which you can associate a version number. Methods. properties. delegates are type-safe and secure. What are delegates?where are they used ? A delegate defines a reference type that can be used to encapsulate a method with a specific signature. In . Dynamic assemblies These are PE-formatted. An application uses a private assembly by referring to the assembly using a static path or through an XML-based application configuration file.com 71 Page . however. A delegate instance encapsulates a static or an instance method. Private assemblies These are static assemblies used by a specific application.Reflection.Emit namespace. it ensures that an application uses the correct shared assemblies with which the application was built. and the CLR ensures that the correct version is loaded at runtime. Satish Marwat Dot Net Web Resources satishcm@gmail. and indexers can be virtual. This makes the method in the base class to be overridable. Delegates are roughly similar to function pointers in C++. in-memory assemblies that you dynamically create at runtime using the classes in the System. · Protected .Access is limited to the current assembly or types derived · from the containing class. · Protected inertnal . · Internal .Unboxing is an explicit conversion from the type object to a value type Eg: int i = 123. referred to as objects. This section introduces the four access modifiers: · Public .Access is limited to the current assembly. Boxing Conversion UnBoxing :. The value types consist of two main categories: * Stuct Type * Enumeration Type Reference Type :Variables of reference types. // Boxing int j = (int)box.Access is limited to the containing class or types derived from the containing class. // Unboxing What is Value type and refernce type in .Access is limited to the containing type.com 72 Page . Value Type : A variable of a value type always contains a value of that type.Access is not restricted.Boxing is an implicit conversion of a value type to the type object type Eg:Consider the following declaration of a value-type variable: int i = 123. The assignment to a variable of a value type creates a copy of the assigned value.Net?.What are class access modifiers ? Access modifiers are keywords used to specify the declared accessibility of a member or a type. // A value type object box = i. while the assignment to a variable of a reference type creates a copy of the reference but not of the referenced object. This section introduces the following keywords used to declare reference types: * Class * Interface * Delegate This section also introduces the following built-in reference types: * object * string Satish Marwat Dot Net Web Resources satishcm@gmail. What Is Boxing And Unboxing? Boxing :. · Private . object o = (object) i. store references to the actual data.. structs are value types and do not require heap allocation. This information is called as Assembly Manifest. How do you create shared assemblies?. They are derived from System. This is very similar to packages in Java as far as scoping is concerned. * Every assembly file contains information about itself. They are unique types that allow to declare symbolic names to integral values. Enums are value types. Satish Marwat Dot Net Web Resources satishcm@gmail. whereas a variable of a class type contains a reference to the data..What is the difference between structures and enumeration?. it tracks through each of the different imported namespaces to the type name and searches each referenced assembly until it is found. Just look through the definition of Assemblies. C } What is namespaces?. It seems as if these directives specify a particular assembly. public enum Grade { A. A namespace can span multiple assemblies.ValueType class. but they don't.com 73 Page . Namespace is a logical naming scheme for group related types. When the compiler needs the definition for a class type. text files etc.They are strongly typed constants. and an assembly can define multiple namespaces. They are imported as "using" in C# or "Imports" in Visual Basic. A variable of a struct type directly contains the data of the struct. can't inherit or be inherited from and assignment copies the value of one enum to another. B. They prevent namespace collisions and they provide scoping. Enum->An enum type is a distinct type that declares a set of named constants. Namespaces can be nested.Some class types that logically belong together they can be put into a common namespace. Unlike classes. * An Assembly is a logical unit of code * Assembly physically exist as DLLs or EXEs * One assembly can contain one or more files * The constituent files can include any file types like image files. which means they contain their own value. initializing. The presence of metadata in the file along with the MSIL enables your code to describe itself. exception handling. There are several ways to deploy an assembly into the global assembly cache: · Use an installer designed to work with the global assembly cache. storing. the compiler translates your source code into Microsoft intermediate language (MSIL). including the definition of each type. enables the operating system to recognize common language runtime images. The MSIL and metadata are contained in a portable executable (PE) file that is based on and extends the published Microsoft PE and common object file format (COFF) used historically for executable content. control flow. · Use a developer tool called the Global Assembly Cache tool (Gacutil. This file format. When a compiler produces MSIL. which accommodates MSIL or native code as well as metadata. it also produces metadata. direct memory access. · Use Windows Explorer to drag assemblies into the cache. provided by the . The runtime locates and extracts the metadata from the file as needed during execution. the signatures of each type's members. Before code can be run. usually by a justin-time (JIT) compiler.exe). and other operations. MSIL includes instructions for loading. The global assembly cache stores assemblies specifically designated to be shared by several applications on the computer. which means that there is no need for type libraries or Interface Definition Language (IDL). and other data that the runtime uses at execution time.com 74 Page . What is MSIL?. Satish Marwat Dot Net Web Resources satishcm@gmail. Metadata describes the types in your code. When compiling to managed code. the members that your code references. MSIL must be converted to CPU-specific code. which is a CPU-independent set of instructions that can be efficiently converted to native code. This is the preferred option for installing assemblies into the global assembly cache.NET Framework SDK. the same set of MSIL can be JIT-compiled and run on any supported architecture. as well as instructions for arithmetic and logical operations. Because the common language runtime supplies one or more JIT compilers for each computer architecture it supports. and calling methods on objects. .it converts the language that you write in ... A listener is an object that receives the trace output and outputs it somewhere. Functionality of these functions is same except that the target media for the tracing output is determined by the Trace Listener. or any other customized data store. a Windows Event log. edit the application's web. that somewhere could be a window in your development environment.To set ASP. All Trace Listeners have the following functions.com 75 Page . In . < / configuration > Satish Marwat Dot Net Web Resources satishcm@gmail. You can analyze these log files to find the cause of the errors.how many are available in clr? Just-In-Time compiler. a file on your hard drive.config and assign the "debug" attribute in < compilation > section to "true" as show below: < configuration > < system. classes. Method Name Result Fail Outputs the specified text with the Call Stack.Diagnostics namespace provides two classes named Trace and Debug that are used for writing errors and application execution information in logs.. You use tracing information to troubleshoot an application. The System. Flush Flushes the output buffer to the target media. there are tqo types of JITs one is memory optimized & other is performace optimized. enumerations and structures that are used for tracing The System.NET appplication in debugging mode.NET applications . . Tracing allows us to observe and correct programming errors.Net into machine language that a computer can understand. a SQL Server or Oracle database. WriteLine Outputs the specified text and a carriage return.NET we have objects called Trace Listeners. Write Outputs the specified text. Close Closes the output stream in order to not receive the tracing/debugging output How to set the debug mode? Debug Mode for ASP.web > < compilation . What is tracing?Where it used.What is Jit compilers?. Tracing enables you to record information in various log files about the errors that might occur at run time....Explain few methods available Tracing refers to collecting information about the application while it is running.Diagnostics namespace provides the interfaces. com 76 Page . read-only cursor for processing an XML document stream. Debug Mode for ASP. to ascertain whether the page is posted. Satish Marwat Dot Net Web Resources satishcm@gmail.NET is similar to the debugging an ASP. you can derive an class/interface from multiple interfaces.NET Web application. That means a class can only derived from one class. The Page. XmlReader and XMLWriter are the two abstract classes at the core of .NET Framework XML classes: 1. i. Which are the abstract classes available under system.NET to generate symbols for dynamically generated files and enables the debugger to attach to the ASP. Both XmlReader and XmlWriter are abstract base classes.NET will detect this change automatically.NET supports only multiple type/interface inheritance.IsPostBack property facilitates execution of certain routine in Page_Load. we check for true value for IsPostback value and then invoke server-side code to update data). which define the functionality that all derived classes must support. C# & VB. There are two types of multiple inheritance: multiple type/interface inheritance and multiple implementation inheritance. while its value is False. 2.XML namespace provides XML related processing ability in . The value of Page. forward-only.NET framework.net? Multiple Inheritance is an ability to inherit from more than one base class i.This case-sensitive attribute 'debug tells ASP.IsPostBack is True. XmlWriter provides an interface for producing XML document streams that conform to the W3C's XML standards.IsPostBack gets a value indicating whether the page is being loaded in response to the client postback. Is it possible to use multipe inheritance in . when page is loaded for the first time.NET application. What is the property available to check if the page posted or not? The Page_Load event handler in the page checks for IsPostBack property value. ASP.NET.e. On post back. XmlReader provides a fast. without the need to restart the server.e. The Page.xml namespace? The System.g. only once (for e.Debugging an XML Web service created with ASP. when the page is loaded for the first time. if the page is being loaded in response to the client postback.NET Webservices . ability of a class to have more than one superclass. we need to set default value in controls. by inheriting from different sources and thus combine separately-defined behaviors in a single class. or it is for the first time. in Page load. There is no support for multiple implementation inheritance in . Code that runs outside the CLR is referred to as "unmanaged code. calendar. Using Satellite assemblies.NET framework provides several core run-time services to the programs that run within it ..for example exception handling and security. code executing under the control of the CLR is called managed code.XmlNodeReader 3." COM components.NET is managed code. Satish Marwat Dot Net Web Resources satishcm@gmail.XmlTextReader 2. others are use and the setup projects in . sorting rules. 1.XmlValidatingReader There are two concrete implementations of XmlWriter: 1. For these services to work.NET assemblies? One way is simply use xcopy.com 77 Page . What is managed and unmanaged code? The . Detect and redirect 2. For example. date and time format. Run-time adjustment 3.e. i.XmlNodeWriter XmlTextReader and XmlTextWriter support reading data to/from text-based stream.net. How you deploy .XmlTextWriter 2. and one more way is use of nontuch deployment. This can be achieved by using any of the following 3 approaches. There are three concrete implementations of XmlReader: 1. writing direction. any code written in C# or Visual Basic . What is Globalizationa and Localization ? Globalization is the process of creating an application that meets the needs of users from multiple cultures. while XmlNodeReader and XmlNodeWriter are designed for working with in-memory DOM tree structure. and Win32 API functions are examples of unmanaged code. and other issues. ActiveX components. Accommodating these cultural differences in an application is called localization.Using classes of System. which define the functionality that all derived classes must support. the code must provide a minimum level of information to the runtime.Globalization namespace.What are the derived classes from xmlReader and xmlWriter? Both XmlReader and XmlWriter are abstract base classes. The custom readers and writers can also be developed to extend the built-in functionality of XmlReader and XmlWriter. It includes using the correct currency. you can set application's current culture. NET we basically require them storing culture specific informations by localizing application's resources.Whate are Resource Files ? How are they used in . you just want to make sure the state of the bike is changed to 'running' afterwards. The GC calls this method when it founds no more references to the object. Satish Marwat Dot Net Web Resources satishcm@gmail. For instance. A GUID is a 128-bit integer (16 bytes) that can be used across all computers and networks wherever a unique identifier is required.Key word public sealed class Planet { //code goes here } class Moon:Planet { //Not allowed as base class is sealed } What is GUID and why we need to use it and in what condition? How this is created. Such an identifier has a very low probability of being duplicated. Difference between Dispose and Finallize method? Finalize method is used to free the memory used by some unmanaged resources like window handles (HWND).com 78 Page .These files can contain data in a number of formats including strings. What is encapsulation ? Encapsulation is the ability to hide the internal workings of an object's behavior and its data.NET IDE has a utility under the tools menu to generate GUIDs. images and persisted objects. In . But.NET? Resource files are the files containing data that is logically deployed with an application. Visual Studio . When you create an instance of a Bike object and call its start() method you are not worried about what happens to accomplish this. In some cases we may need release the memory used by the resources explicitely. It's similar to the destructor syntax in C#. You can deploy your resources using satellite assemblies. let's say you have a object named Bike and this object has a method named start(). It has the main advantage of If we store data in these files then we don't need to compile these if the data get changed.To release the memory explicitly we need to implement the Dispose method of IDisposable interface. This kind of behavior hiding is encapsulation and it makes programming much easier. How can you prevent your class to be inherated further? By setting Sealed . native Win32. using System.versioning Managed code is compiled for the .NET Framework.? We need to serialize the object. What's involved in certain piece of code being managed? "Advantage includes automatic garbage collection.Schema can be an external file which uses the XSD or XDR extension called external schema.This is useful when it is inconvenient to physically seprate the schema and the XML document. Unmanaged code includes all code written before the .NET Framework was introduced—this includes code written to use COM. and relationships of the elements that constitute the data contained inside the XML document or in another XML document.type checking.The ISerializable interface allows you to make any class Serializable. namespace SampleMultiCastDelegate{ class MultiCast{ public delegate string strMultiCast(string s). 1. It runs in the Common Language Runtime (CLR). Describe the advantages of writing a managed code application instead of unmanaged one. how does it works? Schemas can be included inside of XML file is called Inline Schemas. which is the heart of the ..A schema is an XML document that defines the structure.com 79 Page . data types.if you want to pass object from one computer/application domain to another. Inline schema can take place even when validation is turned off.Why do you need to serialize. } } Satish Marwat Dot Net Web Resources satishcm@gmail. The CLR provides services such as security. constraints.Binary Serialization 2.Process of converting complex objects into stream of bytes that can be persisted or transported. and Visual Basic 6.Serialization. and take better advantage of developers existing expertise in languages that support the . memory management.Runtime. Because it does not run inside the .Namespace for serialization is System.security.NET framework features 2 serializing method. and cross-language integration.NET Framework. unmanaged code cannot make use of any . Managed applications written to take advantage of the features of the CLR perform more efficiently and safely.NET environment.NET run-time environment.memory management.NET managed facilities.XML Serialization What is inline schema." What are multicast delegates ? give me an example ? Delegate that can have more than one element in its invocation List. namespace SampleMultiCastDelegate { public class MainMultiCastDelegate { public static void Main() { MultiCast. MultiCast.WriteLine("Run"). return String. } public static string Run(string s) { Console.com 80 Page . Satish Marwat Dot Net Web Resources satishcm@gmail. using System. } } } The Main class: using System.strMultiCast Run. return String. using System.WriteLine("Walk"). } public static string Walk(string s) { Console.Jump.Walk.Empty.MainClass defines the static methods having same signature as delegate.WriteLine("Jump").Threading. namespace SampleMultiCastDelegate { public class MainClass { public MainClass() { } public static string Jump(string s) { Console.Empty.Empty.strMultiCast myDelegate. return String. A process can have multiple Thread. and if those classes have been marked as serializable.Walk). Difference between int and int32 ? Both are same. but I personally prefer strong typing because I like my errors to be found as soon as possible. each thread gets a memory for storing the variables in it and plus they can access to the global variables which is common for all the thread. System. What is the difference between an EXE and a DLL? You can create an objects of Dll but not of the EXE. Dll is an In-Process Component whereas EXE is an OUt-Process Component.com 81 Page . And a thread is the Execution stream of the Process. and are implicitly converted as required.NET class. Eg. } } } Can a nested object be used in Serialization ? Yes. weak typing implies that they are associated to the value. checked at compile-time.Combine(Run. then their objects are serialized too.Int32 is a .) Satish Marwat Dot Net Web Resources satishcm@gmail. Exe can be started as standalone where dll cannot be.A Microsoft Word is a Application.an instance of the Word starts and a process is allocated to this instance which has one thread.Int32. What is strong-typing versus weak-typing? Which is preferred? Why? Strong typing implies that the types of variables involved in operations are associated to the variable. Describe the difference between a Thread and a Process? A Process is an instance of an running application. Int is an alias name for System. and require explicit conversion. When you open a word file.strMultiCast)System. If a class that is to be serialized contains references to objects of other classes. When there is multiple thread in a process.MulticastDelegate ///and the delegates combine myDelegate=(MultiCast. Exe is for single use whereas you can use Dll for multiple use.Delegate. (Which is preferred is a disputable point.///here mydelegate used the Combine method of System. checked at run-time. When a process starts a specific memory area is allocated to it. However it is not necessary to install assemblies into the global assembly cache to make them accessible to COM interop or unmanaged code.exe).NET Framework SDK. our Windows debugger does the things required to find out What is the GAC? What problem does it solve? Each computer where the common language runtime is installed has a machine-wide code cache called the global assembly cache. How do you get the PID to appear? In Task Manger. This ensures that the applications which access a particular assembly continue to access the same assembly even if another version of that assembly is installed on that machine. Satish Marwat Dot Net Web Resources satishcm@gmail. Microsoft has launched a SDK called as Microsoft Operations Management (MOM).What is a PID? How is it useful when troubleshooting a system? PID is the process Id of the application in Windows. GAC can hold two assemblies of the same name but different version. Unlike earlier situations. Whenever a process starts running in the Windows environment.com 82 Page . Personally I have never used a PID. In Linux. · Use Windows Explorer to drag assemblies into the cache. This area is typically the folder under windows or winnt in the machine. provided by the . The PID (Process ID) a unique number for each item on the Process Tab. There are several ways to deploy an assembly into the global assembly cache: · Use an installer designed to work with the global assembly cache. All the assemblies that need to be shared across applications need to be done through the Global assembly Cache only. This is essentially helpful in situations where the Process which has a memory leak is to be traced to a erring dll. GAC solves the problem of DLL Hell and DLL versioning. it is associated with an individual process Id or PID. The global assembly cache stores assemblies that are to be shared by several applications on the computer. then select columns and check PID (Process Identifier). PID is used to debug a process explicitly. · Use a developer tool called the Global Assembly Cache tool (Gacutil. This is the preferred option for installing assemblies into the global assembly cache. However we cannot do this in a windows environment. This uses the PID to find out which dll’s have been loaded by a process in the memory. Image Name list. select the View menu. If a class implements an interface. This is enforced by the compiler. What is the difference between XML Web Services using ASMX and . while . The syntax for creating interfaces follows: interface Identifier { InterfaceBody } Identifier is the name of the interface and InterfaceBody refers to the abstract methods and static final variables that make up the interface.Xml. • Interface should provide high level abstraction from the implementation.Describe what an Interface is and how it’s different from a Class.NET Web services rely on the System. Because it is assumed that all the methods in an interface are abstract. the syntax typically looks similar to a class definition. Serialization and Metadata ASP.NET remoting . Broadly the differentiators between classes and interfaces is as follows • Interface should not have any implementation. except that there's no code defined for the methods — just their name. then it must have the properties and methods of the interface defined in the class. But you create an interface so that classes will implement it. • Interface can have multiple inheritances. In general.com 83 Page . But what does it mean to implement an interface. In practice. Interfaces provide a means to define the protocols for a class without worrying about the implementation details.NET Remoting is designed for common language runtime type-system fidelity and supports additional data format and communication channels.Net framework is requried which may or may not present for the other platform.NET Web services and . • Default access level of the interface is public. it isn't necessary to use the abstract keyword An interface is a description of some of the members available from a class.NET Remoting provide a full suite of design options for cross-process and cross-plaform communication in distributed applications.Serialization.XmlSerializer Satish Marwat Dot Net Web Resources satishcm@gmail. ASP. The interface acts as a contract or promise. So what good is it? None by itself. Hence if we looking cross-platform communication than web services is the choice coz for . An interface is a prototype for a class and is useful from a logical design perspective. An interface is a structure of code which is similar to a class. • Interface can not create any instance.NET Web services provide the highest levels of interoperability with full support for WSDL and SOAP over HTTP.NET Remoting using SOAP? ASP. the arguments passed and the type of the value returned. . Messages can be sent over either channel independent of format. In addition to pluggable formatters. The reliance on pure WSDL and XSD makes ASP.Binary.NET leverages the security features available with IIS to provide strong support for standard HTTP authentication schemes including Basic. which abstract away the details of how messages are sent. it includes all of a class's public and private members. and provide a simple programming model with broad cross-platform reach.Serialization. Security Since ASP. marshal types in binary and SOAP format respectively.NET Remoting layer supports pluggable channels. digital certificates.Collections. this imposes constraints on the types you can expose from a Web service—XmlSerializer will only marshal things that can be expressed in XSD. However.NET constructs in order to communicate with a . and expose it via reflection. security.NET Remoting relies on the common language runtime assemblies. As a result. For metadata.Serialization. Distributed Application Design: ASP.NET Web services rely on HTTP. and even Microsoft® . performance. . it expresses data structures in a way that other Web service toolkits on different platforms and with different programming models can understand. The reliance on the assemblies for metadata makes it easy to preserve the full runtime type-system fidelity.NET Web Services vs.NET Passport. (You can also use Windows Integrated authentication. the reliance on runtime metadata also limits the reach of a . However.Runtime.Serialization engine to marshal data to and from messages. Specifically. including transport protocols.Hashtable).Runtime. but Satish Marwat Dot Net Web Resources satishcm@gmail. handles object graphs correctly. There are two standard channels. and support for transactions to consider as well.BinaryFormatter and System. In some cases.class to marshal data to and from SOAP messages at runtime.NET Remoting favors the runtime type system.g. the . host processes. System. There are two standard formatters. The BinaryFormatter and SoapFormatter.NET Remoting plumbing marshals data. one for raw TCP and one for HTTP. as the names suggest.Soap.NET Remoting system—a client has to understand . state management. they integrate with the standard Internet security infrastructure.NET Web services metadata portable.com 84 Page . For metadata. System.Runtime.NET Web services favor the XML Schema type system.NET Remoting relies on the pluggable implementations of the IFormatter interface used by the System.Formatters. .NET Remoting ASP.SoapFormatter. . which contain all the relevant information about the data types they implement. there are a wide range of other design factors.NET Remoting endpoint. This essential difference is the primary factor in determining which technology to use. Digest.Formatters. XmlSerializer will not marshal object graphs and it has limited support for container types. they generate WSDL and XSD definitions that describe what their messages contain. and provides a more complex programming model with much more limited reach. and supports all container types (e.. when the . ASP. Although these standard transport-level techniques to secure Web services are quite effective.NET Remoting proxy from a semi-trusted environment.NET code access security (CAS) infrastructure.NET Web Services are a simpler choice because security policy changes are not required.NET also provides support for . you need a special serialization permission that is not given to code loaded from your intranet or the Internet by default. message integrity. you have to alter the default security policy for code loaded from those zones. In order to use a .NET Web Services client proxies work in these environments. ASP.NET Remoting proxies do not. for instance—ASP. and by integrating with the . which defines a framework for messagelevel credential transfer.NET Remoting endpoint hosted in IIS with ASP. including support for secure communication over the wire using SSL. IIS performs authentication before the ASP. what is the difference between early-binding and late-binding? Early binding – Binding at Compile Time Late Binding – Binding at Run Time Early binding implies that the class of the called object is known at compiletime. If you are using the TCP channel or the HTTP channel hosted in processes other than aspnet_wp. As noted in the previous section. you have to implement authentication.NET Web services are called.exe. and message confidentiality.) One advantage of using the available HTTP authentication schemes is that no code change is required in a Web service.NET Web services. you have to build custom ad hoc solutions. late-binding implies that the class is not known until run-time. One additional security concern is the ability to execute code from a semitrusted environment without having to change the default security policy. but . authorization and privacy mechanisms yourself. such as a call through an interface or via Reflection.only for clients in a trusted domain.NET can leverage all the same security features available to ASP.NET Remoting plumbing does not secure cross-process invocations in the general case. If you want to use a . Conceptually.NET Passport-based authentication and other custom authentication schemes. the . A . SSL can be used to ensure private communication over the wire. they only go so far.NET supports access control based on target URLs.NET Remoting client from within a semi-trusted environment. ASP. Microsoft and others are working on a set of security specifications that build on the extensibility of SOAP messages to offer message-level security capabilities.com 85 Page . In situations where you are connecting to systems from clients running in a sandbox—like a downloaded Windows Forms application. ASP. One of these is the XML Web Services Security Language (WS-Security). Satish Marwat Dot Net Web Resources satishcm@gmail. In complex scenarios involving multiple Web services in different trust domains. It is the best performer because your application binds directly to the address of the function being called and there is no extra overhead in doing a run-time lookup. System. either by accident or intentionally. thus making it unique.3300. These strong names are created by a . In general.XmlDocument. (""System. What is an Asssembly Qualified Name? Is it a filename? How is it different? An assembly qualified name isn't the filename of the assembly.Early binding is the preferred method. When resolving a reference to an assembly. Visual Basic also warns you if the data type of a parameter or return value is incorrect. signs the file containing the manifest with the private key.0.NET utility – sn. it is at least twice as fast as late binding. and makes the public key available to callers. Strong names are implemented using standard public key cryptography.exe Strong names have three goals: · Name uniqueness. strong names are used to guarantee the assembly that is loaded came from the expected publisher.0 CallByName function for example) then you need to use late binding. If your application seeks to talk with multiple unknown servers or needs to invoke functions by name (using the Visual Basic 6. and public key. it's the internal name of the assembly combined with the assembly version. Visual Basic provides IntelliSense support to help you code each function correctly. Early binding also provides type safety. Shared assemblies must have names that are globally unique. When you have a reference set to the component's type library.0. · Provide identity on reference.Xml. Late binding is still useful in situations where the exact interface of an object is not known at design-time. saving a lot of time when writing and debugging code. PublicKeyToken=b77a5c561934e089"") How is a strongly-named assembly different from one that isn’t strongly-named? Strong names are used to enable the stricter naming requirements associated with shared assemblies. Late binding is also useful to work around compatibility problems between multiple versions of a component that has improperly modified or adapted its interface between versions. In terms of overall execution speed. culture. Developers don't want someone else releasing a subsequent version of one of your assemblies and falsely claim it came from you.g. When Satish Marwat Dot Net Web Resources satishcm@gmail.Xml. the process works as follows: The author of an assembly generates a key pair (or uses an existing one). Culture=neutral. · Prevent name spoofing. Version=1.com 86 Page . e. enabling that object to release any unmanaged resources it holds. it starts by assuming everything to be garbage. even if it does so by an exception being thrown. then goes through and builds a list of everything reachable. and thus that resources are always released.references are made to the assembly. However. What makes it generational is that every time an object goes through this process and survives. whereas there is no guarantee that Finalize() will be called immediately when an object goes out of scope . Non-deterministic finalization implies that the destructor (if any) of an object will not necessarily be run (nor its memory cleaned up. When the garbage-collector is trying to free memory. Those become not-garbage.and as such Dispose() is generally preferred.note the usually there. and if the process ends before this happens.) What is the difference between Finalize() and Dispose()? Dispose() is called by the user of an object to indicate that he is finished with it. and then the finalisation queue empties down to it. Instead. and gets thrown away. everything else doesn't. if the program ends before that object is GCed . Strong naming prevents tampering and enables assemblies to be placed in the GAC alongside other assemblies of the same name. Weak named assemblies are not suitable to be added in GAC and shared. it may not be finalised at all. Dispose() operates determinalistically. on the grounds that shorter-lived objects are more likely to have been freed than longer-lived ones. it will wait until first the garbage collector gets around to finding it. it starts with the lowest generation (0) and only works up to higher ones if it can't free up enough space.com 87 Page . (Although the operating system will usually clean up any process-external resources left open . it is noted as being a member of an older generation (up to 2. Finalize() is called by the run-time to allow an object which has not had Dispose() called on it to do the same. right now). and thus the Dispose() method) goes out of scope. How is the using() pattern useful? What is IDisposable? How does it support deterministic finalization? The using() pattern is useful because it ensures that Dispose() will always be called when a disposable object (defined as one that implements IDisposable. but that's a relatively minor issue) immediately upon its going out of scope. the caller records the public key corresponding to the private key used to generate the strong name. especially as the exceptions tend to hurt a lot. It is essential for an assembly to be strong named. How does the generational garbage collector in the .NET CLR manage object lifetime? What is non-deterministic finalization? The hugely simplistic version is that every time it garbage-collects.or indeed at all. Satish Marwat Dot Net Web Resources satishcm@gmail. pdb. SkipVerification.NET Framework existed.1.There are several different types of symbolic debugging information. If anyone were to lock down the security policy by changing the grant set of the local machine to something less than FullTrust.com 88 Page .0 and VC70. This old model was a binary trust model. and if your assembly did not get extra Satish Marwat Dot Net Web Resources satishcm@gmail.NET include FullTrust. LocalIntranet. which in nearly all cases means "all the . or it wouldn't run at all. Note that the Visual C++ compiler by default creates an additional PDB file called VC60. unmanaged code. like a traditional ActiveX control. you can think of fully trusted code as being similar to native. the fact that assemblies in the GAC seem to always get a FullTrust grant is actually a side effect of the fact that the GAC lives on the local machine. The linker can merge this temporary PDB file into the main one if you tell it to. What is FullTrust? Do GAC’ed assemblies have FullTrust? Before the .PDB file for VisulaC++7.NET program with /debug. Internet and Everything.But If the string is not a valid DateTime.pdb for VisulaC++6. What are PDBs? Where must they be located for debugging to work? A program database (PDB) files holds debugging and project state information that allows incremental linking of debug configuration of your program. A PDB file is a separate file. GAC assemblies are granted FullTrust. The permission sets in . In v1. placed by default in the Debug project subdirectory. The PDB file can be useful to display the detailed stack trace with source files and line numbers. What’s wrong with a line like this? DateTime. The compiler setting for creating this file is /Zi. but it won't do it by default. The compiler creates this file during compilation of the source code. nonprivileged user cannot do administrative tasks. The code could either do anything you could do. Fully trusted code run by a normal.What does this useful command line do? tasklist /m "mscor*" Lists all the applications and associated tasks/process currently running on the system with a module whose name begins "mscor" loaded into them.Converts the specified string representation of a date and time to its DateTime equivalent. The default type for Microsoft compiler is the so-called PDB file. Therez nothing wrong with this declaration.NET processes". and do anything the user can do.0. when the compiler isn't aware of the final name of the executable. but can access any resources the user can access. or /ZI for C/C++(which creates a PDB file with additional information that enables a feature called ""Edit and Continue"") or a Visual Basic/C#/JScript . Nothing. Execution. Windows had two levels of trust for downloaded code.It throws an exception. From a security standpoint. that has the same name as the executable file with the extension . Full Trust Grants unrestricted permissions to system resources.Parse(myString). and No Trust.0 and 1. You only had two choices: Full Trust. The Release build is the program compiled employing optimization and contains no symbolic debug information. Sn. If you specify the assemblyName parameter(/l [assemblyName]). Abstract class can have concrete methods 2. Explain the use of virtual. it would no longer have FullTrust even though it lives in the GAC.permission from some other code group.-k < file-name > What is the difference between a Debug and Release build? Is there a significant speed difference? Why or why not? The Debug build is the program compiled with full symbolic debug information and no optimization.NET provides an utility called strong name tool. To save space.The tool comes with various optional params to do that.. What does this do . sn -t foo.e no one can derive class from a sealed class. It stops the type from further derivation i. You can run this toolfrom the VS. we dont need to provide implementation of the method in the class but the derived class need to implement/override this method. i. override. These settings can be changed as per need from Project Configuration properties. 1.NET command prompt to generate a strong name with an option "-k" and providing the strong key file name. and abstract. sn. the tool lists only the assemblies matching that name. The -tp option displays the public key in addition to the token. The contents of infile must be previously generated using -p. Class: If we use abstract keyword for a class it makes the class an abstract class. Though it is not nessacary to make all the method within the abstract class to be virtual. How do you generate a strong name? . Method: If we make a method as abstract.e. which means it cant be instantiated. The release runs faster since it does not have any debug symbols and is optimized.com 89 Page .dll ? Sn -t option displays the token for the public key stored in infile.ie A sealed class cannot be inherited. sealed.exe computes the token using a hash function from the public key. the common language runtime stores public key tokens in the manifest as part of a reference to another assembly when it records a dependency to an assembly that has a strong name. ie. What does this do? gacutil /l | find /i "Corillian" The Global Assembly Cache tool allows you to view and manipulate the contents of the global assembly cache and download cache. Abstract: The keyword can be applied for a class or method. ""/l"" option Lists the contents of the global assembly cache.A sealed class Satish Marwat Dot Net Web Resources satishcm@gmail. Sealed: It can be applied on a class and methods. revision. protected. PublicKeyToken: Each assembly can have a public key embedded in its manifest that identifies the developer. that method is said to be a sealed method. Version.minor. no one can modify the code or other resources contained in the assembly. private and internal.WriteLine("Derived"). Explain the differences between public. A base class can make some of its methods as virtual which allows the derived class a chance to override the base class implementation by using override keyword. When a assebly is referenced with all three.WriteLine("Sealed Method").It is of the following form major.cannot be a abstract class.A compile time error is thrown if you try to specify sealed class as a base class.WriteLine("Shape"). } } Explain the importance and use of each.build.com 90 Page . Culture: Specifies which culture the assembly supports Version: The version number of the assembly. class Shape { int a public virtual void Display() { Console. This ensures that once the assembly ships. Culture and PublicKeyToken for an assembly. For e. This three alongwith name of the assembly provide a strong name or fully qualified name to the assembly. it must also include the override modifier. When an instance method declaration includes a sealed modifier. } Virtual & Override: Virtual & Override keywords provides runtime polymorphism. They can be Satish Marwat Dot Net Web Resources satishcm@gmail.g. If an instance method declaration includes the sealed modifier. } } class Rectangle:Shape { public override void Display() { Console. These all are access modifier and they governs the access level. Use of the sealed modifier prevents a derived class from further overriding the method For Egs: sealed override public void Sample() { Console. GetType is used to get the runtime type of the object. Console. they can be accessed by anyone within an assembly but outside assembly they are not visible. MyBaseClass b = myDerived.GetType()). Console. myBase.GetType()? Typeof is operator which applied to a object returns System. } } Satish Marwat Dot Net Web Resources satishcm@gmail.Type object. fields. Console. Internal: They are public within the assembly i. myDerived. b.com 91 Page .e.WriteLine("myDerived: Type is {0}".GetType()).GetType()). Protected: Similar to private but can be accessed by members of derived class also. fields to be accessible from anywhere i.WriteLine("mybase: Type is {0}". Private: When applied to field and method allows to be accessible within a class.GetType()). What is the difference between typeof(foo) and myFoo.WriteLine("object o = myDerived: Type is {0}". Public: Allows class. methods.GetType is a method which also returns System.applied to class. within and outside an assembly.e. Typeof cannot be overloaded white GetType has lot of overloads.Type of an object. Example from MSDN showing Gettype used to retrive type at untime:public class MyBaseClass: Object { } public class MyDerivedClass: MyBaseClass { } public class Test { public static void Main() { MyBaseClass myBase = new MyBaseClass(). methods.WriteLine("MyBaseClass b = myDerived: Type is {0}". object o = myDerived. MyDerivedClass myDerived = new MyDerivedClass(). Console. o. 7< /addr:Street > < addr:City >Darmstadt< /addr:City > < addr:State >Hessen< /addr:State > < addr:Country >Germany< /addr:Country > < addr:PostalCode >D-64285< /addr:PostalCode > < /addr:Address > < serv:Server xmlns: < serv:Name >OurWebServer< /serv:Name > < serv:Address >123.tu-darmstadt.. The various purpose of XML Namespace are 1. (See example below.com 92 Page . Universally unique names guarantee that such modules are invoked only for the correct elements and attributes. It consists of 2 parts 1) The first part is the URI used to identify the namespace 2) The second part is the element type or attribute name itself.tu-darmstadt. Define elements and attributes that can be reused in other schemas or instance documents without fear of name collisions.45.de/ito/addresses" > < addr:Street >Wilhelminenstr. Or you might use the nil attribute defined in XML Schemas to indicate a missing value. Write reusable code modules that can be invoked for specific elements and attributes./* This code produces the following output. 3. < Department > < Name >DVS1< /Name > < addr:Address xmlns:addr=". As only static variables/methods can be used in a static method. Together they form a unique name.) 2. you might use XHTML elements in a parts catalog to provide part descriptions.67. essentially a multi file assembly . they don’t contain Manifest but their complete structure is defined by their respective metadata .Net modules use Manifest Metadata tables of parent assembly which contain them . fully called as “manifest metadata tables” . Essentially .net framework .g : a single dll can contain multiple modules . Satish Marwat Dot Net Web Resources satishcm@gmail. which maintains the list of given type and other details like access specifier . it contains the details of the references needed by the assembly of any other external assembly / type . Now Manifest is a part of metadata only . so that it can be fully described assembly and can be ported anywhere without any system dependency . Ultimately . .< /serv:Server > < /Department > What is difference between MetaData and Manifest ? Metadata and Manifest forms an integral part of an assembly( dll / exe ) in .com 93 Page . But for . return type etc. class etc. Properties Metadata tables . until they are being packaged as a part of an assembly .Net world both the things ( Metadata with Manifest ) are mandatory . that can’t be used independently . properties . it could be a custom assembly or standard System namespace . but it forms a single binary component . Essentially Metadata maintains details in form of tables like Methods Metadata tables .Net framework . for e.Net modules . which as the name suggests gives the details about various components of IL code viz : Methods . What is the use of Internal keyword? Internal keyword is one of the access specifier available in . fields . Out of which Metadata is a mandatory component . so any type with internal keyword will be visible throughout the assembly and can be used in any of the modules .Net framework can read all assembly related information from assembly itself at runtime . that makes a type visible in a given assembly . Now for an assembly that can independently exists and used in the . thus allocating memory on Heap .Reverse is unboxing . they don’t internally contain a Value type to Unboxed via explicit casting . IList . For any other Reference type .com 94 Page . a. It happens only to those Reference type variables that have been earlier created by Boxing of a Value Type . Must doing Method updates too . ICloneable . Size . d. IConvertible . f. Why only boxed types can be unboxed? Unboxing is the process of converting a Reference type variable to Value type and thus allocating memory on the stack . b. If yes add the new item and increase count by 1 . What is Boxing and unboxing? Does it occure automaatically or u need to write code to box and unbox? Boxing – Process of converting a System.Object type and allocating it memory on Heap . Mostly base class System. It terms of in memory structure following is the implementation . thus allocating memory on stack . If No Copy the whole thing to a temporary Array of Last Max.What actually happes when you add a something to arraylistcollection ? Following things will happen : Arraylist is a dynamic array class in c# in System. need to check it up . Unboxing converts already boxed reference types to value types through explicit casting .ValueType to Reference Type . which can be obtained through explicit casting . c. Satish Marwat Dot Net Web Resources satishcm@gmail. Check up the total space if there’s any free space on the declared list . Create new Array with size ( Last Array Size + Increase Value ) e. Boxing is always implicit but Unboxing needs to be explicitly done via casting . How Boxing and unboxing occures in memory? Boxing converts value type to reference type . Copy back values from temp and reference this new array as original array .Collections namespace derived from interfaces – ICollection . but can only be done with prior boxed variables. thus ensuring the value type contained inside . therefore internally they contain a value type . This is why only boxed types can be unboxed . When you write a multilingual or multi-cultural application in . you could call the garbage collector when you are done using a large object (or set of objects) to force the garbage collector to dispose of those very large objects from memory.Assembly Questions 1. When should you call the garbage collector in . What is a satellite assembly? An MSI installer. 4. the localized assemblies that modify the core application are called satellite assemblies. How is the DLL Hell problem solved in . What is the smallest unit of execution in .Resources. What namespaces are necessary to create a localized application? System. What are the ways to deploy an assembly? 3. a CAB archive. and want to distribute the core application separately from the localized modules. 8. 2. thus storing the value on the stack. Unboxing converts a reference-type to a valuetype. How do you convert a value-type to a reference-type? Use Boxing. Satish Marwat Dot Net Web Resources satishcm@gmail. this is usually not a good practice. you should not call the garbage collector.NET. and XCOPY command. 6.NET? an Assembly. thus storing the object on the heap. 7.NET? As a good rule. What happens in memory when you Box and Unbox a value- type? Boxing converts a value-type to a reference-type. However. However.Globalization and System. but also the version of the assembly.NET? Assembly versioning allows the application to specify not only the library it needs to run (which was available under Win32). 5.com 95 Page . In .Using pagination option in DataGrid control.NET. Resource Files: How to use the resource files. C#. We have to set the number of records for a page. 8. Server side validation is also possible. We can switch off the client side and server side can be done.NET page? . This Managed code is run in .com 96 Page .Net as a separate inmemory database where in I can use relationships between the tables and select insert and updates to the database.NET. COBOL and Perl.Scripting is separated from the HTML.The web is stateless.When .NET. 9. How? The values are encrypted and saved in hidden controls. The site DotNetLanguages. etc. 4. What is ADO . how to know which language to use? 5. How ASP . We have Range Validator. then it takes care of pagination by itself. 10.a language should comply with the Common Language Runtime standard to become a .Using special validation controls that are meant for this.NET is supporting now? . How do you validate the controls in an ASP .How to manage pagination in a page? .NET was introduced it came with several languages. What is smart navigation? . these DLLs can be executed on the server.NET is stateless mechanism.Net says 44 languages are supported.NET. 11.NET environment.Client side is done by default.NET? ADO. VB.NET page.NET and what is difference between ADO and ADO. Explain the life cycle of an ASP .1. What is view state? .NET different from ASP? . How is . So after compilation to this IL the language is not a barrier. Email Validator.The cursor position is maintained when the page gets refreshed due to the server side validation and the page gets refreshed. Can the validation be done in the server side? Or this can be done only in the Client side? . code is compiled to Microsoft Intermediate Language (MSIL for short). This is called as Managed Code. Code is compiled as a DLL. 3. This can be switched off / on for a single control 7.NET language. 2. I can update the actual database as a batch Satish Marwat Dot Net Web Resources satishcm@gmail. 6. the state of a page is maintained in the in the page itself automatically.NET able to support multiple languages? . A code can call or use a function written in another language. I can treat the ADO. How many languages . But in ASP. this is done automatically by the ASP. Left.Windows. Debug. Satish Marwat Dot Net Web Resources satishcm@gmail."Please enter your Name"). When would you use ErrorProvider control? ErrorProvider control is used in Windows Forms application. A control can be docked to one edge of its parent container or can be docked to all edges and fill the parent container.ComponentModel.Write is for when you want it in release build as well. if (textBox1.Form What is the difference between Debug. ErrorProvider control is used to provide validations in Windows forms and display user friendly messages to the user if the validation fails.Write is for information you want only in debug builds.CancelEventArgs e) { ValidateName(). Anchoring a control to its parent ensures that the anchored edges remain in the same position relative to the edges of the parent container when the parent container is resized.WEB FORMS What base class do all Web Forms inherit from? System.g If we went to validate the textBox1 should be empty. bStatus = false. if you set this property to DockStyle. It is like Validation Control for ASP. Additionally.Write and Trace.Write calls will be compiled. the docked edge of the control is resized to match that of its container control. E. A control can be anchored to one or more edges of its parent container. Trace.Text == "") { errorProvider1.SetError (textBox1. then we can validate as below 1). For example. Trace. Anchor Property->Gets or sets which edges of the control are anchored to the edges of its container.Write call won't be compiled when the DEBUGsymbol is not defined (when doing a release build). } private bool ValidateName() { bool bStatus = true. You need to place the errorprovide control on the form private void textBox1_Validating(object sender. Difference between Anchor and Dock Properties? Dock Property->Gets or sets which edge of the parent container a control is docked to. the left edge of the control will be docked to the left edge of its parent control.com 97 Page .NET pages. System.Forms.Write? When should each be used? The Debug. the program runs within security sandbox.NET are supported through the API to allow storing and retrieving information. You are designing a GUI application with a windows and several widgets on it. then a message Please enter your name is displayed. properly written app will not require additional security privileges. return bStatus. Call the GetValue method of AppSettingsReader class. use Dynamic Properties for automatic .SetError (textBox1. and the background process being the other. sort of like what . What's the safest way to deploy a Windows Forms app? Web deployment: the user always downloads the latest version of the code. } it check the textBox1 is empty . naturally.ini files were before for Win32 apps. Satish Marwat Dot Net Web Resources satishcm@gmail. Can you write a class without specifying namespace? Which namespace does it belong to by default?? Yes. The user then resizes the app window and sees a lot of grey space. then the class belongs to global namespace which has no name.config creation. Assign the result to the appropriate variable. My progress bar freezes up and dialog window shows blank. Otherwise the default property of a widget on a form is top-left. How can you save the desired properties of Windows Forms application? . If it is empty. you wouldn't want global namespace. so it stays at the same location when resized. while the widgets stay in place. you should've multi-threaded your GUI.config files in . For commercial products. when an intensive background process takes over. with taskbar and main form being one thread. you can. So how do you retrieve the customized properties of a . storage and retrieval. Can you automate this process? In Visual Studio yes. Yes.com 98 Page . passing in the name of the property and the type expected."").} else errorProvider1.config file? Initialize an instance of AppSettingsReader class. What's the problem? One should use anchoring for correct resizing.NET application from XML . They are nothing more than simple XML files. use anchoring. and then to force it to repaint? Painting is the slowest thing the OS does. Satish Marwat Dot Net Web Resources satishcm@gmail. The Update method forces the repaint. Docking treats the component location as absolute and disregards the component size. an ampersand '&\' would underline the next letter. which will effectively make the background of the form transparent. How's anchoring different from docking? Anchoring treats the component as having the absolute size and adjusts its location relative to the parent form.Drawing? Invalidate the current form. the OS will take care of repainting. So if a status bar must always be at the bottom no matter what. What's the difference between WindowsDefaultLocation and WindowsDefaultBounds? WindowsDefaultLocation tells the form to start up at a location selected by OS. but change its position with the form being resized. so usually telling it to repaint. Also. What's the difference between Move and LocationChanged? Resize and SizeChanged? Both methods do the same. How would you create a non-rectangular window. use docking. If a button should be on the top right.com 99 Page . How do you trigger the Paint event in System. set the TransparencyKey property to the same value as BackColor. why wouldn't Microsoft combine Invalidate and Paint. but with internally specified size. How do you create a separator in the Menu Designer? A hyphen '-' would do it.None.Why is it not a good idea to insert code into InitializeComponent method when working with Visual Studio? The designer will likely through it away. Then set the FormBorderStyle to FormBorderStyle. WindowsDefaultBounds delegates both size and starting position choices to the OS. let's say an ellipse? Create a rectangular form. With these events. but not forcing it allows for the process to take place in the background. Move and Resize are the names adopted from VB to ease migration to C#. most of the code inside InitializeComponent is auto-generated. so that you wouldn't have to tell it to repaint. which will remove the contour and contents of the form. What is the wildcard character in SQL? Let’s say you want to query database with LIKE for all employees whose name starts with La. like Oracle. Icon lives in System.NET and Database Questions 1. Atomic . An em is the number of pixels that it takes to display the letter M ADO. However.NET data provider is high-speed and robust.SystemIcons.How can you assign an RGB color to a System. 3. How can I load the icons provided by .Drawing. What class does Icon derive from? Isn't it just a Bitmap with a wrapper name around it? No. Explain ACID rule of thumb for transactions. what's the difference between pixels. The wildcard character is %. 2. What are advantages and disadvantages of Microsoft-provided data provider classes in ADO.Drawing namespace.NET? SQLServer. so it’s not as fastest and efficient as SqlServer.NET layer on top of the OLE layer. What is the role of the DataReader class in ADO. DB2.NET is universal for accessing other sources.it is one unit of work and does not dependent on previous and following transactions. 4. A point is always 1/72 of an inch. forward-only rowset from the data source.NET connections? It returns a read-only. Before in my VB app I would just load the icons from DLL. no “inbetween” case where something has been updated and something hasn’t. When displaying fonts. 2. It's not a Bitmap by default. and is treated separately by .NET is a .com 100 Page . but requires SQL Server license purchased from Microsoft. Microsoft Access and Informix.Drawing. Consistent .data is either committed or roll back. Its size depends on user's settings and monitor size. A transaction must be: 1. you can use ToBitmap method to get a valid Bitmap object from a valid Icon object.Color object? Call the static method FromArgb of this class and pass it the RGB values. A DataReader provides fast access when a forward-only sequential read is needed. Satish Marwat Dot Net Web Resources satishcm@gmail. the proper query with LIKE would involve ‘La%’.NET. OLE-DB.NET dynamically? By using System.Warning produces an Icon with a warning sign in it.SystemIcons class. for example System. OLE-DB. points and ems? A pixel is the lowest-resolution dot the computer monitor supports.NET.Drawing. The program proceeds without any interruption if the condition is true.NET SDK? 1.com 101 Page . Between Windows Authentication and SQL Server Authentication. assert takes in a Boolean condition as a parameter. The connection string must be identical. Visual Studio . use Trace class for both debug and release builds. What debugging tools come with the . What does the Initial Catalog parameter define in the connection string? The database name to connect to.3. 6. 5. DbgCLR – graphic debugger. since SQL Server is the only verifier participating in the transaction. where every parameter is the same. 7. Durable .no transaction sees the intermediate results of the current transaction). Use Debug class for debug builds. To Do: answer better. 2. 2. including the security settings. CorDBG – command-line debugger. What connections does Microsoft SQL Server support? Windows Authentication (via Active Directory) and SQL Server authentication (via Microsoft SQL Server username and password). Satish Marwat Dot Net Web Resources satishcm@gmail. 9. 8. Isolated . The current answer is not entirely correct. you must compile the original C# file using the /debug switch.NET uses the DbgCLR. What does the Dispose method do with the connection object? Deletes it from the memory. 3. What does assert() method do? In debug compilation. 4.the values persist if the data had been committed even if the system crashes right after. What’s the difference between the Debug class and Trace class? Documentation looks the same. To use CorDbg. What is a pre-requisite for connection pooling? Multiple processes must agree that they will share the same connection. which one is trusted and which one is untrusted? Windows Authentication is trusted because the username and password are checked with the Active Directory. the SQL Server authentication is untrusted. and shows the error dialog if the condition is false. Debugging and Testing Questions 1. Can you change the value of a variable while debugging a C# application? Yes. User Controls: In ASP. Five levels range from None to Verbose. ASP.TraceSwitcher? The tracing dumps can be quite verbose. allowing you to fine-tune the tracing activities.NET Web application? Attach the aspnet_wp. 2. What are three test cases you should go through in unit testing? 1.NET page and those of any ASP. correct output).NET server controls contained within the page.NET Framework class library. This is a generic term that includes user controls.ascx extension.com 102 Page . Satish Marwat Dot Net Web Resources satishcm@gmail.NET page to be re-used as a server control.NET pages).NET. Where is the output of TextWriterTraceListener redirected? To the Console or a text file depending on the parameter passed to the constructor.4. just go to Immediate window.NET: A user-authored server control that enables an ASP. Positive test cases (correct data. Why are there five tracing levels in System. If you are debugging via Visual Studio.Diagnostics. What is view state and use of it? The current property settings of an ASP. Negative test cases (broken or missing data. 7.NET page framework compiles a user control on the fly to a class that derives from the System. which allows you to program accordingly. How do you debug an ASP. For applications that are constantly running you run the risk of overloading the machine and the hard drive.UserControl class. 3. A custom client control is used in Windows Forms applications. 6.exe process to the DbgClr debugger. A custom server control is used in Web Forms (ASP. 5. The ASP.NET can detect when a form is requested for the first time versus when the form is posted (sent to the server). Exception test cases (exceptions are thrown and caught properly). What are user controls and custom controls? Custom controls: A control authored by a user or a third-party software vendor that does not belong to the . proper handling).NET user control is authored declaratively and persisted as a text file with an . An ASP.UI. 8.Web. writing an event processing routine for each object (cell. Where does the Web page belong in the .when the page is loaded into server memory. the validation controls can also perform validation using client script. What's the difference between Response.NET has 3 kinds of caching strategiesOutput CachingFragment CachingData Satish Marwat Dot Net Web Resources satishcm@gmail. allowing the main DataGrid event handler to take care of its constituents.Web.ASP. etc.row."someClientCode().g.Page.the brief moment before the page is displayed to the user as HTML.com 103 Page .Web.NET only. e.Page Where do you store the information about the user's locale? System. Where do you add an event handler? It's the Attributesproperty.UI.aspx.) is quite tedious.NET that test user input in HTML and Web server controls for programmer-defined requirements. the Add function inside that property. Unload() .Add("onMouseOver". In context of web application.What are the validation controls? A set of server controls included with ASP. Suppose you want a certain ASP. What's a bubbled event? When you have a complex control.cs" and Src="MyCode. What are the different types of caching? Caching is a technique widely used in computing to increase performance by keeping frequently accessed or expensive data in memory. The controls can bubble up their eventhandlers. Load() .NET function executed on MouseOver over a certain button.Write()? The latter one allows you to write formattedoutput.NET Framework class hierarchy? System.Write() andResponse.cs"? CodeBehind is relevant to Visual Studio.when page finishes loading. likeDataGrid.String and Date. caching is used to retain the pages or data across HTTP requests and reuse them without the expense of recreating them. If the user is working with a browser that supports DHTML. btnSubmit. button.UI. Validation controls perform input checking in server code.aspx.PreRender () .Attributes. What methods are fired during the page load? Init() When the page is instantiated.Output.Culture What's the difference between Codebehind="MyCode.") What data type does the RangeValidator control support? Integer. NET framework interface. <%@ Assembly Name="MyAssembly" %><%@ Assembly Src="MySource Satish Marwat Dot Net Web Resources satishcm@gmail. <%@ Control Language="VB" EnableViewState="false" %> @Import: Explicitly imports a namespace into a page or user control.NET page parser and compiler. <% @ Import Namespace="System.net provides a cache object for eg: cache["States"] = dsStates.NET page parser and compiler. Some times it is not practical to cache the entire page. The Import directive cannot have more than one namespace attribute. To import multiple namespaces.com 104 Page .Web.web" %> @Implements: Indicates that the current page or user control implements the specified . making all the assembly's classes and interfaces available for use on the page.<%@ Register Tagprefix="Acme" Tagname="AdRotator" Src="AdRotator.IPostBackEventHandler" %> @Register: Associates aliases with namespaces and class names for concise notation in custom server control syntax.<%@ OutputCache Duration="60" VaryByParam="state" %> Fragment Caching: Caches the portion of the page generated by the request.CachingOutput Caching: Caches the dynamic output generated by a request.<%@ Implements Interface="System. For caching the whole page the page should have OutputCache directive. which will result in a better performance. in such cases we can cache a portion of page<%@ OutputCache Duration="120" VaryByParam="CategoryID. Can be included only in .vb" %> @OutputCache: Declaratively controls the output caching policies of an ASP. It access is limited it is known as authorization.NET? @Page: Defines page-specific attributes used by the ASP. What do you mean by authentication and authorization? Authentication is the process of validating a user on the credentials (username and password) and authorization performs after authentication.ascx files.UI.aspx files <%@ Page AspCompat="TRUE" language="C#" %> @Control:Defines control-specific attributes used by the ASP. After Authentication a user will be verified for performing the various tasks. What are different types of directives in . For data caching asp. Can be included only in .SelectedID"%> Data Caching: Caches the objects programmatically. Some times it is useful to cache the output of a website even for a minute.ascx" %> @Assembly: Links an assembly to the current page during compilation. use multiple @Import directives. com 105 Page . The latter positions script blocks near the end of the document so elements on the page that the script interacts are loaded before the script runs. Session objects.config or including an section in a local Web.<%@ Referencestatement in a Web.) Click the Attach button to attach to aspnet_wp.NET application that wasn't written with Visual Studio. You can enable tell ASP.NET and that doesn't use code-behind? Start the DbgClr debugger that comes with the . What does the "EnableViewState" property do? Why would I want it on or off? Satish Marwat Dot Net Web Resources satishcm@gmail. choose Debug Processes from the Tools menu. and selected other file types to an HTTP handler named HttpForbiddenHandler.config.RegisterStartupScript? RegisterClientScriptBlock is for returning blocks of client-side script containing functions. Transfer transfers excution directly to another page. Q. All child classes retain the properties and methods of their parent classes but may override them. If you don't need to execute code on the client. Q.Transfer and Response. The Page class. use interfaces instead. When you want to inherit (use the functionality of) another class. What does WSDL stand for? What does it do? A.Redirect sends a response to the client and directs the client (the browser) to load the new page (it causes a roundtrip). What does the keyword “virtual” declare for a method or property? A.com 106 Page . No.Redirect ? Why would I choose one over the other? A. It is a way to describe services and how they should be bound to specific network addresses. Q. The keyword “sealed” will prevent the class from inherited. Q. Operations.dalmations inherist from dog which inherits from canine which inherits from mammal). Base Class Employee. One should only have it enabled when needed because it adds to the page size and can get fairly large for complex pages with many controls. Yes. being Satish Marwat Dot Net Web Resources satishcm@gmail. Transfer is more efficient. Q. What is the difference between Server. Inheritance allows us to extend the functionality of a base class. What base class do all Web Forms inherit from? A. Server. Can you prevent your class from being inherited by another class? A. How can I maintain Session state in a Web Farm or Web Garden? A. The method or property can be overridden. Use a State Server or SQL Server to store the session state. Q. Does C# support multiple-inheritance? A. It is an "Is a" type of relationship rather than a "Uses" type of relationship (a dalmation IS A dog which IS A canine which IS A mammal . (It takes longer to download the page). A Manager class could be derived from the Employee base class. (Web Services Description Language). It allows page objects to save their state in a Base64 encoded string in the page HTML.A. Q. WSDL has three parts: Definitions. Response. Can you explain what inheritance is and an example of when you might use it? A. Service bindings C# Questions Q. Q. Whats MSIL. In a Try . Presentation (UI). What is the role of the DataReader class in ADO. What is SOA? A. A. as multiple Q. All .NET compatible languages will get converted to MSIL. such concatenations. will the finally block execute if an exception has not occurred? If an Exception has occurred? A.Q. In SOA you create an abstract layer that your applications use to access various "services" and can aggregate the services. The Service Layer provides a way to access these services that the applications do not need to know how the access is done.NET connections? A. It returns a forward-only. Strings cannot be altered. read-only view of data from the data source when the command is executed. The Service layer hides this from the calling application. StringBuilder. Yes. If I have to alter a string many times. to get a full customer record.Catch . Q. Q. MSIL is the Microsoft Intermediate Language.com 107 Page . if at all? A. System.NET class that everything is derived from? A. web services. Common Language Runtime Satish Marwat Dot Net Web Resources satishcm@gmail. Service Oriented Architecture. Q. Q. It is not immutable and is very efficient.Object. message queues or other sources. and why should developers need an appreciation of it. For example. what class should I use? A. Explain the three tier or n-Tier model. a web service and a message queue. What is the CLR? A. Yes and yes. Q. business (logic and underlying code) and data (from storage or other sources). What does it mean that a String is immutable? A. All the application knows is that it asked for a full customer record. What's the top . you are actually creating a new string. I might need to get data from a SGL Server database. It doesn't know what system or systems it came from or how it was retrieved.Finally block. Q. Q. These services could be databases. Is XML case-sensitive? A. When you alter a string (by adding to it for example). NET Dataset and an ADO Recordset? (Or describe some features of a Dataset). IIS . ther objects in ADO.NET. A DataSet is designed to work without any continuing connection to the original data source. relations. rather than being loaded on demand. system. Can you explain some differences between an ADO. and write them to the original data source in a single operation. You can store many edits in a DataSet. Visual C++ Q. ADO.Net web applications Q. Data in a DataSet is bulk-loaded. Visual Basic. Data will be retrieved through Datasets 2. 1. asp contains scrips which are not compiled where as in asp.NET will be compiled Q.object Q. Have you used any? Which ones? A. and views. Name some of the Microsoft Application Blocks.Internet Information Server IIS is used to access the ASP. There's no concept of cursor types in a DataSet.NET Configuration Management Application Block for .NET A. A DataSet can represent an entire relational database in memory. A. Scalability Satish Marwat Dot Net Web Resources satishcm@gmail.NET A. A. Main differences between ASP and ASP.Q.NET (there are others) We use Exception and Data Access Q. 1. DataSets have no current record pointer You can use For Each loops to move through the data. Visual C# 3. ASP code will be interpretted whereas the code written in ASP. Main difference between ASP and ASP.net the code is compiled Q.com 108 Page .NET Asynchronous Invocation Application Block for . Though the DataSet is universal.NET features A. What is the base class of Button control? A. Examples: Exception Management Logging Data Access User Interface Caching Application Block for . Some of the languages that are supported by . complete with tables.NET 2.NET come in different versions for different data sources Q. What is IIS? Have you used it? A. Button Q. Listing from visual studio . Both has the reusable pieces of code in the form of classes/ functions.net > Button Class System. 1. Assembly also contains namespaces. it also stores the information about itself called metadata and includes name and verison of the assembly.NET? A.Windows.Windows. ADO. but does not execute on of normal control flow.NET features A. 1. What is the base class of Button control? A. applications are deployed in the form of assemblies.Forms.NET? A.com 109 Page .Forms. security information. Data transfer in XML format 4.MarshalByRefObject System. Explain Assemblies? A. Strutured Exception Handling Q. Assembly is a single deployable unit that contains information about the implementation of classes. Unstructured Exception Handling 2. information about the dependencies and the list of files that constitute the assembly.ComponentModel. The exception information table represents four types of exception handlers for protected blocks: A finally handler that executes whenever the block exits.ButtonBase System. Satish Marwat Dot Net Web Resources satishcm@gmail.Object System.Control System.Component System. Disconnected Data Architecture 2.Windows. Explain assemblies A.Q. structures and interfaces. In the . How many types of exception handlers are there in . Interaction with the database is done through data commands Q.Net Framework. whether that occurs by normal control flow or by an unhandled exception. A fault handler that must execute if an exception occurs. How many types of exception handlers are there in . Q. Data cached in Datasets 3. Q. Assemblies are similar to dll files.Forms. Dll needs to be registered but assemblies have its own metadata. Difference between Panel and GroupBox classes? A. much faster at the same tasks than its predecessor. Pros ==== ADO. Panel & Group box both can used as container for other controls like radio buttons & check box. Microsoft wouldn’t even be able to get anyone to use the Beta.NET performs much.Data namespace.A type-filtered handler that handles any exception of a specified class or any of its derived classes. In fact.NET is faster than ADO are discussed in the ADO versus ADO.NET section later in this chapter.NET is rich with plenty of features that are bound to impress even the most skeptical of programmers. A user-filtered handler that runs user-specified code to determine whether the exception should be handled by the associated handler or should be passed to the next protected block. Group box 1) Captions can be displayed. * Optimized SQL Provider – in addition to performing well under general circumstances. The difference in panel & group box are Panel 1) In case of panel captions cannot be displayed 2) Can have scroll bars. Q.NET is extremely fast.NET includes a SQL Server Data Provider that is highly optimized for interaction with SQL Server.NET architecture and the System. but ADO. What are the advantages and drawbacks of using ADO. your SQL Server 7 and above data access operations will run blazingly fast utilizing this optimized Data Provider. Difference between Panel and GroupBox classes? A. * XML Support (and Reliance) – everything you do in ADO. Without question. The actual figures vary depending on who performed the test and which benchmark was being used. Some of the reasons why ADO. 2) Cannot have a scroll bar Q.NET? A. If this weren’t the case.com 110 Page . ADO. many of the classes in Satish Marwat Dot Net Web Resources satishcm@gmail.NET at some point will boil down to the use of XML. ADO. It uses SQL Server’s own TDS (Tabular Data Stream) format for exchanging information. Panel is scrollable Q. What we’ve done here is come up with a short list of some of the more outstanding benefits to using the ADO. * Performance – there is no doubt that ADO. then you may be out of luck. Once you start looking for things you need within this namespace. This means that there is no COM interoperability allowed for ADO. such as the DataSet. in order to take advantage of the advanced SQL Server Data Provider and any other feature like DataSets. are so intertwined with XML that they simply cannot exist or function without utilizing the technology. I’m sure others can find many more faults than we list here. * Learning Curve – despite the misleading name.NET framework is pushing toward a trend of strong application design and strong OOP implementations. This may be new to some programmers. there are a couple of drawbacks or disadvantages to using the ADO. etc. you cannot utilize the ADO. * Managed-Only Access – for a few obvious reasons.NET is not simply a new version of ADO.ADO.NET class.NET architecture from anything but managed code. in which you are invoking multiple layers of abstraction as well as crossing the COM InterOp gap. operates in an entirely disconnected fashion. * Only Three Managed Data Providers (so far) – unfortunately.NET.NET architecture is built on a hierarchy of class inheritance and interface implementation. many advantages. but we decided to stick with a short list of some of the more obvious and important shortcomings of the technology.com 111 Page . both to the framework and to the programmer utilizing the class library. ADO. Therefore. Because the disconnected model allows for the DataSet class to beunaware of the origin of its data. * Rich Object Model – the entire ADO. It is just another example of how everything in the . Satish Marwat Dot Net Web Resources satishcm@gmail. you’ll find that the logical inheritance of features and base class support makes the entire system extremely easy to use. However. At that point the down-side becomes one of performance. nor should it even be considered a direct successor. but it is a remarkably efficient and scalable architecture. Cons ==== Hard as it may be to believe. an unlimited number of supported data sources can be plugged into code without any hassle in the future. * Disconnected Operation Model – the core ADO. and very customizable to suit your own needs. the good news is that the OLEDB provider for ODBC is available for download from Microsoft.NET architecture. XML internal data storage.NET. and some far more technical. your code must be running under the CLR. You’ll see later when we compare and contrast the “old” and the “new” why the reliance on XML for internal storage provides many. the DataSet. incurring some initial overhead as well. if you need to access any data that requires a driver that cannot be used through either an OLEDB provider or the SQL Server Data Provider. classes .NET DataSet is nothing at all like a disconnected ADO RecordSet. It is useful for displaying information to the user (or) redirecting the client.com 112 Page .NET should be thought of more as the data access class library for use with the . An assembly is a single deployable unit that contains all the information about the implementation of : .structures and .Net Button Is post backed on the server & not yet Submit & when It goes to the server its states is lost So if we r using javascript in our application so we always use the Input Button in the asp Button Satish Marwat Dot Net Web Resources satishcm@gmail. there is actually a considerable amount of difference in the internal workings of many classes. Some may consider a learning curve a drawback.Write(”Hello World”) Q. There’s a learning curve in learning anything new.NET to its fullest is that a lot of it does seem familiar. but I consider learning curves more like scheduling issues.NET framework.NET framework are made up of assemblies. information about the dependencies and a lost of files that constitute the assembly. Namespaces are also stored in assemblies Q. This information is called METADATA and include the name and the verison number of the assembly. Eg: Response.interfaces An assembly stores all the information about itself. security information. For example (this will be discussed in far more detail later). All the application developed using the . The Asp. it’s just up to you to schedule that curve into your time so that you can learn the new technology at a pace that fits your schedule Q. What is Response object? How is it related to ASP’s Response object? A. What are assemblies ? A. Response object allows the server to communicate with the client (browser).Net Button But Run SuccessFully On The HTML Button A. The difficulty in learning to use ADO. It is this that causes some common pitfalls. an ADO. Why The JavaScript Validation Not Run on the Asp.ADO. Programmers need to learn that even though some syntax may appear the same. the brief moment before the page is displayed to the user as HTML Unload() ."). Satish Marwat Dot Net Web Resources satishcm@gmail.exe. What’s the difference between Response. or OnLoad() for a control.Attributes.when the page is instantiated Load() . allowing the main DataGrid event handler to take care of its constituents.Describe the role of inetinfo. inetinfo.Output.com 113 Page .NET requests among other things.NET function executed on MouseOver for a certain button. handling ASP.when page finishes loading When during the page processing cycle is ViewState available? After the Init() and before the Page_Load().Web. like DataGrid.Write() allows you to write formatted output.NET only.UI. Example: btnSubmit. What’s a bubbled event? When you have a complex control. Where do you add an event handler? Add an OnMouseOver attribute to the button. Client-side code executes in the client's browser.Add("onmouseover".NET Framework class hierarchy? System.exe is theMicrosoft IIS server running.Write() andResponse.cs" andSrc="MyCode. etc.when the page is loaded into server memory PreRender() .dll andaspnet_wp.NET request is received (usually a file with . What methods are fired during the page load? Init() . What namespace does the Web page belong in the .Output.exe in the page loading process. The controls can bubble up their eventhandlers. What data types do the RangeValidator control support? Integer. and Date Explain the differences between Server-side and Client-side code? Server-side code executes on the server.Write()? Response.) is quite tedious. row. the ISAPI filter aspnet_isapi."someClientCodeHere().aspx. button.aspx extension).cs"? CodeBehind is relevant to Visual Studio.exe.When an ASP. Suppose you want a certain ASP. writing an event processing routine for each object (cell.dll takes care of it by passing the request tothe actual worker process aspnet_wp.Page What’s the difference between Codebehind="MyCode. aspnet_isapi.aspx. String. other objects in ADO. Can you explain the difference between an ADO. Server. · You can store many edits in a DataSet. What is the Global. Additionally. it can render client-side code such as JavaScript to be processed in the clients browser.Redirect? Why would I choose one over the other? Server. client-side validation can be performed where deemed appropriate and feasable to provide a richer.Redirect is used to redirect the user's browser to another page or site. · A DataSet is designed to work without any continuing connection to the original data source.Transfer transfers page processing from one page directly to the next page without making a round-trip back to the client's browser. rather than being loaded on demand.asax used for? The Global.Transfer and Response. complete with tables. What is the difference between Server. What are the Application_Start and Session_Start subroutines used for? This is where you can set the specific variables for the Application and Session objects.Transfer does not update the clients url history list or current url. · Though the DataSet is universal. relations. This provides a faster response with a little less overhead on the server. · DataSets have no current record pointer You can use For Each loops to move through the data.NET come in different versions for different data sources. · Data in a DataSet is bulk-loaded. · There's no concept of cursor types in a DataSet. Satish Marwat Dot Net Web Resources satishcm@gmail. more responsive experience for the user.asax (including the Global. The user's browser history list is updated to reflect the new address. This performas a trip back to the client where the client's browser is redirected to the new page.asax. thus making it server-side code Should user input data validation occur server-side or client-side? Why? All user input data validation should occur on the server at a minimum.cs file) is used to implement application and session level events. Response.com 114 Page .What type of code (server or client) is found in a Code-Behind class? The answer is server-side code since code-behind is executed on the server. during the code-behind's execution on the server. and write them to the original data source in a single operation. However. and views. But just to be clear. code-behind executes on the server.NET Dataset and an ADO Recordset? Valid answers are: · A DataSet can represent an entire relational database in memory. Can you explain what inheritance is and an example of when you might use it? When you want to inherit (use the functionality of) another class. Example: With a base class named a data source to the Repeater control? You must set the DataSource property and call the DataBind method What base class do all Web Forms inherit from? The Page class. Satish Marwat Dot Net Web Resources satishcm@gmail.com 115 Page Name two properties common in every validation control? ControlToValidate property and Text property. Which property on a Combo Box do you set with a column name, prior to setting the DataSource, to display data in the combo box? DataTextField property. Which control would you use if you needed to make sure the values in two different controls matched? CompareValidator control. How many classes can a single .NET DLL contain? It can contain many classes. web service. Q. Which WebForm Validator control would you use if you needed to make sure the values in two different WebForm controls matched? A. CompareValidator Control Q. What property must you set, and what method must you call in your code, in order to bind the data from some data source to the Repeater control? A. You must set the DataSource property and call the DataBind method.GET method to test. Satish Marwat Dot Net Web Resources satishcm@gmail.com 116 Page State Management Questions 1.? Item stored in ViewState exist for the life of the current page. This includes postbacks (to the same page). 3.. C# Interview Questions General Questions. Satish Marwat Dot Net Web Resources satishcm@gmail.com 117 Page What’s the difference between System. What’s the top . What’s the . 8. In contrast. What’s the advantage of using System. A shallow copy of an Array copies only the elements of the Array. Satish Marwat Dot Net Web Resources satishcm@gmail. 10.Array.com 118 Page .Array. Can you store multiple data types in System. It is available to classes that are within the same assembly and derived from the specified base class.Text. 11. 6. System.Text. The references in the new Array point to the same objects that the references in the original Array point to. 7.StringBuilder over System.CopyTo() and System. Describe the accessibility modifier “protected internal”.String and System.Array? No. but the original immutable data value was discarded and a new data value was created in memory. so each time a string is changed. 12.4.NET collection class that allows an element to be accessed using a unique key? HashTable. Strings are immutable.String? StringBuilder is more efficient in cases where there is a large amount of string manipulation. the second one is shallow. What’s the difference between the System.NET class that everything is derived from? System.String is immutable.Clone()? The first one performs a deep copy of the array.StringBuilder classes? System. a deep copy of an Array copies the elements and everything directly or indirectly referenced by the elements. 9. but it does not copy the objects that the references refer to.StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed. Note: The variable value may be changed. whether they are reference types or value types. What does the term immutable mean? The data value may not be changed.Object. a new instance in memory is created. How can you sort the elements of the array in descending order? By calling Sort() and then Reverse() methods. 5. Can you prevent your class from being inherited by another class? Yes. but prevent the method from being over-ridden? Yes. Satish Marwat Dot Net Web Resources satishcm@gmail.13. Once the proper catch block processed. Presentation (UI). Just leave the class public and make the method sealed. Can multiple catch blocks be executed for a single try statement? No.Explain the three services model commonly know as a threetier application. 15. 3. 14.com 119 Page . When do you absolutely have to declare a class as abstract? 1. 16. but not all base abstract methods have been overridden. The keyword “sealed” will prevent the class from being inherited. Can you allow a class to be inherited. Example: class MyNewClass : MyBaseClass 2. An abstract class is essentially a blueprint for a class without any implementation. Will the finally block get executed if an exception has not occurred? Yes. 5. What’s an abstract class? A class that cannot be instantiated. 4. What is the syntax to inherit from a class in C#? Place a colon and then the name of the base class. Class Questions 1. An abstract class is a class that must be inherited and have the methods overridden.Exception. What class is underneath the SortedList class? A sorted HashTable. control is transferred to the finally block (if there are any). What’s the C# syntax to catch any possible exception? A catch block that catches the exception of type System. When the class itself is inherited from an abstract class. 17. You can also omit the parameter data type in this case and just write catch {}. Business (logic and underlying code) and Data (from storage or other sources). Method and Property Questions 1. What does the keyword “virtual” declare for a method or property? Satish Marwat Dot Net Web Resources satishcm@gmail.there is no implementation. An abstract class may have accessibility modifiers. like classes. When at least one of the methods in the class is abstract.com 120 Page . define a set of properties. 6. 11. methods. 2. so implementation is left entirely up to you. What happens if you inherit multiple interfaces and they have conflicting method names? It’s up to you to implement the method inside your own class. In an abstract class some methods can be concrete.2. Why can’t you specify the accessibility modifier for methods inside the interface? They all must be public. interfaces do not provide implementation. and are therefore public by default. 7. This might cause a problem on a higher-level scale if similarly named methods from different interfaces expect different data. all methods are abstract . 10. no accessibility modifiers are allowed. and events. 8. In an interface class. What is an interface class? Interfaces. But unlike classes.NET does support multiple interfaces. The data type of the value parameter is defined by whatever data type the property is declared as. 9. but as far as compiler cares you’re okay. . They are implemented by classes. and defined as separate entities from classes. What is the difference between a Struct and a Class? Structs are value-type variables and are thus saved on the stack. To Do: Investigate What’s the difference between an interface and abstract class? In an interface class. Can you inherit multiple interfaces? Yes. additional overhead but faster retrieval. Another difference is that structs cannot inherit. What’s the implicit name of the parameter that gets passed into the set method/property of a class? Value. Overloading a method simply involves having another method with the same name within the class. multi-line comments. you change the behavior of the method for the derived class. different order of parameters. Satish Marwat Dot Net Web Resources satishcm@gmail. and then keyword base (parameter list to invoke the appropriate constructor) in the overloaded constructor definition inside the inherited class. Is XML case-sensitive? Yes. How is method overriding different from method overloading? When overriding a method. Can you declare an override method to be static if the original method is not static? No. 3. and XML documentation comments. 2. Events and Delegates 1. What’s the difference between // comments. What’s a multicast delegate? A delegate that has multiple handlers assigned to it.The method or property can be overridden. different number of parameters. What’s a delegate? A delegate object encapsulates a reference to a method.com 121 Page . 4. 2. just place a colon. What are the different ways a method can be overloaded? Different parameter data types. 6. If a base class has a number of overloaded constructors. can you enforce a call from an inherited constructor to a specific base constructor? Yes. Each assigned handler (method) is called. /* */ comments and /// comments? Single-line comments. XML Documentation Questions 1. The signature of the virtual method must remain the same. and an inheriting class has a number of overloaded constructors. (Note: Only the keyword virtual is changed to keyword override) 5. Satish Marwat Dot Net Web Resources satishcm@gmail.3.com 122 Page . How do you generate documentation from the C# file commented properly with a command-line compiler? Compile it with the /doc switch. This action might not be possible to undo. Are you sure you want to continue? We've moved you to where you read on your other device. Get the full title to continue listening from where you left off, or restart the preview.
https://www.scribd.com/doc/173587732/Dot-Net-Interview-Questions
CC-MAIN-2016-30
refinedweb
38,110
62.04
#include <hallo.h> * Davide Viti [Sun, Jul 23 2006, 10:03:18AM]: > On Sun, 23 Jul 2006 06:10:07 +0200, Junichi Uekawa wrote: > > > Actually, I managed to get it working on MacBook with Ekiga. > > I'm looking for success/failure reports now. > > I installed the following: > linux-uvc-source_0.1.0-1_i386.deb > linux-uvc-tools_0.1.0-1_i386.deb How? Let me guess: you used dpkg --force-... because the architecture did not match? Then it would be PEBCAK, AFAICS. > then run > > # m-a prepare > # m-a a-i linux-uvc > > Updated infos about 1 packages > Getting source for kernel version: 2.6.17-1-686 > Kernel headers available in /lib/modules/2.6.17-1-686/build > apt-get install build-essential > Reading package lists... Done > Building dependency tree... Done > build-essential is already the newest version. > 0 upgraded, 0 newly installed, 0 to remove and 20 not upgraded. > > Done! > W: Unable to locate package linux-uvc-source: > sh: line 1: linux-uvc-source:: command not found > sh: line 2: -source: command not found Which version of module-assistant are you using? Eduard.
https://lists.debian.org/debian-devel/2006/07/msg00837.html
CC-MAIN-2016-36
refinedweb
185
60.31
/* Declarations useful when processing input. Copyright (C) 1985, 1986, 1987, 1993, "systime.h" /* for EMACS_TIME */ /* Length of echobuf field in each KBOARD. */ /* Each KBOARD represents one logical input stream from which Emacs gets input. If we are using an ordinary terminal, it has one KBOARD object. Usually each X display screen has its own KBOARD, but when two of them are on the same X server, we assume they share a keyboard and give them one KBOARD in common. Some Lisp variables are per-kboard; they are stored in the KBOARD structure and accessed indirectly via a Lisp_Misc_Kboard_Objfwd object. So that definition of keyboard macros, and reading of prefix arguments, can happen in parallel on various KBOARDs at once, the state information for those activities is stored in the KBOARD. Emacs has two states for reading input: ** Any kboard. Emacs can accept input from any KBOARD, and as soon as any of them provides a complete command, Emacs can run it. ** Single kboard. Then Emacs is running a command for one KBOARD and can only read input from that KBOARD. All input, from all KBOARDs, goes together in a single event queue at interrupt level. read_char sees the events sequentially, but deals with them in accord with the current input state. In the any-kboard state, read_key_sequence processes input from any KBOARD immediately. When a new event comes in from a particular KBOARD, read_key_sequence switches to that KBOARD. As a result, as soon as a complete key arrives from some KBOARD or other, Emacs starts executing that key's binding. It switches to the single-kboard state for the execution of that command, so that that command can get input only from its own KBOARD. While in the single-kboard state, read_char can consider input only from the current KBOARD. If events come from other KBOARDs, they are put aside for later in the KBOARDs' kbd_queue lists. The flag kbd_queue_has_data in a KBOARD is 1 if this has happened. When Emacs goes back to the any-kboard state, it looks at all the KBOARDs to find those; and it tries processing their input right away. */ typedef struct kboard KBOARD; struct kboard { KBOARD *next_kboard; /* If non-nil, a keymap that overrides all others but applies only to this KBOARD. Lisp code that uses this instead of calling read-char can effectively wait for input in the any-kboard state, and hence avoid blocking out the other KBOARDs. See universal-argument in lisp/simple.el for an example. */ Lisp_Object Voverriding_terminal_local_map; /* Last command executed by the editor command loop, not counting commands that set the prefix argument. */ Lisp_Object Vlast_command; /* Normally same as last-command, but never modified by other commands. */ Lisp_Object Vreal_last_command; /* The prefix argument for the next command, in raw form. */ Lisp_Object Vprefix_arg; /* Saved prefix argument for the last command, in raw form. */ Lisp_Object Vlast_prefix_arg; /* Unread events specific to this kboard. */ Lisp_Object kbd_queue; /* Non-nil while a kbd macro is being defined. */ Lisp_Object defining_kbd_macro; /* The start of storage for the current keyboard macro. */ Lisp_Object *kbd_macro_buffer; /* Where to store the next keystroke of the macro. */ Lisp_Object *kbd_macro_ptr; /* The finalized section of the macro starts at kbd_macro_buffer and ends before this. This is not the same as kbd_macro_ptr, because we advance this to kbd_macro_ptr when a key's command is complete. This way, the keystrokes for "end-kbd-macro" are not included in the macro. This also allows us to throw away the events added to the macro by the last command: all the events between kbd_macro_end and kbd_macro_ptr belong to the last command; see cancel-kbd-macro-events. */ Lisp_Object *kbd_macro_end; /* Allocated size of kbd_macro_buffer. */ int kbd_macro_bufsize; /* Last anonymous kbd macro defined. */ Lisp_Object Vlast_kbd_macro; /* Alist of system-specific X windows key symbols. */ Lisp_Object Vsystem_key_alist; /* Cache for modify_event_symbol. */ Lisp_Object system_key_syms; /* Minibufferless frames on this display use this frame's minibuffer. */ Lisp_Object Vdefault_minibuffer_frame; /* Number of displays using this KBOARD. Normally 1, but can be larger when you have multiple screens on a single X display. */ int reference_count; /* The text we're echoing in the modeline - partial key sequences, usually. This is nil when not echoing. */ Lisp_Object echo_string; /* This flag indicates that events were put into kbd_queue while Emacs was running for some other KBOARD. The flag means that, when Emacs goes into the any-kboard state again, it should check this KBOARD to see if there is a complete command waiting. Note that the kbd_queue field can be non-nil even when kbd_queue_has_data is 0. When we push back an incomplete command, then this flag is 0, meaning we don't want to try reading from this KBOARD again until more input arrives. */ char kbd_queue_has_data; /* Nonzero means echo each character as typed. */ char immediate_echo; /* If we have echoed a prompt string specified by the user, this is its length in characters. Otherwise this is -1. */ char echo_after_prompt; }; #ifdef MULTI_KBOARD /* Temporarily used before a frame has been opened, and for termcap frames */ extern KBOARD *initial_kboard; /* In the single-kboard state, this is the kboard from which input is accepted. In the any-kboard state, this is the kboard from which we are right now considering input. We can consider input from another kboard, but doing so requires throwing to wrong_kboard_jmpbuf. */ extern KBOARD *current_kboard; /* A list of all kboard objects, linked through next_kboard. */ extern KBOARD *all_kboards; /* Nonzero in the single-kboard state, 0 in the any-kboard state. */ extern int single_kboard; #else extern KBOARD the_only_kboard; #define current_kboard (&the_only_kboard) #define all_kboards (&the_only_kboard) #define single_kboard 1 #endif extern Lisp_Object Vlucid_menu_bar_dirty_flag; extern Lisp_Object Qrecompute_lucid_menubar, Qactivate_menubar_hook; /* Total number of times read_char has returned. */ extern int num_input_events; /* Total number of times read_char has returned, outside of macros. */ extern EMACS_INT num_nonmacro_input_events; /* Nonzero means polling for input is temporarily suppressed. */ extern int poll_suppress_count; /* Keymap mapping ASCII function key sequences onto their preferred forms. Initialized by the terminal-specific lisp files. */ extern Lisp_Object Vfunction_key_map; /* Vector holding the key sequence that invoked the current command. It is reused for each command, and it may be longer than the current sequence; this_command_key_count indicates how many elements actually mean something. */ extern Lisp_Object this_command_keys; extern int this_command_key_count; /*. */ extern Lisp_Object internal_last_event_frame; /* This holds a Lisp vector that holds the properties of a single menu item while decoding it in parse_menu_item. Using a Lisp vector to hold this information while we decode it takes care of protecting all the data from GC. */ extern Lisp_Object item_properties; /* This describes the elements of item_properties. The first element is not a property, it is a pointer to the item properties that is saved for GC protection. */ #define ITEM_PROPERTY_ITEM 0 /* The item string. */ #define ITEM_PROPERTY_NAME 1 /* Start of initialize to nil */ /* The binding: nil, a command or a keymap. */ #define ITEM_PROPERTY_DEF 2 /* The keymap if the binding is a keymap, otherwise nil. */ #define ITEM_PROPERTY_MAP 3 /* Nil, :radio or :toggle. */ #define ITEM_PROPERTY_TYPE 4 /* Nil or a string describing an equivalent key binding. */ #define ITEM_PROPERTY_KEYEQ 5 /* Not nil if a selected toggle box or radio button, otherwise nil. */ #define ITEM_PROPERTY_SELECTED 6 /* Place for a help string. Not yet used. */ #define ITEM_PROPERTY_HELP 7 /* Start of initialize to t */ /* Last property. */ /* Not nil if item is enabled. */ #define ITEM_PROPERTY_ENABLE 8 /* Macros for dealing with lispy events. */ /* True iff EVENT has data fields describing it (i.e. a mouse click). */ #define EVENT_HAS_PARAMETERS(event) (CONSP (event)) /* Extract the head from an event. This works on composite and simple events. */ #define EVENT_HEAD(event) \ (EVENT_HAS_PARAMETERS (event) ? XCAR (event) : (event)) /* Extract the starting and ending positions from a composite event. */ #define EVENT_START(event) (XCAR (XCDR (event))) #define EVENT_END(event) (XCAR (XCDR (XCDR (event)))) /* Extract the click count from a multi-click event. */ #define EVENT_CLICK_COUNT(event) (Fnth (make_number (2), (event))) /* Extract the fields of a position. */ #define POSN_WINDOW(posn) (XCAR (posn)) #define POSN_POSN(posn) (XCAR (XCDR (posn))) #define POSN_SET_POSN(posn,x) (XSETCAR (XCDR (posn), (x))) #define POSN_WINDOW_POSN(posn) (XCAR (XCDR (XCDR (posn)))) #define POSN_TIMESTAMP(posn) (XCAR (XCDR (XCDR (XCDR (posn))))) #define POSN_SCROLLBAR_PART(posn) (Fnth (make_number (4), (posn))) /* A cons (STRING . STRING-CHARPOS), or nil in mouse-click events. It's a cons if the click is over a string in the mode line. */ #define POSN_STRING(posn) (Fnth (make_number (4), (posn))) /* If POSN_STRING is nil, event refers to buffer location. */ #define POSN_INBUFFER_P(posn) (NILP (POSN_STRING (posn))) #define POSN_BUFFER_POSN(posn) (Fnth (make_number (5), (posn))) /* Some of the event heads. */ extern Lisp_Object Qswitch_frame; /* Properties on event heads. */ extern Lisp_Object Qevent_kind, Qevent_symbol_elements; /* Getting an unmodified version of an event head. */ #define EVENT_HEAD_UNMODIFIED(event_head) \ (Fcar (Fget ((event_head), Qevent_symbol_elements))) /* The values of Qevent_kind properties. */ extern Lisp_Object Qfunction_key, Qmouse_click, Qmouse_movement; extern Lisp_Object Qscroll_bar_movement; /* Getting the kind of an event head. */ #define EVENT_HEAD_KIND(event_head) \ (Fget ((event_head), Qevent_kind)) /* Symbols to use for non-text mouse positions. */ extern Lisp_Object Qmode_line, Qvertical_line, Qheader_line; /* Forward declaration for prototypes. */ struct input_event; extern Lisp_Object parse_modifiers P_ ((Lisp_Object)); extern Lisp_Object reorder_modifiers P_ ((Lisp_Object)); extern Lisp_Object read_char P_ ((int, int, Lisp_Object *, Lisp_Object, int *, EMACS_TIME *)); /* User-supplied string to translate input characters through. */ extern Lisp_Object Vkeyboard_translate_table; extern int parse_menu_item P_ ((Lisp_Object, int, int)); extern void echo_now P_ ((void)); extern void init_kboard P_ ((KBOARD *)); extern void delete_kboard P_ ((KBOARD *)); extern void single_kboard_state P_ ((void)); extern void not_single_kboard_state P_ ((KBOARD *)); extern void push_frame_kboard P_ ((struct frame *)); extern void pop_frame_kboard P_ ((void)); extern void record_asynch_buffer_change P_ ((void)); extern SIGTYPE input_poll_signal P_ ((int)); extern void start_polling P_ ((void)); extern void stop_polling P_ ((void)); extern void set_poll_suppress_count P_ ((int)); extern void gobble_input P_ ((int)); extern int input_polling_used P_ ((void)); extern void clear_input_pending P_ ((void)); extern int requeued_events_pending_p P_ ((void)); extern void bind_polling_period P_ ((int)); extern void stuff_buffered_input P_ ((Lisp_Object)); extern void clear_waiting_for_input P_ ((void)); extern void swallow_events P_ ((int)); extern int help_char_p P_ ((Lisp_Object)); extern void quit_throw_to_read_char P_ ((void)) NO_RETURN; extern void cmd_error_internal P_ ((Lisp_Object, char *)); extern int lucid_event_type_list_p P_ ((Lisp_Object)); extern void kbd_buffer_store_event P_ ((struct input_event *)); extern void kbd_buffer_store_event_hold P_ ((struct input_event *, struct input_event *)); extern void kbd_buffer_unget_event P_ ((struct input_event *)); #ifdef POLL_FOR_INPUT extern void poll_for_input_1 P_ ((void)); #endif extern void show_help_echo P_ ((Lisp_Object, Lisp_Object, Lisp_Object, Lisp_Object, int)); extern void gen_help_event P_ ((Lisp_Object, Lisp_Object, Lisp_Object, Lisp_Object, int)); extern void kbd_buffer_store_help_event P_ ((Lisp_Object, Lisp_Object)); extern Lisp_Object menu_item_eval_property P_ ((Lisp_Object)); extern int kbd_buffer_events_waiting P_ ((int)); extern void add_user_signals P_ ((int, const char *)); /* arch-tag: 769cbade-1ba9-4950-b886-db265b061aa3 (do not change this comment) */
http://opensource.apple.com//source/emacs/emacs-88.1/emacs/src/keyboard.h
CC-MAIN-2016-40
refinedweb
1,683
55.34
This is the first in a pair of articles on SQL indices. Part 1 - Know your indices What is an index, anyway? Picture the last time you went to a library. Typically they have books sorted by subject matter (and then author and title), and each shelf has an end-plate with a code describing the subject of its books. If you wanted to collect books of a certain subject, instead of walking across every aisle and reading the inside cover of every book, you could head straight for the bookshelf labelled with your desired subject matter and choose your books. A SQL index has the same general function: improving performance by giving a quick reference to the value of fields for each row in a table. Setting up indices is one of the main steps in preparing your classes for optimal SQL performance. In this article, we’ll cover: - What is an index and why/when should I use them? - What types of indices exist and which scenarios are they ideal for? - What does an index look like? - How do I create one? - And when I have indices, what do I do with them? I will be referring to classes from our Sample schema. These are available through the following Github repository, and they are also provided in the Samples namespace in Caché and Ensemble installations: The basics You can index any persistent property and any property that can be reliably computed from persistent data. Say we want to index the property TaxID in Sample.Company. In Studio or Atelier, we would add the following to the class definition: Index TaxIDIdx On TaxID; The equivalent DDL SQL statement would look something like this: CREATE INDEX TaxIDIdx ON Sample.Company (TaxID); The default global index structure is as follows: ^Sample.CompanyI("TaxIDIdx ",<TaxIDValueAtRowID>,<RowID>) = "" Note that there are fewer subscripts to read than fields in a typical data global. Consider the query “SELECT Name,TaxID FROM Sample.Company WHERE TaxID = 'J7349'”. It’s logically straightforward, and the query plan for executing this query reflects this: This plan essentially says we check the index global for rows with the given TaxID value, then refer back to the data global (“master map”) to retrieve the matching row. Now consider the same query without an index on TaxIDX. The resulting query plan is, as expected, less efficient: Without indices, IRIS's underlying query execution relies on reading into memory and applying the WHERE clause’s condition to each row of the table – and since we would not logically expect any company to share a TaxID, we’re doing all this work for just one row! Of course, having indices means having index and row data on disk. Depending on what we have a condition on and how much data our table contains, this can prove to have its own challenges when we create and populate an index. So when do we add an index to a property? The blanket case is when we frequently condition on a property. Some examples are identifying information such as a person’s SSN or a banking account number. You can also consider birth dates or an account’s funds. Going back to Sample.Company, perhaps the class would benefit from indexing property Revenue if we wanted to collect data on high-earning organizations. Conversely, properties we’re unlikely to condition on are less fitting to be indexed: say a company slogan or description. Simple – except we must also consider which type of index is best! Types of Indices There are six major types of indices I’ll go over here: standard, bitmap, compound, collection, bitslice, and data. I’ll also touch briefly on iFind indices, which are based on streams. There are possible overlaps here, and we’ve already touched on standard indices with the example above. I will share examples on how to create indices in your class definition, but adding new indices to a class is more involved than simply adding a line in your class definition. We’ll go over additional considerations in the next part. Let’s use Sample.Person as an example. Note that Person has subclass Employee, which will be relevant in understanding some examples. Employee shares its data global storage with Person, and all of Person’s indices are inherited by Employee – this means Employee uses Person’s index global for these inherited indices. If you’re unfamiliar, here’s a general overview of these classes: Person has properties SSN, DOB, Name, Home (an embedded Address object containing State and City), Office (also an Address), and list collection FavoriteColors. Employee has additional property Salary (which I myself defined). Standard Index DateIDX On DOB; Here I’m using ‘standard’ loosely to refer to indices that store the plain value of a property (as opposed to a binary representation). If the value is a string, it will be stored under some collation – SQLUPPER by default. Compared to bitmap or bitslice indices, standard indices are more human-readable and relatively effortless to maintain. We have one global node for each row in the table. Below is how DateIDX is stored at a global level. ^Sample.PersonI("DateIDX",51274,100115)="~Sample.Employee~" ; Date is 05/20/81 Note the first subscript after the index’s name is the date value, the last subscript is the ID of the Person with that DOB, and the value stored at this global node indicates that this Person is also a member of the subclass Sample.Employee. If this Person were not a member of any subclass, the value at the node would be an empty string. This base structure will be consistent with most non-bit indices, where indices on more than one property create more subscripts in the global, and having more than one value stored at the node produces a $listbuild object, for example: ^Package.ClassI(IndexName,IndexValue1,IndexValue2,IndexValue3,RowID) = $lb(SubClass,DataValue1,DataValue2) Bitmap – A bitwise representation of the set of IDs corresponding to a property value. Index HomeStateIDX On Home.State [ Type = bitmap]; Bitmap indices are stored per unique value as opposed to standard indices, which are stored per row. Going further into the example above, let’s say the Person with ID 1 lives in Massachusetts, ID 2 in New York, ID 3 in Massachusetts, and ID 4 in Rhode Island. HomeStateIDX is essentially stored as follows: If we wanted a query to return data from people living in New England, the system performs a bitwise OR on the bitmap index’s relevant rows. It’s quick to see that we must load into memory Person objects with ID 1, 3, and 4 at the very least. Bitmaps can be efficient for AND, RANGE, and OR operators in your WHERE clauses. While there is no official cap of how many unique values you can have for a property before a bitmap index will be less efficient than a standard index, the general rule of thumb is up to about 10,000 distinct values. So, while a bitmap index may be effective on a US state, a US city or county bitmap index would not be as useful. Another concept to consider is storage efficiency. If you’re planning on adding and removing rows from your table frequently, your bitmap index’s storage can become less efficient. Consider the example above: say we removed many rows for whatever reason, and we no longer have people in our table who live in less populated states such as Wyoming or North Dakota. The bitmap thus has several rows with only zeroes. On the other side of the coin, creating new rows on large tables can eventually become slower as large bitmap storage must accommodate more unique values. In these examples, I have about 150,000 rows in Sample.Person. Each global node stores up to 64,000 IDs, so the bitmap index global at value MA is split into three parts: ^Sample.PersonI("HomeStateIDX"," MA",1)=$zwc(135,7992)_$c(0,(...)) ^Sample.PersonI("HomeStateIDX"," MA",2)=$zwc(404,7990,(…)) ^Sample.PersonI("HomeStateIDX"," MA",3)=$zwc(132,2744)_$c(0,(…)) Special case: Extent Bitmap An extent bitmap, often named $<ClassName>, is a bitmap index on the IDs of a class – this gives IRIS a quick way of knowing whether a row exists and can be helpful for COUNT queries or queries on subclasses. These indices are generated automatically when a bitmap index is added to the class; you can also manually create a bitmap extent index in a class definition as follows: Index Company [ Extent, SqlName = "$Company", Type = bitmap ]; Or via DDL keyword BITMAPEXTENT: CREATE BITMAPEXTENT INDEX "$Company" ON TABLE Sample.Company Compound – Indices based on two or more properties Index OfficeAddrIDX On (Office.City, Office.State); The general use case of compound indices is having frequent queries conditioning on two or more properties. The order of properties in a compound index matters due to how the index is stored on a global level. Having the more selective property first is more performance efficient because it will save initial disk reads of the index global; in this example, Office.City is first because there more unique cities than states in the US. Having a less selective property first is more space efficient. In terms of global structure, the index tree would be more balanced were State to be first. Think about it: each state contains plenty of cities, but some city names belong to only one state. You can also consider whether you’d expect to run frequent queries conditioning on only one of either property – this can save you from defining yet another index. Here’s an example of the compound index’s global structure: ^Sample.PersonI("OfficeAddrIDX"," BOSTON"," MA",100115)="~Sample.Employee~" Aside: Compound index or bitmap indices? For queries with conditions on multiple properties, you may also want to consider whether separate bitmap indices would be more effective than a single compound index. Bitwise operations on two different indices may be more efficient provided that bitmap indices suit each property appropriately. You can also have compound bitmap indices – these are bitmap indices where the unique value is the intersection of the multiple properties you’re indexing on. Consider the table given in the previous section, but instead of states we have every possible pair of a state and city (e.g. Boston, MA, Cambridge, MA, even Los Angeles, MA, etc.), and cells get 1’s for rows that adhere to both values. Collection – Indices based on collection properties Here we have property FavoriteColors defined as follows: Property FavoriteColors As list Of %String; With each of the following indices defined for demonstration purposes: Index fcIDX1 On FavoriteColors(ELEMENTS); Index fcIDX2 On FavoriteColors(KEYS); Here I’m using ‘collection’ to refer more broadly to single-cell properties containing more than one value. List Of and Array Of properties are relevant here, and if you want, even delimited strings. Collection properties are automatically parsed to build their indices. For delimited properties, say a phone number, you’d need to define this method, <PropertyName>BuildValueArray(value, .valueArray), explicitly. Given the above example for FavoriteColors, fcIDX1 would look something like this for a Person with favorite colors blue and white: ^Sample.PersonI("fcIDX1"," BLUE",100115)="~Sample.Employee~" (…) ^Sample.PersonI("fcIDX1"," WHITE",100115)="~Sample.Employee~" fcIDX2 would look like: ^Sample.PersonI("fcIDX2",1,100115)="~Sample.Employee~" ^Sample.PersonI("fcIDX2",2,100115)="~Sample.Employee~" In this case, since FavoriteColors is a List collection, an index based on its keys is less useful than an index based on its elements. Please refer to our documentation for more in-depth considerations of creating and managing indices on collection properties: Bitslice – Bitmap representation of the bit string representation of numeric data Index SalaryIDX On Salary [ Type = bitslice ]; //In Sample.Employee Unlike bitmap indices, which contain flags representing which rows contain a specific value, bitslice indices first convert numeric values from decimal to binary, then create a bitmap on each digit of the binary value. Let’s take the example above and, for realism’s sake, simplify Salary as being in units of $1000 – so If an employee’s salary is stored as 65, it is understood to represent $65,000. Say we have Employee with ID 1 who has Salary 15, ID 2 Salary 40, ID 3 Salary 64, and ID 4 Salary 130. The corresponding bit values are: Our bit string spans over 8 digits. The corresponding bitmap representation – the bitslice index values – is essentially stored as follows: ^Sample.PersonI("SalaryIDX",1,1) = "1000" ; Row 1 has value in 1’s place ^Sample.PersonI("SalaryIDX",2,1) = "1001" ; Rows 1 and 4 have values in 2’s place ^Sample.PersonI("SalaryIDX",3,1) = "1000" ; Row 1 has value in 4’s place ^Sample.PersonI("SalaryIDX",4,1) = "1100" ; Rows 1 and 2 have values in 8’s place ^Sample.PersonI("SalaryIDX",5,1) = "0000" ; etc… ^Sample.PersonI("SalaryIDX",6,1) = "0100" ^Sample.PersonI("SalaryIDX",7,1) = "0010" ^Sample.PersonI("SalaryIDX",8,1) = "0001" Note that operations modifying Sample.Employee or its rows’ salaries, i.e. INSERTs, UPDATES, and DELETEs, now require each of these global nodes, or bitslices, to be updated. Adding a bitslice index to multiple properties in a table or a frequently modified property can have performance risks. In general, maintaining a bitslice index is more costly than maintaining standard or bitmap indices. Bitslice indices are highly specialized and thus have specific use cases: queries that need to perform aggregate calculations, e.g. SUM, COUNT, or AVG. In addition, they can only be effectively used on numeric values – character strings are converted to a binary 0. Note that if the data table, as opposed to indices, must be read to check a query’s condition, bitslice indices will not be chosen to execute the query. Let’s say Sample.Person does not have an index on Name. If we were to calculate the average salary of employees with the last name Smith – “SELECT AVG(Salary) FROM Sample.Employee WHERE Name %STARTSWITH 'Smith,' “ – we would need to read data rows to apply the WHERE condition, and thus the bitslice index would not be used in practice. There are similar storage concerns for bitslice and bitmap indices on tables where rows are frequently created or removed. Data - Indices with data stored at their global nodes. Index QuickSearchIDX On Name [ Data = (SSN, DOB, Name) ]; In several of the previous examples, you may have observed the string “~Sample.Employee~” stored as the value at the node itself. Recall that Sample.Employee inherits indices from Sample.Person. When we query on Employees in particular, we read the value at index nodes matching our property condition to check that said Person is also an Employee. We can also explicitly define what values to store. Having data defined at your index global nodes can save reads of the data global altogether; this can be useful for frequent selective or ordered queries. Take the above index as an example. If we wanted to pull identifying information about a person given all or part of their name (e.g. to search for clients’ information in a front-desk application), we could have a query such as “SELECT SSN, Name, DOB FROM Sample.Person WHERE Name %STARTSWITH 'Smith,J' ORDER BY Name”. Since our query conditions on Name and the values we’re retrieving are all contained within the QuickSearchIDX global nodes, we only need to read our I global to execute this query. Note that data values cannot be stored with bitmap or bitslice indices. ^Sample.PersonI("QuickSearchIDX"," LARSON,KIRSTEN A.",100115)=$lb("~Sample.Employee~","555-55-5555",51274,"Larson,Kirsten A.") iFind Indices Ever heard of these? Neither have I. iFind indices are used on stream properties, but to use them you need to specify their names with keywords in the query. I could explain more, but Kyle Baxter already has a helpful article on this: See Part 2, on managing defined indices, here. [EDIT 04/16/2020: Adjustments for readability.] Discussion (0)
https://dev.to/intersystems/know-your-indices-37mi
CC-MAIN-2021-39
refinedweb
2,678
53.92
MongoDB database with Mongoose as ORM. If you haven't installed MongoDB on your machine yet, head over to this guide on how to install MongoDB for your machine. It comes with a MacOS and a Windows setup guide. Afterward come back to the next section of this guide to learn more about using MongoDB in Express. MongoDB with Mongoose in Express Installation To connect MongoDB Mongoose as ORM. Mongoose provides a comfortable API to work with MongoDB databases from setup to execution. Before you can implement database usage in your Node.js application, install mongoose on the command line for your Node.js application: npm install mongoose --save After you have installed the library: import mongoose from 'mongoose';const userSchema = new mongoose.Schema({username: {type: String,unique: true,},});const User = mongoose.model('User', userSchema);export default User; As you can see, the user has a username field which is represented as string type. Also we don't want to have duplicated usernames in our database, hence we add the unique attribute to the field.;};const User = mongoose.model('User', userSchema);export default User; The message model looks quite similar, even though we don't add any custom methods to it and the fields are pretty straightforward with only a text field: import mongoose from 'mongoose';const messageSchema = new mongoose.Schema({text: {type: String,required: true,},});const Message = mongoose.model('Message', messageSchema);export default Message; However, we may want to associate the message with a user: import mongoose from 'mongoose';const messageSchema = new mongoose.Schema({text: {type: String,required: true,},user: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },});const Message = mongoose.model('Message', messageSchema);export default Message; Now, in case a user is deleted, we may want to perform a so called cascade delete for all messages in relation to the user. That's why you can extend schemas with hooks. In this case, we add a pre hook to our user schema to remove all messages of this user on its deletion:;};userSchema.pre('remove', function(next) {this.model('Message').deleteMany({ user: this._id }, next);});const User = mongoose.model('User', userSchema);export default User; Mongoose is used to define the model with its content (composed of types and optional configuration). Furthermore, additional methods can be added to shape the database interface and references can be used to create relations between models. An user can have multiple messages, but a Message belongs to only one user. You can dive deeper into these concepts in the Mongoose documentation. Next, in your src/models/index.js file, import and combine those models and export them as unified models interface: import mongoose from 'mongoose';import User from './user';import Message from './message';const connectDb = () => {return mongoose.connect(process.env.DATABASE_URL);};const models = { User, Message };export { connectDb };export default models; At the top of the file, you create a connection function by passing the database URL as mandatory argument to it. In our case, we are using environment variables, but you can pass the argument as string in the source code too. For example, the environment variable could look like the following in an .env file: DATABASE_URL=mongodb://localhost:27017/node-express-mongodb-server Note: The database URL can seen when you start up your MongoDB on the command line. You only need to define a subpath for the URL to define a specific database. If the database doesn't exist yet, MongoDB will create one for you. Lastly, use the function in your Express application. It connects to the database asynchronously and once this is done you can start your Express application. import express from 'express';// Express related imports// other node package imports...import models, { connectDb } from './models';const app = express();// additional Express stuff: middleware, routes, ......connectDb().then(async () => {app.listen(process.env.PORT, () =>console.log(`Example app listening on port ${process.env.PORT}!`),);}); If you want to re-initialize your database on every Express server start, you can add a condition to your function: ...const eraseDatabaseOnSync = true;connectDb().then(async () => {if (eraseDatabaseOnSync) {await Promise.all([models.User.deleteMany({}),models.Message.deleteMany({}),]); MongoDB Database? Last but not least, you may want to seed your MongoDB;connectDb().then(async () => {if (eraseDatabaseOnSync) {await Promise.all([models.User.deleteMany({}),models.Message.deleteMany({}),]) MongoDB with Mongoose: ...const createUsersWithMessages = async () => {const user1 = new models.User({username: 'rwieruch',});await user1.save();}; Each of our user entities has only a username as property. But what about the message(s) for this user? We can create them in another function which associates the message to a user by reference (e.g. user identifier): ...const createUsersWithMessages = async () => {const user1 = new models.User({username: 'rwieruch',});const message1 = new models.Message({text: 'Published the Road to learn React',user: user1.id,});await message1.save();await user1.save();}; We can create each entity on its own but associate them with the neccassary information to each other. Then we can save all entities to the actual database. Let's create a second user, but this time with two messages: ...const createUsersWithMessages = async () => {const user1 = new models.User({username: 'rwieruch',});const user2 = new models.User({username: 'ddavids',});const message1 = new models.Message({text: 'Published the Road to learn React',user: user1.id,});const message2 = new models.Message({text: 'Happy to release ...',user: user2.id,});const message3 = new models.Message({text: 'Published a complete ...',user: user2.id,});await message1.save();await message2.save();await message3.save();await user1.save();await user2.save();}; MongoDB MongoDB in this section yet. - Explore: - What else could be used instead of Mongoose as ORM alternative? - What else could be used instead of MongoDB as database alternative? - Compare your source code with the source code from the PostgreSQL + Sequelize alternative. - Ask yourself: - When would you seed an application in a production ready environment? - Are ORMs like Mongoose essential to connect your application to a database? This tutorial is part 4 of 5 in this series.
https://www.robinwieruch.de/mongodb-express-setup-tutorial/
CC-MAIN-2020-05
refinedweb
981
52.05
String.Split Method (Char[], Int32) Returns a string array that contains the substrings in this instance that are delimited by elements of a specified Unicode character array. A parameter specifies the maximum number of substrings to return. Assembly: mscorlib (in mscorlib.dll) Parameters - separator - Type: System.Char[] An array of Unicode characters that delimit the substrings in this instance, an empty array that contains no delimiters, or null. - count - Type: System.Int32 The maximum number of substrings to return.. If count is zero, an empty array is. For example:. The following example demonstrates how count affects the number of strings returned by Split. using System; public class StringSplit2 { public static void Main() { string delimStr = " ,.:"; char [] delimiter = delimStr.ToCharArray(); string words = "one two,three:four."; string [] split = null; Console.WriteLine("The delimiters are -{0}-", delimStr); for (int x = 1; x <= 5; x++) { split = words.Split(delimiter, x); Console.WriteLine("\ncount = {0,2} ..............", x); foreach (string s in split) { Console.WriteLine("-{0}-", s); } } } } // The example displays the following output: // The delimiters are - ,.:- // count = 1 .............. // -one two,three:four.- // count = 2 .............. // -one- // -two,three:four.- // count = 3 .............. // -one- // -two- // -three:four.- // count = 4 .............. // -one- // -two- // -three- // -four.- // count = 5 .............. // -one- // -two- // -three- // .
http://msdn.microsoft.com/en-us/library/windows/apps/c1bs0eda(v=vs.90)
CC-MAIN-2014-42
refinedweb
199
62.44
Interactive plotting for Python.). Gang: If you aren’t aware of it, Python 2 will not be maintained after 2020 (), and many scientific tools have pledged to stop supporting Python 2 along similar timelines (). Since numpy is a critical Toyplot dependency on that list, I decided to get out ahead of this and commit to a similar timeline. So: Toyplot will stop supporting Python 2 on December 31, 2018. Currently, all of my Toyplot development is on Python 3, and we have Python 2 and 3 builds on Travis to catch any regressions, so what this change will mean in practice is that the Python 2 build gets shut down. For what it’s worth, I switched to Python 3 exclusively for all my work at the beginning of the year, and it has been fairly uneventful. The only time I’ve had to fall back to Python 2 was with a pair of commercial applications that embed it - module dependencies have been a complete non-issue. Cheers, Tim y = layer_map[layer]and negate it: y = -layer_map[layer]. Hello~ I'm doing a object detection project and want to use Toyplot for visualization when training. The code I tried so far is: import numpy as np import toyplot import toyplot.svg from skimage.data import astronaut img = astronaut() w, h = img.shape[:2] canvas = toyplot.Canvas(width=w, height=h) mark = canvas.image(img, rect=(0, 0, w, h)) axes = canvas.cartesian(show=False, margin=0, padding=0) bbox = np.float32([ [22, 33, 44, 55], ]) # x1, x2, y1, y2 mark = axes.rects(bbox[:, 0], bbox[:, 1], bbox[:, 2], bbox[:, 3], style={ 'stroke': 'orange', 'stroke-width': 2, 'fill-opacity': 0.0 }) toyplot.svg.render(canvas, './vis.svg') However, the result seems incorrect. I expect a small rectangle but got a rectangle same size as the image. Are there any problem in the code? Or are there any other way to overlay bounding boxes on an image?. hannesis the "proper" way of labeling categories in a bar chart? my x axis is categorical hannesi would like to render some bigger matrix
https://gitter.im/sandialabs/toyplot?at=5ac5763c270d7d370893e1e3
CC-MAIN-2022-33
refinedweb
349
66.64
This may or may not be the right forum to ask. So I have upgraded to Monodevelop 4.0.12 from an old version of Monodevelop. I think it was 2.xx. In the old version, everything works fine. In the new version, I get "unknown resolve error" at the line using MicrosoftResearch.Infer.Models; in my IDE. All references to classes in there turn red. However, the strange thing is that I can compile and run my code. Anyone got the same problem ? More information - It seems I don't have the mentioned problem with references to classes in Infer.Runtime.dll but only with references to Infer.Compiler.dll - When typing MicrosoftResearch.Infer. to get a list of autocompletions, MicrosoftResearch.Infer.Models is not shown. Other items in Infer.Runtime.dll are listed. I have the same problem with Monodevelop as well. So far I just live with that. But, if you manage to code in F# with Monodevelop and Infer.net, open MicrosoftResearch.Infer.Models resolves fine
https://social.microsoft.com/Forums/en-US/1f3ea63b-dc74-409b-beb0-eba175ed6b13/infernet-with-monodevelop-ide?forum=infer.net
CC-MAIN-2022-33
refinedweb
170
64.47
Hi, I am writing my very first C++ program using classes. I am trying to doit in small steps so I can catch the error early and quick... I have defined the class, and I tried to place some calls for methods from that class in main. But I get this error: invalid use of 'class Stack' I've checked what I could, and I really do not know why I get this. So, my class is defined as such: What am I doing wrong?What am I doing wrong?Code:/* some includes, namespace std etc. */ class Stack { private: int *ptr; int top; int array[MaxStack]; int tmp; public: void Stack::init() { top = -1; } Stack::Stack() { ptr = new int[MaxStack]; top = 10; ptr = array; for (int i = 0; i < 10; i++) array[i] = 0; } /* some more methods here */ }; int main() { Stack s; s.init(); s.Stack(); /* the line error indicates */ return 0; }
http://cboard.cprogramming.com/cplusplus-programming/76732-invalid-use-%27class-%27.html
CC-MAIN-2014-35
refinedweb
152
80.82
JavaScript One-Liners That Make Me Excited Andrew Healey Updated on ・4 min read Dust unique ids when prototyping. I've even seen people using it in production in the past. It's not secure but ... there are worse random generation functions out there. // Generate a random alphanumerical string of length 11 Math Alex Lohr for code golfing it (and 齐翊 too). ?foo=bar&baz=bing => ). Michiel Hendriks helped us save a few characters here 👍.` `)() Amazing. I post unique content to my weekly newsletter 📧. Who is hiring? (As of September 2018) Members of the dev.to community sharing open job opportunities at their companies. I've got another good one to create arrays of a specific size and map over it at the same time. Oh SHID. This is exactly what I needed so many times, and it finally seems like it's a performant approach?! It looks quite clean and sleek, so I decided to test out the performance on my pc Weirdly using Array(N) is about 20% faster than using an array-like {length: N} when used inside Array.from() I also added comparisons of mapping as a parameter vs (dot)map too. Wow, that's... humbling. BTW, you could beat out ForLoopwith: since the size is known in advance. You can shave off one more char for your hex color code generator without resorting to padEnd: A clever change. Probably faster too? Thanks. Not sure if it's faster, but that's usually a non-issue for code golfing :) I was curious and created a test: jsperf.com/hex-color-code-generator :) Awesome! Close to what I expected 👍 I'm not a big Javascript person so I don't know what the difference is between window.location, document.locationand just location(which I assume uses the global window context). I know substrworks fine on an empty string, and I'm making the (heroically cavalier) assumption that query strings start with a ?in all browsers' implementations of location.search. But both of these return something incorrect if there's no query string: Oops. Well, we can do something about that: And now it's longer and even less maintainable, but hey :) This is brilliant, Ben! 😄 I can probably do it in even less characters... let me try: Hey, that one could not accept empty value (eg: '?a=&b=1&c=') try this instead: Does this count? 😈 I'll allow it! 😀 It's a shorthand for returning one of three colors if the score is truthy. Otherwise it returns a fallback value. that can be even more minified: you could lose the first array item and use score - 1, but that would have more characters. Would it? Wouldn't you shorten by 4 chars to remove "",, or 3 if whitespace doesn't count, and only add 2 chars to go from [score]to [score-1]? Seems like it'd still be shorter by at least a character, or am I missing something? Why waste all those extra characters, this also works Nice find, thanks! Edited 👍. Be careful with that shuffle, it won’t yield truly random results because sortexpects its comparator to uphold Math.sign(compare(a, b)) === -Math.sign(compare(b, a)). Microsoft once screwed up by using exactly that. What an interesting story! Thanks for sharing. And yes, for any production code just use Fisher/Yates! Awesome one liners... Until you hit save and Prettier formats it to two 🤣 I did this one for a challenge. It finds if a number is in a range of two other numbers so find if b is in range of a to c Wouldn't you just check b >= a && b <= c? That was definitely a way to do it. However, I am pretty sure that only works with constraints on the range values, and the way I wanted to solve it was to be sure it could handle any range. I could be wrong which in that case, I will certainly remember this way lol Nope to me lol, you're just right and I am pretty sure that works for any size range not just that but the Big O is significantly better ahahaha! I use Set often to remove duplicates, but I didn't know it's possible to use the spread operator on a Set. I have been using Array.from(new Set(myArray))until now. Since Array.fromtake an iterable I could have guessed but... Nice post ! Glad it helped ya! One of the intriguing trait of functional programming is to look unreadable despite being working. There are a lot of byte saving tips one can employ in code golfing. A nice collection can be found here: github.com/jed/140bytes/wiki/Byte-... got a problem like this: lost key 'a' and 'c' solution: replace the 2nd '+' by '*' Thanks! Fixed it :) //only rounds up 15 can be changed to what ever number you want to use roundMinutes = (mins) => { return (~(mins / 15) * 15) * -1 ; } roundMinutes(35) -> 45 // will now round down instead of up roundMinutes = (mins) => { return (~~(mins / 5) * 5) ; } Not really a one-liner, but good for when making generative art. How about my one-line, unreadable quick sort implementation? I like it a lot. great stuff thanks Love it! Good stuff thanks!! Good stuff! Note that list shuffle approach has a bunch of bias and doesn't perform very good shuffling. See beesbuzz.biz/code/6719-How-not-to-... for a detailed explanation. Yup! 😀 The function is short but scary. Raphael linked another article that covers the same topic. I'll add a note. Please don't use code in production that multiplies 86400000 (24*60*60*1000) for computing dates; date/time is way more complicated than that, you will shoot yourself in the foot. Use a library.
https://practicaldev-herokuapp-com.global.ssl.fastly.net/healeycodes/javascript-one-liners-that-make-me-excited-56aj?utm_source=additional_box&amp;utm_medium=internal&amp;utm_campaign=regular&amp;booster_org=
CC-MAIN-2019-30
refinedweb
966
75
From: Nick Coghlan ncoghlan@gmail.com Sent: Thursday, July 11, 2013 11:01 PM So, what if we instead added a new alternative API based on Haskell's "fold" [1] where the initial value is mandatory: def fold(op, start, iterable): ... Note that Haskell, and many other functional languages, actually have both functions: def fold(op, start, iterable): def fold1(op, iterable): And really, they're only separate functions because a language with strict types and automatic currying can't handle variable arguments. Meanwhile, there are an awful lot of people who just don't like reduce/fold in any situation. The quote "Inside every reduce is a loop trying to get out" appears quite frequently, on this list and elsewhere. And I don't think it's because it's easy to get the fold/fold1 distinction wrong, but because they consider any use of reduce unreadable. I think the idea is that folding only makes immediate sense if you're thinking of your data structures recursively instead of iteratively, which you usually aren't in Python. But I'm probably not the best one to characterize the objection, since I don't share it. (Of course there are cases where reduce _is_ unreadable, and the only reason people use it is because in Haskell or OCaml or Scheme the explicit loop would be _more_ unreadable, even though that isn't even remotely true in Python… but there are also cases where it makes sense to me.) One more thing: The name "fold" to me really implies there's going to be "foldr" function as well, in a way that "reduce" doesn't. But I could probably get over that—after all, right-folding isn't nearly as important for code with arrays or iterators the same way it is for recursive code with cons lists or lazy lists.. This could also be introduced as an alternative API in functools. (Independent of this idea, it would actually be nice if the operator module had a dictionary mapping from op symbols to names, like operator.by_symbol["+="] giving operator.iadd) And that answers the "easy to add to new functions" bit! Except a helper function might be nice, something like operator.get_op (but with a better name): def get_op(func): if callable(func): return func else: return by_symbol[func]
https://mail.python.org/archives/list/python-ideas@python.org/message/FQL6Q5PUJBYVTFOOB3OEOSQMHRF4WXL7/
CC-MAIN-2020-40
refinedweb
388
58.62
In the past it was very common to see global variables in snippets of JavaScript code across the web, such as: name = "Spock"; function greeting() { return "Hello " + name; } A better approach is to place all of your code within a namespace; an object that contains all of your code and helps to prevent name clashes with JavaScript code written by others. The simplest method of creating a namespace is to use an object literal. var foo = {}; foo.name = "Spock"; foo.greeting = function() { return "Hello " + foo.name; } This can also be specified using a different syntax. var foo = { name: "Spock", greeting: function() { return "Hello " + foo.name; } }; This approach is better that having outright global variables, but it exposes everything within the namespace as global. In other words both foo.name and foo.greeting are available everywhere. Another problem with this approach is that greeting needs to refer to ‘foo.name’ rather than just ‘name’. Another method of creating a namespace is through the use of a self executing function. var foo = (function(){ // Create a private variable var name = "Spock"; // Create a private function var greeting = function() { return "Hello " + name; }; // Return an object that exposes our greeting function publicly return { greeting: greeting }; })(); Here, when the function is executed it creates a private variable and a private inner function. The inner function can refer to the private variable directly. The main function then returns an object literal containing a reference to the greeting private function – this then exposes the greeting function as a public function so we can call it via the foo namespace. console.log(foo.greeting() === "Hello Spock"); // true This post was inspired by a good post from David B. Calhoun about spotting outdated JavaScript. 3 Comments This article was very helpful! Thanks for putting this out there, it was easy to understand! Nice article! I make some improvement to make namespace. The code usage is look like this: I put the source code in github: 2 Trackbacks [...] Essa solução serve para vários arquivos ou trechos de código com namespace. A solução com apenas 1 arquivo JS pode ser como feito no post creating namespace. [...] [...] When your global context is the DOM window, it’s easy to muddy the waters with global variables. Instead, use a method to create a namespace for your program. In this namespace you can create one entry on the window DOM and concisely write and extend your program. There are two or three main ways to do this, but they are best outlined elsewhere. [...]
http://blog.stannard.net.au/2011/01/14/creating-namespaces-in-javascript/
CC-MAIN-2014-52
refinedweb
418
65.73
Warning This project is abandoned. We recommend you to use typeguard instead. It has been well maintained, and provides the mostly same API to tsukkomi so that typeguard module is drop-in replacement of tsukkomi.typed module. tsukkomitsukkomi do tsukkomi for python types. What is tsukkomi?What is tsukkomi? tsukkomi is a japanese word means straight man in the comedy duos of western culture. As straight man react partner's ridiculous behaviors, tsukkomi will react incorrect types. How to use tsukkomi?How to use tsukkomi? tsukkomi take type hints from typing. write code with annotation, decorate all callable objects with tsukkomi.typed.typechecked. FYI generic types are not supported, see tsukkomi dosen't support generic section for the detail. from typing import Sequence from tsukkomi.typed import typechecked @typechecked def greeting(name: str) -> str: return name greeting('a') # it is ok greeting(1) # this will raise `TypeError` tsukkomi dosen't support generictsukkomi dosen't support generic tsukkomi dosen't support generic type checking, includes types already inherited a generic type like typing.Sequence, typing.Mutable and etc. following example codes can be passed by tsukkomi.typed.typechecked. import typing from tsukkomi.typed import typechecked T = typing.TypeVar('T') class Boke(typing.Generic[T]): @typechecked def stupid(self, word: T) -> T: return type(word) @typechecked def correction(self, words: Sequence[T]) -> T: return random.sample(words, 1)[0] @typechecked def boke_and_tsukkomi(stupid_words: Sequence[str], correction: Sequence[str]) -> bool: return any(s == c for s, c in zip(stupid_words, correction))) boke = Boke[str]() print(boke.stupid('hello world')) print(boke.correction([1, 2, 3])) print(boke_and_tsukkomi([1, 2], [1.0, 2.0])) ChangelogsChangelogs 0.0.5 --- 2016-05-190.0.5 --- 2016-05-19 ModifiedModified - Interpret None as type(None)
https://libraries.io/pypi/tsukkomi
CC-MAIN-2021-21
refinedweb
288
53.98
KENWU/Win32-INET-0.03 - 01 Sep 2009 12:27 4.5 (2 reviews) - 04 Jan 2016 17:37:13 GMT - Search in distribution - IO::Lambda::Socket - wrapper condition for socket functions "Sys::Syslog" is an interface to the UNIX syslog(3) program. Call "syslog()" with a string priority and a list of "printf()" args just like syslog(3)....SAPER/Sys-Syslog-0.33 3.5 (2 reviews) - 24 May 2013 00:13:07.12 4.5 (2 reviews) - 06 Oct 2015 15:56:58 - Net::Server::Fork - Net::Server personality - Net::Server::PreFork - Net::Server personality - Net::Server::PreForkSimple - Net::Server personality This document describes differences between the 5.005 release and the 5.6.0 release....SHAY/perl-5.22.1 4.5 (6 reviews) - 13 Dec 2015 19:48:31 GMT - Search in distribution - perl58delta - what is new for perl v5.8.0 - perl561delta - what's new for perl v5.6.1 - perl5101delta - what is new for perl v5.10.1 Lock::Socket provides cooperative inter-process locking for applications that need to ensure that only one process is running at a time. This module works by binding an INET socket to a port on a loopback address which the operating system convenient...MLAWREN/Lock-Socket-0.0.6 - 19 Sep 2014 14:54:19 GMT - Search in distribution JDB/Win32-Internet-0.087 - 17 Dec 2013 22:19 defi...MNOONING/PlRPC-0.2020 - 17 Jun 2007 20:00:21 GMT - Search in distribution This task contains all distributions under the POE namespace....APOCAL/Task-POE-All-1.102 - 09 Nov 2014 11:07:41 GMT - Search in distribution This document serves to answer the most frequently asked questions on both the perl-ldap Mailing List and those sent to Graham Barr. The latest version of this FAQ can be found at 4.5 (14 reviews) - 06 Apr 2015 18:02:34 GMT - Search in distribution You can use this module for all your ESC-POS Printing needs. If some of your printer's functions are not included, you may extend this module by adding specialized funtions for your printer in it's own subclass. Refer to Printer::ESCPOS::Roles::Profi...SHANTANU/Printer-ESCPOS-0.024 - 04 Apr 2016 09:32:1527 4.5 (2 reviews) - 20 Apr 2016 14:22:50 GMT - Search in distribution...RCAPUTO/POE-1.367 5 (12 reviews) - 03 Jun 2015 14:20:42 GMT - Search in distribution When you load this module, any regex in the same lexical scope will be visually (and interactively) debugged as it matches....DCONWAY/Regexp-Debugger-0.001020 4.5 (4 reviews) - 24 Feb 2014 03:21:48 GMT - Search in distribution
https://metacpan.org/search?q=Win32-INET
CC-MAIN-2016-18
refinedweb
446
56.86
Ember.js: Rich Web Applications Done Right - | - - - - - - Read later Reading List Ember.js sprung out of the SproutCore project. For those who don’t know what SproutCore is, it is a JavaScript Model-View-Controller framework that enables you to write rich internet applications with a desktop-like feel, both in regards to the application being developed as well as to its source code. The SproutCore core team and community had been working on SproutCore 2.0 for quite some time before SproutCore 2.0 in effect became Ember.js. You can read more about the transition on Yehuda Katz’ blog. Although Ember.js has the same roots as SproutCore, with a similar object-model and template-model, Ember.js has a very different view of the world than SproutCore has. In many ways SproutCore aims to hide away HTML and CSS code for the developer, while Ember.js has HTML and CSS at the core of the development model. The advantage of the SproutCore model is that it will be easier to support a different target rendering platform in the future (like the HTML5 Canvas element), or even a native application deployment. This is a very nice idea, but just as the JavaServer Faces (JSF) project I have not seen a single application that targets anything but HTML, CSS and JavaScript. The advantage of the Ember.js model is the fact that the HTML and CSS are developed in plain-sight, very easily visible to the developer while still being very easy to adapt to whichever specific needs your web-application might have. Now this brings me nicely along to the next topic: What is Ember.js ? Ember.js, what’s that? As stated on the Ember.js website, Ember.js is “a JavaScript framework for creating ambitious web applications that eliminates boilerplate and provides a standard application architecture”. In my own opinion, Ember.js is a framework for developing Rich Internet Applications (RIA) the right way. It is rooted in the languages that shape our web experience (HTML, CSS and of course JavaScript), it helps the developer keep the source code in a clean, MVC pattern, while it leverages the strengths from SproutCore: a rich object model and automatically updating templates, powerful and consistent bindings that support rich views that are able to accept events, as well as a bunch of extra addons, some of which I will go through in this article. You can find the Source code for Ember.js on GitHub and the addons being worked at in the ember-addons repository. This article will take a closer look at three addons, Ember Data, the Ember.js adapted sproutcore-statecharts and the Ember.js adapted Sproutcore-Touch. Project Structure and Setup During this article we will develop a simple photo viewer/carousel Ember.js application that is able to display a horizontal list of images. When these images are clicked, the selected image will be shown. The application will have Play and Pause, as well as Next and Previous buttons to control the flow of the images. Near the end of the article we will enable dynamic loading of images from a JSON file, as well as enable touch gestures for touch-enabled devices. The gestures tap, pinch (zoom), swipe and pan will be implemented. The source code shown for this application is available from GitHub. I generally use IntelliJ IDEA as my IDE of choice when developing with Ember.js or SproutCore. The reason there is a Maven pom.xml file in the repository is mainly a convenience for me, in order to get the project nicely and easily imported into IDEA. You do not at all need to consider this file, but do keep in mind that all of the source code resides inside the src/main/webapp directory. If you’re not familiar with the Maven nomenclature, think nothing of it and navigate straight into src/main/webapp. The example application is will have a total of three JavaScript library dependencies in addition to Ember version 0.9.4: When you clone the Ember-Example repo, these dependencies will be included, all ready to go. If you would like to follow along, and start from scratch, you can download the JavaScript dependencies directly from GitHub. Whenever I post code examples in this article, I am posting the contents as an image. In addition to the image, I will also refer to the correct GitHub revision of the file, to make it possible for you to copy and paste the file contents. Short introduction to Bindings Bindings are used to synchronize the values of a variable between objects. Consider the following example: (Click on the image to enlarge it) Figure 0 - Simple bindings example Line 15 to 23 above created a new Ember.js application called BindingsExample, which has two objects defined, one BindingsExample.Person and one Bindingsexample.Car. The name property for the Person object is set to the string “Joachim Haagen Skeie”. Looking at the Car object, you will notice that it has one property called “ownerBinding”. Because the property name ends with the string .nme property changes, that the contents on the website will also be updated. Try typing the following into you Browsers console and watch that the contents of the displayed website changes with it: BindingsExample.Person.set('name', 'Some random dude') The contents of the displayed webpage will now be the string “Some random dude”. With that in mind, it is time to start bootstrapping our example application. Bootstrapping your Ember application If you would like to get a feel for what we are building in this example application, you can have a look at the finished application, which is hosted at this URL To get started, lets create an empty index.html file, add the directories app, css, img and scripts. The end result are depicted below: (Click on the image to enlarge it) Figure 1 – Project directory structure Inside you app directory, create four empty files with the following names: - app.js - main.js - stateManager.js - fixtureData.js Inside the css directory, create a single file named: - master.css We will fill these files with content as we progress through this article. Lets get started with our index.html file. We will start out with a rather empty file, only referencing our script and CSS files, and a single div-element that will house the main area of our application. The contents of the file should be: (Click on the image to enlarge it) Figure 2 – Our Initial index.html file The first thing we need to do, is to create a namespace for our application, which we will place inside app.js. I have decided to create the namespace EME (EMber-Example). Add the following to your app.js file: Figure 3 – Ember-Example namespace (EME) The last part, before we move on to defining the objet model for our application, is to add some minor content to the applications CSS file. I would like the application to have a white background, with rounded borders, and I would like the application’s main area to fill the entire screen. Add the following to your css/master.css file. Figure 4 – CSS for the application mainArea Defining your object model with Ember Data At this point we first need to add ember-data to our list of included scripts in our index.html file. Review GitHub Commit if you are unsure of how this is done. Inside app/app.js we need to initialize a datastore that we will use to keep our data in. We will call our datastore EME.store. Figure 5 – Creating the Datastore For this application we will only require one type of data – a photograph – which will have three properties, an ID, a title and a URL. We define our photograph data model by extending DS.Model. Add the following to your app/main.js file, note that we are using the extend keyword rather than the create keyword we have been using up until now. I tend to think of create as a synonym for new, and extend as a synonym for interface. Figure 6 – The Photograph Model Object The primaryKey property defaults to “id”, so strictly speaking its redundant in the above example. I tend to include it anyway as I like to be explicit in my data model definition. Defining controllers and adding Fixture Data Our application will have two types of controls, one that controls the flow of displaying clickable thumbnails, and one that will display the currently selected photograph. Inside app/main.js create the two controllers EME.PhotoListController and EME.SelectedPhotoController. Figure 7 – Controllers Definition Note that the PhotoListController is using the Em.ArrayProxy object, whereas the SelectedPhotoController is using the Em.Object object. Note also that the contents for the SelectedPhotoController is bound to the PhotoListController.selected property by using the Binding suffix. Whenever you suffix your properties with the keyword Binding Ember.js will ensure that whenever the value that you have bound to changes, that your property will automatically update. Bindings are a key component of Ember.js, and one of its main strengths. At this point, it would be useful to add some fixture data into the mix, so that we have some data to display when defining our views in the next section. Inside the projects “img” directory there are a set of 10 photographs. You may use these images as you are working through this tutorial, but they are not licensed for redistribution of any kind. We will create 10 Photo objects, one for each photo inside the img directory, inside our app/fixtureData.js file. (Click on the image to enlarge it) Figure 8 – Fixture Data Above we are using our EME.store, that we created earlier in app.js to create new instances of EME.Photo objects. Each EME.Photo object is initialized with the three data properties, id, imageTitle and imageUrl. Defining your view states Ember.js comes with a pretty nice Statechart framework built in. Ember.js’ statecharts are based on the SproutCore Statechart framework, which in turn is based on the KI framework. Ember.js’ Statechart implementation is a bit simpler that what I am used to from SproutCore, while also coming with a new powerful feature: ViewStates. If you have never worked with Statechart before, you might want to read about them in the SproutCore Blog. Even though the structure is slightly different in Ember.js, you should be able to follow along nicely. Our Statechart is defined in app/stateManager.js. (Click on the image to enlarge it) Figure 9 – State Manager I like to place the State Manager code inside a setTimeout(…, 50). This is my personal preference, and it’s strictly not necessary. The reason I tend to do this is because it makes it easy to verify that I have set up bindings correctly, or that any other asynchronous tasks actually do what they are supposed to do. Your opinion or mileage might vary. Just before defining the EME.stateManager object, I make sure that I load my fixtures on line 2. Line 4 defines our main State Manger object. Notice the rootElement definition on line 5, which specifies which DOM-element that the state manager is able to alter. On line 6 we set the initialState to showPhotoView, which is also the only state we need for this application. The code on lines 9-12 is very important. Each state (or ViewState) will always invoke one function upon entering the state – the enter function – and one function upon exiting the state – the exit function. Ember.ViewState will take care of adding and removing our view from the DOM. It does this via the enter and exit functions, and its important that we call this.super(); on line 10 so that we do not override that functionality. On line 11 we are updating the contents array of the PhotoListController to all of the EME.Photo objects present in our EME.store datastore. Each ViewState has exactly one view property that defines the contents which the ViewState will add or remove from the DOM tree. In our application we have defined this view to be of type Ember.ContainerView, which means that it’s a view that can hold multiple sub-views. There is currently only one subview, the photoListView of type Ember.View. The Thumbnail Template and view We have finally come to the point where we are able to create views that actually display our photos. We will start out with the view displaying our thumbnails. We will start out by using Ember.js’ built-in template engine Handlebars. Insert the following code just before the </head>-tag in index.html: (Click on the image to enlarge it) Figure 10 – The Photo List Handlebars Template There are some new elements in the above code that you might not be familiar with. Handlebars uses Mustache as its underlying Template engine and anything between {{ and }} is part of these templates. Line 23 is Handlerbars’ for each loop structure. {{#each content}} means that the contents (until {{/each}}) will be repeated for each item inside the templates content. In this case a single image. Notice that we have bound the src attribute of the img-tag to the imageUrl property (of content). The last bit of important information here is the data-template-name, which we will refer to in our ViewState. There are two steps remaining in order to display our photo list correctly. The first is to define our photoListView (app/stateManager.js) to utilize the template photo-view-list, and the next is to define the CSS to position and size the thumbnails. Add the following to app/stateManager.js: (Click on the image to enlarge it) Figure 11 – photoListView contents There are a couple of things worth noting above. The first is the fact that we are defining the HTML-contents of our photoListView by telling the view to use the template photo-view-list. The second is the way we bind our contents to our EME.PhotoListController.content variable via the contentBinding property. Whenever the contents of our PhotoListController’s content variable changes, Ember.js will make sure that the view is updated automatically. It might feel a bit like “magic” at first but you quickly become accustomed to this quick-and-easy way of binding your views to your controllers. Since we haven’t specified a tagName property the contents of the view will be wapped in a div-tag. We have however, specified that the class-attribute of that div-tag is thumbnailViewList. Next we need to define some CSS for both the thumbnailViewList and the thumbnailItem classes we have defined above. Add the following to your css/master.css file: Figure 12 – CSS for the Thumbnail View The CSS above should be quite straightforward. We are placing the row of thumbnails at the very bottom of the screen, and we are defining each thumbnail to occupy a space of 75x75 pixels with a 10 pixel gap between each thumbnail. Loading (or refreshing) your index.html file in your browser should now give you the following result: (Click on the image to enlarge it) Figure 13 – Results of adding the Thumbnail list In order to make our thumbnails clickable and accept mouse input, I generally recommend creating a view for the image. So we will replace our div-tag inside our template with a view. Define EME.ThumbnailPhotoView inside app/main.js: (Click on the image to enlarge it) Figure 14 – Defining a clickable thumbnail view The code above should start to get familiar to you. We are defining a view extending from Ember.View upon which we are overriding the click-function. We want to set the selected property of the EME.PhotoListController to whichever thumbnail we clicked on. Then finally we need to update our template to use this new view. Change your index.html accordingly: (Click on the image to enlarge it) Figure 15 – The updated photo-view-list template Notice that we have changed all three lines from 24-26. We are specifying that we want to use the view EME.ThumbnailPhotoView, and we are binding the content of each view to this, meaning that each photograph will have its own unique content. Finally we have changed the {{bindAttr src=…}} from imageUrl to content.imageUrl. Your thumbnails are now clickable and will successfully update the content property of the EME.SelectedPhotoController. The Selected Photo Template and view Once an image is selected we want to display a large version of the image above the thumbnail list. Lets start by defining a new view in our app/stateManager.js file: (Click on the image to enlarge it) Figure 16 – Adding the selectedPhotoView Here we have added a new view to the Em.ContainerView that we had previously defined called selectedPhotoView. The contents of the view is very similar to the view we defined above, and should need no additional explanation. Note, though, that we have added the new view to the childViews array on line 15. Next, we need to define the selected-photo template in index.html: (Click on the image to enlarge it) Figure 17 – The template for the selected photo This template is very similar to the thumbnail list template. We have exchanged {{#each}} with {{with}} as we only have one selected image at a time, and we have created a new view called EME.SelectedPhotoView (listed below in figure 18) that we are using to place the selected photograph in. Other than that, the code above shouldn’t require any additional explanation. Add the following to your app/main.js file. Figure 18 – The SelectedPhotoView The only thing missing is the stylesheet definitions for the style selectedPhotoItem. Add the following to your css/master.css file: Figure 19 – CSS for the selected photo If you (re)load your index.html file in the browser, and then click on a thumbnail, the end result should look similar to figure 20 below. (Click on the image to enlarge it) Figure 20 – The result after selecting a photograph In order to better visualize which image is selected we need to add a bit of CSS attention. Ideally the selected photo would be presented slightly larger than the other thumbnails and be presented with a triangle to better distinguish between the selected photo and the selectable photos. (Click on the image to enlarge it) Figure 21 – After adding CSS to visualize the selected photo The changes required to add the extra CSS can be viewed in full in the following GitHub Commit. Adding control buttons with adding a view for our buttons to our app/stateManager.js file. Figure 22 – Adding a view for our control button view The code above implies that we need to define a new template control-button-view and a new CSS class controlButtons. Lets go ahead and add this to our index.html and css/master.css files: (Click on the image to enlarge it) Figure 23 – The Control Button View template In the code above we are using the Ember.Button view directly. We are defining a target – the controller we wish to notify when the button is clicked – and an action – the function on the target object we wish to invoke. As you can probably guess, our PhotoListController needs to implement these four functions. We will come back to the implementation of the actions a bit later on. First lets have a look at the CSS for the control buttons: Figure 24 – The CSS for the control buttons The CSS above should be straight forward an shouldn’t require any additional explanation. Refreshing index.html in your browser should yield the following result: (Click on the image to enlarge it) Figure 25 – The Button Bar Added Lets start with the more complicated action, nextPhoto. Add the following to your app/main.js file: (Click on the image to enlarge it) Figure 26 – The nextPhoto action The nextPhoto action is implemented as a function in our EME.PhotoListController. When we first load our application in the browser, the selected property is null. We cater for this fact on lines 25-27 by setting the selected property to the very first element of our content array. Ember.js will automatically extend the standard JavaScript arrays into Ember.js Enumerables. You can read more about them in the Ember.js documentation, but its this fact that enables us to call get(‘firstObject’) on our content array. The code in lines 27-36 should be fairly straight forward. We start out by finding the selected item index from the content array. Lines 30-34 enables the nextPhoto function to loop back to the first photo if the user hits the next button while viewing the very last photo. Then, finally, we set the selected property of the controller on line 36. The code on line 12-19 will iterate over the content array and figure out which index the selected photo is located at. The code for the prevPhoto function is listed below. It is very similar to the nextPhoto function, so I wont go into the contents of the function in detail. (Click on the image to enlarge it) Figure 27 – The prevPhoto action This brings us nicely along to our slideshow feature. As you might have guessed, the slideshow feature will utilize the nextPhoto function. In addition we need a timer so that we can call the nextPhoto function every 4 seconds. Add the following to the top of your EME.PhotoListController in the app/main.js file: (Click on the image to enlarge it) Figure 28 – The slideshow functionality When we click on the “start” button, we want to move to the next photo immediately. Then we want to start a timer that will call the nextPhoto function every 4 seconds. I am simply using the standard JavaScript function setInterval to implement the timer. I need to store the timer identifier in my controller so that the “stop” button is able to stop the timer via the clearInterval function. Its now time to reload your application and test our your new control buttons. Adding touch gestures with Ember Touch Ember Touch is derived from the SproutCore Touch project. Originally this package is available from the emberjs-addons repository. However, since SproutCore 2.0 became Ember.js, the emberjs-addons repository hasn’t really been updated all that much. To solve this problem, we are going to use ppcano’s fork of SproutCore Touch. This project also builds an ember-touch.js file as well as containing additional touch gestures. There are two types of touch gestures available, instant gestures like a tap and non-instant gestures like swipe, pinch and zoom. The difference between these two gesture types is that while instant gestures only have an event, non-instant gestures also have a start, and end as well as an event that happens while the gesture is in process. This is important to be able to add animation to you swipe, pinch and pan gestures. The very first thing we need to do, however is to disable your touch devices default gesture event handler. Otherwise your HTML elements wont be able to accept any touch gestures. As we want our whole application to be applicable for touch gestures we will prevent the default gesture event handler on our body-tag using the ontouchmove attribute. We will add our touch gestures to our EME.SelectedPhotoView. Lets start with adding the functionality for left and right swipe to move to the next and previous photo respectively. Add the following to you app/main.js file: (Click on the image to enlarge it) Figure 29 – Adding Swipe gesture We start by defining our swipe options on line 87. We have defined swipe to require two fingers, and that we want to accept swipes in the left and right directions. As we do not want to animate our swipe operation we are simply overriding the swipeEnd function. If we wanted to perform animation during our swipe we would also override the swipeChange function, and/or the swipeStart function. For a left swipe we want to display the previous photograph, and for a right swipe we want to display the next photograph. Here we simply reuse out prevPhoto and nextPhoto functions that we added for our previous and next buttons above. Now, lets add some zooming capabilities to our selected photo view. We want to animate the zooming to make the effect more visual and accurate. Therefore we need to override the function pinchChange. Add the following to you app/main.js file: (Click on the image to enlarge it) Figure 30 – Adding pinch gesture Here we are using the jquery.transit library to perform the actual scaling of our photo. The code should be fairly straight forward. While our pinch is changing, the pinchChange function is notified with a recognizer object. We get the scale attribute from the recognizer and use this to zoom in and out of the photo. Notice that we are not zooming on the view itself, but rather on the element with ID “selectedImage”. The next step is to add this to our selected-photo template. Add the ID attribute to line 34 of your index.html file: (Click on the image to enlarge it) Figure 31 – Adding the selectedImage ID Now that we are able to zoom in on the selected photo we also need a way to be able to pan. Otherwise we would not be able to view the edges of the photo while zoomed in. Like the pinch gesture we want to animate the pan gesture. Add the following to you app/main.js file: (Click on the image to enlarge it) Figure 32 – Adding pan gesture As you can see above we define panning to be an operation performed with one finger/touch. As with the pinch gesture we are also using jquery.transit to perform the actual pan operation on the image. The strange looking code on line 119 and 120 is my way of formatting a string that either starts with “+=” or “-=”. This is required if you not want the image to reset its position for each time the panChange function is invoked. Connecting to a backend data source through Ember Data Since we wont have a real server to fetch our results from, we will fake this by creating a file called “photos” inside our webapp root folder. This file will contain JSON content that simulates the response from the url “/photos”. The content of this file is listed below: (Click on the image to enlarge it) Figure 33 – The photos file You can probably recognize the contents of this file from our app/fixtureData.js file. This file is no longer required, and it can be deleted. Remember to remove the call to the EME.generateImages function from the app/stateManager.js file: (Click on the image to enlarge it) Figure 34 – Removing the generateImages call The reason I am showing you’re the code for the stateManager again here is that you need to take an extra look at line 10. Here we call EME.store.findAll(EME.Photo)). Per default this function will return any objects that are already loaded into the data store. Since we are no longer generating fixture data, we need to also add some code to be able to fetch the contents of the photos file. Lets open up app/app.js and add some Ember Data magic: (Click on the image to enlarge it) Figure 35 – The Store Adapter We have added some code to our EME.store object to be able to use a custom Adapter. Ember Data uses this adapter to talk to your server and to load any retrieved objects into the store. For our application we only need to override the findAll function. But in a real application you would also override find, findMany, createRecord, updateRecord, deleteRecord, commit and so on. For a rather complete and thorough walk though of the Ember Data features, please have a look at the Ember Data Documentation. On line 7 we are defining our EME.Adapter class, which has a single function, the findAll function. This function takes two arguments, a store and a type – which represents the object type we are searching for. This type object defines the URL we are retrieving. Since we are not querying for a specific ID or any other parameters we can simply pass this URL on to jQuery.getJSON. On line 15 we load the retrieved items into the store using the loadMany function. Now, you might wonder how on earth our Photo class knows that it will request the photos file URL. Lets navigate to our app/main.js file and add a couple of lines: Figure 36 – reopenClass You should now be able to refresh your browser and see that the images are loaded properly from your photos file. Normally I would not add my Adapter to my app.js file, but rather to its own .js file. This makes it easier to find the Adapter code later on when you want to change your implementation. Conclusion To me Ember.js represents the way that I personally would like to develop web application clients. Ember.js is tightly coupled with the technologies that make up the web today, but I think it’s very nice that it doesn’t attempt to abstract that away. When the time comes to migrate from HTML to Canvas, or any other technology, I am confident that the Ember.js framework will evolve along with the current trends in web frontend technology. What Ember.js brings to the table is a clean and consistent application development model. It makes it very easy to create your own “component”, . Hopefully this article has given you a better understanding of the Ember.js development model and you are left with a clear view on how you can leverage Ember.js for your next project. And as the title of the article reads, I honestly believe that Ember.js is Rich Internet Applications done right! About the Author Joachim Haagen Skeie is a co-owner at Kantega AS in Oslo, Norway. He works as a Senior Consultant within Java and Web technologies, with a keen interest in both application profiling and open source software. He can be contacted via his Twitter account, or Aleksandar Vidakovic Re: Excellent by Joachim Haagen Skeie Best of luck with your Ember.js endeavors Great article by Mosheh EliYahu Thanks for a great article on Ember.js. Although I am new on Ember.js (in fact I am trying to evaluate it for a project). I am interested to see how I can use Ember to communicate with the a backend which is java objects (A Spring based backend). What would you recommend? We want to consider using Ember for the client side but the model objects have to be java objects which get data from a PostGres database (and other systems - such as Solr). If I can get an idea of an architecture of this - that would be great. Would you be able to post a small example of this, please? Again thanks so much for a great article. Shalom Thank you by Josh Gough I am finding it the perfect "next step" after having read the emberjs documentation page. I would suggest that the main site include this tutorial! Re: Thank you by Josh Gough I plan utilize this framework and even some of the article in revamping some image gallery code on a tribute site to my great-grandmother's artwork () Thanks again, Josh Re: Great article by Joachim Haagen Skeie Thank you for our feedback. If you need a working solution for communication with the backend right now, I would recommend using the github.com/emberjs-addons/sproutcore-datastore which is adapted to work with Ember. If you are starting implementation now, but won't be releasing for a couple of moths, I would look closer at Ember Data which promises a simpler usage model working with your Ember application. You can read more about Ember Data here: github.com/emberjs/data. I intend to do a writeup on Ember Data on my blog, but it might still be a few weeks off. Very Best Regards, Joachim Haagen Skeie Re: Thank you by Joachim Haagen Skeie Thank you for your kind feedback. I am very happy that you found the article helpful and interesting! Very Best Regards, Joachim Haagen Skeie Link to working example? by E Schrijver The link to the example of the final app appears to be dead: haagen.name/Ember-Example/ Also, it might be a good idea to display the link somewhat more prominently, at least in the introduction: I had to hunt for it now, it appears only after you have already gone into the detail of introducing Bindings. Thanks! Nice Article, Thank You by Kevin Hein Tried to update from Ember-0.9.4 to Ember-0.9.8.1 and found it breaks... will debug and see if I can spot what might be happening.
https://www.infoq.com/articles/emberjs/
CC-MAIN-2017-26
refinedweb
5,563
64.2
At this point, the schema of the DataSet is entered and you're ready to add some data. Recall that the column collection of the DataTable defines the schema, and the rows collection of the DataTable defines the data. In other words, to add data to our DataTable , all we need to do is add some rows to our DataTable : dtEmployees. Adding rows to the dtEmployees DataTable is easy to do. First, you need to use the NewRow() method of the dtEmployees object. NewRow() returns a reference to a new row for your DataTable . Next , you must specify values for the columns in the newly created row. Lastly, you must add the row to the DataTable . Listings 2.3 and 2.4 demonstrate this by adding a few rows to our existing DataTable , dtEmployees. ") = "Leigh" workRow1("LastName") = "Chase" 'Add new rows to the DataTable dtEmployees.Rows.Add(workRow) dtEmployees.Rows.Add(workRow1) //Create new row DataRow workRow = dtEmployees.NewRow(); workRow["FirstName"] = "John"; workRow["LastName"] = "Fruscella"; //Create another row DataRow workRow1 = dtEmployees.NewRow(); workRow1["FirstName"] = "Leigh"; workRow1["LastName"] = "Chase"; //Add new rows to the DataTable dtEmployees.Rows.Add(workRow); dtEmployees.Rows.Add(workRow1); Until now, you've probably taken it for granted that the code in this hour works. However, with just a few minutes of effort, you can verify that it works. By itself, ADO.NET code is not specific to Web forms or Windows forms. In fact, either can be used to test the code in this chapter. If you are handy with Windows forms using Visual Studio .NET or the tools inside the Microsoft .NET Framework SDK, feel free to plug the code in Listings 2.3 or 2.4 into a Windows form application. The next section walks you through the process of setting up a new virtual directory in Windows 2000 and adding a Web form that can be used to test your code. Web forms were chosen because they are compiled automatically when they are first requested by a Web browser, thus saving you from having to manually compile a Windows form each time you need to test some code. When you save the file, ASP.NET knows to recompile the Web form the next time the file is requested. Installing a new Web site on a Windows 2000 machine is a straightforward process: Make sure you are logged in as a user with administrative rights. Locate (or create) a directory on your computer where you will place the files to be served by Internet Information Server (IIS, Microsoft's Web server that comes built into Windows 2000). In the Administrative Tools program group , load the Internet Services Manager. Expand the entry for your computer. You should now see a screen much like Figure 2.2. If you do not have an entry for the Internet Services Manager, you probably do not have IIS installed. You can use the Add/Remove Programs entry in the Control Panel to add the Windows 2000 IIS components . Please refer to your operating system manual for more details. Expand the Default Web Site entry (which is installed by default). You should see a number of subentries. Right-click on Default Web Site and select New Virtual Directory. The Virtual Directory Creation Wizard appears (see Figure 2.3). Click Next. The wizard prompts you for an alias. Enter 24Hours and click Next. In the next screen, either type or browse to the directory you created in step 1 and click Next. On the Access Permissions screen, leave Read and Run scripts checked and also check Browse. Click Next. You have successfully added a new virtual directory to your Web site! If you are concerned about security, you should change the default security settings for the new virtual directory. Right-click on the 24Hours virtual directory under the Default Web Site. Click on the Directory Security tab. Select the Edit button in the IP Address and Domain Name Restrictions dialog box as shown in Figure 2.4. Select the bottom bullet labeled Denied Access. Then click the Add button, enter 127.0.0.1, and click the OK button. The 24Hours site can now only be loaded from the computer it is loaded on. The site is now only available to users of your computer. If someone tries to access the site from a remote machine, they will be denied access. The site can be accessed by using either or. The site is currently empty, but you will be able to browse to the folders and files of the site after we add some Web forms. Before you can test the code in this chapter, you must create a few pages that will contain the code. One page is needed for the Visual Basic .NET examples and another is needed for the C# examples. Create two new files in the 24Hours directory named _24HoursVB.aspx and _24HoursCS.aspx. These files will be used as templates. Place the code from Listing 2.5 into _24HoursVB.aspx and save the file. Place the code from Listing 2.6 into _24HoursCS.aspx and save the file. Create a copy of the _24HoursVB.aspx file and name it chapter2VB.aspx. Create a copy of the _24HoursCS.aspx file and name it chapter2CS.aspx. By repeating steps 4 and 5 of the previous task, you can use the _24Hours*.aspx files as templates for the examples in this book, unless otherwise noted. When you are done configuring these files, your directory will look like the one in Figure 2.5. <% ) 'Place VB.NET ADO.NET Code here End> <% @Page <!-- End Style Sheet --> <script language="C#" runat="server" > void Page_Load(Object Source, EventArgs E) { //Place C# ADO.NET example code> The Web forms in Listings 2.5 and 2.6 contain: A label Web control that will be used to display text messages A DataGrid Web control that will be used to display the contents of your DataSet s To test this hour's code, just place the code from Listing 2.3 into the VB.NET test harness in Listing 2.5 where it says "Place VB.NET ADO.NET Code here." All that remains is to connect the DataGrid to the DataSet . That can be achieved with two lines of code: myDataGrid.DataSource = dtEmployees myDataGrid.DataBind() This instructs the DataGrid to use the dtEmployees DataSet as its data source and display it on the page when the page loads. Listing 2.7 contains the entire example in VB.NET. When you load the page, your results should look similar to those in Figure 2.6. For more information on the DataGrid Web control, please see Hour 11, "Using the Built-In ASP.NET List Controls." <% ) 'Create Principle Objects dim dsCompany as new DataSet() dim dtEmployees as DataTable = dsCompany.Tables.Add("Employees") 'Create Columns dtEmployees.Columns.Add("EmployeeID", Type.GetType("System.Int32")) dtEmployees.Columns.Add("FirstName", Type.GetType("System.String")) dtEmployees.Columns.Add("LastName", Type.GetType("System.String")) ") = "Santa" workRow1("LastName") = "Claus" 'Add new rows to the DataTable dtEmployees.Rows.Add(workRow) dtEmployees.Rows.Add(workRow1) employees.DataSource = dtEmployees employees.DataBind() End Sub </script> </HEAD> <BODY> <h1>ADO.NET In 24 Hours Examples</h1> <hr> <form runat="server"> <asp:Label</asp:Label> <asp:DataGrid</asp:DataGrid> </form> <hr> </BODY> </HTML> The code in Listing 2.7 may appear a bit daunting at first. However, it's easier to understand the code if you analyze it in logical sections. The code in Lines 13 sets some global properties for the Web form. Specifically, Line 1 sets the language of the Web form to Visual Basic .NET and turns on debugging. Lines 23 load the System.Data and System.Data.SqlClient namespaces. This enables you to access objects such as the DataSet and DataRow in the server-side code. Lines 1039 in Listing 2.7 are a block of script that executes on the server. The code consists of a single method: The Page_Load() event is automatically run whenever the page loads. Inside the Page_Load() event, lines 1314 create new DataSet and DataTable objects. Lines 1619 add some columns directly to the DataTable . These columns define the appearance of the data that is added next. Lines 2133 use the previously defined columns of the DataTable to add a few rows of data. Specifically, two new rows are created, configured, and then finally added to the DataTable object in Lines 3133. Finally, the DataTable is bound to the DataGrid Web control, created on line 49. For now, don't worry about the details of databinding; the DataGrid just knows how to automatically loop through all the rows in the DataTable and display them on the page as in Figure 2.6.
https://flylib.com/books/en/2.622.1.24/1/
CC-MAIN-2020-34
refinedweb
1,452
68.36
How to Populate react-redux-form With Dynamic Default Values How to Populate react-redux-form With Dynamic Default Values In this livecoding/article tutorial, you'll learn how to create auto-populated inputs on a web page using the React framework along with Redux. Join the DZone community and get the full member experience.Join For Free Start coding something amazing with our library of open source Cloud code patterns. Content provided by IBM. Here's a problem that took me embarrassingly long to solve: How do you populate dynamic values into a react-redux-form? First of all, react-redux-form is not the same as redux-form. They're similar but not the same. The internet is confused about this issue, and that makes googling hard. Second of all, we're talking about a form driven by Redux. Pre-filling it with default values should be as easy as filling out its Redux state. Right? Well, forms live in their own reducers that you don't have direct access to. They use a bunch of internal states to mark inputs as dirty and focused and whatnot. It's a mess. Let's start at the beginning. A Simple react-redux-form Here's a simple form built using react-redux-form. It has two input fields. When you Submit, it outputs your values to the console. See the Pen ReactReduxForm - Quick Start by Swizec Teller CodePen.i0. Borrowed the code straight from @davidkpiano's official Quick Start example. Our form starts with a model and a Redux store: const initialUserState = { firstName: '', lastName: '', }; const store = createStore(combineForms({ user: initialUserState, }), applyMiddleware(thunk)); initialUserState describes the shape of a user and combineForms creates a special reducer. That reducer takes care of driving the UI for our form and storing values. You'd think you could add default values to initialUserState, and you can. Hold that thought... let's make sure we understand react-redux-form first. The form itself comes in as a React component using <Control> elements from react-redux-form. class UserForm extends Component { handleSubmit(values) { console.log(values); } render() { return ( <Form model="user" onSubmit={(values) => this.handleSubmit(values)} > <div className="field"> <label>First name:</label> <Control.text </div> <div className="field"> <label>Last name:</label> <Control.text </div> <button type="submit"> Submit </button> </Form> ) } } handleSubmit is the function we call when a user submits either by pressing the Submit button or hitting Enter. In our case, it prints values to the console. The render method uses a <Form> component from react-redux-form. It comes with all the necessary Redux wiring so we don't have to worry about that. We use the children of that component to define how it renders. In our case, that's two divs, some labels, a submit button, and two <Control.text> components. <Control.X> components come with all the necessary wiring for our form to work. They'll handle focus, blur, default values, matching to correct parts of our model, and so on. Everything we don't want to worry about manually. Wonderful! Static Versus Dynamic Default Values Back to that obvious thought. Why can't you just use initialUserState to define default values? You can. As long as your default values are static. Let me explain. Your default form values are static if you know them in advance. Like when you're writing your code. This is pretty rare. What if you're building an edit form? You can't know values for your form until the user chooses what they're editing. And that's when trouble begins. Fill react-redux-form With Dynamic Default Values @lukeed05 helped me find the solution during livecoding. Thanks, mate. Here's how you do it: react-redux-form comes with a bunch of model actions. Actions, its reducer, understands. Actions is what it can use to do special things, like populate your form. See the Pen ReactReduxForm - Dynamic Default Values by Swizec Teller on CodePen. Tap the "Change Defaults" button to pick a new random user. Its name will populate the form, and you can edit it to your heart's content. To make that work, we used a Redux action generator called actions.merge. It lets us merge the form model with a new set of default values. First, we connect our UserForm component to Redux. const mapDispatchToProps = { setDefaultUser: (values) => actions.merge('user', values) } const ConnectedForm = connect(null, mapDispatchToProps)(UserForm); The usual stuff. Use connect to connect to Redux, there are no props we need from state, and we use mapDispatchToProps to add a dispatch function called setDefaultUser. setDefaultUser is a curried application of actions.merge. This takes a value object and merges it with the user model in our store. I wired it to an onClick callback in this example so you can try it multiple times. changeUser() { this.props.setDefaultUser( randomUsers[Math.floor(Math.random()*randomUsers.length)] ) } Another approach you can use is to call this action in componentDidMount. That gives you true defaults - a form populated as soon as a user sees it. Happy hacking! }}
https://dzone.com/articles/how-to-populate-react-redux-form-with-dynamic-defa
CC-MAIN-2018-47
refinedweb
848
59.7
Why can't Python parse this JSON data? Your data is not valid JSON format. You have []when you should have {}: listin Python dictin Python Here's how your JSON file should look: { "maps": [ { "id": "blabla", "iscategorical": "0" }, { "id": "blabla", "iscategorical": "0" } ], "masks": { "id": "valore" }, "om_points": "value", "parameters": { "id": "valore" }} Then you can use your code: import jsonfrom pprint import pprintwith open('data.json') as f: data = json.load(f)pprint(data) With data, you can now also find values like so: data["maps"][0]["id"]data["masks"]["id"]data["om_points"] Try those out and see if it starts to make sense. Your data.json should look like this: { "maps":[ {"id":"blabla","iscategorical":"0"}, {"id":"blabla","iscategorical":"0"} ],"masks": {"id":"valore"},"om_points":"value","parameters": {"id":"valore"}} Your code should be: import jsonfrom pprint import pprintwith open('data.json') as data_file: data = json.load(data_file)pprint(data) Note that this only works in Python 2.6 and up, as it depends upon the with-statement. In Python 2.5 use from __future__ import with_statement, in Python <= 2.4, see Justin Peel's answer, which this answer is based upon. You can now also access single values like this: data["maps"][0]["id"] # will return 'blabla'data["masks"]["id"] # will return 'valore'data["om_points"] # will return 'value' Justin Peel's answer is really helpful, but if you are using Python 3 reading JSON should be done like this: with open('data.json', encoding='utf-8') as data_file: data = json.loads(data_file.read()) Note: use json.loads instead of json.load. In Python 3, json.loads takes a string parameter. json.load takes a file-like object parameter. data_file.read() returns a string object. To be honest, I don't think it's a problem to load all json data into memory in most cases.I see this in JS, Java, Kotlin, cpp, rust almost every language I use.Consider memory issue like a joke to me :) On the other hand, I don't think you can parse json without reading all of it.
https://codehunter.cc/a/python/why-cant-python-parse-this-json-data
CC-MAIN-2022-21
refinedweb
341
59.3
OO style matplotlib? - bennettbrowniowa First, WOW! I love Pythonista already! Thank you to creators and contributors! I am using matplotlib and prefer to use the OO style of coding as described <a href="">here</a>. In other Python environments, I have no difficulty doing this, but in Pythonista the script import matplotlib.pyplot as plt fig, ax = plt.subplots(1, 1) ax.plot(1, 1, 'ro') fig.show() produces the error "UserWarning: matplotlib is currently using a non-GUI backend, so cannot show the figure." I tried adding plt.ioff()to the script, since Pythonista documentation does warn that matplotlib GUIs will not implement interactive behavior, but it still does not produce the plot. I am able to produce the expected plot using plt.plot(1, 1, 'ro'). The <a href=""> Pythonista mirror of matplotlib's documentation </a> seems to suggest I can use the OO style to code with matplotlib. Is it possible to use the OO interface to matplotlib with Pythonista? If so, how? Thanks for the feedback. You can work around this limitation by saving the plot to an image first, and showing that (the non-OO show()does pretty much the same internally): import matplotlib.pyplot as plt import Image fig, ax = plt.subplots(1, 1) ax.plot(1, 1, 'ro') fig.savefig('mpl_out.png') Image.open('mpl_out.png').show()
https://forum.omz-software.com/topic/1125/oo-style-matplotlib
CC-MAIN-2018-05
refinedweb
224
70.9
Introduction In this article I am describing the ActionResult method used in Model View Controller (MVC) based ASP.NET Web Applications. The ActionResult method is derived from the ActionResult Class. The ActionResult Class encloses the output of the action method and does the operation. ActionResult is a very valuable aspect of the MVC. ActionResult The ActionResult method works as a return type of any controller method in the MVC. It acts like the base class of Result classes. It is used to return the models to the Views, file streams and also redirect to the controllers. It is the responsibility of the Controller that it connects the component. The following code is an example of an ActionResult method: public ActionResult Index() { ViewBag.Message = "Modify this template to jump- start your ASP.NET MVC application."; return View(); } public ActionResult About() ViewBag.Message = "Your app description page."; You can use many DerivedTypes of the ActionResult to return the result that works individually for an appropriate view. If you want to use any of the DerivedTypes of ActionResult then simply hover any of them over an ActionResult method. You can see all the DerivedTypes of the Action method using the following procedure. Step 1: Install the Productivity Power Tools for Visual Studio. Step 2: Restart the Visual Studio (if open). Step 2: Just hover the mouse on the ActionResult. You will see the following image: You can watch the ViewBag properties to see the strongly typed collection of the objects. For that use the following procedure. Step 1: Insert the breakpoint at the end of the ActionResult. Step 2: Debug the application and just right-click on the ViewBag and click on "AddWatch". Now you can see and expand the properties. Action Methods and Routing In the MVC app, both the ActionResult method and routing work together to perform the operation. You can see the "Global.asax.cs" file for the defined routing patterns that connect the Action methods and controllers with the HTTP requests. The predefined routing pattern of the Global.asax.cs file is as follows: {Controller}/{action}/{id} Just as in the following code: public class RouteConfig public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } Now let's have a look at the code above in brief: Action methods also nominate which result will be returned, HttpNotFoundResult or HttpStatusCodeResult. In the Controller class, all the action methods defined have normally a corresponding view in the Views folder. For example, here in the previous code the Index() and About() action methods have their View in the Views folder. You can see that in the following image: Summary So far in this article I described the ActionResult method of MVC based ASP.NET Web Application. You can say that it is a very important part of the MVC application. Thanks for reading. ©2016 C# Corner. All contents are copyright of their authors.
http://www.c-sharpcorner.com/UploadFile/4b0136/introduction-to-actionresult-method-in-mvc/
CC-MAIN-2016-18
refinedweb
500
59.3
A captcha library that generates audio and image CAPTCHAs. Project description A captcha library that generates audio and image CAPTCHAs. Features - Image CAPTCHAs Installation Install captcha with pip: $ pip install captcha Usage Audio and Image CAPTCHAs are in seprated modules: from io import BytesIO from captcha.audio import AudioCaptcha from captcha.image import ImageCaptcha audio = AudioCaptcha(voicedir='/path/to/voices') image = ImageCaptcha(fonts=['/path/A.ttf', '/path/B.ttf']) data = audio.generate('1234') assert isinstance(data, bytearray) audio.write('1234', 'out.wav') data = image.generate('1234') assert isinstance(data, BytesIO) image.write('1234', 'out.png') This is the APIs for your daily works. We do have built-in voice data and font data. But it is suggested that you use your own voice and font data. Contribution We need voice wav files. The voice wav file should be in 8-bit, please keep it as small as possible. Name your voice file as: {{language}}-{{character}}-{{username}}.wav # exmaple: zh-1-lepture.wav TODO: we need a place to upload voice files. Project details Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages. Source Distribution captcha-0.1.1.tar.gz (100.4 kB view hashes)
https://pypi.org/project/captcha/0.1.1/
CC-MAIN-2022-40
refinedweb
207
63.36
WlanSetPsdIEDataList function The WlanSetPsdIeDataList function sets the proximity service discovery (PSD) information element (IE) data list. Syntax Parameters - hClientHandle [in] The client's session handle, obtained by a previous call to the WlanOpenHandle function. - strFormat [in] The format of a PSD IE in the PSD IE data list passed in the pPsdIEDataList parameter. This is a NULL-terminated URI string that specifies the namespace of the protocol used for discovery. - pPsdIEDataList [in] A pointer to a WLAN_RAW_DATA_LIST structure that contains the PSD IE data list to be set. - pReserved Reserved for future use. Must be set to NULL. Return value If the function succeeds, the return value is ERROR_SUCCESS. If the function fails, the return value may be one of the following return codes. Remarks The Proximity Service Discovery Protocol is a Microsoft proprietary protocol that allows a client to discover services in its physical proximity, which is defined by the radio range. The purpose of the Proximity Service Discovery Protocol is to convey service discovery information, such as service advertisements, as part of Beacon frames. Access points (APs) and stations (STAs) that operate in ad hoc mode periodically broadcast beacon frames. The beacon frame can contain single or multiple proprietary information elements that carry discovery information pertaining to the services that the device offers. A PSD IE is used to transmit compressed information provided by higher-level discovery protocols for the purpose of passive discovery. One such higher-level protocol used for discovery is the WS-Discovery protocol. Any protocol can be used for discovery. Windows Vista and Windows Server 2008 with the Wireless LAN Service installed support passive discovery for ad hoc clients, ad hoc services, and infrastructure clients. This means an ad hoc service can advertise an available resource or service by transmitting a PSD IE in one or more beacons. There is no guarantee that this beacon is received by an ad hoc or infrastructure client. Windows 7 and Windows Server 2008 R2 with the Wireless LAN Service installed support passive discovery for ad hoc clients, ad hoc services, and infrastructure clients in the same way as in Windows Vista. In addition, the PSD IE is also supported for the wireless Hosted Network, a software-based wireless access point (AP). Applications on the local computer where the wireless Hosted Network is to be run may use the WlanSetPsdIeDataList function to set the PSD IE before starting the wireless Hosted Network. Once set, the PSD IE will be included in the beacon and probe response after the wireless Hosted Network is started. Each application sending or receiving beacons maintains its own PSD IE data list. The pPsdIEDataList parameter points to a list of PSD IEs generated by the application. Each PSD IE has the following format.. The Format identifier hash field describes the format of the information carried in the PSD IE. To ensure uniqueness while circumventing the need for central administration of format identifiers, a string in the form of a Uniform Resource Identifier (URI), as specified in RFC 3986, is used to distinguish the format. However, because the transmission must be efficient and space in the information element is limited, the string is not actually transmitted, but, instead, its hash is transmitted. On the client, which is the receiving side of the beacon, the hash is matched against a known set of format identifiers. The Format identifier hash field is represented by bits 0…31 of a hash-based message authentication code (HMAC) over the format identifier string specified in the strFormat parameter. The HMAC is used to specify the format of the Data field of the PSD IE. The formula used to calculate the HMAC is described in RFC 2104. Sample code for the calculation of the HMAC is as specified in RFC 4634. When calculating the HMAC, use SHA-256 for the hash function. The key used is the "null" key (NULL pointer to the authentication key, and zero length authentication key per the source code in RFC 4634). Use the value of strFormat parameter (including any spaces but excluding the NULL-termination character) as the input text encoded as Unicode UTF-16 in little-endian format. For example, if the strFormat parameter is, then the first four octets of the corresponding HMAC is 0xF8 0xCB 0x35 0x15. If the strFormat parameter is, then the four octets of the corresponding HMAC are 0xCF 0xF1 0x64 0x17. When sending the first 4 octets of an HMAC over the network, send the first (left-most) octet first. Note that there may be collisions in the truncated HMACs, which means that it may be impossible to uniquely determine the discovery protocol corresponding to the payload of a PSD IE from the given bits of an HMAC. An application receiving a PSD IE must take a best guess at the discovery protocol used from a given HMAC, then re-run the higher-level discovery protocol once a connection has been established. At most, five PSD IEs can be passed in a list. Also, the total length, in bytes, of the PSD IE list may be restricted by hardware limitations on the length of a beacon. An application can call WlanSetPsdIeDataList many times. When WlanSetPsdIeDataList is called twice with the same strFormat, the contents of the WLAN_RAW_DATA_LIST populated by the first function call are overwritten by the second call's WLAN_RAW_DATA_LIST payload. When WlanSetPsdIeDataList is called with the pPsdIEDataList parameter set to NULL, the PSD IE list associated with strFormat is cleared. When WlanSetPsdIeDataList is called with both the pPsdIEDataList and strFormat parameters set to NULL, all PSD IE lists set by the application are cleared. The wireless service processes PSD IE data lists set by different applications and generates raw IE data blobs. When a machine creates or joins an ad-hoc network on any wireless adapter, it sends beacons that include a PSD IE data blob associated with the network to other machines. Stations can call WlanExtractPsdIEDataList function to get the PSD IE data list after receiving a beacon from a machine. Requirements See also
https://msdn.microsoft.com/en-us/library/windows/desktop/ms706815(v=vs.85).aspx
CC-MAIN-2017-39
refinedweb
1,009
52.09
All you need to learn about Angular, the best tips and free code examples so you can get the most out of Angular in this article! Let me introduce you to Angular Angular is a JavaScript open-source front-end web application framework. It is primarily sustained by Google together with an extended community of people and companies, to approach many of the challenges faced when developing single page, cross platform, performant applications. It is fully extensible and works well with other libraries. For additional details visit their official documentation pages. My goal in this Angular real world example tutorial is to provide a complete guide for you to learn Angular step by step. We will start explaining the why’s and basic concepts and then continue exploring more advanced notions. We began testing and experimenting with the very first release of Angular 2.0.0-beta.0 on december 2015 with hopes of finding a framework that was clearly better than its predecessor (Angular 1.x aka AngularJS). I’m gonna be completely honest with you here, we almost give up with all the inconsistency, breaking changes and a sort of identity crisis that happened in the middle of the Angular 2+ development. It was a long way until Angular reached a solid milestone with Universal (server-side rendering), ahead-of-time compilation, lazy loading and a solid webpack bundling config working together nicely. You can check our most recent creation with Angular 7 and all these features in Angular Admin Template. Being working, using and trying things out with this framework from the very beginning made us really understand the way Angular was designed and how it evolved. We were witnesses of the constant improvements and saw how they were all aligned to one simple yet important goal: "Angular should be easy to develop". As I mentioned before, for some time during the process, it wasn’t. Now I can tell you, Angular is a super solid and stable framework you would love to work with. Forget what you heard about Angular 2 syntax some years ago, things looked different than you were used to in Angular 1 and no doubt you may feel confused. Current versions of Angular 7 had evolved to the point where you will be quickly impressed. Angular is a great tool that will: Differences between Angular versions When it all started, back in 2010, this framework was called AngularJS, and alludes to what we now know as Angular 1.x. Then in 2016, Angular 2 arrived as a complete rewrite of the framework, improving from lessons learned and promising performance improvements, and a more scalable and more modern framework. AngularJS was completely based on controllers and the view communicates using $scope whereas Angular 2 is 100% a component-based approach. In Angular 2, we don't have anymore the controllers and $scope. Components are the building blocks of an Angular 2 app. We will see the benefits of this change in a few minutes. The first version of Angular was named Angular 2. Later on, it was renamed to "Angular". Between Angular 2 and Angular 7 (the current latest stable version) there was Angular 4 (released early 2017), Angular 5 (released late 2017) and Angular 6 (released early 2018). Don't freak out will all these versions. Because all versions from Angular 2 to Angular 7 are the same framework, they share the same core but they differ in lots of amazing improvements! From now on, every time we use the term Angular we are referring to the latest version of the framework that today is Angular 7. For more information about Angular latest versions please refer to: Let’s go through the main differences between AngularJS and Angular: Angular also recommends using the TypeScript language, which introduces these features: On top of TypeScript features, Angular also includes the benefits taken from ES6: There were some major changes, but mostly on the project structure with lots of refactors that made the framework more stable. Angular 7 is full of new features, bug fixes, performance improvements, and some code deprecation as a clean up of the refactors from old versions. Moving ahead in this Angular tutorial, let’s setup the development environment. After the previous introduction about the current state of the Angular Framework, we are now ready to get started working on our angular 7 app. The best way to learn Angular is by following this step by step tutorial for beginners. Let’s start building a complete web app sample project with Angular We will show you how to setup your local development environment so you can start developing Angular apps. A real application development happens in a local development environment that could be your personal machine. Follow our setup instructions to create a new Angular project. Node.js and npm are fundamental to modern web development using Angular and other platforms. Node empowers client development and build tools. We are gonna use the node package manager (npm) to install all the JavaScript libraries dependencies. Get these right now if they’re not installed on your computer. Note: Verify that you are running at least node 8.x and npm 6.x by running node -v and npm -v in a terminal/console window. Older versions may produce errors, but newer versions are always recommended. Angular apps are created and developed primarily through the Angular CLI (command line interface tool) that helps project creation, adding files, and performing a variety of ongoing development tasks. The Angular CLI takes care of configuration and initialization of various libraries. It also helps us adding components, directives, services, etc, to already existing Angular applications. It’s also worth mentioning that the CLI uses Typescript and Webpack for module bundling, Karma for unit testing, and Protractor for an end to end testing. It includes everything you need to start writing your Angular application right away. To install the Angular CLI globally, run the following command on your console npm install -g @angular/cli Note: although it's not recommended, you may need to add "sudo" in front of these commands to install the utilities globally. Important note: If you have an older version of the CLI installed in your computer, make sure you properly update it to the latest Angular CLI. Now that you have Angular and its dependencies installed, we can move on and start building our Angular app. Let’s get started! Starting a new angular app with the CLI is easy! From your command line, run this command: ng new "my-new-angular-app" The command above will create a folder named "my-new-angular-app" and will copy all the required dependencies and configuration settings. The Angular CLI does this for you: You can also use the ng init command. The difference between ng init and ng new is that ng new requires you to specify the folder name and it will create a folder copying the files while ng init will copy the files to the current folder. Now, you can cd into the created folder. To get a quick preview of your app inside the browser, use the serve command use ng serve This command runs the compiler in watch mode (looks for changes in the code and recompiles if needed), starts the server, launches the app in a browser, and keeps the app running while we continue building it. The Webpack Development server listens on HTTP port 4200. Hence, if you open the url you will see the app running. In Angular, there’s some more boilerplate compared to AngularJS (Angular 1), but don’t panic. The new Angular CLI also has more tools to help you out with this. For example, the new generator functions. They provide an easy way to create angular pages and services for your app. This makes going from a basic app to a full featured navigation web app much easier. I call that an easy learning curve :). To create a new component you can use the following command: ng generate component my-new-component ng g component my-new-component # using the alias √ Create app/pages/my-page/my-page.html √ Create app/pages/my-page/my-page.ts √ Create app/pages/my-page/my-page.scss The angular-CLI will add a reference to components, directives and pipes automatically in the app.module.ts. Note: Please refer to angular CLI documentation for more information about adding components and other elements to your app. What are we going to build? This tutorial takes you through the steps of creating an Angular application with TypeScript. The example app aims to help you learn the fundamental concepts of Angular Framework. With a questions and answers format (Q&A), the users will be able to make questions about different Angular key concepts and answer those from others. It will have a listing of some Angular key concepts such as Angular CLI and Typescript and within each of these categories, a questions list with the corresponding answers, the option to vote them (up-vote, down-vote) and some forms to create/delete/update questions and answers. The following screenshot is from the home page where you can see the list of categories: The plan for this tutorial is to build an app that takes you step-by-step from setup to a full-featured example that serves to demonstrate the essential characteristics of a professional application: a sensible project structure, data binding, services, resolvers, pipes, angular material, dependency injection, navigation and remote data access. We will learn enough core Angular to get started and gain the confidence that Angular can do whatever we need it to do. We will be covering a lot of ground at an introductory level but we will also link to plenty of references to topics with greater depth. The app consists in a CRUD (Create, Read, Update, Delete) of Questions and Answers where people can post new questions and answer other people's questions. In the next tutorial we will explore how to add a backend for this Angular app, using the MEAN stack. The App will have the following functionalities: This is how the final App will look like: In this first part, you will learn how to: Angular is a framework designed to build single page applications (SPAs) and most of its architecture design is focused towards doing that in an effective manner. Single-page application (or SPA) are applications that are accessed via web browser like other websites but offer more dynamic interactions resembling native mobile and desktop apps. The most notable difference between a regular website and SPA is the reduced amount of page refreshes. Typically, 95 percent of SPA code runs in the browser; the rest works in the server when the user needs new data or must perform secured operations such as authentication. As a result, the process of page rendering happens mostly on the client-side. Modules help organize an application into cohesive functionality blocks by wrapping components, pipes, directives, and services. They are just all about developer ergonomics. Angular applications are modular. Every Angular application has at least one module— the root module, conventionally named AppModule. The root module can be the only module in a small application, but most apps have many more modules. As the developer, it's up to you to decide how to use the modules. Typically, you map major functionality or a feature to a module. Let's say you have four major areas in your system. Each one will have its own module in addition to the root module, for a total of five modules. Any angular module is a class with the @NgModule decorator. Decorators are functions that modify JavaScript classes. They are basically used for attaching metadata to classes so that it knows the configuration of those classes and how they should work. The @NgModule decorator properties that describe the module are: Components are the most basic building block of an UI and Angular applications. A component controls one or more sections on the screen (what we call views). For example in this example we have components like AppComponent (the bootstrapped component), CategoriesComponent, CategoryQuestionsComponent, QuestionAnswersComponent etc. A component is self contained and represents a reusable piece of UI that is usually constituted by three important things: Using the Angular @Component decorator we provide additional metadata that determines how the component should be processed, instantiated and used at runtime. For example we set the html template related to the view, then, we set the html selector that we are going to use for that component, we set stylesheets for that component. The Component passes data to the view using a process called Data Binding. This is done by Binding the DOM Elements to component properties. Binding can be used to display property values to the user, change element styles, respond to an user event, etc. A component must belong to an NgModule in order for it to be usable by another component or application. To specify that a component is a member of an NgModule, you should list it in the declarations property of that NgModule. One side note on the components importance from a point of software architecture principles: It’s super important and recommended to have separate components, and here’s why. Imagine we have two different UI blocks in the same component and in the same file. At the beginning, they may be small but each could grow. We are sure to receive new requirements for one and not the other. Yet every change puts both components at risk and doubles the testing burden without any benefits. If we had to reuse some of those UI blocks elsewhere in our app, the other one would be glued along. That scenario violates the Single Responsibility Principle. You may think this is only a tutorial, but we need to do things right — especially if doing them right is easy and we learn how to build Angular apps in the process. Angular encourages this principle by having each patch of the page controlled with it’s own component. A typical Angular application looks like a tree of components. The following diagram illustrates this concept. Note that the modal components are on the side of the parent component because they are imperative components which are not declared on the component html template. Templates are used to define a component view. A template looks like regular HTML, but it also has some differences. Code like *ngFor, {{hero.name}}, (click), and [hero] uses Angular template syntax to enhance HTML markup capabilities. Templates can also include custom components like in the form of non-regular html tags. These components mix seamlessly with native HTML in the same layouts. Almost anything can be a service, any value, function, or feature that your application needs. A service is typically a class with a narrow, well-defined purpose. It should do something specific and do it well. The main purpose of Angular Services is sharing resources across components. Take Component classes, they should be lean, component's job is to enable the user experience (mediate between the view and the application logic) and nothing more. They don't fetch data from the server, validate user input, or log directly to the console. They delegate such tasks and everything nontrivial to services. Services are fundamental to any Angular application, and components are big consumers of services as they help them being lean. The scenario we’ve just described has a lot to do with the Separation of Concerns principle. Angular doesn't enforce these principles, but it helps you follow these principles by making it easy to structure your application logic into services and make those services available to components through dependency injection. In our example app we have three services: AnswersService, QuestionsService, CategoriesService. Each of them has only the functions related to them. In this specific tutorial we will only focus on CategoriesService and in the following parts we will discuss the others. CategoriesService has the following methods: //gets all the question categories from a local json getCategories(){ return this.http.get("./assets/categories.json") .map((res:any) => res.json()) .toPromise(); } //finds a specific category by slug getCategoryBySlug(slug: string){ return this.getCategories() .then(data =>{ return data.categories.find((category) => { return category.slug == slug; }); }) } External resources like Databases, API’s, etc, are fundamental as they will enable our app to interact with the outside world. There’s much more to cover about the basic building blocks of Angular applications like Dependency Injection, Data Binding, Directives, etc. You can find these and much more information in our upcoming post about "Angular: The learning path". Now, let’s go deeper and map the project structure to the app’s architecture so we can understand better how all the pieces interact with each other. After following the setup instructions for creating a new project in the previous section, let’s walk through the anatomy of our Angular 7 app. The cli setup procedures install lots of different files. Most of them can be safely ignored. In the project root we have three important folders and some important files: /src/ This is the most important folder. Here we have all the files that make our Angular app. /e2e/ This folder is for the End-to-end tests of the application, written in Jasmine and run by the protractor e2e test runner. Please note that we will not enter in details about testing in this post. nodemodules/ The npm packages installed in the project with the npm install command.. Inside of the /src directory we find our raw, uncompiled code. This is where most of the work for your Angular app will take place. When we run ng serve, our code inside of /src gets bundled and transpiled into the correct Javascript version that the browser understands (currently, ES5). That means we can work at a higher level using TypeScript, but compile down to the older form of Javascript that the browser needs. Under this folder you will find two main folder structures. /app has all the components, modules, pages you will build the app upon. /environments this folder is to manage the different environment variables such as dev and prod. For example we could have a local database for our development environment and a product database for production environment. When we run ng serve it will use by default the dev env. If you like to run in production mode you need to add the --prod flag to the ng serve. index.html/ It’s the app host page but you won’t be modifying this file often, as in our case it only serves as a placeholder. All the scripts and styles needed to make the app work are gonna be injected automatically by the webpack bundling process, so you don’t have to do this manually. The only thing that comes to my mind now, that you may include in this file, are some meta tags (but you can also handle these through Angular as well). And there are other secondary but also important folders /assets in this folder you will find images, sample-data json’s, and any other asset you may require in your app. This is the core of the project. Let’s have a look at the structure of this folder so you get an idea where to find things and where to add your own modules to adapt this project to your particular needs. /shared The SharedModule that lives in this folder exists to hold the common components, directives, and pipes and share them with the modules that need them. It imports the CommonModule because its component needs common directives. You will notice that it re-exports other modules. If you review the application, you may notice that many components requiring SharedModule directives also use NgIf and NgFor from CommonModule and bind to component properties with [(ngModel)], a directive in the FormsModule. Modules that declare these components would have to import CommonModule, FormsModule, and SharedModule. You can reduce repetition by having SharedModule re-export CommonModule and FormsModule so that importers of SharedModule get CommonModule and FormsModule for free. SharedModule can still export FormsModule without listing it among its imports. /styles Here you will find all the variables, mixins, shared styles, etc, that will make your app customizable and extendable. Maybe you don’t know Sass? Briefly, it is a superset of css that will ease and speed your development cycles incredibly. /services Here you will find all the services needed in this app. Each service has only the functions related to it. Other folders To gain in code modularity, we’ve created a folder for each component. Within those folders you will find every related file for the pages included in that component. This includes the html for the layout, sass for the styles and the main page component. app.component.html This serves as the skeleton of the app. Typically has a to render the routes and their content. It can also be wrapped with content that you want to be in every page (for example a toolbar). app.component.ts It’s the Angular component that provides functionality to the app.component.html file I just mentioned about. app-routing.module.ts Here we define the main routes. These routes are registered to the Angular RouterModule in the AppModule. If you use lazy modules, child routes of other lazy modules are defined inside those modules. app.module.ts This is the main module of the project which will bootstrap the app. As we advance in this tutorial we will be creating more pages and perform basic navigation. After seeing the components diagram and the project structure, this is the navigation we propose for the app. We start in the categories page and from there we can only navigate to the questions of one of the categories. Then follow the arrows from the image below to see the other navigations available in this angular 7 example app. Note that the modals for creating, updating and deleting are not shown in this image because they don’t represent an app navigation. Another important thing to consider is that we used Breadcrumbs to navigate back to the previous pages. Before we start thinking about navigation, we must consider the type and amount of data you want to display in your app. Don't forget you will use navigation to show and structure your data, that is why it should follow the information structure of your app and not the other way around. It is important to keep the best practices for navigation design. This ensures that people will be able to use and find the most valuable features in your app. Good navigation, like good design, is invisible. A little more about the navigation Angular has a specific module dedicated to navigation and routing, the RouterModule. With this module you can create routes, which allows you to move from one part of the application to another part or from one view to another. For routes to work, you need an anchor or element in the UI to map actions (typically clicks on elements) to routes (URL paths). We use the routerLink directive for this purpose. For example, when the user clicks on a Category name in the UI, Angular, through the routerLink directive, knows that it needs to navigate to the following url: <a class="list-title" [routerLink]="['/questions/about', category.slug]">{{category.title}}</a> Next, you'll need to map the URL paths to the components. In the same folder as the root module, create a config file called app.routes.ts (if you don’t have one already) with the following code. import { Routes } from '@angular/router'; export const routes: Routes = [ { path: '', component: CategoriesComponent, resolve: { data: CategoriesResolver } }, { path: 'questions/about/:categorySlug', component: CategoryQuestionsComponent, resolve: { data: CategoryQuestionsResolver } }, { path: 'question/:questionSlug', component: QuestionAnswersComponent, resolve: { data: QuestionAnswersResolver } } ]; For each route we provide a path (also known as the URL) and the component that should be rendered at that path. The empty string for the CategoriesComponent's path means that the CategoriesComponent will be rendered when there is no URL (also known as the root path). Note that for each route we also have a resolve. Using a resolve in our navigation routes allows us to pre-fetch the component’s data before the route is activated. Using resolves is a very good practice to make sure that all necessary data is ready for our components to use and avoid displaying a blank component while waiting for the data. For example in we use a CategoriesResolver to fetch the list of categories. Once the categories are ready, we activate the route. Please note that if the resolve Observable does not complete, the navigation will not continue. Finally, the root module must also know the routes we defined above. Add a reference to the routes in the imports property of the AppModule. import { routes } from './app.routes'; imports: [ RouterModule.forRoot(routes, { useHash: false } ) ], Notice how we use forRoot (or eventually forChild) methods on the RouterModule (the docs explain the difference in detail, but for now just know that forRoot should only be called once in your app for top level routes). Angular Material 2 vs ngx-bootstrap There are some libraries that provide high-level components which allow you to quickly construct a nice interface for your app. These include modals, popups, cards, lists, menus, etc. They are reusable UI elements that serve as the building blocks for your mobile app, made up of HTML, CSS, and sometimes JavaScript. Two of the most used UI component libraries are Angular Material and ngx-bootstrap. Angular Material is the official Angular UI library and provides tons of components. On the other hand, ngx-bootstrap provides a series of Angular components made on top of Twitter Bootstrap framework. In this Angular tutorial we are going to use Angular Material, but feel free to choose the one that best fits your needs as they are both super complete and robust. In this angular 7 example app, we have different layouts. For each view we need different UI components. Here’s a short list with the most important components we used for each view and a link to the specifics of the implementation of that view. Categories view A list showing the different Angular concepts you need to learn. Material Components: List component for the categories list Chips component for the category tags Category Questions view A view to show all the questions of a particular category. Material Components: List component for the questions list Button component Dialog component for the modals Question Answers view A view to show all the answers of a particular question. Material Components: List component for the answers list Button component Dialog component for the modals New Question and New Answer modals Modals to create/update questions and answers Material Components: Dialog component to manage the modal We also used Angular Material Toolbar Component for the breadcrumbs navigation. Please feel free to dig the library of UI components that Angular Material has in their components documentation page. Different alternatives for backend API data integrations The key to an evolving app is to create reusable services to manage all the data calls to your backend. As you may know, there are many ways when it comes to data handling and backend implementations. In this tutorial we will explain how to consume data from a static json file with dummy data. In the next tutorial Learn how to build a MEAN stack application you will learn how to build and consume data from a REST API with Loopback (a node.js framework perfectly suited for REST API’s) and MongoDB (to store the data). Both implementations (static json and remote backend API) need to worry about the app’s side of the problem, how to handle data calls. This works the same and is independent on the way you implement the backend. We will talk about models and services and how they work together to achieve this. We encourage the usage of models in combination with services for handling data all the way from the backend to the presentation flow. Domain Models Domain models are important for defining and enforcing business logic in applications and are especially relevant as apps become larger and more people work on them. At the same time, it is important that we keep our applications DRY and maintainable by moving logic out of components themselves and into separate classes (models) that can be called upon. A modular approach such as this, makes our app's business logic reusable. To learn more about this, please visit this great post about angular 2 domain models. Data Services Angular enables you to create multiple reusable data services and inject them in the components that need them. Refactoring data access to a separate service, keeps the component lean and focused on supporting the view. It also makes it easier to unit test the component with a mock service. To learn more about this, please visit angular 2 documentation about services. In our case, we defined a model for the question categories data we are pulling from the static json file. This model is used by the categories.service.ts. //in category.model.ts export class CategoryModel { slug: string; title: string; image: string; description: string; tags: Array<Object>; } //in categories.service.ts getCategories(): Promise<CategoryModel[]> { return this.http.get("./assets/categories.json") .toPromise() .then(res => res.json() as CategoryModel[]) } And we use this service in the categories.resolver.ts where we fetch the categories view data. //in categories.resolver.ts import { Injectable } from '@angular/core'; import { Resolve } from "@angular/router"; import { CategoriesService } from "../services/categories.service"; @Injectable() export class CategoriesResolver implements Resolve<any> { constructor(private categoriesService: CategoriesService) { } resolve() { return new Promise((resolve, reject) => { let breadcrumbs = [ { url: '/', label: 'Categories' } ]; //get categories from local json file this.categoriesService.getCategories() .then( categories => { return resolve({ categories: categories, breadcrumbs: breadcrumbs }); }, err => { return resolve(null); } ) }); } } Each time we add a new service remember that the Angular injector does not know how to create that Service by default. If we ran our code now, Angular would fail with an error. After creating services, we have to teach the Angular injector how to make that Service by registering a Service provider. According to the Angular documentation page for dependency injection there are two ways to register the Service provider: in the Component itself or in the Module (NgModule). In our case, we register all services in the app.module.ts //in app.module.ts @NgModule({ declarations: [ AppComponent, CategoriesComponent, CategoryQuestionsComponent, NewQuestionModalComponent, NewAnswerModalComponent, UpdateAnswerModalComponent, QuestionAnswersComponent, DeleteQuestionModalComponent, DeleteAnswerModalComponent ], imports: [ RouterModule.forRoot(routes, { useHash: false } ), SharedModule ], entryComponents: [ ], providers: [ CategoriesService, QuestionsService, AnswersService, CategoryQuestionsResolver, CategoriesResolver, QuestionAnswersResolver ], bootstrap: [AppComponent] }) export class AppModule { } One side note on the importance of Dependency Injection from the software architecture principles point: Remember we just mentioned that we "inject" data services in the components that need them? Well, this concept is called Dependency Injection and it is super important to know more about this. Do we new() the Services? No way! That's a bad idea for several reasons including: We get it. Really we do. But it is so ridiculously easy to avoid these problems that there is no excuse for doing it wrong. Final thoughts and next steps In this angular step by step tutorial we went from the basic concepts and why’s of Angular Framework to building a complete Angular 7 app using Angular Material components. We explained one by one the main building blocks of an Angular application as well as the best practices for building a complete app with Angular. Also this tutorial shows how to setup your dev environment so you can start developing Angular apps in your computer right now. In this tutorial we only explained the first part of the code example which is the categories list fetched from a static json file. In our next tutorials we will explore deeper into the details of implementing the remote backend API using Loopback and how to deploy it in a remote server.. Thank for reading ! Originally published on angular-templates.io Learn more on angular angular-js node-js typescript web-development...
https://morioh.com/p/f7c9d191a82a
CC-MAIN-2020-40
refinedweb
5,392
53.41
This It was just another day at the bottom of the ocean until an explosion in one of the storage bays cracked the protective dome around Deep Sea Research Lab Alpha. Now the entire place is flooding, and the emergency pump system is a chaotic jumble of loose parts. Designing a puzzle game The Puzzler has always been a popular game genre. From old standbys like Tetris to modern crazes like Bejeweled, puzzle games are attractive to players because they do not require a long-term time investment or a steep learning curve. The game mechanic is the heart of any good puzzle game. This mechanic is usually very simple, with perhaps a few twists to keep the players on their toes. In Flood Control, the player will be faced with a board containing 80 pieces of pipe. Some will be straight pipes and some will be curved. The objective of the game is to rotate the pipes to form a continuous line to pump water from the left side of the board to the right side of the board. Completing a section of pipe drains water out of the base and scores points for the player, but destroys the pipes used. New pipes will fall into place for the player to begin another row. Time for action - set up the Flood Control projectWhat just happened? You have now set up a workspace for building Flood Control, and created a couple of folders for organizing game content. You have also imported the sample graphics for the Flood Control game into the project. Introducing the Content Pipeline The Flood ControlContent (Content) project inside Solution Explorer is a special kind of project called a Content Project. Items in your game's content project are converted into .XNB resource files by Content Importers and Content Processors. If you right-click on one of the image files you just added to the Flood Control project and select Properties, you will see that for both the Importer and Processor, the Content Pipeline will use Texture - XNA Framework. This means that the Importer will take the file in its native format (.PNG in this case) and convert it to a format that the Processor recognizes as an image. The Processor then converts the image into an .XNB file which is a compressed binary format that XNA's content manager can read directly into a Texture2D object. There are Content Importer/Processor pairs for several different types of content—images, audio, video, fonts, 3D models, and shader language effects files. All of these content types get converted to .XNB files which can be used at runtime. In order to see how to use the Content Pipeline at runtime, let's go ahead and write the code to read these textures into memory when the game starts: Time for action - reading textures into memory - Double-click on Game1.cs in Solution Explorer to open it or bring it to the front if it is already open. - In the Class Declarations area of Game1 (right below SpriteBatch spriteBatch;), add: Texture2D playingPieces; Texture2D backgroundScreen; Texture2D titleScreen; - Add code to load each of the Texture2D objects at the end of LoadContent(): playingPieces = Content.Load(@"Textures\Tile_Sheet"); backgroundScreen = Content.Load(@"Textures\Background"); titleScreen = Content.Load(@"Textures\TitleScreen"); In order to load the textures from disk, you need an in-memory object to hold them. These are declared as instances of the Texture2D class. A default XNA project sets up the Content instance of the ContentManager class for you automatically. The Content object's Load() method is used to read .XNB files from disk and into the Texture2D instances declared earlier. One thing to note here is that the Load() method requires a type identifier, specified in angled brackets (), before the parameter list. Known in C# as a "Generic", many classes and methods support this kind of type specification to allow code to operate on a variety of data types. We will make more extensive use of Generics later when we need to store lists of objects in memory. The Load() method is used not only for textures, but also for all other kinds of content (sounds, 3D models, fonts, etc.) as well. It is important to let the Load() method know what kind of data you are reading so that it knows what kind of object to return. Sprites and sprite sheets As far as XNA and the SpriteBatch class are concerned, a sprite is a 2D bitmapped image that can be drawn either with or without transparency information to the screen. Sprites vs. Textures XNA defines a "sprite" as a 2D bitmap that is drawn directly to the screen. While these bitmaps are stored in Texture2D objects, the term "texture" is used when a 2D image is mapped onto a 3D object, providing a visual representation of the surface of the object. In practice, all XNA graphics are actually performed in 3D, with 2D sprites being rendered via special configurations of the XNA rendering engine. The simple form of the SpriteBatch.Draw() call when drawing squares only needs three parameters: a Texture2D to draw, a Rectangle indicating where to draw it, and a Color to specify the tint to overlay onto the sprite. Other overloads of the Draw() method, however, also allow you to specify a Rectangle representing the source area within the Texture2D to copy from. If no source Rectangle is specified, the entire Texture2D is copied and resized to fit the destination Rectangle. Overloads When multiple versions of the same method are declared with either different parameters lists or different return values, each different declaration is called an "overload" of the method. Overloads allow methods to work with different types of data (for example, when setting a position you could accept two separate X and Y coordinates or a Vector2 value), or leave out parameters that can then be assigned default values. By specifying a source Rectangle, however, individual pieces can be pulled from a large image. A bitmap with multiple sprites on it that will be drawn this way is called a "sprite sheet". The Tile_Sheet.png file for the Flood Control project is a sprite sheet containing 13 different sprites that will be used to represent the pieces of pipe used in the game. Each image is 40 pixels wide and 40 pixels high, with a one pixel border between each sprite and also around the entire image. When we call SpriteBatch.Draw() we can limit what gets drawn from our texture to one of these 40 by 40 squares, allowing a single texture to hold all of the playing piece images that we need for the game: The Tile_Sheet.png file was created with alpha-based transparency. When it is drawn to the screen, the alpha level of each pixel will be used to merge that pixel with any color that already occupies that location on the screen. Using this fact, you can create sprites that don't look like they are rectangular. Internally, you will still be drawing rectangles, but visually the image can be of any shape. What we really need now to be able to work with the playing pieces is a way to reference an individual piece, knowing not only what to draw to the screen, but what ends of the pipe connect to adjacent squares on the game board. Alpha blending Each pixel in a sprite can be fully opaque, fully transparent, or partially transparent. Fully opaque pixels are drawn directly, while fully transparent pixels are not drawn at all, leaving whatever has already been drawn to that pixel on the screen unchanged. In 32-bit color mode, each channel of a color (Red, Green, Blue, and Alpha) are represented by 8 bits, meaning that there are 256 different degrees of transparency between fully opaque (255) and fully transparent (0). Partially transparent pixels are combined with the current pixel color at that location to create a mixed color as if the pixels below were being seen through the new color. Classes used in Flood Control While it would certainly be possible to simply pile all of the game code into the Game1 class, the result would be difficult to read and manage later on. Instead, we need to consider how to logically divide the game into classes that can manage themselves and help to organize our code. A good rule of thumb is that a class should represent a single thing or type of thing. If you can say "This object is made up of these other objects" or "This object contains these objects", consider creating classes to represent those relationships. The Flood Control game contains a game board made up of 80 pipes. We can abstract these pipes as a class called GamePiece, and provide it with the code it needs to handle rotation and provide the code that will display the piece with a Rectangle that can be used to pull the sprite off the sprite sheet. The game board itself can be represented by a GameBoard class, which will handle managing individual GamePiece objects and be responsible for determining which pieces should be filled with water and which ones should be empty. The GamePiece class The GamePiece class represents an individual pipe on the game board. One GamePiece has no knowledge of any other game pieces (that is the responsibility of the GameBoard class), but it will need to be able to provide information about the pipe to objects that use the GamePiece class. Our class has the following requirements: - Identify the sides of each piece that contain pipe connectors - Differentiate between game pieces that are filled with water and that are empty - Allow game pieces to be updated - Automatically handle rotation by changing the piece type to the appropriate new piece type - Given one side of a piece, provide the other sides of the piece in order to facilitate determining where water can flow through the game board - Provide a Rectangle that will be used when the piece is drawn, to locate the graphic for the piece on the sprite sheet While the sprite sheet contains thirteen different images, only twelve of them are actual game pieces (the last one is an empty square). Of the twelve remaining pieces, only six of them are unique pieces. The other six are the water-filled versions of the first six images. Each of the game pieces can be identified by which sides of the square contain a connecting pipe. This results in two straight pieces and four pieces with 90 degree bends in them. A second value can be tracked to determine if the piece is filled with water or not instead of treating filled pieces as separate types of pieces. Time for action - build a GamePiece class - declarations - Switch back to your Visual C# window if you have your image editor open. - Right-click on Flood Control in Solution Explorer and select Add | Class... - Name the class GamePiece.cs and click on Add. - At the top of the GamePiece.cs file, add the following to the using directives already in the class: using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework; - In the class declarations section, add the following: public static string[] PieceTypes = { "Left,Right", "Top,Bottom", "Left,Top", "Top,Right", "Right,Bottom", "Bottom,Left", "Empty" }; public const int PieceHeight = 40; public const int PieceWidth = 40; public const int MaxPlayablePieceIndex = 5; public const int EmptyPieceIndex = 6; private const int textureOffsetX = 1; private const int textureOffsetY = 1; private const int texturePaddingX = 1; private const int texturePaddingY = 1; private string pieceType = ""; private string pieceSuffix = ""; - Add two properties to retrieve information about the piece: public string PieceType { get { return pieceType; } } public string Suffix { get { return pieceSuffix; } } You have created a new code file called GamePiece.cs and included the using statements necessary to access the pieces of the XNA Framework that the class will use. Using Directives Adding the XNA Framework using directives at the top of the class file allows you to access classes like Rectangle and Vector2 without specifying their full assembly names. Without these statements, you would need Microsoft.Xna.Framework.Rectangle in your code every time you reference the type, instead of simply typing Rectangle. In the declarations area, you have added an array called PieceTypes that gives a name to each of the different types of game pieces that will be added to the game board. There are two straight pieces, four angled pieces, and an empty tile with a background image on it, but no pipe. The array is declared as static because all instances of the GamePiece class will share the same array. A static member can be updated at execution time, but all members of the class will see the same changes. Then, you have declared two integer constants that specify the height and width of an individual playing piece in pixels, along with two variables that specify the array index of the last piece that can be placed on the board (MaxPlayablePieceIndex) and of the fake "Empty" piece. Next are four integers that describe the layout of the texture file you are using. There is a one pixel offset from the left and top edge of the texture (the one pixel border) and a single pixel of padding between each sprite on the sprite sheet. Constants vs. Numeric literals Why create constants for things like PieceWidth and PieceHeight and have to type them out when you could simply use the number 40 in their place? If you need to go back and resize your pieces later, you only need to change the size in one place instead of hoping that you find each place in the code where you entered 40 and change them all to something else. Even if you do not change the number in the game you are working on, you may reuse the code for something else later and having easily changeable parameters will make the job much easier. There are only two pieces of information that each instance of GamePiece will track about itself—the type of the piece and any suffix associated with the piece. The instance members pieceType and pieceSuffix store these values. We will use the suffix to determine if the pipe that the piece represents is empty or filled with water. However, these members are declared as private in order to prevent code outside the class from directly altering the values. To allow them to be read but not written to, we create a pair of properties (pieceType and pieceSuffix) that contain get blocks but no set blocks. This makes these values accessible in a read-only mode to code outside the GamePiece class. Creating a GamePiece The only information we need to create an instance of GamePiece is the piece type and, potentially, the suffix. Time for action - building a GamePiece class: constructors - Add two constructors to your GamePiece.cs file after the declarations: public GamePiece(string type, string suffix) { pieceType=type; pieceSuffix=suffix; } public GamePiece(string type) { pieceType=type; pieceSuffix=""; } A constructor is run when an instance of the GamePiece class is created. By specifying two constructors, we will allow future code to create a GamePiece by specifying a piece type with or without a suffix. If no suffix is specified, an empty suffix is assumed. Updating a GamePiece When a GamePiece is updated, you can change the piece type, the suffix, or both. Time for action - GamePiece class methods - part 1 - updating - Add the following methods to the GamePiece class: public void SetPiece(string type, string suffix) { pieceType = type; pieceSuffix = suffix; } public void SetPiece(string type) { SetPiece(type,""); } public void AddSuffix(string suffix) { if (!pieceSuffix.Contains(suffix)) pieceSuffix += suffix; } public void RemoveSuffix(string suffix) { pieceSuffix = pieceSuffix.Replace(suffix, ""); } Additional methods have been added to modify suffixes without changing the pieceType associated with the piece. The AddSuffix() method first checks to see if the piece already contains the suffix. If it does, nothing happens. If it does not, the suffix value passed to the method is added to the pieceSuffix member variable. The RemoveSuffix() method uses the Replace() method of the string class to remove the passed suffix from the pieceSuffix variable. Rotating pieces The heart of the Flood Control play mechanic is the ability of the player to rotate pieces on the game board to form continuous pipes. In order to accomplish this, we can build a table that, given an existing piece type and a rotation direction, supplies the name of the piece type after rotation. We can then implement this code as a switch statement: Time for action - GamePiece class methods - part 2 - rotation - Add the RotatePiece() method to the GamePiece class: public void RotatePiece(bool Clockwise) { switch (pieceType) { case "Left,Right": pieceType = "Top,Bottom"; break; case "Top,Bottom": pieceType = "Left,Right"; break; case "Left,Top": if (Clockwise) pieceType = "Top,Right"; else pieceType = "Bottom,Left"; break; case "Top,Right": if (Clockwise) pieceType = "Right,Bottom"; else pieceType = "Left,Top"; break; case "Right,Bottom": if (Clockwise) pieceType = "Bottom,Left"; else pieceType = "Top,Right"; break; case "Bottom,Left": if (Clockwise) pieceType = "Left,Top"; else pieceType = "Right,Bottom"; break; case "Empty": break; } } The only information the RotatePiece() method needs is a rotation direction. For straight pieces, rotation direction doesn't matter (a left/right piece will always become a top/bottom piece and vice versa). For angled pieces, the piece type is updated based on the rotation direction and the diagram above. Why all the strings? It would certainly be reasonable to create constants that represent the various piece positions instead of fully spelling out things like Bottom,Left as strings. However, because the Flood Control game is not taxing on the system, the additional processing time required for string manipulation will not impact the game negatively and helps clarify how the logic works. Pipe connectors Our GamePiece class will need to be able to provide information about the connectors it contains (Top, Bottom, Left, and Right) to the rest of the game. Since we have represented the piece types as simple strings, a string comparison will determine what connectors the piece contains. Time for action - GamePiece class methods - part 3 -connection methods - Add the GetOtherEnds() method to the GamePiece class: public string[] GetOtherEnds(string startingEnd) { List opposites = new List(); foreach (string end in pieceType.Split(',')) { if (end != startingEnd) opposites.Add(end); } return opposites.ToArray(); } - Add the HasConnector() method to the GamePiece class: public bool HasConnector(string direction) { return pieceType.Contains(direction); } If the end in question is not the same as the startingEnd parameter that was passed to the method, it is added to the list. After all of the items in the string have been examined, the list is converted to an array and returned to the calling code. In the previous example, requesting GetOtherEnds("Top") from a GamePiece with a pieceType value of Top,Bottom will return a string array with a single element containing Bottom. We will need this information in a few moments when we have to figure out which pipes are filled with water and which are empty. The second function, HasConnector() simply returns "true" if the pieceType string contains the string value passed in as the direction parameter. This will allow code outside the GamePiece class to determine if the piece has a connector facing in any particular direction. Sprite sheet coordinates Because we set up the PieceTypes array listing the pieces in the same order that they exist on the sprite sheet texture, we can calculate the position of the rectangle to draw from based on the pieceType. Time for action - GamePiece class methods - part 4 - GetSourceRect - Add the GetSourceRect() method to the GamePiece class: public Rectangle GetSourceRect() { int x = textureOffsetX; int y = textureOffsetY; if (pieceSuffix.Contains("W")) x += PieceWidth + texturePaddingX; y += (Array.IndexOf(PieceTypes, pieceType) * (PieceHeight + texturePaddingY)); return new Rectangle(x, y, PieceWidth, PieceHeight); } Initially, the x and y variables are set to the textureOffsets that are listed in the GamePiece class declaration. This means they will both start with a value of one. Because the sprite sheet is organized with a single type of pipe on each row, the x coordinate of the Rectangle is the easiest to determine. If the pieceSuffix variable does not contain a W (signifying that the piece is filled with water), the x coordinate will simply remain 1. If the pieceSuffix does contain the letter W (indicating the pipe is filled), the width of a piece (40 pixels), along with the padding between the pieces (1 pixel), are added to the x coordinate of the source Rectangle. This shifts the x coordinate from 1 to a value of 1 + 40 + 1, or 42 which corresponds to the second column of images on the sprite sheet. To determine the y coordinate for the source rectangle, Array.IndexOf(PieceTypes, pieceType) is used to locate the pieceType within the PieceTypes array. The index that is returned represents the position of the tile on the sprite sheet (because the array is organized in the same order as the pieces on the image). For example, Left,Right returns zero, while Top,Bottom returns one and Empty returns six. The value of this index is multiplied by the height of a game piece plus the padding between pieces. For our sprite sheet, an index of 2 (the Left,Top piece) would be multiplied by 41 (PieceHeight of 40 plus texturePaddingY of 1) resulting in a value of 82 being added to the y variable. Finally, the new Rectangle is returned, comprised of the calculated x and y coordinates and the predefined width and height of a piece: The GameBoard class Now that we have a way to represent pieces in memory, the next logical step is to create a way to represent an entire board of playing pieces. The game board is a two-dimensional array of GamePiece objects, and we can build in some additional functionality to allow our code to interact with pieces on the game board by their X and Y coordinates. The GameBoard class needs to: - Store a GamePiece object for each square on the game board - Provide methods for code using the GameBoard to update individual pieces by passing calls through to the underlying GamePiece instances - Randomly assign a piece type to a GamePiece - Set and clear the "Filled with water" flags on individual GamePieces - Determine which pipes should be filled with water based on their position and orientation and mark them as filled - Return lists of potentially scoring water chains to code using the GameBoard - As you did to create the GamePiece class, right-click on Flood Control in Solution Explorer and select Add | Class... Name the new class file GameBoard.cs. - Add the using directive for the XNA framework at the top of the file: using Microsoft.Xna.Framework; - Add the following declarations to the GameBoard class: Random rand = new Random(); public const int GameBoardWidth = 8; public const int GameBoardHeight = 10; private GamePiece[,] boardSquares = new GamePiece[GameBoardWidth, GameBoardHeight]; private List WaterTracker = new List(); We used the Random class in SquareChase to generate random numbers. Since we will need to randomly generate pieces to add to the game board, we need an instance of Random in the GameBoard class. The two constants and the boardSquares array provide the storage mechanism for the GamePiece objects that make up the 8 by 10 piece board. Finally, a List of Vector2 objects is declared that we will use to identify scoring pipe combinations. The List class is one of C#'s Generic Collection classes—classes that use the Generic templates (angle brackets) we first saw when loading a texture for SquareChase. Each of the Collection classes can be used to store multiple items of the same type, with different methods to access the entries in the collection. We will use several of the Collection classes in our projects. The List class is much like an array, except that we can add any number of values at runtime, and remove values in the List if necessary. A Vector2 is a structure defined by the XNA Framework that holds two floating point values, X and Y. Together the two values represent a vector pointing in any direction from an imaginary origin (0, 0) point. We will use Vector2 structures to represent the locations on our game board in Flood Control, placing the origin in the upper left corner of the board. Creating the game board If we were to try to use any of the elements in the boardSquares array, at this point, we would get a Null Reference exception because none of the GamePiece objects in the array have actually been created yet. Time for action - initialize the game board - Add a constructor to the GameBoard class: public GameBoard() { ClearBoard(); } - Add the ClearBoard() helper method to the GameBoard class: public void ClearBoard() { for (int x = 0; x for (int y = 0; y boardSquares[x, y] = new GamePiece("Empty"); } When a new instance of the GameBoard class is created, the constructor calls the ClearBoard() helper method, which simply creates 80 empty game pieces and assigns them to each element in the array. Helper methods Why not simply put the two for loops that clear the board into the GameBoard constructor? Splitting the work into methods that accomplish a single purpose greatly helps to keep your code both readable and maintainable. Additionally, by splitting ClearBoard() out as its own method we can call it separately from the constructor. When we add increasing difficulty levels, we make use of this call when a new level starts. Updating GamePieces The boardSquares array in the GameBoard class is declared as a private member, meaning that the code that uses the GameBoard will not have direct access to the pieces contained on the board. In order for code in our Game1 class to interact with a GamePiece, we will need to create public methods in the GameBoard class that expose the pieces in boardSquares. Time for action - manipulating the game board - Add public methods to the GameBoard class to interact with GamePiece: public void RotatePiece(int x, int y, bool clockwise) { boardSquares[x, y].RotatePiece(clockwise); } public Rectangle GetSourceRect(int x, int y) { return boardSquares[x, y].GetSourceRect(); } public string GetSquare(int x, int y) { return boardSquares[x, y].PieceType; } public void SetSquare(int x, int y, string pieceName) { boardSquares[x, y].SetPiece(pieceName); } public bool HasConnector(int x, int y, string direction) { return boardSquares[x, y].HasConnector(direction); } public void RandomPiece(int x, int y) { boardSquares[x, y].SetPiece(GamePiece.PieceTypes[rand.Next(0, GamePiece.MaxPlayablePieceIndex+1)]); } RotatePiece(), GetSourceRect(), GetSquare(), SetSquare(), and HasConnector() methods simply locate the appropriate GamePiece within the boardSquares array and pass on the function request to the piece. The RandomPiece() method uses the rand object to get a random value from the PieceTypes array and assign it to a GamePiece. It is important to remember that with the Random.Next() method overload used here, the second parameter is non-inclusive. In order to generate a random number from 0 through 5, the second parameter needs to be 6. Filling in the gaps Whenever the player completes a scoring chain, the pieces in that chain are removed from the board. Any pieces above them fall down into the vacated spots and new pieces are generated. Time for action - filling in the gaps - Add the FillFromAbove() method to the GameBoard class. public void FillFromAbove(int x, int y) { int rowLookup = y - 1; while (rowLookup >= 0) { if (GetSquare(x, rowLookup) != "Empty") { SetSquare(x, y, GetSquare(x, rowLookup)); SetSquare(x, rowLookup, "Empty"); rowLookup = -1; } rowLookup--; } } Given a square to fill, FillFromAbove() looks at the piece directly above to see if it is marked as Empty. If it is, the method will subtract one from rowLookup and start over until it reaches the top of the board. If no non-empty pieces are found when the top of the board is reached, the method does nothing and exits. When a non-empty piece is found, it is copied to the destination square, and the copied piece is changed to an empty piece. The rowLookup variable is set to -1 to ensure that the loop does not continue to run. Generating new pieces We can create a single method that will fill any empty spaces on the game board, and use it when the game begins and when pieces are removed from the board after scoring. Time for action - generating new pieces - Add the GenerateNewPieces() method to the GameBoard class: public void GenerateNewPieces(bool dropSquares) { if (dropSquares) { for (int x = 0; x { for (int y = GameBoard.GameBoardHeight - 1; y >= 0; y--) { if (GetSquare(x, y) == "Empty") { FillFromAbove(x, y); } } } } for (int y = 0; y for (int x = 0; x { if (GetSquare(x, y) == "Empty") { RandomPiece(x, y); } } } When GenerateNewPieces() is called with "true" passed as dropSquares, the looping logic processes one column at a time from the bottom up. When it finds an empty square it calls FillFromAbove() to pull a filled square from above into that location. The reason the processing order is important here is that, by filling a lower square from a higher position, that higher position will become empty. It, in turn, will need to be filled from above. After the holes are filled (or if dropSquares is set to false) GenerateNewPieces() examines each square in boardSquares and asks it to generate random pieces for each square that contains an empty piece. Water filled pipes Whether or not a pipe is filled with water is managed separately from its orientation. Rotating a single pipe could change the water-filled status of any number of other pipes without changing their rotation. Instead of filling and emptying individual pipes, however, it is easier to empty all of the pipes and then refill the pipes that need to be marked as having water in them. Time for action - water in the pipes - Add a method to the GameBoard class to clear the water marker from all pieces: public void ResetWater() { for (int y = 0; y for (int x = 0; x boardSquares[x,y].RemoveSuffix("W"); } - Add a method to the GameBoard class to fill an individual piece with water: public void FillPiece(int X, int Y) { boardSquares[X,Y].AddSuffix("W"); } The ResetWater() method simply loops through each item in the boardSquares array and removes the W suffix from the GamePiece. Similarly, to fill a piece with water, the FillPiece() method adds the W suffix to the GamePiece. Recall that by having a W suffix, the GetSourceRect() method of GamePiece shifts the source rectangle one tile to the right on the sprite sheet, returning the image for a pipe filled with water instead of an empty pipe. Propagating water Now that we can fill individual pipes with water, we can write the logic to determine which pipes should be filled depending on their orientation. Time for action - making the connection - Add the PropagateWater() method to the GameBoard class: public void PropagateWater(int x, int y, string fromDirection) { if ((y >= 0) && (y (x >= 0) && (x { if (boardSquares[x,y].HasConnector(fromDirection) && !boardSquares[x,y].Suffix.Contains("W")) { FillPiece(x, y); WaterTracker.Add(new Vector2(x, y)); foreach (string end in boardSquares[x,y].GetOtherEnds(fromDirection)) switch (end) { case "Left": PropagateWater(x - 1, y, "Right"); break; case "Right": PropagateWater(x + 1, y, "Left"); break; case "Top": PropagateWater(x, y - 1, "Bottom"); break; case "Bottom": PropagateWater(x, y + 1, "Top"); break; } } } } - Add the GetWaterChain() method to the GameBoard class: public List GetWaterChain(int y) { WaterTracker.Clear(); PropagateWater(0, y, "Left"); return WaterTracker; } Together, GetWaterChain() and PropagateWater() are the keys to the entire Flood Control game, so understanding how they work is vital. When the game code wants to know if the player has completed a scoring row, it will call the GetWaterChain() method once for each row on the game board: The WaterTracker list is cleared and GetWaterChain() calls PropagateWater() for the first square in the row, indicating that the water is coming from the Left direction. The PropagateWater() method checks to make sure that the x and y coordinates passed to it exist within the board and, if they do, checks to see if the piece at that location has a connector matching the fromDirection parameter and that the piece is not already filled with water. If all of these conditions are met, that piece gets filled with water and added to the WaterTracker list. Finally, PropagateWater() gets a list of all other directions that the piece contains (in other words, all directions the piece contains that do not match fromDirection). For each of these directions PropagateWater() recursively calls itself, passing in the new x and y location as well as the direction the water is coming from. Building the game We now have the component classes we need to build the Flood Control game, so it is time to bring the pieces together in the Game1 class. Declarations We only need a handful of game-wide declarations to manage things like the game board, the player's score, and the game state. Time for action - Game1 declarations - Double click on the Game1.cs file in Solution Explorer to reactivate the Game1.cs code file window. - Add the following declarations to the Game1 class member declaration area: GameBoard gameBoard; Vector2 gameBoardDisplayOrigin = new Vector2(70, 89); int playerScore = 0; enum GameStates { TitleScreen, Playing }; GameStates gameState = GameStates.TitleScreen; Rectangle EmptyPiece = new Rectangle(1, 247, 40, 40); const float MinTimeSinceLastInput = 0.25f; float timeSinceLastInput = 0.0f; The gameBoard instance of GameBoard will hold all of the playing pieces, while the gameBoardDisplayOrigin vector points to where on the screen the board will be drawn. Using a vector like this makes it easy to move the board in the event that you wish to change the layout of your game screen. As we did in SquareChase, we store the player's score and will display it in the window title bar. In order to implement a simple game state mechanism, we define two game states. When in the TitleScreen state, the game's title image will be displayed and the game will wait until the user presses the Space bar to start the game. The state will then switch to Playing, which will display the game board and allow the user to play. If you look at the sprite sheet for the game, the pipe images themselves do not cover the entire 40x40 pixel area of a game square. In order to provide a background, an empty tile image will be drawn in each square first. The EmptyPiece Rectangle is a convenient pointer to where the empty background is located on the sprite sheet. Just as we used an accumulating timer in SquareChase to determine how long to leave a square in place before moving it to a new location, we will use the same timing mechanism to make sure that a single click by the user does not send a game piece spinning unpredictably. Remember that the Update() method will be executing up to 60 times each second, so slowing the pace of user input is necessary to make the game respond in a way that feels natural. Initialization Before we can use the gameBoard instance, it needs to be initialized. We will also need to enable the mouse cursor. Time for action - updating the Initialize() method - Update the Initialize() method to include the following: this.IsMouseVisible = true; graphics.PreferredBackBufferWidth = 800; graphics.PreferredBackBufferHeight = 600; graphics.ApplyChanges(); gameBoard = new GameBoard(); After making the mouse cursor visible, we set the size of the BackBuffer to 800 by 600 pixels. On Windows, this will size the game window to 800 by 600 pixels as well. The constructor for the GameBoard class calls the ClearBoard() member, so each of the pieces on the gameBoard instance will be set to Empty. The Draw() method - the title screen In the declarations section, we established two possible game states. The first (and default) state is GameStates.TitleScreen, indicating that the game should not be processing actual game play, but should instead be displaying the game's logo and waiting for the user to begin the game. Time for action - drawing the screen - the title screen - Modify the Draw() method of Game1 to include the code necessary to draw the game's title screen after GraphicsDevice.Clear(Color.CornflowerBlue); if (gameState == GameStates.TitleScreen) { spriteBatch.Begin(); spriteBatch.Draw(titleScreen, new Rectangle(0, 0, this.Window.ClientBounds.Width, this.Window.ClientBounds.Height), Color.White); spriteBatch.End(); } - Run the game and verify that the title screen is displayed. You will not be able to start the game however, as we haven't written the Update() method yet. - Stop the game by pressing Alt + F4. What just happened? The title screen is drawn with a single call to the Draw() method of the spriteBatch object. Since the title screen will cover the entire display, a rectangle is created that is equal to the width and height of the game window. The Draw() method - the play screen Finally, we are ready to display the playing pieces on the screen. We will accomplish this by using a simple loop to display all of the playing pieces in the gameBoard object. Time for action - drawing the screen - the play screen - Update the Draw() method of the Game1 class to add the code to draw the game board after the code that draws the title screen: if (gameState == GameStates.Playing) { spriteBatch.Begin(); spriteBatch.Draw(backgroundScreen, new Rectangle(0, 0, this.Window.ClientBounds.Width, this.Window.ClientBounds.Height), Color.White); for (int x = 0; x for (int y = 0; y { int pixelX = (int)gameBoardDisplayOrigin.X + (x * GamePiece.PieceWidth); int pixelY = (int)gameBoardDisplayOrigin.Y + (y * GamePiece.PieceHeight); spriteBatch.Draw( playingPieces, new Rectangle( pixelX, pixelY, GamePiece.PieceWidth, GamePiece.PieceHeight), EmptyPiece, Color.White); spriteBatch.Draw( playingPieces, new Rectangle( pixelX, pixelY, GamePiece.PieceWidth, GamePiece.PieceHeight), gameBoard.GetSourceRect(x, y), Color.White); } this.Window.Title = playerScore.ToString(); spriteBatch.End(); } As you can see, the code to draw the game board begins exactly like the code to draw the title screen. Since we are using a background image that takes up the full screen, we draw it exactly the same way as the title screen. Next, we simply loop through gameBoard to draw the squares. The pixelX and pixelY variables are calculated to determine where on the screen each of the game pieces will be drawn. Since both x and y begin at 0, the (x * GamePiece.PieceWidth) and (y * GamePiece.PieceHeight) will also be equal to zero, resulting in the first square being drawn at the location specified by the gameBoardDisplayOrigin vector. As x increments, each new piece is drawn 40 pixels further to the right than the previous piece. After a row has been completed, the y value increments, and a new row is started 40 pixels below the previous row. The first spriteBatch.Draw() call uses Rectangle(pixelX, pixelY, GamePiece.PieceWidth, GamePiece.PieceHeight) as the destination rectangle and EmptyPiece as the source rectangle. Recall that we added this Rectangle to our declarations area as a shortcut to the location of the empty piece on the sprite sheet. The second spriteBatch.Draw() call uses the same destination rectangle, overlaying the playing piece image onto the empty piece that was just drawn. It asks the gameBoard to provide the source rectangle for the piece it needs to draw. The player's score is displayed in the window title bar, and spriteBatch.End() is called to finish up the Draw() method. Keeping score Longer chains of filled water pipes score the player more points. However, if we were to simply assign a single point to each piece in the pipe chain, there would be no scoring advantage to making longer chains versus quickly making shorter chains. Time for action - scores and scoring chains - Add a method to the Game1 class to calculate a score based on the number of pipes used: private int DetermineScore(int SquareCount) { return (int)((Math.Pow((SquareCount/5), 2) + SquareCount)*10); } - Add a method to evaluate a chain to determine if it scores and process it: private void CheckScoringChain(List WaterChain) { if (WaterChain.Count > 0) { Vector2 LastPipe = WaterChain[WaterChain.Count - 1]; if (LastPipe.X == GameBoard.GameBoardWidth - 1) { if (gameBoard.HasConnector( (int)LastPipe.X, (int)LastPipe.Y, "Right")) { playerScore += DetermineScore(WaterChain.Count); foreach (Vector2 ScoringSquare in WaterChain) { gameBoard.SetSquare((int)ScoringSquare.X, (int)ScoringSquare.Y, "Empty"); } } } } } DetermineScore() accepts the number of squares in a scoring chain and returns a score value for that chain. The number of squares in the chain is divided by 5, and that number is squared. The initial number of squares is added to the result, and the final amount is multiplied by 10. Score = (((Squares / 5) ^ 2) + Squares) * 10For example, a minimum scoring chain would be 8 squares (forming a straight line across the board). This would result in 1 squared plus 8 times 10, or 90 points. If a chain had 18 squares the result would be 3 squared plus 18 times 10, or 270 points. This makes longer scoring chains (especially increments of five squares) award much higher scores than a series of shorter chains. The CheckScoringRow() method makes sure that there are entries in the WaterChain list, and then examines the last piece in the chain and checks to see if it has an X value of 7 (the right-most column on the board). If it does, the HasConnector() method is checked to see if the last pipe has a connector to the right, indicating that it completes a chain across the board. After updating playerScore for the scoring row, CheckScoringRow() sets all of the pieces in the scoring row to Empty. They will be refilled by a subsequent call to the GenerateNewPieces() method. Input handling The player interacts with Flood Control using the mouse. For readability reasons, we will create a helper method that deals with mouse input and call it when appropriate from the Update() method. Time for action - handling mouse input - Add the HandleMouseInput() helper method to the Game1 class: private void HandleMouseInput(MouseState mouseState) { int x = ((mouseState.X - (int)gameBoardDisplayOrigin.X) / GamePiece.PieceWidth); int y = ((mouseState.Y - (int)gameBoardDisplayOrigin.Y) / GamePiece.PieceHeight); if ((x >= 0) && (x (y >= 0) && (y { if (mouseState.LeftButton == ButtonState.Pressed) { gameBoard.RotatePiece(x, y, false); timeSinceLastInput = 0.0f; } if (mouseState.RightButton == ButtonState.Pressed) { gameBoard.RotatePiece(x, y, true); timeSinceLastInput = 0.0f; } } } The MouseState class reports the X and Y position of the mouse relative to the upper left corner of the window. What we really need to know is what square on the game board the mouse was over. We calculate this by taking the mouse position and subtracting the gameBoardDisplayOrigin from it and then dividing the remaining number by the size of a game board square. If the resulting X and Y locations fall within the game board, the left and right mouse buttons are checked. If the left button is pressed, the piece is rotated counterclockwise. The right button rotates the piece clockwise. In either case, the input delay timer is reset to 0.0f since input was just processed. Letting the player play! Only one more section to go and you can begin playing Flood Control. We need to code the Update() method to tie together all of the game logic we have created so far. Time for action - letting the player play - Modify the Update() method of Game1.cs by adding the following before the call to base.Update(gameTime): switch (gameState) { case GameStates.TitleScreen: if (Keyboard.GetState().IsKeyDown(Keys.Space)) { gameBoard.ClearBoard(); gameBoard.GenerateNewPieces(false); playerScore = 0; gameState = GameStates.Playing; } break; case GameStates.Playing: timeSinceLastInput += (float)gameTime.ElapsedGameTime.TotalSeconds; if (timeSinceLastInput >= MinTimeSinceLastInput) { HandleMouseInput(Mouse.GetState()); } gameBoard.ResetWater(); for (int y = 0; y { CheckScoringChain(gameBoard.GetWaterChain(y)); } gameBoard.GenerateNewPieces(true); break; } The Update() method performs two different functions, depending on the current gameState value. If the game is in TitleScreen state, Update() examines the keyboard, waiting for the Space bar to be pressed. When it is, Update() clears the gameBoard, generates a new set of pieces, resets the player's score, and changes gameState to Playing. While in the Playing state, Update() accumulates time in timeSinceLastInput in order to pace the game play properly. If enough time has passed, the HandleMouseInput() method is called to allow the player to rotate game pieces. Update() then calls ResetWater() to clear the water flags for all pieces on the game board. This is followed by a loop that processes each row, starting at the top and working downward, using CheckScoringChain() and GetWaterChain() to "fill" any pieces that should have water in them and check the results of each row for completed chains. Finally, GenerateNewPieces() is called with the "true" parameter for dropSquares, which will cause GenerateNewPieces() to fill the empty holes from the squares above, and then generate new pipes to replace the empty squares. Play the game You now have all of the components assembled, and can run Flood Control and play! Summary You now have a working Flood Control game. In this article we have looked at: - Adding content objects to your project and loading them into textures at runtime using an instance of the ContentManager class - Dividing the code into classes that represent objects in the game - Building a recursive method - Use the SpriteBatch.Draw() method to display images - Divide the Update() and Draw() code into different units based on the current game state
http://www.gamedev.net/page/resources/_/technical/directx-and-xna/building-a-complete-board-based-puzzle-game-with-microsoft-xna-40-r2871
CC-MAIN-2014-15
refinedweb
7,572
59.33
Every time in my career when I learn something new, I always wish to share it. Every time when someone is new to a subject, at least he has to Google before he can post in the Forum. Sometimes the answers that are found in threads are not complete. I would like to take this chance to increase the pages and results found when you Google the subject “How to Store a Connection string in an App.Config file or Web.Config File. Let’s hear my story first. Every time I write an article, it means I grew to a certain level of understanding. When I came to the .NET world, I was so overwhelmed to create applications. My interest was on Windows applications, I was not that interested in developing Web applications, may be it’s because of the projects I was involved with. Sometimes I would just consume web services from a Windows application. I had fun and I loved ADO.NET as you have seen in my previous articles. I enjoyed database programming and I have learned a lot and am still learning to make my data layers the most beautiful thing in my world. Let’s cut to the chase. Recently I have been hard coding my connection string to a DLL (Data Access Layer). There was nothing wrong with that, because I knew for a fact that My Server name would never change for years. But that is where I made a big mistake, especially on a Windows application. After a while, I mean few weeks ago, the server that had held my database had resigned. Well the database had to be moved to another server, but hey this meant I have to recompile my DLLs. It is because I cannot change my connection string without recompiling my DLLs. It was never going to be a good thing to change the connection and recompile the DLL again. That means I had to look for a way to store the connection string. I have learned that I should never hardcode my connection string or anything that has to do with my application settings. In this article, we are going to look at how to place a connection string in a file that can be opened and edited anytime when the server changes or the password changes. We are going to use multiple comments in our article and we are going to use C# as our language. This is a very short story that is going to have a happy ending. To store a connection string to an App.Config file, you must do the following; Open your Visual Studio on an Existing Project to which you have once hard coded your connection string. Add a new Application.Configuration file: In your project, the file will be named App.config by default. Open the file. Now we are going to add our connection string, like this: <add key="MyConstring" Value = "User Id=sa; Password=password;Server=Myserver;Database=Mydatabase "></add> That means our file will look like this: <?xml version="1.0" encoding="utf-8" ?> < configuration> < add key="MyConstring" Value = "User Id=sa; Password=password;Server=Myserver;Database=Mydatabase "></add> < /configuration> Now remember that your connection string should be added between your configuration tags. Now that you have added your connection string, you have to access it from your C# or VB.NET code, but in this article I will be doing demonstrations in C#, but these languages do not differ that much. Now the first thing we need to do is to add a Reference to a System.Configuration namespace. After that, we are going to our usings and add it like this: configuration System.Configuration using using System.Configuration; After you are done, let's go to a string that you once hardcoded. It will be something like this: string String strcon = "User Id=sde; Password=topology; Server=bkiicoryw004;Database=Tshwane_Valuations " Now convert it to this: string strcon = ConfigurationManager.AppSettings.Get("MyConstring"); Then recompile your project. When you deploy your application, your App.Config will be deployed amongst other dependency, because your application will need the file to be told where the data source is sitting. So the next time the Server name changes or the password changes, you don't have to recompile your application, you just go to your Program Files and locate your Application directory and open the App.config with a text file and change the connection string. The above example is for Windows applications, but for Web applications, you have to add a Web.Config file as I did and add your connection string like this: <configuration> <appSettings> < add key =" MyConstring " value ="User id=sa; Password=password;Server=myserver;Database=mydb"></add> </appSettings> </configuration> When you access it from your code, it should look like this: string strcon = ConfigurationSettings.AppSettings["MyConstring"]; This is the END of the story. At least the story has a happy ending. The next time a server changes, you don't need to recompile. When the password changes, you don't need to recompile.Hope you loved my short story.Thank you.Ngiyabonga
http://www.codeproject.com/Articles/28699/How-to-Store-and-Retrieve-a-ConnectionString-from?fid=1525531&df=90&mpp=25&sort=Position&spc=Relaxed&tid=4231339
CC-MAIN-2014-10
refinedweb
858
64.91
IPFS InterPlanetary File System (IPFS) is a protocol and network designed to create a content-addressable, peer-to-peer (P2P) method of storing and sharing hypermedia in a distributed file system.[2] IPFS was initially designed by Juan Benet, and is now an open-source project developed with help from the community... In 2014, the IPFS protocol took advantage of the Bitcoin blockchain protocol and network infrastructure in order to store unalterable data, remove duplicated files across the network, and obtain address information for accessing storage nodes to search for files in the network....[11] This forms a generalized Merkle directed acyclic graph (DAG). IPFS combines a distributed hash table, an incentivized block exchange, and a self-certifying namespace. IPFS has no single point of failure, and nodes do not need to trust each other not to tamper with data in transit.[12] Distributed Content Delivery saves bandwidth and prevents DDoS attacks, which HTTP struggles with. installing - Edited: | Tweet this! | Search Twitter for discussion
http://webseitz.fluxent.com/wiki/IPFS
CC-MAIN-2022-27
refinedweb
164
53.92
On Mon, 04 Jan 2010 19:12:53 -0800, Nav wrote: > Okay, let me ask another question: > > When we create instances of objects by doing > x = className() > are we using globalnamespace? That depends on whether you are doing x = className() inside a function (or class), or in the top level of the program. If I do this: x = 1234 def function(): y = 4567 then x is defined in the global namespace and y is defined in the namespace which is local to function(). > if yes then: > if using globalnamespace is bad then why does every book or tutorial > about python classes give the above style of assignment as an example? No, you're confused -- the problem isn't with using the global namespace. The problem is that you don't know what names you want to use ahead of time. You use assignment like: x = something() when you know the name x when you are writing the code. That way you can write x in the code, and all is good: x = something() print x.method() mydict = {x: -1} assert mydict.keys() == [x] Now, imagine that you didn't know what names you have to use. Say, for example, that you need a variable number of Somethings: a = Something() b = Something() c = Something() d = Something() # I never know when to stop... z = Something() # ... keep going? too far? who knows??? HELP! process(a) process(b) process(c) # when do I stop??? process(x) process(y) # ... That's the wrong way to deal with it. So instead you use a list: mylist = [] # define ONE NAME in the global namespace for i in range(some_number): mylist.append(Something()) # later... for x in mylist: # again, we use ONE name, `x` process(x) A list implicitly maps numbers (the position) to values. If you want to map strings (names) to values, use a dict. Here is an example. Notice we don't know how many players there are, or what their names are: print "Welcome to the game." print "Please enter the name of each player," print "or the word 'STOP' when there are no more players." players = {} i = 1 while True: # loop forever name = raw_input("Name of player %d? " % i) name = name.strip() # get rid of extra whitespace if name.upper() == 'STOP': # we're done break players[name] = NewPlayer() # much later... for name, player in players.items(): print "Welcome, player %s" % name play_game(player) The only downside is that dicts are unordered, so the order of the players is not the same as the order they were entered in. -- Steven
https://mail.python.org/pipermail/python-list/2010-January/563267.html
CC-MAIN-2016-30
refinedweb
426
80.62
eclipse(How to add a .class file) Discussion in 'Java' started by elak, Dec 2, Eclipse (How to add file to Project?)Duke McPherson, May 8, 2006, in forum: Java - Replies: - 10 - Views: - 103,619 - piyushgupta77 - Jun 1, 2012 How to add jdom library into my jar file in eclipseJTL.zheng, Jul 6, 2007, in forum: Java - Replies: - 6 - Views: - 3,213 - JT - Jul 8, 2007 Eclipse Plugin: how to modify perl build path from an eclipse Plugin java classeser@libero.it, Sep 7, 2007, in forum: Java - Replies: - 1 - Views: - 766 - Lew - Sep 7, 2007 procedure to add web reference which will not create new namespace just add class in existing namespDeep Mehta via .NET 247, May 28, 2005, in forum: ASP .Net Web Services - Replies: - 2 - Views: - 471 - Dave A - May 31, 2005
http://www.thecodingforums.com/threads/eclipse-how-to-add-a-class-file.646885/
CC-MAIN-2014-52
refinedweb
135
78.28
Hi, I'm really new to this thing and I would appreciate some guidance. I have this project using atmega328p I have to test how many times light-bulb was turned on/off but that cycle have tu programmable and I need to change parameters for at least two bulbs. I have four buttons, one to start test, one to select which bulb cycle I'm changing, one to select how long it will be turned on and last one how long it will be turned off. This is the code I was playing around with: #include <avr/io.h> #include <avr/interrupt.h> #include "LCD.H" //including LCD library #include <stdio.h> #include <util/delay.h> #define F_CPU 16000000 volatile unsigned int PL; volatile unsigned int PL2; #define BUTTON1 21 // Button 1 char but; //button state char butl; //button last pass char butos; //button presed oneshot char press; //0,1,2,3 int main(void) { DDRD = 0xFF; // PORTD output PORTD =0; // clear PORTD PORTC =0; // clear PORTC EICRA |= (1 << ISC00) || ( 1 << INT1 ) ; // set INT0 and INT1 to trigger on ANY logic change EIMSK |= (1 << INT0) || ( 1 << INT1 ); // Enable both interrupts sei(); // Enable global interrupts but=BUTTON1; //read button butos=but && !butl; //generate oneshot butl=but; //remember last pass if(butos){ press++; if(press > 1) press=0; } switch(press){ case 0: OCR1A=0; break; case 1: OCR1A=64; break; } _delay_ms(20); //longer than bounce time, so no bounce problemo while (1) { printf("On/off: %i", PL); // Print out the total pulses } } ISR(INT0_vect) { PL++; // Increment the pulse counter by one each time } ISR(INT1_vect) { PL2++; // Increment the pulse counter by one each time } I select a bulb by a number of times I press a button with the help of cases. What I don't know is can I expand upon those cases, for example: I press one button two times to select second bulb, then I press second button three times to select cycle time. Do I add case within case(if so how? because I tried and just got a bunch of errors) or am I going in the completely wrong direction here? Would be really thankful for some help. Err no. You have: press can never be anything but 0. Also this looks very suspicious too: ... At start up but1 is 0 so this code says: !21 is 0. 0 && 0 is 0. So by the end of that all of butos = 0. To be honest I can't actually work out what you had in mind but I can't help thinking it's not this. Do you really mean ! and not ~? Do you really mean && and not & ? Then to top everything else you have all this code OUTSIDE the while(1) so all this code runs only once in the few microseconds after you power on the AVR and then it just holds in the while(1) doing nothing but printing and waiting for INT0. (the INT1 code is irrelevant and nothing ever uses PL2) Top - Log in or register to post comments F_CPU's definition should appear BEFORE the delay.h include. Ross McKenzie ValuSoft Melbourne Australia Top - Log in or register to post comments
https://www.avrfreaks.net/forum/help-cases
CC-MAIN-2019-43
refinedweb
531
77.67
Top Ten Errors Java Programmers Make Top Ten Errors Java Programmers Make Join the DZone community and get the full member experience.Join For Free Download Microservices for Java Developers: A hands-on introduction to frameworks and containers. Brought to you in partnership with Red Hat. I read an article (linked below) on “Top Ten Errors Java Programmers Make“. The author has mentioned the errors which even the most experienced programmers often commit or the New to Java programmers may commit in the future. Not only has he listed the errors but also given the possible solution for the same. I found the article really informative. One can read the article here. I would like to add some more: - A .java source file can contain more than one class but it can contain atmost one Top level class (or interface) definition that is public and the name of the source file must be same as that of the public class (or interface). - Static methods cannot be overridden but can be hidden if they are not final (Read about Overriding vs Hiding here). - The objects created in the String pool are not subjected to GC until the class is unloaded by the JVM. - Only methods or code blocks can be marked “synchronized”. - Local classes cannot access non-final variables. - -0.0 == 0.0 is true. - Collection (singular) is an Interface, but Collections (plural) is a helper class. - continue must be in a loop (e.g., for, do, while). It cannot appear in case constructs. - Instance initializers are executed only if an object is constructed. > }}
https://dzone.com/articles/top-ten-errors-java-programmer
CC-MAIN-2019-04
refinedweb
263
66.84
Symptoms In the Microsoft .NET Framework 2.0, you have an application that sends e-mail messages to a Simple Mail Transfer Protocol (SMTP) server by using the System.Net.Mail namespace. When you send a HELO or EHLO command to the server, only the local computer name of the client is sent to the server. However, you expect the Fully Qualified Domain Name (FQDN) of the client to be sent to the server. have to modify a configuration file to enable this hotfix. For more information about how to do this, see the "More information" section. PrerequisitesYou must have the .NET Framework 2.0 Service Pack 1 (SP1) installed to apply this hotfix. versions of Microsoft Windows 2000, Windows XP, or Windows Server 2003 x64 versions of Windows 2000, Windows XP, or Windows Server 2003 Status Microsoft has confirmed that this is a problem in the Microsoft products that are listed in the "Applies to" section. More Information After you install the hotfix, a new option named clientDomain is added to the configuration file, and a property named ClientDomain is added to the SmtpNetworkElement class. This hotfix lets you change the domain value by using a configuration file. Note If you do not modify the configuration file to enable the clientDomain option, the local computer name will be sent by default. The following is an example of how you can use the clientDomain option. Note If you do not modify the configuration file to enable the clientDomain option, the local computer name will be sent by default. The following is an example of how you can use the clientDomain option. Note You must replace FQDN with the value that you want System.Net.Mail to use in the HELO and EHLO commands. Typically, this is the FQDN of the host. <configuration> <system.net> <mailSettings> <smtp deliveryMethod="network"> <network clientDomain="FQDN" /> </smtp> </mailSettings> </system.net> </configuration> References Section 4.1.1.1 of RFC 2821 specifies that an SMTP client should use FQDN as part of its HELO or EHLO message to a server. For more information, visit the following Internet Engineering Task Force (IETF) Web site: For more information about software update terminology, click the following article number to view the article in the Microsoft Knowledge Base: Propriedades ID do Artigo: 957497 - Última Revisão: 08/10/2011 - Revisão: 1
https://support.microsoft.com/pt-pt/help/957497/fix-when-a-.net-framework-2.0-based-application-sends-e-mail-messages-by-using-the-system.net.mail-namespace,-the-fqdn-is-not-sent-when-you-send-a-helo-or-ehlo-command
CC-MAIN-2017-22
refinedweb
390
55.64
Hello. im a student working in C++ and im fairly new to both C++ and i guess this community.(i was reccomended to come here if i had problems) im just doing some simple exercises or s it seemed. here is the question. Write a C++ program with a case structure. The program reads in a character from the user, then translates it into a different character according to the following rules: i. characters X, Y, Z will be translated to characters x, y, z respectively ii. the space character ' ' will be translated to underscore '_' iii. digits 0, 1, 2, .., 9 will all be translated to the question mark '?' iv. all other characters remain unchanged. The program then displays the translated character. simple? well i guess, i was able to do most of it but im stuck on Q2 and Q4. i cant find a way to enter spacebar through the case(ive tested other characters to give out the underscore and i have tried some 'getline' stuff) and i am lost upon the last bit. I'm sure it ustilises the 'default' part of the code. bleh maybe i explained incorrectly. btw im not a slacker asking for easy answers heres what ive done #include<iostream> using namespace std; int main(){ string type2; char type; char c; cout<<"please enter one of the valid characters "; cin>>type; switch(type) {case 'X': type2="x"; break; case 'Y': type2="y"; break; case 'Z': type2="z"; break; case '0': case '1': case '2': case '3': case '4': case'5': case'6': case'7': case'8': case '9': type2="?"; break; default : type2= ; } cout<<type2<<endl; system("pause"); return 0; } anyways anyhelp is much appreciated. telling me what im supposed to do or simply pointing me in correct direction would be great.(my textbooks fail at this) and yes i have watched through several 'youtube' style tuts and googled lots but to no sucess. thnx, Leone, novice c++ student. Edited 3 Years Ago by Nick Evan: Fixed formatting
https://www.daniweb.com/programming/software-development/threads/308895/39-simple-39-coding-problems-using-case-switch-under-certain-inputs-assistance-please
CC-MAIN-2016-50
refinedweb
335
73.07
For 'created' cannot be null [Sun Nov 15 02:18:12 2009] [error] return self.cursor.execute(query, args) The relevant part of my database is: `created` datetime NOT NULL, `modified` datetime NOT NULL, Is this cause for concern? Side question: in my admin tool, those two fields aren't showing up. Is that expected? Any field with the auto_now attribute set will also inherit editable=False and therefore will not show up in the admin panel. There has been talk in the past about making the auto_now and auto_now_add arguments go away, and although they still exist, I feel you're better off just using a custom save() method. So, to make this work properly, I would recommend not using auto_now or auto_now_add and instead define your own save() method to make sure that created is only updated if id is not set (such as when the item is first created), and have it update modified every time the item is saved. I have done the exact same thing with other projects I have written using Django, and so your save() would look like this: from django.utils import timezone class User(models.Model): created = models.DateTimeField(editable=False) modified = models.DateTimeField() def save(self, *args, **kwargs): ''' On save, update timestamps ''' if not self.id: self.created = timezone.now() self.modified = timezone.now() return super(User, self).save(*args, **kwargs) Hope this helps! Edit in response to comments: The reason why I just stick with overloading save() vs. relying on these field arguments is two-fold: django.utils.timezone.now()vs. datetime.datetime.now(), because it will return a TZ-aware or naive datetime.datetimeobject depending on settings.USE_TZ. To address why the OP saw the error, I don't know exactly, but it looks like created isn't even being populated at all, despite having auto_now_add=True. To me it stands out as a bug, and underscores item #1 in my little list above: auto_now and auto_now_add are flaky at best. But I wanted to point out that the opinion expressed in the accepted answer is somewhat outdated. According to more recent discussions (django bugs #7634 and #12785), auto_now and auto_now_add are not going anywhere, and even if you go to the original discussion, you'll find strong arguments against the RY (as in DRY) in custom save methods. A better solution has been offered (custom field types), but didn't gain enough momentum to make it into django. You can write your own in three lines (it's Jacob Kaplan-Moss' suggestion). from django.db import models from django.utils import timezone class AutoDateTimeField(models.DateTimeField): def pre_save(self, model_instance, add): return timezone.now() #usage created_at = models.DateField(default=timezone.now) updated_at = models.AutoDateTimeField(default=timezone.now)
https://pythonpedia.com/en/knowledge-base/1737017/django-auto-now-and-auto-now-add
CC-MAIN-2020-16
refinedweb
460
57.27
Please advice for below code and implementation814889 Jan 9, 2013 1:41 PM The below code does Read csv files and process it to do some sort of cacluations.This is more of small picture code , to introduce big picture. The csv file contains information of seeds of crop which have some information in number depending upon the numbers the calcuation have to be done.There are different types of calucations based on traits types. The csv file will contains hybrid numbers followed by the traits . I have recorded observations for 6 traits, now at first i will read traits used in the applicaitons some traits may have 2 ,3 or n enteries.This is stored in db so i will pull inforamtion from there , once i read traits then i will read each hybrid number and trait values once i read trait values of particular trait i will either avgerage or do some more processing for som e trait the value depends on other triats. Please have a look at it and let me know if it has to be improveed from design/implementation point of view. Below is the Code: Please have a look at it and let me know if it has to be improveed from design/implementation point of view. I have even entered values for TLSSG01 TLSSG02 TLSSG03 but they are not visible ,I have even entered values for TLSSG01 TLSSG02 TLSSG03 but they are not visible , Hybrid PLTHT01 PLTHT02 Avg YLDTH01 YLDTH01 YLD TLSSG01 TLSSG02 TLSSG03 TLSSV HH01 24 42 23 33 42 34 22 HH02 26 40 27 37 42 34 22 HH03 28 38 31 41 42 34 22 HH04 30 36 35 45 42 34 22 HH05 32 34 39 49 42 34 22 HH06 34 32 43 53 42 34 22 HH07 36 30 47 57 42 34 22 HH08 38 28 51 61 42 34 22 HH09 40 26 55 65 42 34 22 HH10 42 24 59 69 42 34 22 Below is the Code: Now what if no of traits increases let if i add 10 more traits with different calcuations, how will i maintain the code please help.Does this look like oo code.Now what if no of traits increases let if i add 10 more traits with different calcuations, how will i maintain the code please help.Does this look like oo code. mport java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class HybridDataProcessor { public static void main(String[] args) { BufferedReader br = null; try { // holds currentline vlues String sCurrentLine; Map<String, HashMap<String,Float>> hybridTraitValues = new HashMap<String,HashMap<String, Float>>(); // a mapping to traitName and no of columns it will have HashMap<String, Integer> listDataPointMap = new HashMap<String, Integer>(); listDataPointMap.put("PLTHT",2); listDataPointMap.put("YLDTH",2); listDataPointMap.put("YLD",1); listDataPointMap.put("TLSSG",3); listDataPointMap.put("TLSSV",1); List<String> traitList = new ArrayList<String>(); // HashMap<String, Float> traitValues = new HashMap<String, Float>(); br = new BufferedReader(new FileReader("C:\\testing.csv")); int lineNumber = 0; while ((sCurrentLine = br.readLine()) != null) { lineNumber++; String[] itemValues = sCurrentLine.split(","); // if line number then we need to get all the tratis used in csv file if (lineNumber == 1) { for (int j = 1; j < itemValues.length; j++) { String traits = itemValues[j]; // if column name is avg do not consider it as trait if(traits.equalsIgnoreCase("avg")){ continue; } // since yld is special trait and it does not have 01 attached to it we will add it directly if(traits.equalsIgnoreCase("YLD")){ traitList.add(traits); continue; } // since TLSSV is special trait and it does not have 01 attached to it we will add it directly if(traits.equalsIgnoreCase("TLSSV")){ traitList.add(traits); continue; } traits=traits.substring(0,traits.length()-2); if(!traitList.contains(traits)) traitList.add(traits); } } else { String hybridName = itemValues[0]; int datPts=0; int currentPosition = 1; for (String traits : traitList) { // calcutes the vlalue of each trait with respective hybrid if(traits.equalsIgnoreCase("YLD")){ float avg =getYLD(hybridTraitValues.get(hybridName).get("YLDTH")); update(hybridTraitValues, hybridName, avg, traits); currentPosition=currentPosition+1; } else if(traits.equalsIgnoreCase("TLSSV")){ float avg =gettlssv(hybridTraitValues.get(hybridName).get("TLSSG")); update(hybridTraitValues, hybridName, avg, traits); currentPosition=currentPosition+1; } else { datPts=listDataPointMap.get(traits); float avg =getAvg(itemValues, datPts, currentPosition); update(hybridTraitValues, hybridName, avg, traits); if(traits.equalsIgnoreCase("PLTHT")){ currentPosition=currentPosition+datPts+1; }else{ currentPosition=currentPosition+datPts; } } } } } } catch (IOException e) { e.printStackTrace(); } finally { try { if (br != null) br.close(); } catch (IOException ex) { ex.printStackTrace(); } } } public static float getAvg(String[] itemValues,int dataPts,int currentPosition){ float avg=0; for (int j = currentPosition; j < (currentPosition + dataPts); j++) { avg+=Float.parseFloat(itemValues[j]); } return avg=avg/2; } public static float getYLD(float avg){ return avg=avg/10; } public static float gettlssv(float avg){ return avg=avg/10; }); } } This content has been marked as final. Show 5 replies 1. Re: Please advice for below code and implementationgimbal2 Jan 9, 2013 2:01 PM (in response to 814889) Does this look like oo code.Before you ask for opinions you should first give your own. What do you think? 2. Re: Please advice for below code and implementation814889 Jan 9, 2013 2:05 PM (in response to gimbal2)it is not hence i wanted to know 3. Re: Please advice for below code and implementationmarlin Jan 17, 2013 9:58 PM (in response to 814889)No this does not look like OO code1 person found this helpful Rule of thumb: Any fucntion that has more than about 7 lines is too messy so re-factor. Rule of thumb: If a code line is TOO long to display on the forum without haveing to scroll horizontally your code is absolutely unreadable (and so are your questions due to the absolutely lame formatting that is done on this forum) and no one is likely to help you. Well I must be really bored today so here goes. You need to learn to use classes to help you document and to reduce complexity.. Of course, as soon as you do that, you start to wonder why your update routine is a public static routine up in the main class. Shouldn't update be an object function applied to a single trait? I mean, instead of calling update(hybridTraitValues, hybridName, avg, traitName) shouldn't you be calling something like hybridTraitValues.get(hybridName).update(avg, traitName) Your main routine is way too long. Too much detail. Impossible to read. You need to reduce it. First of all factor out all the bufferedReader junk from the parsing of the lines while(...){ String[] splitLIne = sCurrentLint.split(","); if(lineNumber == 1){ parseFirstLine(splitLine...); } else { parseDataLine(splitLine...); } } Sorry for the look of the above code. I don't live on this forum, I haven't memorized the markup that they require for monospaced fonts, and they don't bother to list that option in the little plain text help window that I am looking at as I type this. WHAT A BAG!! Seriously, a froum dedicated to talking about code does not list the one single markup tag that actually matters in their help box. Does no one complain about this? I am now remembering why I abandoned this forum after Oracle picked it up. Anyway, the point being that a division like that allows you to split the fileReading from the details of extracting the data. Can you see in my code where you need to patch it if the second line is blank or if there is some screwy last line? Can you see the same thing easily in your code? What if you aren't reading from a file anymore - you want to split the file details from the data details. Your line parsing is garbage. Why? You are using a long pile of ifs to special case your special columns. Ugly, unseperable, unmaintainable..} } Now you got a list of Columns (or a map collected by name) that can contain both the standard ones and the non-standard one. Parse away. Basically you want your names to map to objects and then those objects KNOWS what to do. Instead you are looking at the names in your main routine and making decisions about what to do using if statements at that high level. Polymorphism is allowing different classes, to do different things given the same name. As a result piles of conditionals (doing different things here and there) can generally be replaced by having piles of classes that each do slightly differen things. Same work but split up into smaller more manageable chunks. I got curious and looked at some of your other postings. You had one with code like this: else if(cropId.equalsIgnoreCase("TO") && traitName.equalsIgnoreCase("TLSSG_70")) { traitAvg=calculateTLCV(traitName, traitAvg,dataPoint, dataTraits, hybrid, repl, traitValues, dataPvalues,50); } else if(cropId.equalsIgnoreCase("TO") && traitName.equalsIgnoreCase("TLSSG_100")) { traitAvg=calculateTLCV(traitName, traitAvg,dataPoint, dataTraits, hybrid, repl, traitValues, dataPvalues,50); That is disgusting. You have elevated a detail (like ignoring the case) to be right in my eyes on every single line. One single helper function boolean ct(String c, String t){return cropId.equalsIgnoreCase(c) && traitName.equalsIgnoreCase(t);} allows you to change your code to: else if(ct("TO", "TLSSG_70") || ct("TO", "TLSSG_100")){ traitAvg=calculateTLCV(traitName, traitAvg,dataPoint, dataTraits, hybrid, repl, traitValues, dataPvalues,50); } And the fact is, even that is the wrong way to do it. Instead of a huge list of ifs based on cropID and NameYou want something more like Calc calc = Calc.get(cropID, traitName); // get the calculation associated with this crop and trait calc.do(blah blah); // do whatever calcualtion is in the calc object. Yes, you have to build those calc objects somewhere and you had to load up a map that associated the right calcualtion with the right trait BUT you don't need to look at those details at the moment that you are doing the calcualtion. My code for doing the calculation is two lines long. Get the calcualtion out of some kind of map and then do it. Notice that I don't even require that you use an actual Map. That is a lower level detail managed in some other class. I just get the calc and do it. Can you tell that my code works (assuming that the lower level stuff works) at a glance? Can you make the same statement for your code? Basically your code is not extensible and not maintainable because you are using none of the features of OOP or even good programming to MANAGE and HIDE detail. You have one single long flat unreadable thing with irrelevant detail visible everywhere. Basically Little Tiny readable chunks - good, Big is Bad. Learn to think NOT in terms of code that works. Learn to think in terms of code that you can read. Call routines that don't even exist to hide details. Pretend that those routines exist. Can you read your code? If not rewrite it. AFTER you code looks good, AFTER you have code that you could hand to your MOTHER and have her read it and check that it makes sense - THEN you go implement the routines that make it happen. In your long flat code you are remembering where you are and what you have to do next and it is one long list of details that bury you and bury your MOM. Factor that into small routines. Delay all decisions that you possibly can to lower levels of your code. Try to make only one decision in each chunk of code. This is what allows your MOM to look at it and say, "Oh I see, if it is this way I do this otherwise I do that. That's pretty simple. Yes, that is right." The point is that you look at one routine, no more than 7 or so lines, and verify that it does the correct thing. You never need to understand more than 7 lines or so at one time. Divide and Conquer! Enjoy your rewrite! 4. Re: Please advice for below code and implementation814889 Jan 18, 2013 11:40 AM (in response to marlin)Great , this is the Sort of reply i always wanted .Great . I have some doubts if you could clear them it would be great . Can you please explain me more on this .} } " How can i acutally implement it if you can some more inputs on this it would be great . One more doubt is on below . " How should i define Triat Class. 5. Re: Please advice for below code and implementationmarlin Jan 20, 2013 11:18 PM (in response to 814889)I can't very well help you rewrite your code, because I can't read your code. The lines are so long that I must horizontally scroll them to see both the start and the end. And they are so long vertically that the horizontal scroll bar is not visible when I look at the top of the file. And I am not going to copy the data, put it into my code editor and edit your code. I don't understand what you are doing and don't want to read a bunch of code to try to figure out what you are doing by seeing what the code does. You are probably in the wrong forum, Algorithms, but we're both here so I'll let that pass. You are not looking for Algorithm assistance but how to write code assistance which would be over in the newbie section. My comment about the class wrapping is essentially this: Your update code looks like this:); } If you wrap it in classes it could look like this: class TraitValues{ private Map<String, Float> Values = new HashMap<String, Float>(); public void add(String trait, Float value){Values.put(triat, value);} } class Hybrid{ String name // a single hybrid has a name TraitValues values = new TraitValues(); // .. and a list of values static Map<String, Hybrid> all = new HashMap<String, Hybrid>(); public Hybrid(String name){this.name = name; all.add(this);} public void add(String trait, Float value){values.add(trait, value);} public static Hybrid get(String name){ String up name.toUpperCase(); Hybrid h = all.get(up); if(h == null){h = new Hybrid(up);} return h; } } This allows you to create Hybrid objects that have a name and a list of values. Hybrid has a constructor that take a name, creates a blank values list, and adds the Hybrid to the static Map of all Hybrids. Hybrid has a static function, getHybrid, that will fetch a single Hybrid by name from the static list of all of them. In places that you used to call update(hybridTraitValues, hybridName, avg, traitName) You would call Hybrid.get(hybridName).add(traitName, avg); More intelligently, up where you have code that sets the hybridName; String hybridName = itemValues[0]; you would get the Hybrid object that you are working with like this: Hybrid hy = Hybrid.get(itemValues[0]); and then in the places you used to call update you would have: hy.add(traitName, avg) You see, I have replaced your String that happens to be a hybrid name with a Hybrid class that maintains hybrid objects (that happen to have names). I have replaced your hybridTraitValues structure, with a static variable in the Hybrid class called Hybrid.all I did not do the same for your Traits, but I suspect that you want to do something similar like: class Trait{ String name; Float value; ... I don't know what you want traits to do, possibly different calculations. } if You do that, you would need to fix the TraitValues class so that instead of being Maps from Strings to Floats it is a Map from Strings to Traits. You tend to be using Strings (like hybrid names and trait names) as keys to fetch values out of large structures and your code is littered with testing and fecthing using these String values. You can't abandon strings entirely because apparently, you have a text file with string values in it for your input data. But strings are stupid things. You want to map those Strings into objects, which can have code embedded which can be used to reduce your surface code. In nearly any code that looks like: if(str == "FOO"){ .. bunch of code dealing with Foo } else if (str == "BAR"){ ... bunch of code dealing with Bar } else if { str == "BAZ" ... You can probably do that with classes, creating classes FOO, BAR, BAZ, mapping your string to an object (like I did with Hybrid) and then calling code like: SomeObject so = SomeObject.get(str); // fetch out the appropriate type of object so.doSomething(); // let the object do the right thing And the doSomething is defined differently in your different classes. In your code I see you testing for strings like YLD, TLSSV and branching into different chunks of code. This suggests to me that you may need classes like YLD and TLSSV. I don't know what those are, ao I called them Columns and suggested code having a Column interface. If you are not familiar with static values and interfaces, I would recommend looking them up. They are an essential part of the OOP toolkit.
https://community.oracle.com/message/10785721
CC-MAIN-2017-13
refinedweb
2,875
63.49
PeakDetect — Peak detection of peaks and valleys.¶ This module defines a peak detection utility that looks for local maxima and minima. It is based on code by Marcos Duarte,. - class admit.util.peakfinder.PeakDetect. PeakDetect(spec, x=None, **kwarg)[source]¶ Detect peaks in data based on their amplitude and other features. Examples from admit.util.peakfinder.PeakDetect import PeakDetect import numpy as np x = np.random.randn(100) x[60:81] = np.nan # detect all peaks pd = PeakDetect(x) ind = pd.find() print(ind) x = np.sin(2*np.pi*5*np.linspace(0, 1, 200)) + np.random.randn(200)/5 # set minimum peak height = 0 and minimum peak distance = 20 pd = PeakDetect(x, min_sep=20, thresh=0) ind = pd.find() x = [0, 1, 0, 2, 0, 3, 0, 2, 0, 1, 0] # set minimum peak distance = 2 pd = PeakDetect(x, min_sep=2) ind = pd.find() x = [0, 1, 1, 0, 1, 1, 0] # detect both edges pd = PeakDetect(x, edge='both') ind = pd.find() Attributes Methods detect_peaks(spec, valley=False)[source]¶ Detects peaks. Notes The detection of valleys instead of peaks is performed internally by simply negating the data: ind_valleys = detect_peaks(-x) The function can handle NaN’s See this IPython Notebook [R5]. References
http://admit.astro.umd.edu/module/admit.util.peakfinder/PeakDetect.html
CC-MAIN-2021-31
refinedweb
205
60.61
As a fan of World Of Warcraft game I recently went shoping for mouse with extra buttons. The idea was that binding extra spells in game to those buttons will radically improve my reaction times. Such was the theory. But as I unpacked my brand new mouse and started so called mouse configuration panel i found out that only 2 of additional 6 extra buttons were programmable . And even those 2 had just limited assignable functionality such as "start email client" etc. Errrr But I am curious person and i started to study this driver software. Soon i discovered that majority of the cheap mouses use the same drivers. So if you see KMProcess running you are a lucky guy. By launching usefull microsoft Spy++ I also soon found out that for each extra mouse button pressed this universal mouse driver generates custom WM_USER based message. So the idea was to capture those messages and react by emulating driver level keyboard imput so those buttons will be seen as regullar bindable keyboard buttons to games. If you don't have KMProcess running don't worry. There is second and what is more important vendor / driver independent method. I will add code sample for this method soon so stay in touch #include <windows.h> #include <stdio.h> HHOOK hook = 0; char target[32] = {0}; int last = 0; void btn(int i,int up) { if(3*up+i != last) keybd_event(VK_F1+i,MapVirtualKey(VK_F1+i,0),up,0); last = 3*up+i; } LRESULT CALLBACK proc(int disabled,WPARAM wp,LPARAM lp) { int *m = (int *)lp; if (!disabled) { if( m[1] == 0x0465 && m[2] == 0x0000 && m[3] == 2 ) btn(0,0); if( m[1] == 0x0464 && m[2] == 0x0000 && m[3] == 2 ) btn(0,2); if( m[1] == 0x0465 && m[2] == 0x0000 && m[3] == 4 ) btn(1,0); if( m[1] == 0x0464 && m[2] == 0x0000 && m[3] == 4 ) btn(1,2); if( m[1] == 0x1f58 && m[2] == 0x1b70 && m[3] == 0 ) btn(2,0); if( m[1] == 0x1f58 && m[2] == 0x1b70 && m[3] == 1 ) btn(2,2); if( m[1] == 0x1f58 && m[2] == 0x1b71 && m[3] == 0 ) btn(3,0); if( m[1] == 0x1f58 && m[2] == 0x1b71 && m[3] == 1 ) btn(3,2); if( m[1] == 0x1f58 && m[2] == 0x1b72 && m[3] == 0 ) { btn(4,0); Sleep(10); btn(4,2); } if( m[1] == 0x1f58 && m[2] == 0x1b73 && m[3] == 0 ) { btn(5,0); Sleep(10); btn(5,2); } } return CallNextHookEx(hook,disabled,wp,lp); } extern "C" __declspec(dllexport) void inst(HWND, HINSTANCE, char* cmd){ if(!cmd||hook) return; strncpy(target,cmd,sizeof(target)); hook = SetWindowsHookEx(WH_GETMESSAGE,proc,GetModuleHandle("hook"),0); MSG msg; while(GetMessage(&msg,0,0,0)) { TranslateMessage( &msg ); DispatchMessage( &msg ); Sleep(10); } } long __stdcall DllMain( HINSTANCE dll,DWORD reason){ return strstr(GetCommandLine(),target) ? 1 : 0; } Just build dll in whatever developmnet environment you have copy it do windows dir and install it from Start->Run.. Dialog rundll32 hook,inst KMProcess or from command line start rundll32 hook,inst KMProcess where hook is the name of dll and KMProcess is the name of the mouse driver process Also if you are a not programmer don't worry. Just extract included zip file and run bat file. As soon as I will have time I will add second method plus version with some nice Gui allowing to record and play mouse and keyboard macros on any mouse button press. General News Question Answer Joke Rant Admin
http://www.codeproject.com/KB/audio-video/ReprogramYourMouse.aspx
crawl-002
refinedweb
573
59.43
I am a little confused about how python deal with reference to an element in a list, considering these two examples: First example: import random a = [[1,2],[3,4],[5,6],[7,8]] b = [0.1,0.2] c = random.choice(a) c[:] = b print(a) import random a = [1, 2, 3, 4, 5, 6, 7, 8] b = 0.1 c = random.choice(a) c = b print(a) Let's start with the second case. You write c = random.choice(a) so the name c gets bound to some element of a, then c = b so the name c gets bound to some other object (the one to which the name b is referring - the float 0.1). Now to the first case. You start with c = random.choice(a) So the name c gets bound to an object in a, which is a list itself. Then you write c[:] = b which means, replace all items in the list bound to by the name c, by some other list. In fact, this is called slice assignment, and is basically syntactic sugar for calling a method of the object to which c is bound. The difference, then, is that in the first case, it doesn't just bind a name first to one object, then to another. It binds a name to a list, then uses this name to indirectly call a method of the list.
https://codedump.io/share/3YQoptlgpOMM/1/reference-to-an-element-in-a-list
CC-MAIN-2017-39
refinedweb
236
81.53
Walkthrough: Using ASP.NET Routing in a Web Forms Application This walkthrough shows how to modify an existing ASP.NET Web site to include ASP.NET routing features. At the end of this walkthrough the site will have three new Web pages. Hyperlinks in one of the new pages link to the other two pages by using routes. Because these hyperlinks use routing to create the link URLs, they do not need to be changed if the target pages change names or location. This walkthrough shows how you can do the following with a minimum amount of code: Define custom URL patterns that are not dependent on physical file names. Generate URLs based on route URL parameter values by using markup or code. In a routed page, retrieve values passed in URL segments by using markup or code. A Visual Studio Web site project with source code is available to accompany this topic: Download. In order to run this walkthrough, you must have the following: Visual Studio 2010 or later versions. An ASP.NET Web site that targets the .NET Framework version 4 or later versions. If you do not already have a Web site to work with, see Walkthrough: Creating a Basic Web Page in Visual Studio. Routes map URL patterns to physical files. To add routes to a Web site, you add them to the static (Shared in Visual Basic) Routes property of the RouteTable class by using the RouteCollection.MapPageRoute method. In the following procedure, you create a method that you will use to add the routes. You call the new method from the Application_Start handler of the Global.asax page. To add a method to the Global.asax file for adding routes If the Web site does not already have a Global.asax file, add one by following these steps: Right-click the Web project in Solution Explorer and then select Add New Item. Select Global Application Class and then click Add. Open the Global.asax file. After the Application directive, add an Import directive for the System.Web.Routing namespace, as shown in the following example: After the Session_End method, add the following code: In the following procedure you will add code to this method that creates routes. In the Application_Start method, call RegisterRoutes as shown in the following example: This code passes the static (Shared in Visual Basic) Routes property of the RouteData class to RegisterRoutes. The preceding procedure added an empty method that you can use to register routes. You will now add code to this method that adds routes to the Web site. When you have finished this procedure, your application will accept URLs like the following: ASP.NET routing will route URLs such as these to the Sales.aspx and Expenses.aspx pages. To add routes In the RegisterRoutes method, add the following code: This code adds an unnamed route that has a URL pattern that contains the literal value "SalesReportSummary" and a placeholder (URL parameter) named year. It maps the route to a file that is named Sales.aspx. In the RegisterRoutes method, add the following code: This code adds a route that is named SalesRoute. You are naming this route because it has the same parameter list as the route that you will create in the following step. Assigning names to these two routes enables you to differentiate them when you generate URLs for them. In the RegisterRoutes method, add the following code: This code adds a route that is named ExpensesRoute. This route includes a catch-all parameter named extrainfo. The code sets the default value of the locale parameter to "US", and it sets the default value of the year parameter to the current year. Constraints specify that the locale parameter must consist of two alphabetic characters and the year parameter must consist of four numeric digits. When you add hyperlinks to a Web page, if you want to specify a route URL instead of a physical file you have two options: You can hard-code the route URL. You can specify the route parameter names and values and let ASP.NET generate the URL that corresponds to them. You can also specify the route name if required in order to uniquely identify the route. If you change route URL patterns later, you would have to update any hard-coded URLs, but if you let ASP.NET generate the URLs, the correct URLs are always automatically generated (unless the parameters in the patterns are changed). In the following procedure you add hyperlinks that use hard-coded URLs to a Web page. To create hard-coded URLs In Solution Explorer, right-click the Web project and click Add New Item. The Add New Item dialog box is displayed. Select the Web Form template, make sure Place code in separate file is checked, set the name to Links.aspx, and then click Add. The Links.aspx page opens in Source view. Between the opening and closing <div> tags, add the following markup: <asp:HyperLink Sales Report - All locales, 2010 </asp:HyperLink> <br /> <asp:HyperLink Sales Report - WA, 2011 </asp:HyperLink> <br /> <asp:HyperLink Expense Report - Default Locale and Year (US, current year) </asp:HyperLink> <br /> This markup creates three HyperLink controls with hard-coded URLs. The first hyperlink matches the URL pattern of the sales summary route, the second matches the route named SalesRoute, and the third matches the route named ExpensesRoute. Because no parameters are specified for the URL of the third hyperlink, the default values defined for that route will be passed to Expenses.aspx. Next you will you add markup that creates hyperlinks that specify route parameters and route names to create route URLs. To create automatically generated URLs by using markup With Links.aspx still open in Source view, add the following code after the HyperLink controls that you created in the previous procedure: <asp:HyperLink Sales Report - All locales, 2011 </asp:HyperLink> <br /> <asp:HyperLink Sales Report - CA, 2009 </asp:HyperLink> <br /> This markup uses RouteUrl expressions to create URLs for the routes that are named SalesSummaryRoute and SalesRoute. The second RouteUrl expression specifies the name of the route because the parameter list that is provided in the code could match either the ExpensesRoute URL pattern or the SalesRoute URL pattern. The ExpensesRoute URL pattern has an extrainfo placeholder which the SalesRoute URL pattern does not have, but extrainfo is a catch-all placeholder, which means it is optional. In the following procedure you add markup that creates a hyperlink and you use code to generate a URL for the hyperlink by specifying route parameters and a route name. To create automatically generated URLs by using code With Links.aspx still open in Source view, add the following code after the HyperLink control that you created in the previous procedure: This markup does not set the NavigateUrl property because that property will be set in code. In Solution Explorer, expand Links.aspx, and then open Links.aspx.vb or Links.aspx.cs. Add a using statement (Imports in Visual Basic) for the System.Web.Routing namespace, as shown in the following example: In the Page_Load method, add the following code: This code creates an instance of the RouteValueDictionary class that contains three parameters. The third parameter is category, which is not in the URL pattern. Because it is not in the URL pattern, the category parameter and its value will be rendered as a query-string parameter. Following the code that you added in the previous step, add the following code: This code instantiates a VirtualPathData object by calling the GetVirtualPath method of the RouteCollection class. Because the SalesRoute URL pattern and the ExpensesRoute URL pattern have similar placeholders, it calls the overload that accepts route name and specifies the ExpensesRoute value. Following the code that you added in the previous step, add the following code to set the NavigateUrl property of the hyperlink: In an ASP.NET page that has been invoked by ASP.NET routing, you can retrieve the values of URL parameters in markup or in code. For example, the SalesReport route includes parameters named locale and year, and when a URL request that matches this pattern is received, code in the Sales.aspx page might need to pass the values of those parameters to a SQL query. In the following procedure, you access URL parameter values by using markup. This method is useful for displaying parameter values in the Web page. To access URL parameter values by using markup Right-click the Web project and click Add New Item. The Add New Item dialog box is displayed. Select the Web Form template and set the name to Expenses.aspx. The Expenses.aspx page opens in Source view. Add the following markup between the opening and closing <div> tags: This markup uses RouteValue expressions to extract and display the values of the URL parameters that are passed to the page. In the following procedure you access parameter values by using code. This method is useful when you must process the data in some way, such as by translating null values to a default value as shown in this procedure, or by passing the information to a SQL query. To access URL parameter values by using code Right-click the Web project and click Add New Item. The Add New Item dialog box is displayed. Select the Web Form template, make sure Place code in separate file is checked, set the name to Sales.aspx, and then click Add. The Sales.aspx page opens in Source view. Add the following markup between the opening and closing <div> tags: This markup includes Literal controls but does not set their Text properties because those properties will be set in code. In Solution Explorer, expand Sales.aspx and then open Sales.aspx.vb or Sales.aspx.cs. In the Page_Load method, add the following code to set the Text property of the first Literal control to one of the following values: The literal All locales if the locale parameter is null. The value of the locale parameter if the locale parameter is not null. In the Page_Load method, add the following code to set the Text property of the first Literal control to the value of the year URL parameter: Now you can test routing. To test routing In Solution Explorer, right-click Links.aspx and select View in Browser. The page is displayed in the browser, as shown in the following figure: Click each hyperlink. Notice that each hyperlink goes to a page that has a heading that corresponds to the text of the hyperlink. Go back to the Links.aspx page, select your browser's View Source command, and examine the URLs for the last three hyperlinks. You see the following automatically generated URLs: http://[server]/[application]/SalesReportSummary/2011 http://[server]/[application]/SalesReport/CA/2009 http://[server]/[application]/ExpenseReport/CA/2008?category=recreation Copy the URL that ends in SalesReport/CA/2009 to the Windows Clipboard and close the View Source window. Paste the URL into the browser's address bar, change CA to invalidlocale and 2009 to invalidyear, and then press ENTER. A page is displayed that is similar to the following figure: You see the Sales Report page that shows the values invalidlocale and invalidyear. Because you did not specify any constraints for the SalesRoute route, invalid data is accepted. Paste the URL into the browser's address bar again, change CA to invalidlocale, change 2009 to invalidyear, change SalesReport to ExpenseReport, and press Enter. A page is displayed that is similar to the following figure: You see a "not found" error because the URL cannot be resolved to a route. The ExpenseReport route will accept only locale parameters that have two alphabetic characters, and year parameters that have four numeric digits. A typical use for URL parameters is in database queries. You can provide the value of a URL parameter to a data source control in markup by using the asp:RouteParameter.element. For more information, see the RouteParameter class.
http://msdn.microsoft.com/en-us/library/dd329551(v=vs.100).aspx?cs-save-lang=1&cs-lang=csharp
CC-MAIN-2014-10
refinedweb
2,010
63.09
2465/what-do-we-understand-from-string-pool-in-java This prints true (even though we don't use equals method: correct way to compare strings) String x = "p" + "qr"; String y = "pq" + "r"; System.out.println(x == y); When compiler optimizes your string literals, it sees that both x and y have same value and thus you need only one string object. It's safe because String is immutable in Java. As result, both x and y point to the same object and some little memory saved. Name 'string pool' comes from the idea that all already defined string are stored in some 'pool' and before creating new String object compiler checks if such string is already defined. @Override annotation is used when we override ...READ MORE If you're looking for an alternative that ...READ MORE You can use ArrayUtils class remove method which ...READ MORE String str = "..."; // write the ...READ MORE You can use Java Runtime.exec() to run python script, ...READ MORE First, find an XPath which will return ...READ MORE See, both are used to retrieve something ...READ MORE Nothing to worry about here. In the ...READ MORE import java.util.regex.Matcher; import java.util.regex.Pattern; String pattern="[\\s]"; String replace=""; part="name=john age=13 year=2001"; Pattern ...READ MORE String aString = "world"; int aInt = 20; String.format("Hello, ...READ MORE OR Already have an account? Sign in.
https://www.edureka.co/community/2465/what-do-we-understand-from-string-pool-in-java?show=2466
CC-MAIN-2019-51
refinedweb
236
77.33
Installing an Add-on Product Instructions for how to install an add-on Product, after you have taken the necessary precautions. Introduction With Plone 3.0, the Plone community adopted new standards for packaging, distributing and installing add-on Products for Plone. Instead of shipping Products as folders that get copied into a "magic" Products folder in your Zope instance, add-on Products (and the products that make up Plone itself!) are now shipped as Python eggs, which are installed into the instance of Python that is powering your Zope instance using the Buildout installation system. These new installation methods can make it far easier and simpler to install add-on Products in a consistent, repeatable way. However, the Plone community is still in the midst of adopting these new techniques, which means you may find add-on Products that require different approaches to installation. The purpose of this document is to provide a single point of documentation that covers the common add-on Product installation techniques for typical real-world deployment scenarios. Always backup your Plone installation before changing the configuration of a production installation. Always read your product's documentation, usually in a README.txt or similar file. Your product may have specific installation instructions, which you must obviously follow. Installing Products Using Buildout Buildout is a powerful, easy-to-use utility for creating scripted, repeatable installations of Plone, Zope and Python. As of Plone 3.2, Plone's Unified Installer began using Buildout, and so Buildout is now the "mainstream best practice" way to install Plone add-on Products. Buildout can be used to install both Zope 2-style and egg-based Products. If Buildout is available for your installation, it is the recommended way to manage add-on product installation. How to install a new third-party products will depend on whether it is packaged as an egg, or a traditional Zope 2 product. Installing eggs Most modern Plone add-on Products are now packaged as eggs, the Python community's standard distribution format. Egg-based packages are very simple to install with Buildout. Here's how. Step 1: Add the egg to your buildout.cfg file Find your "buildout.cfg" file, typically located in the "zinstance" subdirectory of your Plone installation directory. Simply list the egg in the eggs section of your buildout, and optionally a version (otherwise, you get the latest available). Buildout will automatically download and install the egg and any dependencies it specifies. [buildout] ... eggs = Products.PloneFormGen collective.recaptcha If you want buildout to search other egg repositories, you can add a URL to find-links that contains download links for the eggs. By default, Plone searches the following repositories, in addition to PyPi, the Python community's master repository for eggs. [buildout] ... find-links = Step 2: If your product is not named "Products.*", add it to the zcml section of your buildout It is important to realize that Zope will not load configure.zcml files automatically for packages that are not in the Products.* namespace. Instead, you must explicitly reference the package. Buildout can create such a reference (known as a ZCMLslug) with the zcml option under the [instance] part. Here is how to ensure that collective.recaptcha is available to Zope: [buildout] ... eggs = Products.PloneFormGen collective.recaptcha ... [instance] ... zcml = collective.recaptcha Step 3: Rerun buildout and restart your Zope instance Now that you've reconfigured your buildout, you must rerun buildout and restart your Zope instance to download and install your new eggs. Navigate to your zinstance directory, and type: $ ./bin/buildout Buildout will run, and install your new products. Then, start (or restart) Zope, typically with $ ./bin/plonectl restart Step. Installing a traditional Zope 2 product with Buildout The easiest way to install Installing Egg-based Products Without Buildout Installing egg-based add-on Products for Plone without Buildout is not recommended unless you are an advanced developer. It is far better to migrate your Plone installation to Buildout (or upgrade to Plone 3.2 or higher, which use Buildout). Relatively few egg-based add-on Products are compatible with versions of Plone below 3.0 in any case. Installing Zope 2-style Products Without Buildout You can install Zope 2-style add-on Products without Buildout. Typically, you'd only do this if you are running Plone 2.x, which predates mainstream use of Buildout. Step 1: Place the Product's Directory in Your Zope Instance's "Products" Directory Remember to use a test instance unless you know that the Product is compatible with your Plone setup! Generally you will download a file like SomeProduct-0.5.3.tar.gz. Extract the contents of this file. On a Unix-like system, you might say: $ tar -zxvf SomeProduct-0.5.3.tar.gz On a Windows system, use 7zip or another zip extraction tool. Make sure that you preserve the directory structure when extracting; some tools, such as WinZip, have a habit of flatting the directory structure of the compressed archive, thus giving you all the files in a single directory. In this case, you may need to select an option to preserve the structure when you extract the archive. You should end up with a directory structure like either: SomeProduct-0.5.3/ SomeProduct/ __init__.py ... or: SomeProduct/ __init__.py ... The SomeProduct/ directory is the "Product directory", recognizable by the __init__.py file. Sometimes there might be several Products packaged into a single archive. Place the Product's directory (or directories) in your Zope instance's Products/ directory. In Windows, the instance directory is often named Data. Note that you do not want to use the lib/python/Products directory. Make sure the folder has the same owner and permissons as the other Products in your Zope instance, and is readable by the user that your Zope server runs as. For example, the Unified Installer build of Plone runs as a user named "plone" and all Plone Products are owned by this user. On *nix and Mac OS X you can move to your Products directory and execute the command sudo chown -R plone * to set the ownership of all files in the Products folder to user "plone". Step 2: Restart Zope Unless you restart Zope, it will never know that there are new Products available. When restarted, the new Products will show up in the Zope Control Panel's Products section. This means the software is now available for use in the Plone instance. (Some Products will start to take effect at this point, like DocFinderTab or anything that does monkeypatching.) Step. Further information Troubleshooting Add-on Product Installation Problems For more advanced information on using Buildout when doing custom development work, see Managing projects with Buildout - Packages, products and eggs. Credits Thanks to J. Cameron Cooper for the first version of the Zope 2-style Products installation instructions. Martin Aspeli, Graham Perrin, Jon Stahl and Steve McMahon conspired on updates. Uninstalling
http://plone.org/documentation/tutorial/third-party-products/installing
crawl-002
refinedweb
1,155
56.45
Top 26 Python Programming Interview Questions 1. Python Programming Interview Questions And we’re back with our third series of Python Programming interview questions. Here we have taken some basic Python Interview questions and answers for freshers, advanced Python Interview Questions and Answers for Experienced, Python Developers interview Question and Answer, Python Coding interview questions, Python Scripting Interview questions as well as data structure interview questions. You can First go through the Python Interview Question Part I and Part II Read along to learn something new and out of the blue. So, let’s start our Python Programming Interview Questions. The journey of a THOUSAND miles begins with ONE step. Q.1. What does the following code output? >>> def extendList(val, list=[]): list.append(val) return list >>> list1 = extendList(10) >>> list2 = extendList(123,[]) >>> list3 = extendList('a') >>> list1,list2,list3 Ans. (. Let’s revise the Basis of Python Programming Q.2. What is a decorator? Ans.. For more on decorators, read Python 2. Basic Python Programming Interview Questions Below are some Basic Python Programming Interview Questions and answers for freshers. Q.3. Write a regular expression that will accept an email id. Use the re module. Ans. >>> import re >>> e=re.search(r'[0-9a-zA-Z.]+@[a-zA-Z]+\.(com|co\.in)$','ayushiwashere@gmail.com') >>> e.group() ‘ayushiwashere@gmail.com’ To brush up on regular expressions, check Regular Expressions in Python. Q.4. How many arguments can the range() function take? Ans..5. Does Python have a switch-case statement? Ans.. Any doubt yet in Python Programming interview Questions. Please Comment. Q.6. How do you debug a program in Python? Answer in brief. Ans. To debug a Python program, we use the pdb module. This is the Python debugger; we will discuss it in a tutorial soon. If we start a program using pdb, it will let us step through the code. Q.7. List some pdb commands. Some pdb commands include- <b> — Add breakpoint <c> — Resume execution <s> — Debug step by step <n> — Move to next line <l> — List source code <p> — Print an expression Q.8. What command do we use to debug a Python program? Ans. To start debugging, we first open the command prompt, and get to the location the file is at. Microsoft Windows [Version 10.0.16299.248] C:\Users\lifei> cd Desktop C:\Users\lifei\Desktop> Then, we run the following command (for file try.py): C:\Users\lifei\Desktop>python -m pdb try.py > c:\users\lifei\desktop\try.py(1)<module>() -> for i in range(5): (Pdb) Then, we can start debugging. Q.9. What is a Counter in Python? Ans. The function Counter() from the module ‘collections’. It counts the number of occurrences of the elements of a container. >>> from collections import Counter >>> Counter([1,3,2,1,4,2,1,3,1]) Counter({1: 4, 3: 2, 2: 2, 4: 1}) Python provides us with a range of ways and methods to work with a Counter. Read Python Counter. Q.10. What is NumPy? Is it better than a list? Ans. NumPy, a Python package, has made its place in the world of scientific computing. It can deal with large data sizes, and also has a powerful N-dimensional array object along with a set of advanced functions. Yes, a NumPy array is better than a Python list. This is in the following ways: - It is more compact. - It is more convenient. - It Is more efficiently. - It is easier to read and write items with NumPy. Read our latest tutorial on Python NumPy Q.11. How would you create an empty NumPy array? Ans. To create an empty array with NumPy, we have two options: a. Option 1 >>> import numpy >>> numpy.array([]) array([], dtype=float64) b. Option 2 >>> numpy.empty(shape=(0,0)) array([], shape=(0, 0), dtype=float64) Refer Python Libraries Q.12. What is PEP 8? Ans. PEP 8 is a coding convention that lets us write more readable code. In other words, it is a set of recommendations. Q.13. What is pickling and unpickling? Ans. To create portable serialized representations of Python objects, we have the module ‘pickle’. It accepts a Python object (remember, everything in Python is an object). It then converts it into a string representation and uses the dump() function to dump it into a file. We call this pickling. In contrast, retrieving objects from this stored string representation is termed ‘unpickling’. Q.14. What is a namespace in Python? Ans.. Just Follow this link to know more about Python Namespace Q.15. So Q2 to Q15 were some Basic Python Programming Interview Questions and Answers for Freshers. Experienced can also refer these Python Interview Questions for revision. 3. Advanced Python Interview Questions and Answers Below are some Advanced Python Programming Interview Questions For Experienced. I recommend freshers to also refer these interview questions for advanced knowledge. Q.16. Explain the use of the ‘nonlocal’ keyword in Python. Ans. First, let’s discuss the local and global scope. By example, a variable defined inside a function is local to that function. Another variable defined outside any other scope is global to the function. Suppose we have nested functions. We can read a variable in an enclosing scope from inside he inner function, but cannot make a change to it. For that, we must declare it nonlocal inside the function. First, let’s see this without the nonlocal keyword. >>> def outer(): a=7 def inner(): print(a) inner() >>> outer() 7 >>> def outer(): a=7 def inner(): print(a) a+=1 print(a) inner() >>> outer() Traceback (most recent call last): File “<pyshell#462>”, line 1, in <module> outer() File “<pyshell#461>”, line 7, in outer inner() File “<pyshell#461>”, line 4, in inner print(a) UnboundLocalError: local variable ‘a’ referenced before assignment So now, let’s try doing this with the ‘nonlocal’ keyword: >>> def outer(): a=7 def inner(): nonlocal a print(a) a+=1 print(a) inner() >>> outer() 7 8 Q.17. So, then, what is the global keyword? Ans. Like we saw in the previous question, the global keyword lets us deal with, inside any scope, the global version of a variable. The problem: >>> a=7 >>> def func(): print(a) a+=1 print(a) The solution: >>> a=7 >>> def func(): global a print(a) a+=1 print(a) >>> func() 7 8 Q.18. How would you make a Python script executable on Unix? Ans. For this to happen, two conditions must be met: - The script file’s mode must be executable - The first line must begin with a hash(#). An example of this will be: #!/usr/local/bin/python Q.19. What functions or methods will you use to delete a file in Python? Ans..20. What are accessors, mutators, and @property? Ans. What we call getters and setters in languages like Java, we term accessors and mutators in Python. In Java, if we have a user-defined class with a property ‘x’, we have methods like getX() and setX(). In Python, we have @property, which is syntactic sugar for property(). This lets us get and set variables without compromising on the conventions. For a detailed explanation on property, refer to Python property. Any Doubt yet in Advanced Python Interview Questions and Answers for Experienced? Please Comment. Q.21. Explain a few methods to implement Functionally Oriented Programming in Python. Ans..22. Differentiate between the append() and extend() methods of a list. Ans.] Refer Python Lists Q.23. Consider multiple inheritances here. Suppose class C inherits from classes A and B as class C(A,B). Classes A and B both have their own versions of method func(). If we call func() from an object of class C, which version gets invoked? Ans. In our article on Multiple Inheritance in Python, we discussed Method Resolution Order (MRO). C does not contain its own version of func(). Since the interpreter searches in a left-to-right fashion, it finds the method in A, and does not go to look for it in B. Q.24. Which methods/functions do we use to determine the type of instance and inheritance? Ans..25. What do you mean by overriding methods? Ans. Suppose class B inherits from class A. Both have the method sayhello()- to each, their own version. B overrides the sayhello() of class A. So, when we create an object of class B, it calls the version that class B has. >>> class A: def sayhello(self): print("Hello, I'm A") >>> class B(A): def sayhello(self): print("Hello, I'm B") >>> a=A() >>> b=B() >>> a.sayhello() Hello, I’m A >>> b.sayhello() Hello, I’m B Refer this link to know more about Method Overriding in Python Q.26. What is JSON? Describe in brief how you’d convert JSON data into Python data? Ans. JSON stands for JavaScript Object Notation. It is a highly popular data format, and it stores data into NoSQL databases. JSON is generally built on the following two structures: - A collection of <name,value> pairs - An ordered list of values. Python supports JSON parsers. In fact, JSON-based data is internally represented as a dictionary in Python. To convert JSON data into Python data, we use the load() function from the JSON module. These were the advanced Python Programming Interview Questions. This was all about the Python Programming Interview Questions and Answers. 4. Conclusion: Python Programming Interview Questions Again, we discussed a variety of Python Programming Interview Questions and answers. But stay put, folks, this isn’t all. We meet again with another string of questions to guide you to your interview. Comment if you have a query on Python Programming Interview Questions. Also see:
https://data-flair.training/blogs/python-programming-interview-questions/
CC-MAIN-2019-35
refinedweb
1,619
67.96
! 20181201 .3225 2018/12/01 20:59:08 20181201 49 + add midnightbsd to CF_XOPEN_SOURCE macro (patch by Urs Jansen). 50 + add "@" command to test/ncurses F-test, to allow rapid jump to 51 different character pages. 52 + update config.guess, config.sub from 53 54 55 20181125 56 + build-fix (reports by Chih-Hsuan Yen, Sven Joachim). 57 58 20181124 59 + check --with-fallbacks option to ensure there is a value, and add 60 the fallback information to top-level Makefile summary. 61 + add some traces in initialization to show whether a fallback entry is 62 used. 63 + build-fix for test/movewindow with ncurses-examples on Solaris. 64 + add "-l" option to test/background, to dump screen contents in a form 65 that lets different curses implementations be compared. 66 + modify the initialization checks for mouse so that the xterm+sm+1006 67 block will work with terminal descriptions not mentioning xterm 68 (report by Tomas Janousek). 69 70 20181117 71 + ignore the hex/b64 $TERMINFO in toe's listing. 72 + correct a status-check in _nc_read_tic_entry() so that if reading 73 a hex/b64 $TERMINFO, and the $TERM does not match, fall-through to 74 the compiled-in search list. 75 76 20181110 77 + several workarounds to ensure proper C compiler used in parts of 78 Ada95 tree. 79 + update config.guess, config.sub from 80 81 82 20181027 83 + add OpenGL clients alacritty and kitty -TD 84 + add Smulx for tmux, vte-2018 -Nicholas Marriott 85 86 20181020 87 + ignore $TERMINFO as a default value in configure script if it came 88 from the infocmp -Q option. 89 + allow value for --with-versioned-syms to be a relative pathname 90 + add a couple of broken-linker symbols to the list of versioned 91 symbols to help with link-time optimization versus weak symbols. 92 + apply shift/control/alt logic when decoding xterm's 1006 mode to 93 wheel-mouse events (Redhat #1610681). 94 95 20181013 96 + amend change from 20180818, which undid a fix for the $INSTALL value 97 to make it an absolute path. 98 99 20181006 100 + improve a configure check to work with newer optimizers (report by 101 Denis Pronin, Gentoo #606142). 102 + fix typo in tput.c (Sven Joachim, cf: 20180825). 103 104 20180929 105 + fix typo in tvi955 -TD 106 + corrected acsc for regent60 -TD 107 + add alias n7900 -TD 108 + corrected acsc for tvi950 -TD 109 + remove bogus kf0 from tvi950 -TD 110 + added function-key definitions to agree with Televideo 950 manual -TD 111 + add bel to tvi950 -TD 112 + add shifted function-keys to regent60 -TD 113 + renumber regent40 function-keys to match manual -TD 114 + add cd (clr_eos) to adds200 -TD 115 116 20180923 117 + build-fix: remove a _tracef call which was used for debugging (report 118 by Chris Clayton). 119 120 20180922 121 + ignore interrupted system-call in test/ncurses's command-line, e.g., 122 if the terminal were resized. 123 + add shift/control/alt logic for decoding xterm's 1006 mode (Redhat 124 #1610681, cf: 20141011). 125 + modify rpm test-packages to not use --disable-relink with Redhat, 126 since Fedora 28's tools do not work with that feature. 127 128 20180908 129 + document --with-pcre2 configure option in INSTALL. 130 + improve workaround for special case in PutAttrChar() where a cell is 131 marked as alternate-character set, to handle a case where the 132 character in the cell does not correspond to any of the ASCII 133 fallbacks (report by Leon Winter, cf: 20180505). 134 + amend change to form library which attempted to avoid unnecessary 135 update of cursor position in non-public fields, to simply disable 136 output in this case (patch by Leon Winter, cf: 20180414). 137 + improve check for LINE_MAX runtime limit, to accommodate broken 138 implementations of sysconf(). 139 140 20180901 141 + improve manual page for wgetnstr, giving background for the length 142 parameter. 143 + define a limit for wgetnstr, wgetn_wstr when length is negative or 144 "too large". 145 + update configure script to autoconf 2.52.20180819 (Debian #887390). 146 147 20180825 148 + add a section to tput manual page clarifying how it determines the 149 terminal size (prompted by discussion with Grant Jenks). 150 + add "--disable-relink" to rpm test-packages, for consistency with the 151 deb test-packages. 152 + split spec-file into ncurses6.spec and ncursest6.spec to work around 153 toolset breakage in Fedora 28. 154 + drop mention of "--disable-touching", which was not in the final 155 20180818 updates. 156 157 20180818 158 + build-fix for PDCurses with ncurses-examples. 159 + improved CF_CC_ENV_FLAGS. 160 + modify configure scripts to reduce relinking/ranlib during library 161 install (Debian #903790): 162 + use "install -p" when available, to avoid need for ranlib of 163 static libraries. 164 + modify scripts which use "--disable-relink" to add a 1-second 165 sleep to work around tools which use whole-second timestamps, e.g., 166 in utime() rather than the actual file system resolution. 167 168 20180804 169 + improve logic for clear with E3 extension, in case the terminal 170 scrolls content onto its saved-lines before actually clearing 171 the display, by clearing the saved-lines after clearing the 172 display (report/patch by Nicholas Marriott). 173 174 20180728 175 + improve documentation regarding feature-test macros in curses.h 176 + improve documentation regarding the virtual and physical screens. 177 + formatting fixes for manpages, regenerate man-html documentation. 178 179 20180721 180 + build-fixes for gcc8. 181 + corrected acsc for wy50 -TD 182 + add wy50 and wy60 shifted function-keys as kF1 to kF16 -TD 183 + remove ansi+rep mis-added to interix in 2018-02-23 -TD 184 185 20180714 186 + add enum, regex examples to test/demo_forms 187 + add configure check for pcre-posix library to help with MinGW port. 188 189 20180707 190 + build-fixes for gcc8. 191 + correct order of WINDOW._ttytype versus WINDOW._windowlist in 192 report_offsets. 193 + fix a case where tiparm could return null if the format-string was 194 empty (Debian #902630). 195 196 20180630 197 + add acsc string to vi200 (Nibby Nebbulous) 198 add right/down-arrow to vi200's acsc -TD 199 + add "x" to tput's getopt string so that "tput -x clear" works 200 (Nicholas Marriott). 201 + minor fixes prompted by anonymous report on stack overflow: 202 + correct order of checks in _nc_get_locale(), for systems lacking 203 locale support. 204 + add "#error" in a few places to flag unsupported configurations 205 206 20180623 207 + use _WIN32/_WIN64 in preference to __MINGW32__/__MINGW64__ symbols 208 to simplify building with MSVC, since the former are defined in both 209 compiler configurations (report by Ali Abdulkadir). 210 + further improvements to configure-checks from work on dialog, i.e., 211 updated CF_ADD_INCDIR, CF_FIND_LINKAGE, CF_GCC_WARNINGS, 212 CF_GNU_SOURCE, CF_LARGEFILE, CF_POSIX_C_SOURCE, CF_SIZECHANGE, and 213 CF_TRY_XOPEN_SOURCE. 214 + update config.guess, config.sub from 215 216 217 20180616 218 + build-fix for ncurses-examples related to gcc8-fixes (cf: 20180526). 219 + reduce use of _GNU_SOURCE for current glibc where _DEFAULT_SOURCE 220 combines with _XOPEN_SOURCE (Debian #900987). 221 + change target configure level for _XOPEN_SOURCE to 600 to address 222 use of vsscanf and setenv. 223 + improved configure-checks CF_SIZECHANGE and CF_STRUCT_TERMIOS from 224 work on dialog. 225 226 20180609 227 + modify generated ncurses*config and ncurses.pc, ncursesw.pc, etc., 228 to list helper libraries such as gpm for static linking (Debian 229 #900839). 230 + marked vwprintw and vwscanw as deprecated; recommend using vw_printw 231 and vw_scanw, respectively. 232 233 20180602 234 + add RPM test-package "ncursest-examples". 235 + modified RPM test-package to work with Mageia6. 236 237 20180526 238 + add note in curs_util.3x about unctrl.h 239 + review/improve header files to ensure that those include necessary 240 files except for the previously-documented cases (report by Isaac 241 Pascual Monells). 242 + improved test-package scripts, adapted from byacc 1.9 20180525. 243 + fix some gcc8 warnings seen in Redhat package build, but 244 work around bug in gcc8 compiler warnings in comp_parse.c 245 246 20180519 247 + formatting fixes for manpages, regenerate man-html documentation. 248 + trim spurious whitespace from tmux in 2018-02-24 changes; 249 fix some inconsistencies in/between tmux- and iterm2-entries for SGR 250 (report by C Anthony Risinger) 251 + improve iterm2 using some xterm features which it has adapted -TD 252 + add check in pair_content() to handle the case where caller asks 253 for an uninitialized pair (Debian #898658). 254 255 20180512 256 + remove trailing ';' from GCC_DEPRECATED definition. 257 + repair a change from 20110730 which left an error-check/warning dead. 258 + fix several minor Coverity warnings. 259 260 20180505 261 + add deprecation warnings for internal functions called by older 262 versions of tack. 263 + fix a special case in PutAttrChar() where a cell is marked as 264 alternate-character set, but the terminal does not actually support 265 the given graphic character. This would happen in an older terminal 266 such as vt52, which lacks most line-drawing capability. 267 + use configure --with-config-suffix option to work around filename 268 conflict with Debian packages versus test-packages. 269 + update tracemunch to work with perl 5.26.2, which changed the rules 270 for escaping regular expressions. 271 272 20180428 273 + document new form-extension O_EDGE_INSERT_STAY (report by Leon 274 Winter). 275 + correct error-returns listed in manual pages for a few form functions 276 (report by Leon Winter). 277 + add a check in form-library for null-pointer dereference: 278 unfocus_current_field (form); 279 form_driver (form, REQ_VALIDATION); 280 (patch by Leon Winter). 281 282 20180414 283 + modify form library to optionally delay cursor movement on a field 284 edge/boundary (patch by Leon Winter). 285 + modify form library to avoid unnecessary update of cursor position in 286 non-public fields (patch by Leon Winter). 287 + remove unused _nc_import_termtype2() function. 288 + also add/improve null-pointer checks in other places 289 + add a null-pointer check in _nc_parse_entry to handle an error when 290 a use-name is invalid syntax (report by Chung-Yi Lin). 291 292 20180407 293 + clarify in manual pages that vwprintw and vwscanw are obsolete, 294 not part of X/Open Curses since 2007. 295 + use "const" in some prototypes rather than NCURSES_CONST where X/Open 296 Curses was updated to do this, e.g., wscanw, newterm, the terminfo 297 interface. Also use "const" for consistency in the termcap 298 interface, which was withdrawn by X/Open Curses in Issue 5 (2007). 299 As of Issue 7, X/Open Curses still lacks "const" for certain return 300 values, e.g., keyname(). 301 302 20180331 303 + improve terminfo write/read by modifying the fourth item of the 304 extended header to denote the number of valid strings in the extended 305 string table (prompted by a comment in unibilium's sources). 306 307 20180324 308 + amend Scaled256() macro in test/picsmap.c to cover the full range 309 0..1000 (report by Roger Pau Monne). 310 + add some checks in tracemunch for undefined variables. 311 + trim some redundant capabilities from st-0.7 -TD 312 + trim unnecessary setf/setb from interix -TD 313 314 20180317 315 + fix a check in infotocap which may not have detected a problem when 316 it should have. 317 + add a check in tic for the case where setf/setb are given using 318 different strings, but provide identical results to setaf/setab. 319 + further improve fix for terminfo.5 (patch by Kir Kolyshkin). 320 + reorder loop-limit checks in winsnstr() in case the string has no 321 terminating null and only the number of characters is used (patch 322 by Gyorgy Jeney). 323 324 20180303 325 + modify TurnOn/TurnOff macros in lib_vidattr.c and lib_vid_attr.c to 326 avoid expansion of "CUR" in trace. 327 + improve a few lintian warnings in test-packages. 328 + modify lib_setup to avoid calling pthread_self() without first 329 verifying that the address is valid, i.e., for weak symbols 330 (report/patch by Werner Fink). 331 + modify generated terminfo.5 to not use "expand" and related width 332 on the last column of tables, making layout on wide terminals look 333 better (adapted from patch by Kir Kolyshkin). 334 + add a category to report_offsets, e.g., "w" for wide-character, "t" 335 for threads to make the report more readable. Reorganized the 336 structures reported to make the categories more apparent. 337 + simplify some ifdef's for extended-colors. 338 + add NCURSES_GLOBALS and NCURSES_PRESCREEN to report_offsets, to show 339 how similar the different tinfo configurations are. 340 341 20180224 342 + modify _nc_resolve_uses2() to detect incompatible types when merging 343 a "use=" clause of extended capabilities. The problem was seen in a 344 defective terminfo integrated from simpleterm sources in 20171111, 345 compounded by repair in 20180121. 346 + correct Ss/Ms interchange in st-0.7 entry (tmux #1264) -TD 347 + fix remaining flash capabilities with trailing mandatory delays -TD 348 + correct cut/paste in NEWS (report by Sven Joachim). 349 350 20180217 351 + remove incorrect free() from 20170617 changes (report by David Macek). 352 + correct type for "U8" in user_caps.5; it is a number not boolean. 353 + add a null-pointer check in safe_sprintf.c (report by Steven Noonan). 354 + improve fix for Debian #882620 by reusing limit2 variable (report by 355 Julien Cristau, Sven Joachim). 356 357 20180210 358 + modify misc/Makefile.in to install/uninstall explicit list in case 359 the build-directory happens to have no ".pc" files when an uninstall 360 is performed (report by Jeffrey Walton). 361 + deprecate safe-sprintf, since the vsnprintf function, which does what 362 was needed, was standardized long ago. 363 + add several development/experimental options to development packages. 364 + minor reordering of options in configure script to make the threaded 365 and reentrant options distinct from the other extensions which are 366 normally enabled. 367 368 20180203 369 + minor fixes to test/*.h to make them idempotent. 370 + add/use test/parse_rgb.h to show how the "RGB" capability works. 371 + add a clarification in user_caps.5 regarding "RGB" capability. 372 + add extended_slk_color{,_sp} symbols to the appropriate 373 package/*.{map,sym} files (report by Sven Joachim, cf: 20170401). 374 375 20180129 376 + update "VERSION" file, used in shared-library naming. 377 378 20180127 6.1 release for upload to 379 380 20180127 381 + updated release notes 382 + amend a warning message from tic which should have flagged misuse 383 of "XT" capability in "screen" terminal description. 384 > terminfo changes: 385 + trim "XT" from screen entry, add comments to explain why it was 386 not suitable -TD 387 + modify iterm to use xterm+sl-twm building block -TD 388 + mark konsole-420pc, konsole-vt100, konsole-xf3x obsolete reflecting 389 konsole's removal in 2008 -TD 390 + expanded the history section of konsole to explain its flawed 391 imitation of xterm's keyboard -TD 392 + use xterm+x11mouse in screen.* entries because screen does not yet 393 support xterm's 1006 mode -TD 394 + add nsterm-build400 for macOS 10.13 -TD 395 + add ansi+idc1, use that in ansi+idc adding dch for consistency -TD 396 + update vte to vte-2017 -TD 397 + add ecma+strikeout to vte-2017 -TD 398 + add iterm2-direct -TD 399 + updated teraterm, added teraterm-256color -TD 400 + add mlterm-direct -TD 401 + add descriptions for ANSI building-blocks -TD 402 403 20180121 pre-release 404 > terminfo changes: 405 + add xterm+noalt, xterm+titlestack, xterm+alt1049, xterm+alt+title 406 blocks from xterm #331 -TD 407 + add xterm+direct, xterm+indirect, xterm-direct entries from xterm 408 #331 -TD 409 + modify xterm+256color and xterm+256setaf to use correct number of 410 color pairs, for ncurses 6.1 -TD 411 + add rs1 capability to xterm-256color -TD 412 + modify xterm-r5, xterm-r6 and xterm-xf86-v32 to use xterm+kbs to 413 match xterm #272, reflecting packager's changes -TD 414 + remove "boolean" Se, Ss from st-0.7 -TD 415 + add konsole-direct and st-direct -TD 416 + remove unsupported "Tc" capability from st-0.7; use st-direct if 417 direct-colors are wanted -TD 418 + add vte-direct -TD 419 + add XT, hpa, indn, and vpa to screen, and invis, E3 to tmux (patch by 420 Pierre Carru) 421 + use xterm+sm+1006 in xterm-new, vte-2014 -TD 422 + use xterm+x11mouse in iterm, iterm2, mlterm3 because xterm's 1006 423 mode does not work with those programs. konsole is debatable -TD 424 + add "termite" entry (report by Markus Pfeiffer) -TD 425 > merge branch begun April 2, 2017 which provides these features: 426 + support read/write new binary-format for terminfo which stores 427 numeric capabilities as a signed 32-bit integer. The test programs 428 such as picsmap, ncurses were created or updated during 2017 to use 429 this feature. 430 + the new format is written by the wide-character configuration of 431 tic when it finds a numeric capability larger than 32767. 432 + other applications such as infocmp built with the wide-character 433 ncurses library work as expected. 434 + applications built with the "narrow" (8-bit) configuration will 435 read the new format, but will limit those extended values to 32767. 436 + in either wide/narrow configuration, the structure defined in 437 term.h still uses signed 16-bit values. 438 + because it is incompatible with the legacy (mid-1980s) binary format, 439 a new magic value is provided for the "file" program. 440 + the term.5 manual page is updated to describe this new format. 441 + the limit on file-size for compiled terminfo is increased in the 442 wide-character configuration to 32768. 443 444 20180120 445 + build-fix in picsmap.c for stdint.h existence. 446 + add --disable-stripping option to configure scripts. 447 + modify ncurses-examples to install test-scripts in the data directory. 448 + work around tool-breakage in Debian 9 and later by invoking 449 gprconfig to specify the C compiler to be used by gnatmake, 450 and conditionally suppressing Library_Options line for static 451 libraries. 452 + bump the compat level for test-packages to 7, i.e., Debian 5. 453 454 20180106 455 + fixes for writing extended color pairs in putwin. 456 + modify test/savescreen.c to add test patterns that exercise 88-, 457 256-, etc., colors. 458 + modify configure option --with-build-cc, adding clang, c89 and c99 459 as possible default values. 460 + modify ncurses-examples configure script to use pkg-config for the 461 extra form/menu/panel libraries, to be more consistent with the 462 handling of the curses/ncurses library. 463 + modify test-packages for mingw to supply "pc" files. 464 + modify gen-pkgconfig.in to list -lpthread as a private library when 465 configured to access it via weak symbols. 466 + simplify gen-pkgconfig.in, adding -ltinfo without the special linker 467 checks because some versions of the linker simply hard-code the 468 behavior. 469 + update URLs for ncurses website to use https. 470 + modify CF_CURSES_LIBS to fill in $cf_nculib_root in case the 471 ncurses-examples are built with a system ncurses that lacks the 472 standard "curses" symbolic link, as done by SuSE. The symbol is 473 needed to make a followup check for the pthread library work, and 474 would be set properly using the options "--with-screen", etc. 475 + generate misc/*.pc with "all" rule, as done for "sources" rule 476 (report by Jeffrey Walton). 477 478 20171230 479 + build-fix for ncurses-examples with Fedora27, adding check for 480 reset_color_pairs() -- not yet in Fedora's package. 481 + consistently add $CFLAGS to $MK_SHARED_LIB symbol in configure 482 script when the latter happens to use the C compiler rather than 483 directly using the loader (report by Jeffrey Walton). 484 + set ABI for upcoming 6.1 release in "*.map" files. While there are 485 some remaining internals to apply, no ABI-related changes are 486 anticipated. 487 + add configure --with-config-suffix option to work around filename 488 conflict with Redhat packages versus test-packages. 489 490 20171223 491 + modify ncurses-examples to quiet const-warnings when building with 492 PDCurses. 493 + modify toe to not exit if unable to read a terminal description, 494 e.g., if there is a permission problem. 495 + minor fix for progs/toe.c, using _nc_free_termtype2. 496 + assign 0 to pointer in _nc_tgetent_leak() after freeing it. Also 497 avoid reusing pointer from previous successful call to tgetent 498 if the latest call is unsuccessful (patch by Michael Schroeder, 499 OpenSuSE #1070450). 500 + minor fix for test/tracemunch, initialize $awaiting variable. 501 502 20171216 503 + repair template in test/package/ncurses-examples.spec (cf: 20171111). 504 + improve tic's warning about the number of parameters tparm might use 505 for u1-u9 by making a special case for u6. 506 + improve curs_attr.3x discussion of color pairs. 507 508 20171209 509 + modify misc/ncurses-config.in to make output with --includedir 510 consistent with --cflags, i.e., when --disable-overwrite option was 511 configured the output should show the subdirectory where headers 512 are. 513 + modify MKlib_gen.sh to suppress macros when calling an "implemented" 514 function in link_test.c 515 + updated ftp-url used in test-packages, etc. 516 + modify order of -pie/-shared options in configure script in case 517 LDFLAGS uses "-pie", working around a defect or limitation in the GNU 518 linker (prompted by patch by Yogesh Prasad, forwarded by Jay Shah). 519 + add entry in man_db.renames for user_caps.5 520 521 20171125 522 + modify MKlib_gen.sh to avoid tracing result from getstr/getnstr 523 before initialized. 524 + add "-a" aspect-ratio option to picsmap. 525 + add configure check for default path of rgb.txt, used in picsmap. 526 + modify _nc_write_entry() to truncate too-long filename (report by 527 Hosein Askari, Debian #882620). 528 + build-fix for ncurses-examples with NetBSD curses: 529 + it lacks the use_env() function. 530 + it lacks libpanel; a recent change used the wrong ifdef symbol. 531 + add a macro for is_linetouched() and adjust the function's return 532 value to make it possible for most applications to check for an 533 error-return (report by Midolikawa H). 534 + additional manpage cleanup. 535 + update config.guess, config.sub from 536 537 538 20171118 539 + add a note to curs_addch.3x on portability. 540 + add a note to curs_pad.3x on the origin and portability of pads. 541 + improve manpage description of getattrs (report by Midolikawa H). 542 + improve manpage macros (prompted by discussion in Debian #880551. 543 + reviewed test-programs using KEY_RESIZE, made fixes to test/worm.c 544 + add a "-d" option to picsmap for default-colors. 545 + modify old terminology entry and a few other terminal emulators to 546 account for xon -TD 547 + correct sgr string for tmux, which used screen's "standout" code 548 rather than the standard code (patch by Roman Kagan) 549 + correct sgr/sgr0 strings in a few other cases reported by tic, making 550 those correspond to the non-sgr settings where they differ, but 551 otherwise use ECMA-48 consistently: 552 jaixterm, aixterm, att5420_2, att4424, att500, decansi, d410-7b, 553 dm80, hpterm, emu-220, hp2, iTerm2.app, mterm-ansi, ncrvt100an, 554 st-0.7, vi603, vwmterm -TD 555 + build-fix for diagnostics warning in lib_mouse.c for pre-5.0 versions 556 of gcc which did not recognize the diagnostic "push" pragma (patch by 557 Vassili Courzakis). 558 559 20171111 560 + add "op" to xterm+256setaf -TD 561 + reviewed terminology 1.0.0 -TD 562 + reviewed st 0.7 -TD 563 + suppress debug-package for ncurses-examples rpm build. 564 565 20171104 566 + check for interrupt in color-pair initialization of dots_curses.c, 567 dots_xcurses.c 568 + add z/Z zoom feature to test/ncurses.c C/c screens. 569 + add '<' and '>' commands to test/ncurses.c S/s screens, to better 570 test off-by-ones in the overlap/copywin functions. 571 572 20171028 573 + improve man/curs_inwstr.3x, correct end-logic for lib_inwstr.c 574 (report by Midolikawa H). 575 + fix typo in a few places for "improvements" (patch by Sven Joachim). 576 + clear the other half of a double-width character on which a line 577 drawing character is drawn. 578 + make test/ncurses.c "s" test easier to understand which subtests are 579 available; add a "S" wide-character overlap test-screen. 580 + modify test/ncurses.c C/c tests to allow for extended color pairs. 581 + add endwin() call in error-returns from test/ncurses.c omitted in 582 recent redesign of its menu (cf: 20170923). 583 + improve install of hashed-db by removing the ".db" file as done for 584 directory-tree terminal databases. 585 + repair a few overlooked items in include/ncurses_defs from recent 586 port/refactoring of test-programs (cf: 20170909). 587 + add test/padview.c, to compare pads with direct updates in view.c 588 589 20171021 590 + modify test/view.c to expand tabs using the ncurses library rather 591 than in the test-program. 592 + remove very old SIGWINCH example in test/view.c, just use KEY_RESIZE. 593 + add -T, -e, -f -m options to "dots" test-programs. 594 + fix a few typos in usage-messages for test-programs. 595 596 20171014 597 + minor cleanup to test/view.c: 598 + eliminate "-n" option by simply reading the whole file. 599 + implement page up/down commands. 600 + add check in tput for init/reset operands to ensure those use a 601 terminal. 602 + improve manual pages which discuss chtype, cchar_t types and the 603 attribute values which can be stored in those types. 604 + correct array-index when parsing "-T" command-line option in tabs 605 program. 606 + modify demo_new_pair.c to pass extended pairs to setcchar(). 607 + add test/dots_xcurses.c to illustrate a different approach used for 608 extended colors which can be contrasted with dots_curses.c. 609 + add a check in tic to note when a description uses non-mandatory 610 delays without xon_xoff. This is not an error, but some descriptions 611 for a terminal emulator may use the combination incorrectly. 612 613 20171007 614 + modify "-T" option of clear and tput to call use_tioctl() to obtain 615 the operating system's notion of the screensize if possible. 616 + review/repair some exit-codes for tput, making usage-message exit 617 with 2 rather than 1, and a failure to open terminal 4+errno. 618 + amend check in tput, tabs and clear to allow those to use the 619 database-only features in cron if a -T option gives a suitable 620 terminal name (report by Lauri Tirkkonen). 621 + correct an ifdef in test/ncurses.c for systems with soft-keys but 622 not slk_color(). 623 + regenerate man-html documentation. 624 625 20170930 626 + fix a symbol conflict that made ncurses.c C/c menu not work with 627 Solaris xpg4 curses. 628 + add refresh() call to dots_mvcur.c, needed to use mvcur() with 629 Solaris xpg4 curses after calling newterm(). 630 + minor fixes for configure script from work on ncurses-examples and 631 tin. 632 + improve animation in test/xmas.c by adding a time-delay in blinkit(). 633 + modify several test programs to reflect that ncurses honors existing 634 signal handlers in initscr(), while other implementations do not. 635 + modify bs.c to make it easier to quit. 636 + change ncurses-examples to use attr_t vs chtype to follow X/Open 637 documentation more closely since Solaris xpg4-curses uses different 638 values for WA_xxx vs A_xxx that rely on attr_t being an unsigned 639 short. Tru64 aka OSF1, HPUX, AIX did as ncurses does, equating the 640 two sets. 641 642 20170923 643 + modify menu for test/ncurses.c to fit on 24-line screen. 644 + build-fix for configure --with-caps=uwin 645 + add options to test_arrays.c, for selecting termcap vs terminfo, etc. 646 647 20170916 648 + minor fix to test/filter.c to avoid clearing the command in one case. 649 + modify filter() to discard clr_eos if back_color_erase is set. 650 651 20170909 652 + improve wide-character implementation of myADDNSTR() in frm_driver.c, 653 which was inconsistent with the normal implementation. 654 + save/restore cursor position in Undo_Justification(), matching 655 behavior of Buffer_To_Window() (report by Leon Winter). 656 + modify test/knight to provide the "slow" solution for small screens 657 using "R", noting that Warnsdorf's method is easily done with "a". 658 + modify several test-programs which call use_default_colors() to 659 consistently do this only if "-d" option is given. 660 + additional changes to test with non-standard variants of curses: 661 + modify a loop limit in firework.c to work around absense of limit 662 checks in some libraries. 663 + fill the last row of a window with "?" in firstlast if waddch does 664 not return ERR on the lower-right corner. 665 + add checks in test/configure for some functions not in 4.3BSD curses. 666 + fix a regression in test/configure (cf: 20170826). 667 668 20170902 669 + amend change for endwin-state for better consistency with the older 670 logic (report/patch by Jeb Rosen, cf: 20170722). 671 + modify check in fmt_entry() to handle a cancelled reset string 672 (Debian #873746). Make similar fixes in other parts of dump_entry.c 673 and tput.c 674 675 20170827 676 + fix a bug in repeat_char logic (cf: 20170729, report by Chris Clayton). 677 678 20170826 679 + fixes for "iterm2" (report by Leonardo Brondani Schenkel) -TD 680 + corrected a warning from tic about keys which are the same, to skip 681 over missing/cancelled values. 682 + add check in tic for unnecessary use of "2" to denote a shifted 683 special key. 684 + improve checks in trim_sgr0, comp_parse.c and parse_entry.c, for 685 cancelled string capabilities. 686 + add check in _nc_parse_entry() for invalid entry name, setting the 687 name to "invalid" to avoid problems storing entries. 688 + add/improve checks in tic's parser to address invalid input 689 + add a check in comp_scan.c to handle the special case where a 690 nontext file ending with a NUL rather than newline is given to tic 691 as input (Redhat #1484274). 692 + allow for cancelled capabilities in _nc_save_str (Redhat #1484276). 693 + add validity checks for "use=" target in _nc_parse_entry (Redhat 694 #1484284). 695 + check for invalid strings in postprocess_termcap (Redhat #1484285) 696 + reset secondary pointers on EOF in next_char() (Redhat #1484287). 697 + guard _nc_safe_strcpy() and _nc_safe_strcat() against calls using 698 cancelled strings (Redhat #1484291). 699 + correct typo in curs_memleaks.3x (Sven Joachim). 700 + improve test/configure checks for some curses variants not based on 701 X/Open Curses. 702 + add options for test/configure to disable checks for form, menu and 703 panel libraries. 704 705 20170819 706 + update "iterm" entry -TD 707 + add "iterm2" entry (report by Leonardo Brondani Schenkel) -TD 708 + regenerate llib-* files. 709 + regenerate HTML manpages. 710 + improve picsmap test-program: 711 + reduce memory used for tsearch 712 + add report in log file showing cumulative color coverage. 713 + add -x option to clear/tput to make the E3 extension optional 714 (cf: 20130622). 715 + add options -T and -V to clear command for compatibility with tput. 716 + add usage message to clear command (Debian #371855). 717 + improve usage messages for tset and tput. 718 + minor fixes to "RGB" extension and reset_color_pairs(). 719 720 20170812 721 + improve description of -R option in infocmp manual page (report by 722 Stephane Chazelas). 723 + add reset_color_pairs() function. 724 + add user_caps.5 manual page to document the terminfo extensions used 725 by ncurses. 726 + improve build scripts, using SIGQUIT vs SIGTRAP; add other configure 727 script fixes from work on xterm, lynx and tack. 728 + modify install-rule for ncurses-examples to put the data files in 729 /usr/share/ncurses-examples 730 + improve tracemunch, by changing address-parameters of add_wch(), 731 color_content() and pair_content() to dummy parameters. 732 + minor optimization to _nc_change_pair, to return quickly when the 733 current screen is marked for clearing. 734 + in-progress changes to improve performance of test/picsmap.c for 735 loading image files. 736 + modify allocation for SCREEN's color-pair table to start small, grow 737 on demand up to the existing limit. 738 + add "RGB" extension capability for direct-color support, use this to 739 improve color_content(). 740 + improve picsmap test-program: 741 + if no palette file is needed, attempt to load one based on $TERM, 742 checking first in the current directory, then by adding ".dat" 743 suffix, and finally in the data-directory, e.g., 744 /usr/share/ncurses-examples 745 + add "-l" option for logging 746 + add "-d" option for debugging 747 + add "-s" option for stepping automatically through list of images, 748 with time delay. 749 + use tsearch to improve time for loading color table for images. 750 + update config.guess, config.sub from 751 752 753 20170729 754 + update interix entry using tack and SFU on Windows 7 Ultimate -TD 755 + use ^? for kdch1 in interix (reported by Jonathan de Boyne Pollard) 756 + add "rep" to xterm-new, available since 1997/01/26 -TD 757 + move SGR 24 and 27 from vte-2014 to vte-2012 (request by Alain 758 Williams) -TD 759 + add a check in newline_forces_scroll() in case a program moves the 760 cursor outside scrolling margins (report by Robert King). 761 + improve _nc_tparm_analyze, using that to extend the checks made by 762 tic for reporting inconsistencies between the expected number of 763 parameters for a capability and the actual. 764 + amend handling of repeat_char capability in EmitRange (adapted from 765 report/patch by Dick Wesseling): 766 + translate the character to the alternate character set when the 767 alternate character set is enabled. 768 + do not use repeat_char for characters past 255. 769 + document "_nc_free_tinfo" in manual page, because it could be used in 770 tack for memory-leak checking. 771 + add "--without-tack" configure option to refine "--with-progs" 772 configure option. Normally tack is no longer built in-tree, but 773 a few packagers combine it during the build. If term_entry.h is 774 installed, there is no advantage to in-tree builds. 775 + adjust configure-script to define HAVE_CURSES_DATA_BOOLNAMES symbol 776 needed for tack 1.08 when built in-tree. Rather than relying upon 777 internal "_nc_" functions, tack now uses the boolean, number and 778 string capability name-arrays provided by ncurses and SVr4 Unix 779 curses. It still uses term_entry.h for the definitions of the 780 extended capability arrays. 781 + add an overlooked null-pointer check in mvcur changes from 20170722 782 783 20170722 784 + improve test-packages for ncurses-examples and AdaCurses for lintian 785 + modify logic for endwin-state to be able to detect the case where 786 the screen was never initialized, using that to trigger a flush of 787 ncurses' buffer for mvcur, e.g., in test/dots_mvcur.c for the 788 term-driver configuration. 789 + add dependency upon ncurses_cfg.h to a few other internal header 790 files to allow each to be compiled separately. 791 + add dependency upon ncurses_cfg.h to tic's header-files; any program 792 using tic-library will have to supply this file. Legacy tack 793 versions supply this file; ongoing tack development has dropped the 794 dependency upon tic-library and new releases will not be affected. 795 796 20170715 797 + modify command-line parameters for "convert" used in picsmap to work 798 with ImageMagick 6.8 and newer. 799 + fix build-problem with tack and ABI-5 (Debian #868328). 800 + repair termcap-format from tic/infocmp broken in 20170701 fixes 801 (Debian #868266). 802 + reformat terminfo.src with 20170513 updates. 803 + improve test-packages to address lintian warnings. 804 805 20170708 806 + add a note to tic manual page about -W versus -f options. 807 + correct a limit-check in fixes from 20170701 (report by Sven Joachim). 808 809 20170701 810 + modify update_getenv() in db_iterator.c to ensure that environment 811 variables which are not initially set will be checked later if an 812 application happens to set them (patch by Guillaume Maudoux). 813 + remove initialization-check for calling napms() in the term-driver 814 configuration; none is needed. 815 + add help-screen to test/test_getstr.c and test/test_get_wstr.c 816 + improve compatibility between different configurations of new_prescr, 817 fixing a case with threaded code and term-driver where c++/demo did 818 not work (cf: 20160213). 819 + the fixes for Redhat #1464685 obscured a problem subsequently 820 reported in Redhat #1464687; the given test-case was no longer 821 reproducible. Testing without the fixes for the earlier reports 822 showed a problem with buffer overflow in dump_entry.c, which is 823 addressed by reducing the use of a fixed-size buffer. 824 + add/improve checks in tic's parser to address invalid input 825 (Redhat #1464684, #1464685, #1464686, #1464691). 826 + alloc_entry.c, add a check for a null-pointer. 827 + parse_entry.c, add several checks for valid pointers as well as 828 one check to ensure that a single character on a line is not 829 treated as the 2-character termcap short-name. 830 + fix a memory leak in delscreen() (report by Bai Junq). 831 + improve tracemunch, showing thread identifiers as names. 832 + fix a use-after-free in NCursesMenu::~NCursesMenu() 833 + further amend incorrect calls for memory-leaks from 20170617 changes 834 (report by Allen Hewes). 835 836 20170624 837 + modify c++/etip.h.in to accommodate deprecation of throw() and 838 throws() in c++17 (prompted by patch by Romain Geissler). 839 + remove some incorrect calls for memory-leaks from 20170617 changes 840 (report by Allen Hewes). 841 + add test-programs for termattrs and term_attrs. 842 + modify _nc_outc_wrapper to use the standard output if the screen was 843 not initialized, rather than returning an error. 844 + improve checks for low-level terminfo functions when the terminal 845 has not been initialized (Redhat #1345963). 846 + modify make_hash to allow building with address-sanitizer, 847 assuming that --disable-leaks is configured. 848 + amend changes for number_format() in 20170506 to avoid undefined 849 behavior when shifting (patch by Emanuele Giaquinta). 850 851 20170617 852 + fill in some places where TERMTYPE2 vs TERMTYPE was not used 853 (report by Allen Hewes). 854 + use ExitTerminfo() internally in error-exits for ncurses' setupterm 855 to help with leak checking. 856 + use ExitProgram() in error-exit from initscr() to help with leak 857 checking. 858 + review test-programs, adding checks for cases where the terminal 859 cannot be initialized. 860 861 20170610 862 + add option "-xp" to picsmap.c, to use init_extended_pair(). 863 + make simple performance fixes for picsmap.c 864 + improve aspect ratio of images read from "convert" in picsmap.c 865 866 20170603 867 + add option to picsmap to use color-palette files, e.g., for mapping 868 to xterm-256color. 869 + move the data in SCREEN used for the alloc_pair() function to the 870 end, to restore compatibility between ncurses/ncursesw libtinfo 871 (report/patch by Miroslav Lichvar). 872 + add build-time utility "report_offsets" to help show when the various 873 configurations of tinfo library are compatible or not. 874 875 20170527 876 + improved test/picsmap.c: 877 + lookup named colors for xpm files in rgb.txt 878 + accept blanks in color-keys for xpm files. 879 + if neither xbm/xpm work, try "convert", which may be available. 880 881 20170520 882 + modify test/picsmap.c to read xpm files. 883 + modify package/debian/* to create documentation packages, so the 884 related files can be checked with lintian. 885 + fix some typos in manpages (report/patch by Sven Joachim). 886 887 20170513 888 + add test/picsmap.c to fill in some testing issues not met by dots. 889 The initial version reads X bitmap (".xbm") files. 890 + repair logic which forces a repaint where a color-pair's content is 891 changed (cf: 20170311). 892 + improve tracemunch, showing screenXX pointers as names. 893 894 20170506 895 + modify tic/infocmp display of numeric values to use hexadecimal when 896 they are "close" to a power of two, making the result more readable. 897 + improve discussion of portability in curs_mouse.3x 898 + change line-length for generated html/manpages to 78 columns from 65. 899 + improve discussion of line-drawing characters in curs_add_wch.3x 900 (prompted by discussion with Lorinczy Zsigmond). 901 + cleanup formatting of hackguide.html and ncurses-intro.html 902 + add examples for WACS_D_PLUS and WACS_T_PLUS to test/ncurses.c 903 904 20170429 905 + corrected a case where $with_gpm was set to "maybe" after CF_WITH_GPM, 906 overlooked in 20160528 fixes (report by Alexandre Bury). 907 + improve a couple of test-program's help-messages. 908 + corrected loop in rain.c from 20170415 changes. 909 + modify winnstr and winchnstr to return error if the output pointer is 910 null, as well as adding a null pointer check of the window pointer 911 for better compatibility with other implementations. 912 + improve discussion of NetBSD curses in scr_dump.5 913 + modify LIMIT_TYPED macro in new_pair.h to avoid changing sign of the 914 value to be limited (reports by Darby Payne, Rob Boudreau). 915 + update config.guess, config.sub from 916 917 918 20170422 919 + build-fix for termcap-configuration (report by Chi-Hsuan Yen). 920 + improve terminfo manual page discussion of control- and graphics- 921 characters. 922 + remove tic warning about "^?" in string capabilities, which was 923 marked as an extension (cf: 20000610, 20110820); however all Unix 924 implementations support this and X/Open Curses does not address it. 925 On the other hand, termcap never did support this feature. 926 + correct missing comma-separator between string capabilities in 927 icl6402 and m2-nam -TD 928 + restore rmir/smir in ansi+idc to better match original ansiterm+idc, 929 add alias ansiterm (report by Robert King). 930 + amend an old check for ambiguous use of "ma" in terminfo versus 931 a termcap use, if the capability is cancelled to treat it as number. 932 + correct a case in _nc_captoinfo() which read "%%" and emitted "%". 933 + modify sscanf calls in _nc_infotocap() for patterns "%{number}%+%c" 934 and "%'char'%+%c" to check that the final character is really 'c', 935 avoiding a case in icl6404 which cannot be converted to termcap. 936 + in _nc_infotocap(), add a check to ensure that terminfo "^?" is not 937 written to termcap, because the BSDs did not implement that. 938 + in _nc_tic_expand() and _nc_infotocap(), improve string-length check 939 when deciding whether to use "^X" or "\xxx" format for control 940 characters, to make the output of tic/infocmp more predictable. 941 + limit termcap "%d" width to 2 digits on input, and use "%2" in 942 preference to "%02" on output. 943 + correct terminfo/termcap conversion of "%02" and "%03" into "%2" and 944 "%3"; the result repeated the last character. 945 + add man/scr_dump.5 to document screen-dump format. 946 947 20170415 948 + modify several test programs to use new popup_msgs, adapted from 949 help-screen used in test/edit_field.c 950 + drop two symbols obsoleted in 2004: _nc_check_termtype, and 951 _nc_resolve_uses 952 + fix some old copyright dates (cf: 20031025). 953 + build-fixes for test/savescreen.c to work with AIX and HPUX. 954 + minor fix to configure script, adding a backslash/continuation. 955 + extend TERMINAL structure for ABI 6 to store numbers internally as 956 integers rather than short, by adding new data for this purpose. 957 + more fixes for minor memory-leaks in test-programs. 958 959 20170408 960 + change logic in wins_nwstr() to avoid addressing data past the output 961 of mbstowcs(). 962 + correct a call to setcchar() in Data_Entry_w() from 20131207 changes. 963 + fix minor memory-leaks in test-programs. 964 + further improve ifdef in term_entry.h for internal definitions not 965 used by tack. 966 967 20170401 968 + minor fixes for vt100+4bsd, e.g., delay in sgr for consistency -TD 969 + add smso for env230, to match sgr -TD 970 + remove p7/protect from sgr in fbterm -TD 971 + drop setf/setb from fbterm; setaf/setab are enough -TD 972 + make xterm-pcolor sgr consistent with other capabilities -TD 973 + add rmxx/smxx ECMA-48 strikeout extension to tmux and xterm-basic 974 (discussion with Nicholas Marriott) 975 + add test-programs sp_tinfo and extended_color 976 + modify no-leaks code for lib_cur_term.c to account for the tgetent() 977 cache. 978 + modify setupterm() to save original tty-modes so that erasechar() 979 works as expected. Also modify _nc_setupscreen() to avoid redundant 980 calls to get original tty-modes. 981 + modify set_curterm() to update ttytype[] data used by longname(). 982 + modify wattr_set() and wattr_get() to return ERR if win-parameter is 983 null, as documented. 984 + improve cast used for null-pointer checks in header macros, to 985 reduce compiler warnings. 986 + modify several functions, using the reserved "opts" parameter to pass 987 color- and pair-values larger than 16-bits: 988 + getcchar(), setcchar(), slk_attr_set(), vid_puts(), wattr_get(), 989 wattr_set(), wchgat(), wcolor_set(). 990 + Other functions call these with the corresponding altered behavior, 991 including chgat(), mvchgat(), mvwchgat(), slk_color_on(), 992 slk_color_off(), vid_attr(). 993 + add new functions for manipulating color- and pair-values larger 994 than 16-bits. These are extended_color_content(), 995 extended_pair_content(), extended_slk_color(), init_extended_color(), 996 init_extended_pair(), and the corresponding sp-funcs. 997 998 20170325 999 + fix a memory leak in the window-list when creating multiple screens 1000 (reports by Andres Martinelli, Debian #783486). 1001 + reviewed calls from link_test.c, added a few more null-pointer 1002 checks. 1003 + add a null-pointer check in ungetmouse, in case mousemask was not 1004 called (report by "Kau"). 1005 + updated curs_sp_funcs.3x for new functions. 1006 1007 20170318 1008 + change TERMINAL structure in term.h to make it opaque. Some 1009 applications misuse its members, e.g., directly modifying it 1010 rather than using def_prog_mode(). 1011 + modify utility headers such as tic.h to make it clearer which are 1012 externals that are used by tack. 1013 + improve curs_slk.3x in particular its discussion of portability. 1014 + fix cut/paste in legacy_encoding.3x 1015 + add prototype for find_pair() to new_pair.3x (report by Branden 1016 Robinson). 1017 + fix a couple of broken links in generated man-html documentation. 1018 + regenerate man-html documentation. 1019 1020 20170311 1021 + modify vt100 rs2 string to reset vt52 mode and scrolling regions 1022 (report/analysis by Robert King) -TD 1023 + add vt100+4bsd building block, use that for older terminals rather 1024 than "vt100" which is now mostly used as a building block for 1025 terminal emulators -TD 1026 + correct a few spelling errors in terminfo.src comments -TD 1027 + add fbterm -TD 1028 + fix a typo in ncurses.c test_attr legend (patch by Petr Vanek). 1029 + changed internal colorpair_t to a struct, eliminating an internal 1030 8-bit limit on colors 1031 + add ncurses/new_pair.h 1032 + add ncurses/base/new_pair.c with alloc_pair(), find_pair() and 1033 free_pair() functions 1034 + add test/demo_new_pair.c 1035 1036 20170304 1037 + improve terminfo manual description of terminfo syntax. 1038 + clarify the use of wint_t vs wchar_t in curs_get_wstr.3x 1039 + improve description of endwin() in manual. 1040 + modify setcchar() and getcchar() to treat negative color-pair as an 1041 error. 1042 + fix a typo in include/hashed_db.h (Andre Sa). 1043 1044 20170225 1045 + fixes for CF_CC_ENV_FLAGS (report by Ross Burton). 1046 1047 20170218 1048 + fix several formatting issues with manual pages. 1049 + correct read of terminfo entry in which all strings are absent or 1050 explicitly cancelled. Before this fix, the result was that all were 1051 treated as only absent. 1052 + modify infocmp to suppress mixture of absent/cancelled capabilities 1053 that would only show as "NULL, NULL", unless the -q option is used, 1054 e.g., to show "-, @" or "@, -". 1055 1056 20170212 1057 + build-fixes for PGI compilers (report by Adam J. Stewart) 1058 + accept whitespace in sed expression for generating expanded.c 1059 + modify configure check that g++ compiler warnings are not used. 1060 + add configure check for -fPIC option needed for shared libraries. 1061 + let configure --disable-ext-funcs override the default for the 1062 --enable-sp-funcs option. 1063 + mark some structs in form/menu/panel libraries as potentially opaque 1064 without modifying API/ABI. 1065 + add configure option --enable-opaque-curses for ncurses library and 1066 similar options for the other libraries. 1067 1068 20170204 1069 + trim newlines, tabs and escaped newlines from terminfo "paths" passed 1070 to db-iterator. 1071 + ignore zero-length files in db-iterator; these are useful for 1072 instance to suppress "$HOME/.terminfo" when not wanted. 1073 + amended "b64:" encoder to work with the terminfo reader. 1074 + modify terminfo reader to accept "b64:" format using RFC-3548 in 1075 as well as RFC-4648 url/filename-safe format. 1076 + modify terminfo reader to accept "hex:" format as generated by 1077 "infocmp -0qQ1" (cf: 20150905). 1078 + adjust authors comment to reflect drop below 1% for SV. 1079 1080 20170128 1081 + minor comment-fixes to help automate links to bug-urls -TD 1082 + add dvtm, dvtm-256color -TD 1083 + add settings corresponding to xterm-keys option to tmux entry to 1084 reflect upcoming change to make that option "on" by default 1085 (patch by Nicholas Marriott). 1086 + uncancel Ms in tmux entry (Harry Gindi, Nicholas Marriott). 1087 + add dumb-emacs-ansi -TD 1088 1089 20170121 1090 + improve discussion of early history of tput program. 1091 + incorporate A_COLOR mask into COLOR_PAIR(), in case user application 1092 provides an out-of-range pair number (report by Elijah Stone). 1093 + clarify description in tput manual page regarding support for 1094 termcap names (prompted by FreeBSD #214709). 1095 + remove a restriction in tput's support for termcap names which 1096 omitted capabilities normally not shown in termcap translations 1097 (cf: 990123). 1098 + modify configure script for clang as used on FreeBSD, to work around 1099 clang's differences in exit codes vs gcc. 1100 1101 20170114 1102 + improve discussion of early history of tset/reset programs. 1103 + clarify in manual pages that the optional verbose option level is 1104 available only when ncurses is configured for tracing. 1105 + amend change from 20161231 to avoid writing traces to the standard 1106 error after initializing the trace feature using the environment 1107 variable. 1108 1109 20170107 1110 + amend changes for tput to reset tty modes to "sane" if the program 1111 is run as "reset", like tset. Likewise, ensure that tset sends 1112 either reset- or init-strings. 1113 + improve manual page descriptions of tput init/reset and tset/reset, 1114 to make it easier to see how they are similar and different. 1115 + move a static result from key_name() to _nc_globals 1116 + modify _nc_get_screensize to allow for use_env() and use_tioctl() 1117 state to be per-screen when sp-funcs are configured, better matching 1118 the behavior when using the term-driver configuration. 1119 + improve cross-references in manual pages for often used functions 1120 + move SCREEN field for use_tioctl() data before the ncursesw fields, 1121 and limit that to the sp-funcs configuration to improve termlib 1122 compatibility (cf: 20120714). 1123 + correct order of initialization for traces in use_env() and 1124 use_tioctl() versus first trace calls. 1125 1126 20161231 1127 + fix errata for ncurses-howto (report by Damien Ruscoe). 1128 + fix a few places in configure/build scripts where DESTDIR and rpath 1129 were combined (report by Thomas Klausner). 1130 + merge current st description (report by Harry Gindi) -TD 1131 + modify flash capability for linux and wyse entries to put the delay 1132 between the reverse/normal escapes rather than after -TD 1133 + modify program tabs to pass the actual tty file descriptor to 1134 setupterm rather than the standard output, making padding work 1135 consistently. 1136 + explain in clear's manual page that it writes to stdout. 1137 + add special case for verbose debugging traces of command-line 1138 utilities which write to stderr (cf: 20161126). 1139 + remove a trace with literal escapes from skip_DECSCNM(), added in 1140 20161203. 1141 + update config.guess, config.sub from 1142 1143 1144 20161224 1145 + correct parameters for copywin call in _nc_Synchronize_Attributes() 1146 (patch by Leon Winter). 1147 + improve color-handling section in terminfo manual page (prompted by 1148 patch by Mihail Konev). 1149 + modify programs clear, tput and tset to pass the actual tty file 1150 descriptor to setupterm rather than the standard output, making 1151 padding work. 1152 1153 20161217 1154 + add tput-colorcube demo script. 1155 + add -r and -s options to tput-initc demo, to match usage in xterm. 1156 + flush the standard output in _nc_flush for the case where SP is zero, 1157 e.g., when called via putp. This fixes a scenario where "tput flash" 1158 did not work after changes in 20130112. 1159 1160 20161210 1161 + add configure script option --disable-wattr-macros for use in cases 1162 where one wants to use the same headers for ncurses5/ncurses6 1163 development, by suppressing the wattr* macros which differ due to 1164 the introduction of extended colors (prompted by comments in 1165 Debian #230990, Redhat #1270534). 1166 + add test/tput-initc to demonstrate tput used to initialize palette 1167 from a data file. 1168 + modify test/xterm*.dat to use the newer color4/color12 values. 1169 1170 20161203 1171 + improve discussion of field validation in form_driver.3x manual page. 1172 + update curs_trace.3x manual page. 1173 1174 20161126 1175 + modify linux-16color to not mask dim, standout or reverse with the 1176 ncv capability -TD 1177 + add 0.1sec mandatory delay to flash capabilities using the VT100 1178 reverse-video control -TD 1179 + omit selection of ISO-8859-1 for G0 in enacs capability from linux2.6 1180 entry, to avoid conflict with the user-defined mapping. The reset 1181 feature will use ISO-8859-1 in any case (Mikulas Patocka). 1182 + improve check in tic for delays by also warning about beep/flash 1183 when a delay is not embedded, or if those use the VT100 reverse 1184 video escape without using a delay. 1185 + minor fix for syntax-check of delays from 20161119 changes. 1186 + modify trace() to avoid overwriting existing file (report by Maor 1187 Shwartz). 1188 1189 20161119 1190 + add check in tic for some syntax errors of delays, as well as use of 1191 proportional delays for non-line capabilities. 1192 + document history of the clear program and the E3 extension, prompted 1193 by various discussions including 1194 1195 1196 20161112 1197 + improve -W option in tic/infocmp: 1198 + correct order of size-adjustments in wrapped lines 1199 + if -f option splits line, do not further split it with -W 1200 + begin a new line when adding "use=" after a wrapped line 1201 1202 20161105 1203 + fix typo in man/terminfo.tail (Alain Williams). 1204 + correct program-name in adacurses6-config.1 manual page. 1205 1206 20161029 1207 + add new function "unfocus_current_field" (Leon Winter) 1208 1209 20161022 1210 + modify tset -w (and tput reset) to update the program's copy of the 1211 screensize if it was already set in the system, to improve tabstop 1212 setting which relies upon knowing the actual screensize. 1213 + add functionality of tset -w to tput, like the "-c" feature this is 1214 not optional in tput. 1215 + add "clear" as a possible link/alias to tput. 1216 + improve tput's check for being called as "init" or "reset" to allow 1217 for transformed names. 1218 + split-out the "clear" function from progs/clear.c, share with 1219 tput to get the same behavior, e.g., the E3 extension. 1220 1221 20161015 1222 + amend internal use of tputs to consistently use the number of lines 1223 affected, e.g., for insert/delete character operations. While 1224 merging terminfo source early in 1995, several descriptions used the 1225 "*" proportional delay for these operations, prompting a change in 1226 doupdate. 1227 + regenerate llib-* files. 1228 + regenerate HTML manpages. 1229 + fix several formatting issues with manual pages. 1230 1231 20161008 1232 + adjust size in infocmp/tic to work with strlcpy. 1233 + fix configure script to record when strlcat is found on OpenBSD. 1234 + build-fix for "recent" OpenBSD vs baudrate. 1235 1236 20161001 1237 + add -W option to tic/infocmp to force long strings to wrap. This is 1238 in addition to the -w option which attempts to fit capabilities into 1239 a given line-length. 1240 + add linux-m1 minitel entries (patch by Alexandre Montaron). 1241 + correct rs2 string for vt100-nam -TD 1242 1243 20160924 1244 + modify _nc_tic_expand to escape comma if it immediately follows a 1245 percent sign, to work with minitel change. 1246 + updated minitel and viewdata descriptions (Alexandre Montaron). 1247 1248 20160917 1249 + build-fix for gnat6, which unhelpfully attempts to compile C files. 1250 + fix typo in 20160910 changes (Debian #837892, patch by Sven Joachim). 1251 1252 20160910 1253 + trim dead code ifdef'd with HIDE_EINTR since 970830 (discussion with 1254 Leon Winter). 1255 + trim some obsolete/incorrect wording about EINTR from wgetch manual 1256 page (patch by Leon Winter). 1257 + really correct 20100515 change (patch by Rich Coe). 1258 + add "--enable-string-hacks" option to test/configure 1259 + completed string-hacks for "sprintf", etc., including test-programs. 1260 + make "--enable-string-hacks" work with Debian by checking for the 1261 "bsd" library and its associated "<bsd/string.h>" header. 1262 1263 20160903 1264 + correct 20100515 change for weak signals versus sigprocmask (report 1265 by Rich Coe). 1266 + modify misc/Makefile.in to work around OpenBSD "make" which unlike 1267 all other versions of "make" does not recognize continuation lines 1268 of comments. 1269 + amend the last change to CF_C_ENV_FLAGS to move only the 1270 preprocessor, optimization and warning flags to CPPFLAGS and CFLAGS, 1271 leaving the residue in CC. That happens to work for gcc's various 1272 "model" options, but may require tuning for other compilers (report 1273 by Sven Joachim). 1274 1275 20160827 1276 + add "v" menu entry to test/ncurses.c to show baudrate and other 1277 values. 1278 + add "newer" baudrate symbols from Linux and FreeBSD to progs/tset.c, 1279 lib_baudrate.c 1280 + modify CF_XOPEN_SOURCE macro: 1281 + add "uclinux" to case for "linux" (patch by Yann E. Morin) 1282 + modify _GNU_SOURCE for cygwin headers, tested with cygwin 2.3, 2.5 1283 (patch by Corinna Vinschen, from changes to tin). 1284 + improve CF_CC_ENV_FLAGS macro to allow for compiler wrappers such 1285 as "ccache" (report by Enrico Scholz). 1286 + update config.guess, config.sub from 1287 1288 1289 20160820 1290 + update tput manual page to reflect changes to manipulate terminal 1291 modes by sharing functions with tset. 1292 + add the terminal-mode parts of "reset" (aka tset) to the "tput reset" 1293 command, making the two almost the same except for window-size. 1294 + adapt logic used in dialog "--keep-tite" option for test/filter.c as 1295 "-a" option. When set, test/filter attempts to suppress the 1296 alternate screen. 1297 + correct a typo in interix entry -TD 1298 1299 20160813 1300 + add a dependency upon generated-sources in Ada95/src/Makefile.in to 1301 handle a case of "configure && make install". 1302 + trim trailing blanks from include/Caps*, to work around a problem 1303 in sed (Debian #818067). 1304 1305 20160806 1306 + improve CF_GNU_SOURCE configure macro to optionally define 1307 _DEFAULT_SOURCE work around a nuisance in recent glibc releases. 1308 + move the terminfo-specific parts of tput's "reset" function into 1309 the shared reset_cmd.c, making the two forms of reset use the same 1310 strings. 1311 + split-out the terminal initialization functions from tset as 1312 progs/reset_cmd.c, as part of changes to merge the reset-feature 1313 with tput. 1314 1315 20160730 1316 + change tset's initialization to allow it to get settings from the 1317 standard input as well as /dev/tty, to be more effective when 1318 output or error are redirected. 1319 + improve discussion of history and portability for tset/reset/tput 1320 manual pages. 1321 1322 20160723 1323 + improve error message from tset/reset when both stderr/stdout are 1324 redirected to a file or pipe. 1325 + improve organization of curs_attr.3x, curs_color.3x 1326 1327 20160709 1328 + work around Debian's antique/unmaintained version of mawk when 1329 building link_test. 1330 + improve test/list_keys.c, showing ncurses's convention of modifiers 1331 for special keys, based on xterm. 1332 1333 20160702 1334 + improve test/list_keys.c, using $TERM if no parameters are given. 1335 1336 20160625 1337 + build-fixes for ncurses "test_progs" rule. 1338 + amend change to CF_CC_ENV_FLAGS in 20160521 to make multilib build 1339 work (report by Sven Joachim). 1340 1341 20160618 1342 + build-fixes for ncurses-examples with NetBSD curses. 1343 + improve test/list_keys.c, fixing column-widths and sorting the list 1344 to make it more readable. 1345 1346 20160611 1347 + revise fix for Debian #805618 (report by Vlado Potisk, cf: 20151128). 1348 + modify test/ncurses.c a/A screens to make exiting on an escape 1349 character depend on the start of keypad and timeout modes, to allow 1350 better testing of function-keys. 1351 + modify rs1 for xterm-16color, xterm-88color and xterm-256color to 1352 reset palette using "oc" string as in linux -TD 1353 + use ANSI reply for u8 in xterm-new, to reflect vt220-style responses 1354 that could be returned -TD 1355 + added a few capabilities fixed in recent vte -TD 1356 1357 20160604 1358 + correct logic for -f option in test/demo_terminfo.c 1359 + add test/list_keys.c 1360 1361 20160528 1362 + further workaround for PIE/PIC breakage which causes gpm to not link. 1363 + fix most cppcheck warnings, mostly style, in ncurses library. 1364 1365 20160521 1366 + improved manual page description of tset/reset versus window-size. 1367 + fixes to work with a slightly broken compiler configuration which 1368 cannot compile "Hello World!" without adding compiler options 1369 (report by Ola x Nilsson): 1370 + pass appropriate compiler options to the CF_PROG_CC_C_O macro. 1371 + when separating compiler and options in CF_CC_ENV_FLAGS, ensure 1372 that all options are split-off into CFLAGS or CPPFLAGS 1373 + restore some -I options removed in 20140726 because they appeared 1374 to be redundant. In fact, they are needed for a compiler that 1375 cannot combine -c and -o options. 1376 1377 20160514 1378 + regenerate HTML manpages. 1379 + improve manual pages for wgetch and wget_wch to point out that they 1380 might return values without names in curses.h (Debian #822426). 1381 + make linux3.0 entry the default linux entry (Debian #823658) -TD 1382 + modify linux2.6 entry to improve line-drawing so that the linux3.0 1383 entry can be used in non-UTF-8 mode -TD 1384 + document return value of use_extended_names (report by Mike Gran). 1385 1386 20160507 1387 + amend change to _nc_do_color to restore the early return for the 1388 special case used in _nc_screen_wrap (report by Dick Streefland, 1389 cf: 20151017). 1390 + modify test/ncurses.c: 1391 + check return-value of putwin 1392 + correct ifdef which made the 'g' test's legend not reflect changes 1393 to keypad- and scroll-modes. 1394 + correct return-value of extended putwin (report by Mike Gran). 1395 1396 20160423 1397 + modify test/ncurses.c 'd' edit-color menu to optionally read xterm 1398 color palette directly from terminal, as well as handling KEY_RESIZE 1399 and screen-repainting with control/L and control/R. 1400 + add 'oc' capability to xterm+256color, allowing palette reset for 1401 xterm -TD 1402 1403 20160416 1404 + add workaround in configure script for inept transition to PIE vs 1405 PIC builds documented in 1406 1407 + add "reset" to list of programs whose names might change in manpages 1408 due to program-transformation configure options. 1409 + drop long-obsolete "-n" option from tset. 1410 1411 20160409 1412 + modify test/blue.c to use Unicode values for card-glyphs when 1413 available, as well as improving the check for CP437 and CP850. 1414 1415 20160402 1416 + regenerate HTML manpages. 1417 + improve manual pages for utilities with respect to POSIX versus 1418 X/Open Curses. 1419 1420 20160326 1421 + regenerate HTML manpages. 1422 + improve test/demo_menus.c, allowing mouse-click on the menu-headers 1423 to switch the active menu. This requires a new extension option 1424 O_MOUSE_MENU to tell the menu driver to put mouse events which do not 1425 apply to the active menu back into the queue so that the application 1426 can handle the event. 1427 1428 20160319 1429 + improve description of tgoto parameters (report by Steffen Nurpmeso). 1430 + amend workaround for Solaris line-drawing to restore a special case 1431 that maps Unicode line-drawing characters into the acsc string for 1432 non-Unicode locales (Debian #816888). 1433 1434 20160312 1435 + modified test/filter.c to illustrate an alternative to getnstr, that 1436 polls for input while updating a clock on the right margin as well 1437 as responding to window size-changes. 1438 1439 20160305 1440 + omit a redefinition of "inline" when traces are enabled, since this 1441 does not work with gcc 5.3.x MinGW cross-compiling (cf: 20150912). 1442 1443 20160220 1444 + modify test/configure script to check for pthread dependency of 1445 ncursest or ncursestw library when building ncurses examples, e.g., 1446 in case weak symbols are used. 1447 + modify configure macro for shared-library rules to use -Wl,-rpath 1448 rather than -rpath to work around a bug in scons (FreeBSD #178732, 1449 cf: 20061021). 1450 + double-width multibyte characters were not counted properly in 1451 winsnstr and wins_nwstr (report/example by Eric Pruitt). 1452 + update config.guess, config.sub from 1453 1454 1455 20160213 1456 + amend fix for _nc_ripoffline from 20091031 to make test/ditto.c work 1457 in threaded configuration. 1458 + move _nc_tracebits, _tracedump and _tracemouse to curses.priv.h, 1459 since they are not part of the suggested ABI6. 1460 1461 20160206 1462 + define WIN32_LEAN_AND_MEAN for MinGW port, making builds faster. 1463 + modify test/ditto.c to allow $XTERM_PROG environment variable to 1464 override "xterm" as the name of the program to run in the threaded 1465 configuration. 1466 1467 20160130 1468 + improve formatting of man/curs_refresh.3x and man/tset.1 manpages 1469 + regenerate HTML manpages using newer man2html to eliminate some 1470 unwanted blank lines. 1471 1472 20160123 1473 + ifdef'd header-file definition of mouse_trafo() with NCURSES_NOMACROS 1474 (report by Corey Minyard). 1475 + fix some strict compiler-warnings in traces. 1476 1477 20160116 1478 + tidy up comments about hardcoded 256color palette (report by 1479 Leonardo Brondani Schenkel) -TD 1480 + add putty-noapp entry, and amend putty entry to use application mode 1481 for better consistency with xterm (report by Leonardo Brondani 1482 Schenkel) -TD 1483 + modify _nc_viscbuf2() and _tracecchar_t2() to trace wide-characters 1484 as a whole rather than their multibyte equivalents. 1485 + minor fix in wadd_wchnstr() to ensure that each cell has nonzero 1486 width. 1487 + move PUTC_INIT calls next to wcrtomb calls, to avoid carry-over of 1488 error status when processing Unicode values which are not mapped. 1489 1490 20160102 1491 + modify ncurses c/C color test-screens to take advantage of wide 1492 screens, reducing the number of lines used for 88- and 256-colors. 1493 + minor refinement to check versus ncv to ignore two parameters of 1494 SGR 38 and 48 when those come from color-capabilities. 1495 1496 20151226 1497 + add check in tic for use of bold, etc., video attributes in the 1498 color capabilities, accounting whether the feature is listed in ncv. 1499 + add check in tic for conflict between ritm, rmso, rmul versus sgr0. 1500 1501 20151219 1502 + add a paragraph to curs_getch.3x discussing key naming (discussion 1503 with James Crippen). 1504 + amend workaround for Solaris vs line-drawing to take the configure 1505 check into account. 1506 + add a configure check for wcwidth() versus the ncurses line-drawing 1507 characters, to use in special-casing systems such as Solaris. 1508 1509 20151212 1510 + improve CF_XOPEN_CURSES macro used in test/configure, to define as 1511 needed NCURSES_WIDECHAR for platforms where _XOPEN_SOURCE_EXTENDED 1512 does not work. Also modified the test program to ensure that if 1513 building with ncurses, that the cchar_t type is checked, since that 1514 normally is since 20111030 ifdef'd depending on this test. 1515 + improve 20121222 workaround for broken acs, letting Solaris "work" 1516 in spite of its misconfigured wcwidth which marks all of the line 1517 drawing characters as double-width. 1518 1519 20151205 1520 + update form_cursor.3x, form_post.3x, menu_attributes.3x to list 1521 function names in NAME section (patch by Jason McIntyre). 1522 + minor fixes to manpage NAME/SYNOPSIS sections to consistently use 1523 rule that either all functions which are prototyped in SYNOPSIS are 1524 listed in the NAME section, or the manual-page name is the sole item 1525 listed in the NAME section. The latter is used to reduce clutter, 1526 e.g., for the top-level library manual pages as well as for certain 1527 feature-pages such as SP-funcs and threading (prompted by patches by 1528 Jason McIntyre). 1529 1530 20151128 1531 + add option to preserve leading whitespace in form fields (patch by 1532 Leon Winter). 1533 + add missing assignment in lib_getch.c to make notimeout() work 1534 (Debian #805618). 1535 + add 't' toggle for notimeout() function in test/ncurses.c a/A screens 1536 + add viewdata terminal description (Alexandre Montaron). 1537 + fix a case in tic/infocmp for formatting capabilities where a 1538 backslash at the end of a string was mishandled. 1539 + fix some typos in curs_inopts.3x (Benno Schulenberg). 1540 1541 20151121 1542 + fix some inconsistencies in the pccon* entries -TD 1543 + add bold to pccon+sgr+acs and pccon-base (Tati Chevron). 1544 + add keys f12-f124 to pccon+keys (Tati Chevron). 1545 + add test/test_sgr.c program to exercise all combinations of sgr. 1546 1547 20151107 1548 + modify tset's assignment to TERM in its output to reflect the name by 1549 which the terminal description is found, rather than the primary 1550 name. That was an unnecessary part from the initial conversion of 1551 tset from termcap to terminfo. The termcap program in 4.3BSD did 1552 this to avoid using the short 2-character name (report by Rich 1553 Burridge). 1554 + minor fix to configure script to ensure that rules for resulting.map 1555 are only generated when needed (cf: 20151101). 1556 + modify configure script to handle the case where tic-library is 1557 renamed, but the --with-debug option is used by itself without 1558 normal or shared libraries (prompted by comment in Debian #803482). 1559 1560 20151101 1561 + amend change for pkg-config which allows build of pc-files when no 1562 valid pkg-config library directory was configured to suppress the 1563 actual install if it is not overridden to a valid directory at 1564 install time (cf: 20150822). 1565 + modify editing script which generates resulting.map to work with the 1566 clang configuration on recent FreeBSD, which gives an error on an 1567 empty "local" section. 1568 + fix a spurious "(Part)" message in test/ncurses.c b/B tests due 1569 to incorrect attribute-masking. 1570 1571 20151024 1572 + modify MKexpanded.sh to update the expansion of a temporary filename 1573 to "expanded.c", for use in trace statements. 1574 + modify layout of b/B tests in test/ncurses.c to allow for additional 1575 annotation on the right margin; some terminals with partial support 1576 did not display well. 1577 + fix typo in curs_attr.3x (patch by Sven Joachim). 1578 + fix typo in INSTALL (patch by Tomas Cech). 1579 + improve configure check for setting WILDCARD_SYMS variable; on ppc64 1580 the variable is in the Data section rather than Text (patch by Michel 1581 Normand, Novell #946048). 1582 + using configure option "--without-fallbacks" incorrectly caused 1583 FALLBACK_LIST to be set to "no" (patch by Tomas Cech). 1584 + updated minitel entries to fix kel problem with emacs, and add 1585 minitel1b-nb (Alexandre Montaron). 1586 + reviewed/updated nsterm entry Terminal.app in OSX -TD 1587 + replace some dead URLs in comments with equivalents from the 1588 Internet Archive -TD 1589 + update config.guess, config.sub from 1590 1591 1592 20151017 1593 + modify ncurses/Makefile.in to sort keys.list in POSIX locale 1594 (Debian #801864, patch by Esa Peuha). 1595 + remove an early-return from _nc_do_color, which can interfere with 1596 data needed by bkgd when ncurses is configured with extended colors 1597 (patch by Denis Tikhomirov). 1598 > fixes for OS/2 (patches by KO Myung-Hun) 1599 + use button instead of kbuf[0] in EMX-specific part of lib_mouse.c 1600 + support building with libtool on OS/2 1601 + use stdc++ on OS/2 kLIBC 1602 + clear cf_XOPEN_SOURCE on OS/2 1603 1604 20151010 1605 + add configure check for openpty to test/configure script, for ditto. 1606 + minor fixes to test/view.c in investigating Debian #790847. 1607 + update autoconf patch to 2.52.20150926, incorporates a fix for Cdk. 1608 + add workaround for breakage of POSIX makefiles by recent binutils 1609 change. 1610 + improve check for working poll() by using posix_openpt() as a 1611 fallback in case there is no valid terminal on the standard input 1612 (prompted by discussion on bug-ncurses mailing list, Debian #676461). 1613 1614 20150926 1615 + change makefile rule for removing resulting.map to distclean rather 1616 than clean. 1617 + add /lib/terminfo to terminfo-dirs in ".deb" test-package. 1618 + add note on portability of resizeterm and wresize to manual pages. 1619 1620 20150919 1621 + clarify in resizeterm.3x how KEY_RESIZE is pushed onto the input 1622 stream. 1623 + clarify in curs_getch.3x that the keypad mode affects ability to 1624 read KEY_MOUSE codes, but does not affect KEY_RESIZE. 1625 + add overlooked build-fix needed with Cygwin for separate Ada95 1626 configure script, cf: 20150606 (report by Nicolas Boulenguez) 1627 1628 20150912 1629 + fixes for configure/build using clang on OSX (prompted by report by 1630 William Gallafent). 1631 + do not redefine "inline" in ncurses_cfg.h; this was originally to 1632 solve a problem with gcc/g++, but is aggravated by clang's misuse 1633 of symbols to pretend it is gcc. 1634 + add braces to configure script to prevent unwanted add of 1635 "-lstdc++" to the CXXLIBS symbol. 1636 + improve/update test-program used for checking existence of stdc++ 1637 library. 1638 + if $CXXLIBS is set, the linkage test uses that in addition to $LIBS 1639 1640 20150905 1641 + add note in curs_addch.3x about line-drawing when it depends upon 1642 UTF-8. 1643 + add tic -q option for consistency with infocmp, use it to suppress 1644 all comments from the "tic -I" output. 1645 + modify infocmp -q option to suppress the "Reconstructed from" 1646 header. 1647 + add infocmp/tic -Q option, which allows one to dump the compiled 1648 form of the terminal entry, in hexadecimal or base64. 1649 1650 20150822 1651 + sort options in usage message for infocmp, to make it simpler to 1652 see unused letters. 1653 + update usage message for tic, adding "-0" option. 1654 + documented differences in ESCDELAY versus AIX's implementation. 1655 + fix some compiler warnings from ports. 1656 + modify --with-pkg-config-libdir option to make it possible to install 1657 ".pc" files even if pkg-config is not found (adapted from patch by 1658 Joshua Root). 1659 1660 20150815 1661 + disallow "no" as a possible value for "--with-shlib-version" option, 1662 overlooked in cleanup-changes for 20000708 (report by Tommy Alex). 1663 + update release notes in INSTALL. 1664 + regenerate llib-* files to help with review for release notes. 1665 1666 20150810 1667 + workaround for Debian #65617, which was fixed in mawk's upstream 1668 releases in 2009 (report by Sven Joachim). See 1669 1670 1671 20150808 6.0 release for upload to 1672 1673 20150808 1674 + build-fix for Ada95 on older platforms without stdint.h 1675 + build-fix for Solaris, whose /bin/sh and /usr/bin/sed are non-POSIX. 1676 + update release announcement, summarizing more than 800 changes across 1677 more than 200 snapshots. 1678 + minor fixes to manpages, etc., to simplify linking from announcement 1679 page. 1680 1681 20150725 1682 + updated llib-* files. 1683 + build-fixes for ncurses library "test_progs" rule. 1684 + use alternate workaround for gcc 5.x feature (adapted from patch by 1685 Mikhail Peselnik). 1686 + add status line to tmux via xterm+sl (patch by Nicholas Marriott). 1687 + fixes for st 0.5 from testing with tack -TD 1688 + review/improve several manual pages to break up wall-of-text: 1689 curs_add_wch.3x, curs_attr.3x, curs_bkgd.3x, curs_bkgrnd.3x, 1690 curs_getcchar.3x, curs_getch.3x, curs_kernel.3x, curs_mouse.3x, 1691 curs_outopts.3x, curs_overlay.3x, curs_pad.3x, curs_termattrs.3x 1692 curs_trace.3x, and curs_window.3x 1693 1694 20150719 1695 + correct an old logic error for %A and %O in tparm (report by "zreed"). 1696 + improve documentation for signal handlers by adding section in the 1697 curs_initscr.3x page. 1698 + modify logic in make_keys.c to not assume anything about the size 1699 of strnames and strfnames variables, since those may be functions 1700 in the thread- or broken-linker configurations (problem found by 1701 Coverity). 1702 + modify test/configure script to check for pthreads configuration, 1703 e.g., ncursestw library. 1704 1705 20150711 1706 + modify scripts to build/use test-packages for the pthreads 1707 configuration of ncurses6. 1708 + add references to ttytype and termcap symbols in demo_terminfo.c and 1709 demo_termcap.c to ensure that when building ncursest.map, etc., that 1710 the corresponding names such as _nc_ttytype are added to the list of 1711 versioned symbols (report by Werner Fink) 1712 + fix regression from 20150704 (report/patch by Werner Fink). 1713 1714 20150704 1715 + fix a few problems reported by Coverity. 1716 + fix comparison against "/usr/include" in misc/gen-pkgconfig.in 1717 (report by Daiki Ueno, Debian #790548, cf: 20141213). 1718 1719 20150627 1720 + modify configure script to remove deprecated ABI 5 symbols when 1721 building ABI 6. 1722 + add symbols _nc_Default_Field, _nc_Default_Form, _nc_has_mouse to 1723 map-files, but marked as deprecated so that they can easily be 1724 suppressed from ABI 6 builds (Debian #788610). 1725 + comment-out "screen.xterm" entry, and inherit screen.xterm-256color 1726 from xterm-new (report by Richard Birkett) -TD 1727 + modify read_entry.c to set the error-return to -1 if no terminal 1728 databases were found, as documented for setupterm. 1729 + add test_setupterm.c to demonstrate normal/error returns from the 1730 setupterm and restartterm functions. 1731 + amend cleanup change from 20110813 which removed redundant definition 1732 of ret_error, etc., from tinfo_driver.c, to account for the fact that 1733 it should return a bool rather than int (report/analysis by Johannes 1734 Schindelin). 1735 1736 20150613 1737 + fix overflow warning for OSX with lib_baudrate.c (cf: 20010630). 1738 + modify script used to generate map/sym files to mark 5.9.20150530 as 1739 the last "5.9" version, and regenerated the files. That makes the 1740 files not use ".current" for the post-5.9 symbols. This also 1741 corrects the label for _nc_sigprocmask used in when weak symbols are 1742 configured for the ncursest/ncursestw libraries (prompted by 1743 discussion with Sven Joachim). 1744 + fix typo in NEWS (report by Sven Joachim). 1745 1746 20150606 pre-release 1747 + make ABI 6 the default by updates to dist.mk and VERSION, with the 1748 intention that the existing ABI 5 should build as before using the 1749 "--with-abi-version=5" option. 1750 + regenerate ada- and man-html documentation. 1751 + minor fixes to color- and util-manpages. 1752 + fix a regression in Ada95/gen/Makefile.in, to handle special case of 1753 Cygwin, which uses the broken-linker feature. 1754 + amend fix for CF_NCURSES_CONFIG used in test/configure to assume that 1755 ncurses package scripts work when present for cross-compiling, as the 1756 lessor of two evils (cf: 20150530). 1757 + add check in configure script to disallow conflicting options 1758 "--with-termlib" and "--enable-term-driver". 1759 + move defaults for "--disable-lp64" and "--with-versioned-syms" into 1760 CF_ABI_DEFAULTS macro. 1761 1762 20150530 1763 + change private type for Event_Mask in Ada95 binding to work when 1764 mmask_t is set to 32-bits. 1765 + remove spurious "%;" from st entry (report by Daniel Pitts) -TD 1766 + add vte-2014, update vte to use that -TD 1767 + modify tic and infocmp to "move" a diagnostic for tparm strings that 1768 have a syntax error to tic's "-c" option (report by Daniel Pitts). 1769 + fix two problems with configure script macros (Debian #786436, 1770 cf: 20150425, cf: 20100529). 1771 1772 20150523 1773 + add 'P' menu item to test/ncurses.c, to show pad in color. 1774 + improve discussion in curs_color.3x about color rendering (prompted 1775 by comment on Stack Overflow forum): 1776 + remove screen-bce.mlterm, since mlterm does not do "bce" -TD 1777 + add several screen.XXX entries to support the respective variations 1778 for 256 colors -TD 1779 + add putty+fnkeys* building-block entries -TD 1780 + add smkx/rmkx to capabilities analyzed with infocmp "-i" option. 1781 1782 20150516 1783 + amend change to ".pc" files to only use the extra loader flags which 1784 may have rpath options (report by Sven Joachim, cf: 20150502). 1785 + change versioning for dpkg's in test-packages for Ada95 and 1786 ncurses-examples for consistency with Debian, to work with package 1787 updates. 1788 + regenerate html manpages. 1789 + clarify handling of carriage return in waddch manual page; it was 1790 discussed only in the portability section (prompted by comment on 1791 Stack Overflow forum): 1792 1793 20150509 1794 + add test-packages for cross-compiling ncurses-examples using the 1795 MinGW test-packages. These are only the Debian packages; RPM later. 1796 + cleanup format of debian/copyright files 1797 + add pc-files to the MinGW cross-compiling test-packages. 1798 + correct a couple of places in gen-pkgconfig.in to handle renaming of 1799 the tinfo library. 1800 1801 20150502 1802 + modify the configure script to allow different default values 1803 for ABI 5 versus ABI 6. 1804 + add wgetch-events to test-packages. 1805 + add a note on how to build ncurses-examples to test/README. 1806 + fix a memory leak in delscreen (report by Daniel Kahn Gillmor, 1807 Debian #783486) -TD 1808 + remove unnecessary ';' from E3 capabilities -TD 1809 + add tmux entry, derived from screen (patch by Nicholas Marriott). 1810 + split-out recent change to nsterm-bce as nsterm-build326, and add 1811 nsterm-build342 to reflect changes with successive releases of OSX 1812 (discussion with Leonardo B Schenkel) 1813 + add xon, ich1, il1 to ibm3161 (patch by Stephen Powell, Debian 1814 #783806) 1815 + add sample "magic" file, to document ext-putwin. 1816 + modify gen-pkgconfig.in to add explicit -ltinfo, etc., to the 1817 generated ".pc" file when ld option "--as-needed" is used, or when 1818 ncurses and tinfo are installed without using rpath (prompted by 1819 discussion with Sylvain Bertrand). 1820 + modify test-package for ncurses6 to omit rpath feature when installed 1821 in /usr. 1822 + add OSX's "*.dSYM" to clean-rules in makefiles. 1823 + make extra-suffix work for OSX configuration, e.g., for shared 1824 libraries. 1825 + modify Ada95/configure script to work with pkg-config 1826 + move test-package for ncurses6 to /usr, since filename-conflicts have 1827 been eliminated. 1828 + corrected build rules for Ada95/gen/generate; it does not depend on 1829 the ncurses library aside from headers. 1830 + reviewed man pages, fixed a few other spelling errors. 1831 + fix a typo in curs_util.3x (Sven Joachim). 1832 + use extra-suffix in some overlooked shared library dependencies 1833 found by 20150425 changes for test-packages. 1834 + update config.guess, config.sub from 1835 1836 1837 20150425 1838 + expanded description of tgetstr's area pointer in manual page 1839 (report by Todd M Lewis). 1840 + in-progress changes to modify test-packages to use ncursesw6 rather 1841 than ncursesw, with updated configure scripts. 1842 + modify CF_NCURSES_CONFIG in Ada95- and test-configure scripts to 1843 check for ".pc" files via pkg-config, but add a linkage check since 1844 frequently pkg-config configurations are broken. 1845 + modify misc/gen-pkgconfig.in to include EXTRA_LDFLAGS, e.g., for the 1846 rpath option. 1847 + add 'dim' capability to screen entry (report by Leonardo B Schenkel) 1848 + add several key definitions to nsterm-bce to match preconfigured 1849 keys, e.g., with OSX 10.9 and 10.10 (report by Leonardo B Schenkel) 1850 + fix repeated "extra-suffix" in ncurses-config.in (cf: 20150418). 1851 + improve term_variables manual page, adding section on the terminfo 1852 long-name symbols which are defined in the term.h header. 1853 + fix bug in lib_tracebits.c introduced in const-fixes (cf: 20150404). 1854 1855 20150418 1856 + avoid a blank line in output from tabs program by ending it with 1857 a carriage return as done in FreeBSD (patch by James Clarke). 1858 + build-fix for the "--enable-ext-putwin" feature when not using 1859 wide characters (report by Werner Fink). 1860 + modify autoconf macros to use scripting improvement from xterm. 1861 + add -brtl option to compiler options on AIX 5-7, needed to link 1862 with the shared libraries. 1863 + add --with-extra-suffix option to help with installing nonconflicting 1864 ncurses6 packages, e.g., avoiding header- and library-conflicts. 1865 NOTE: as a side-effect, this renames 1866 adacurses-config to adacurses5-config and 1867 adacursesw-config to adacursesw5-config 1868 + modify debian/rules test package to suffix programs with "6". 1869 + clarify in curs_inopts.3x that window-specific settings do not 1870 inherit into new windows. 1871 1872 20150404 1873 + improve description of start_color() in the manual. 1874 + modify several files in ncurses- and progs-directories to allow 1875 const data used in internal tables to be put by the linker into the 1876 readonly text segment. 1877 1878 20150329 1879 + correct cut/paste error for "--enable-ext-putwin" that made it the 1880 same as "--enable-ext-colors" (report by Roumen Petrov) 1881 1882 20150328 1883 + add "-f" option to test/savescreen.c to help with testing/debugging 1884 the extended putwin/getwin. 1885 + add logic for writing/reading combining characters in the extended 1886 putwin/getwin. 1887 + add "--enable-ext-putwin" configure option to turn on the extended 1888 putwin/getwin. 1889 1890 20150321 1891 + in-progress changes to provide an extended version of putwin and 1892 getwin which will be capable of reading screen-dumps between the 1893 wide/normal ncurses configurations. These are text files, except 1894 for a magic code at the beginning: 1895 0 string \210\210 Screen-dump (ncurses) 1896 1897 20150307 1898 + document limitations of getwin in manual page (prompted by discussion 1899 with John S Urban). 1900 + extend test/savescreen.c to demonstrate that color pair values 1901 and graphic characters can be restored using getwin. 1902 1903 20150228 1904 + modify win_driver.c to eliminate the constructor, to make it more 1905 usable in an application which may/may not need the console window 1906 (report by Grady Martin). 1907 1908 20150221 1909 + capture define's related to -D_XOPEN_SOURCE from the configure check 1910 and add those to the *-config and *.pc files, to simplify use for 1911 the wide-character libraries. 1912 + modify ncurses.spec to accommodate Fedora21's location of pkg-config 1913 directory. 1914 + correct sense of "--disable-lib-suffixes" configure option (report 1915 by Nicolas Boos, cf: 20140426). 1916 1917 20150214 1918 + regenerate html manpages using improved man2html from work on xterm. 1919 + regenerated ".map" and ".sym" files using improved script, accounting 1920 for the "--enable-weak-symbols" configure option (report by Werner 1921 Fink). 1922 1923 20150131 1924 + regenerated ".map" and ".sym" files using improved script, showing 1925 the combinations of configure options used at each stage. 1926 1927 20150124 1928 + add configure check to determine if "local: _*;" can be used in the 1929 ".map" files to selectively omit symbols beginning with "_". On at 1930 least recent FreeBSD, the wildcard applies to all "_" symbols. 1931 + remove obsolete/conflicting rule for ncurses.map from 1932 ncurses/Makefile.in (cf: 20130706). 1933 1934 20150117 1935 + improve description in INSTALL of the --with-versioned-syms option. 1936 + add combination of --with-hashed-db and --with-ticlib to 1937 configurations for ".map" files (report by Werner Fink). 1938 1939 20150110 1940 + add a step to generating ".map" files, to declare any remaining 1941 symbols beginning with "_" as local, at the last version node. 1942 + improve configure checks for pkg-config, addressing a variant found 1943 with FreeBSD ports. 1944 + modify win_driver.c to provide characters for special keys, like 1945 ansi.sys, when keypad mode is off, rather than returning nothing at 1946 all (discussion with Eli Zaretskii). 1947 + add "broken_linker" and "hashed-db" configure options to combinations 1948 use for generating the ".map" and ".sym" files. 1949 + avoid using "ld" directly when creating shared library, to simplify 1950 cross-compiles. Also drop "-Bsharable" option from shared-library 1951 rules for FreeBSD and DragonFly (FreeBSD #196592). 1952 + fix a memory leak in form library Free_RegularExpression_Type() 1953 (report by Pavel Balaev). 1954 1955 20150103 1956 + modify_nc_flush() to retry if interrupted (patch by Stian Skjelstad). 1957 + change map files to make _nc_freeall a global, since it may be used 1958 via the Ada95 binding when checking for memory leaks. 1959 + improve sed script used in 20141220 to account for wide-, threaded- 1960 variations in ABI 6. 1961 1962 20141227 1963 + regenerate ".map" files, using step overlooked in 20141213 to use 1964 the same patch-dates across each file to match ncurses.map (report by 1965 Sven Joachim). 1966 1967 20141221 1968 + fix an incorrect variable assignment in 20141220 changes (report by 1969 Sven Joachim). 1970 1971 20141220 1972 + updated Ada95/configure with macro changes from 20141213 1973 + tie configure options --with-abi-version and --with-versioned-syms 1974 together, so that ABI 6 libraries have distinct symbol versions from 1975 the ABI 5 libraries. 1976 + replace obsolete/nonworking link to man2html with current one, 1977 regenerate html-manpages. 1978 1979 20141213 1980 + modify misc/gen-pkgconfig.in to add -I option for include-directory 1981 when using both --prefix and --disable-overwrite (report by Misty 1982 De Meo). 1983 + add configure option --with-pc-suffix to allow minor renaming of 1984 ".pc" files and the corresponding library. Use this in the test 1985 package for ncurses6. 1986 + modify configure script so that if pkg-config is not installed, it 1987 is still possible to install ".pc" files (report by Misty De Meo). 1988 + updated ".sym" files, removing symbols which are marked as "local" 1989 in the corresponding ".map" files. 1990 + updated ".map" files to reflect move of comp_captab and comp_hash 1991 from tic-library to tinfo-library in 20090711 (report by Sven 1992 Joachim). 1993 1994 20141206 1995 + updated ".map" files so that each symbol that may be shared across 1996 the different library configurations has the same label. Some 1997 review is needed to ensure these are really compatible. 1998 + modify MKlib_gen.sh to work around change in development version of 1999 gcc introduced here: 2000 2001 2002 (reports by Marcus Shawcroft, Maohui Lei). 2003 + improved configure macro CF_SUBDIR_PATH, from lynx changes. 2004 2005 20141129 2006 + improved ".map" files by generating them with a script that builds 2007 ncurses with several related configurations and merges the results. 2008 A further refinement is planned, to make the tic- and tinfo-library 2009 symbols use the same versions across each of the four configurations 2010 which are represented (reports by Sven Joachim, Werner Fink). 2011 2012 20141115 2013 + improve description of limits for color values and color pairs in 2014 curs_color.3x (prompted by patch by Tim van der Molen). 2015 + add VERSION file, using first field in that to record the ABI version 2016 used for configure --with-libtool --disable-libtool-version 2017 + add configure options for applying the ".map" and ".sym" files to 2018 the ncurses, form, menu and panel libraries. 2019 + add ".map" and ".sym" files to show exported symbols, e.g., for 2020 symbol-versioning. 2021 2022 20141101 2023 + improve strict compiler-warnings by adding a cast in TRACE_RETURN 2024 and making a new TRACE_RETURN1 macro for cases where the cast does 2025 not apply. 2026 2027 20141025 2028 + in-progress changes to integrate the win32 console driver with the 2029 msys2 configuration. 2030 2031 20141018 2032 + reviewed terminology 0.6.1, add function key definitions. None of 2033 the vt100-compatibility issues were improved -TD 2034 + improve infocmp conversion of extended capabilities to termcap by 2035 correcting the limit check against parametrized[], as well as filling 2036 in a check if the string happens to have parameters, e.g., "xm" 2037 in recent changes. 2038 + add check for zero/negative dimensions for resizeterm and resize_term 2039 (report by Mike Gran). 2040 2041 20141011 2042 + add experimental support for xterm's 1005 mouse mode, to use in a 2043 demonstration of its limitations. 2044 + add experimental support for "%u" format to terminfo. 2045 + modify test/ncurses.c to also show position reports in 'a' test. 2046 + minor formatting fixes to _nc_trace_mmask_t, make this function 2047 exported to help with debugging mouse changes. 2048 + improve behavior of wheel-mice for xterm protocol, noting that there 2049 are only button-presses for buttons "4" and "5", so there is no need 2050 to wait to combine events into double-clicks (report/analysis by 2051 Greg Field). 2052 + provide examples xterm-1005 and xterm-1006 terminfo entries -TD 2053 + implement decoder for xterm SGR 1006 mouse mode. 2054 2055 20140927 2056 + implement curs_set in win_driver.c 2057 + implement flash in win_driver.c 2058 + fix an infinite loop in win_driver.c if the command-window loses 2059 focus. 2060 + improve the non-buffered mode, i.e., NCURSES_CONSOLE2, of 2061 win_driver.c by temporarily changing the buffer-size to match the 2062 window-size to eliminate the scrollback. Also enforce a minimum 2063 screen-size of 24x80 in the non-buffered mode. 2064 + modify generated misc/Makefile to suppress install.data from the 2065 dependencies if the --disable-db-install option is used, compensating 2066 for the top-level makefile changes used to add ncurses*-config in the 2067 20140920 changes (report by Steven Honeyman). 2068 2069 20140920 2070 + add ncurses*-config to bin-directory of sample package-scripts. 2071 + add check to ensure that getopt is available; this is a problem in 2072 some older cross-compiler environments. 2073 + expanded on the description of --disable-overwrite in INSTALL 2074 (prompted by reports by Joakim Tjernlund, Thomas Klausner). 2075 See Gentoo #522586 and NetBSD #49200 for examples. 2076 which relates to the clarified guidelines. 2077 + remove special logic from CF_INCLUDE_DIRS which adds the directory 2078 for the --includedir from the build (report by Joakim Tjernlund). 2079 + add case for Unixware to CF_XOPEN_SOURCE, from lynx changes. 2080 + update config.sub from 2081 2082 2083 20140913 2084 + add a configure check to ignore some of the plethora of non-working 2085 C++ cross-compilers. 2086 + build-fixes for Ada95 with gnat 4.9 2087 2088 20140906 2089 + build-fix and other improvements for port of ncurses-examples to 2090 NetBSD. 2091 + minor compiler-warning fixes. 2092 2093 20140831 2094 + modify test/demo_termcap.c and test/demo_terminfo.c to make their 2095 options more directly comparable, and add "-i" option to specify 2096 a terminal description filename to parse for names to lookup. 2097 2098 20140823 2099 + fix special case where double-width character overwrites a single- 2100 width character in the first column (report by Egmont Koblinger, 2101 cf: 20050813). 2102 2103 20140816 2104 + fix colors in ncurses 'b' test which did not work after changing 2105 it to put the test-strings in subwindows (cf: 20140705). 2106 + merge redundant SEE-ALSO sections in form and menu manpages. 2107 2108 20140809 2109 + modify declarations for user-data pointers in C++ binding to use 2110 reinterpret_cast to facilitate converting typed pointers to void* 2111 in user's application (patch by Adam Jiang). 2112 + regenerated html manpages. 2113 + add note regarding cause and effect for TERM in ncurses manpage, 2114 having noted clueless verbiage in Terminal.app's "help" file 2115 which reverses cause/effect. 2116 + remove special fallback definition for NCURSES_ATTR_T, since macros 2117 have resolved type-mismatches using casts (cf: 970412). 2118 + fixes for win_driver.c: 2119 + handle repainting on endwin/refresh combination. 2120 + implement beep(). 2121 + minor cleanup. 2122 2123 20140802 2124 + minor portability fixes for MinGW: 2125 + ensure WINVER is defined in makefiles rather than using headers 2126 + add check for gnatprep "-T" option 2127 + work around bug introduced by gcc 4.8.1 in MinGW which breaks 2128 "trace" feature: 2129 2130 + fix most compiler warnings for Cygwin ncurses-examples. 2131 + restore "redundant" -I options in test/Makefile.in, since they are 2132 typically needed when building the derived ncurses-examples package 2133 (cf: 20140726). 2134 2135 20140726 2136 + eliminate some redundant -I options used for building libraries, and 2137 ensure that ${srcdir} is added to the include-options (prompted by 2138 discussion with Paul Gilmartin). 2139 + modify configure script to work with Minix3.2 2140 + add form library extension O_DYNAMIC_JUSTIFY option which can be 2141 used to override the different treatment of justification for static 2142 versus dynamic fields (adapted from patch by Leon Winter). 2143 + add a null pointer check in test/edit_field.c (report/analysis by 2144 Leon Winter, cf: 20130608). 2145 2146 20140719 2147 + make workarounds for compiling test-programs with NetBSD curses. 2148 + improve configure macro CF_ADD_LIBS, to eliminate repeated -l/-L 2149 options, from xterm changes. 2150 2151 20140712 2152 + correct Charable() macro check for A_ALTCHARSET in wide-characters. 2153 + build-fix for position-debug code in tty_update.c, to work with or 2154 without sp-funcs. 2155 2156 20140705 2157 + add w/W toggle to ncurses.c 'B' test, to demonstrate permutation of 2158 video-attributes and colors with double-width character strings. 2159 2160 20140629 2161 + correct check in win_driver.c for saving screen contents, e.g., when 2162 NCURSES_CONSOLE2 is set (cf: 20140503). 2163 + reorganize b/B menu items in ncurses.c, putting the test-strings into 2164 subwindows. This is needed for a planned change to use Unicode 2165 fullwidth characters in the test-screens. 2166 + correct update to form status for _NEWTOP, broken by fixes for 2167 compiler warnings (patch by Leon Winter, cf: 20120616). 2168 2169 20140621 2170 + change shared-library suffix for AIX 5 and 6 to ".so", avoiding 2171 conflict with the static library (report by Ben Lentz). 2172 + document RPATH_LIST in INSTALLATION file, as part of workarounds for 2173 upgrading an ncurses library using the "--with-shared" option. 2174 + modify test/ncurses.c c/C tests to cycle through subsets of the 2175 total number of colors, to better illustrate 8/16/88/256-colors by 2176 providing directly comparable screens. 2177 + add test/dots_curses.c, for comparison with the low-level examples. 2178 2179 20140614 2180 + fix dereference before null check found by Coverity in tic.c 2181 (cf: 20140524). 2182 + fix sign-extension bug in read_entry.c which prevented "toe" from 2183 reading empty "screen+italics" entry. 2184 + modify sgr for screen.xterm-new to support dim capability -TD 2185 + add dim capability to nsterm+7 -TD 2186 + cancel dim capability for iterm -TD 2187 + add dim, invis capabilities to vte-2012 -TD 2188 + add sitm/ritm to konsole-base and mlterm3 -TD 2189 2190 20140609 2191 > fix regression in screen terminfo entries (reports by Christian 2192 Ebert, Gabriele Balducci) -TD 2193 + revert the change to screen; see notes for why this did not work -TD 2194 + cancel sitm/ritm for entries which extend "screen", to work around 2195 screen's hardcoded behavior for SGR 3 -TD 2196 2197 20140607 2198 + separate masking for sgr in vidputs from sitm/ritm, which do not 2199 overlap with sgr functionality. 2200 + remove unneeded -i option from adacurses-config; put -a in the -I 2201 option for consistency (patch by Pascal Pignard). 2202 + update xterm-new terminfo entry to xterm patch #305 -TD 2203 + change format of test-scripts for Debian Ada95 and ncurses-examples 2204 packages to quilted to work around Debian #700177 (cf: 20130907). 2205 + build fix for form_driver_w.c as part of ncurses-examples package for 2206 older ncurses than 20131207. 2207 + add Hello World example to adacurses-config manpage. 2208 + remove unused --enable-pc-files option from Ada95/configure. 2209 + add --disable-gnat-projects option for testing. 2210 + revert changes to Ada95 project-files configuration (cf: 20140524). 2211 + corrected usage message in adacurses-config. 2212 2213 20140524 2214 + fix typo in ncurses manpage for the NCURSES_NO_MAGIC_COOKIE 2215 environment variable. 2216 + improve discussion of input-echoing in curs_getch.3x 2217 + clarify discussion in curs_addch.3x of wrapping. 2218 + modify parametrized.h to make fln non-padded. 2219 + correct several entries which had termcap-style padding used in 2220 terminfo: adm21, aj510, alto-h19, att605-pc, x820 -TD 2221 + correct syntax for padding in some entries: dg211, h19 -TD 2222 + correct ti924-8 which had confused padding versus octal escapes -TD 2223 + correct padding in sbi entry -TD 2224 + fix an old bug in the termcap emulation; "%i" was ignored in tparm() 2225 because the parameters to be incremented were already on the internal 2226 stack (report by Corinna Vinschen). 2227 + modify tic's "-c" option to take into account the "-C" option to 2228 activate additional checks which compare the results from running 2229 tparm() on the terminfo expressions versus the translated termcap 2230 expressions. 2231 + modify tic to allow it to read from FIFOs (report by Matthieu Fronton, 2232 cf: 20120324). 2233 > patches by Nicolas Boulenguez: 2234 + explicit dereferences to suppress some style warnings. 2235 + when c_varargs_to_ada.c includes its header, use double quotes 2236 instead of <>. 2237 + samples/ncurses2-util.adb: removed unused with clause. The warning 2238 was removed by an obsolete pragma. 2239 + replaced Unreferenced pragmas with Warnings (Off). The latter, 2240 available with older GNATs, needs no configure test. This also 2241 replaces 3 untested Unreferenced pragmas. 2242 + simplified To_C usage in trace handling. Using two parameters allows 2243 some basic formatting, and avoids a warning about security with some 2244 compiler flags. 2245 + for generated Ada sources, replace many snippets with one pure 2246 package. 2247 + removed C_Chtype and its conversions. 2248 + removed C_AttrType and its conversions. 2249 + removed conversions between int, Item_Option_Set, Menu_Option_Set. 2250 + removed int, Field_Option_Set, Item_Option_Set conversions. 2251 + removed C_TraceType, Attribute_Option_Set conversions. 2252 + replaced C.int with direct use of Eti_Error, now enumerated. As it 2253 was used in a case statement, values were tested by the Ada compiler 2254 to be consecutive anyway. 2255 + src/Makefile.in: remove duplicate stanza 2256 + only consider using a project for shared libraries. 2257 + style. Silent gnat-4.9 warning about misplaced "then". 2258 + generate shared library project to honor ADAFLAGS, LDFLAGS. 2259 2260 20140510 2261 + cleanup recently introduced compiler warnings for MingW port. 2262 + workaround for ${MAKEFLAGS} configure check versus GNU make 4.0, 2263 which introduces more than one gratuitous incompatibility. 2264 2265 20140503 2266 + add vt520ansi terminfo entry (patch by Mike Gran) 2267 + further improve MinGW support for the scenario where there is an 2268 ANSI-escapes handler such as ansicon running in the console window 2269 (patch by Juergen Pfeifer). 2270 2271 20140426 2272 + add --disable-lib-suffixes option (adapted from patch by Juergen 2273 Pfeifer). 2274 + merge some changes from Juergen Pfeifer's work with MSYS2, to 2275 simplify later merging: 2276 + use NC_ISATTY() macro for isatty() in library 2277 + add _nc_mingw_isatty() and related functions to windows-driver 2278 + rename terminal driver entrypoints to simplify grep's 2279 + remove a check in the sp-funcs flavor of newterm() which allowed only 2280 the first call to newterm() to succeed (report by Thomas Beierlein, 2281 cf: 20090927). 2282 2283 20140419 2284 + update config.guess, config.sub from 2285 2286 2287 20140412 2288 + modify configure script: 2289 + drop the -no-gcc option from Intel compiler, from lynx changes. 2290 + extend the --with-hashed-db configure option to simplify building 2291 with different versions of Berkeley database using FreeBSD ports. 2292 + improve initialization for MinGW port (Juergen Pfeifer): 2293 + enforce Windows-style path-separator if cross-compiling, 2294 + add a driver-name method to each of the drivers, 2295 + allow the Windows driver name to match "unknown", ignoring case, 2296 + lengthen the built-in name for the Windows console driver to 2297 "#win32console", and 2298 + move the comparison of driver-names allowing abbreviation, e.g., 2299 to "#win32con" into the Windows console driver. 2300 2301 20140329 2302 + add check in tic for mismatch between ccc and initp/initc 2303 + cancel ccc in putty-256color and konsole-256color for consistency 2304 with the cancelled initc capability (patch by Sven Zuhlsdorf). 2305 + add xterm+256setaf building block for various terminals which only 2306 get the 256-color feature half-implemented -TD 2307 + updated "st" entry (leaving the 0.1.1 version as "simpleterm") to 2308 0.4.1 -TD 2309 2310 20140323 2311 + fix typo in "mlterm" entry (report by Gabriele Balducci) -TD 2312 2313 20140322 2314 + use types from <stdint.h> in sample build-scripts for chtype, etc. 2315 + modify configure script and curses.h.in to allow the types specified 2316 using --with-chtype and related options to be defined in <stdint.h> 2317 + add terminology entry -TD 2318 + add mlterm3 entry, use that as "mlterm" -TD 2319 + inherit mlterm-256color from mlterm -TD 2320 2321 20140315 2322 + modify _nc_New_TopRow_and_CurrentItem() to ensure that the menu's 2323 top-row is adjusted as needed to ensure that the current item is 2324 on the screen (patch by Johann Klammer). 2325 + add wgetdelay() to retrieve _delay member of WINDOW if it happens to 2326 be opaque, e.g., in the pthread configuration (prompted by patch by 2327 Soren Brinkmann). 2328 2329 20140308 2330 + modify ifdef in read_entry.c to handle the case where 2331 NCURSES_USE_DATABASE is not defined (patch by Xin Li). 2332 + add cast in form_driver_w() to fix ARM build (patch by Xin Li). 2333 + add logic to win_driver.c to save/restore screen contents when not 2334 allocating a console-buffer (cf: 20140215). 2335 2336 20140301 2337 + clarify error-returns from newwin (report by Ruslan Nabioullin). 2338 2339 20140222 2340 + fix some compiler warnings in win_driver.c 2341 + updated notes for wsvt25 based on tack and vttest -TD 2342 + add teken entry to show actual properties of FreeBSD's "xterm" 2343 console -TD 2344 2345 20140215 2346 + in-progress changes to win_driver.c to implement output without 2347 allocating a console-buffer. This uses a pre-existing environment 2348 variable NCGDB used by Juergen Pfeifer for debugging (prompted by 2349 discussion with Erwin Waterlander regarding Console2, which hangs 2350 when reading in an allocated console-buffer). 2351 + add -t option to gdc.c, and modify to accept "S" to step through the 2352 scrolling-stages. 2353 + regenerate NCURSES-Programming-HOWTO.html to fix some of the broken 2354 html emitted by docbook. 2355 2356 20140209 2357 + modify CF_XOPEN_SOURCE macro to omit followup check to determine if 2358 _XOPEN_SOURCE can/should be defined. g++ 4.7.2 built on Solaris 10 2359 has some header breakage due to its own predefinition of this symbol 2360 (report by Jean-Pierre Flori, Sage #15796). 2361 2362 20140201 2363 + add/use symbol NCURSES_PAIRS_T like NCURSES_COLOR_T, to illustrate 2364 which "short" types are for color pairs and which are color values. 2365 + fix build for s390x, by correcting field bit offsets in generated 2366 representation clauses when int=32 long=64 and endian=big, or at 2367 least on s390x (patch by Nicolas Boulenguez). 2368 + minor cleanup change to test/form_driver_w.c (patch by Gaute Hope). 2369 2370 20140125 2371 + remove unnecessary ifdef's in Ada95/gen/gen.c, which reportedly do 2372 not work as is with gcc 4.8 due to fixes using chtype cast made for 2373 new compiler warnings by gcc 4.8 in 20130824 (Debian #735753, patch 2374 by Nicolas Boulenguez). 2375 2376 20140118 2377 + apply includesubdir variable which was introduced in 20130805 to 2378 gen-pkgconfig.in (Debian #735782). 2379 2380 20131221 2381 + further improved man2html, used this to fix broken links in html 2382 manpages. See 2383 2384 2385 20131214 2386 + modify configure-script/ifdef's to allow OLD_TTY feature to be 2387 suppressed if the type of ospeed is configured using the option 2388 --with-ospeed to not be a short. By default, it is a short for 2389 termcap-compatibility (adapted from suggestion by Christian 2390 Weisgerber). 2391 + correct a typo in _nc_baudrate() (patch by Christian Weisgerber, 2392 cf: 20061230). 2393 + fix a few -Wlogical-op warnings. 2394 + updated llib-l* files. 2395 2396 20131207 2397 + add form_driver_w() entrypoint to wide-character forms library, as 2398 well as test program form_driver_w (adapted from patch by Gaute 2399 Hope). 2400 2401 20131123 2402 + minor fix for CF_GCC_WARNINGS to special-case options which are not 2403 recognized by clang. 2404 2405 20131116 2406 + add special case to configure script to move _XOPEN_SOURCE_EXTENDED 2407 definition from CPPFLAGS to CFLAGS if it happens to be needed for 2408 Solaris, because g++ errors with that definition (report by 2409 Jean-Pierre Flori, Sage #15268). 2410 + correct logic in infocmp's -i option which was intended to ignore 2411 strings which correspond to function-keys as candidates for piecing 2412 together initialization- or reset-strings. The problem dates to 2413 1.9.7a, but was overlooked until changes in -Wlogical-op warnings for 2414 gcc 4.8 (report by David Binderman). 2415 + updated CF_GCC_WARNINGS to documented options for gcc 4.9.0, moving 2416 checks for -Wextra and -Wdeclaration-after-statement into the macro, 2417 and adding checks for -Wignored-qualifiers, -Wlogical-op and 2418 -Wvarargs 2419 + updated CF_CURSES_UNCTRL_H and CF_SHARED_OPTS macros from ongoing 2420 work on cdk. 2421 + update config.sub from 2422 2423 2424 20131110 2425 + minor cleanup of terminfo.tail 2426 2427 20131102 2428 + use TS extension to describe xterm's title-escapes -TD 2429 + modify terminator and nsterm-s to use xterm+sl-twm building block -TD 2430 + update hurd.ti, add xenl to reflect 2011-03-06 change in 2431 2432 (Debian #727119). 2433 + simplify pfkey expression in ansi.sys -TD 2434 2435 20131027 2436 + correct/simplify ifdef's for cur_term versus broken-linker and 2437 reentrant options (report by Jean-Pierre Flori, cf: 20090530). 2438 + modify release/version combinations in test build-scripts to make 2439 them more consistent with other packages. 2440 2441 20131019 2442 + add nc_mingw.h to installed headers for MinGW port; needed for 2443 compiling ncurses-examples. 2444 + add rpm-script for testing cross-compile of ncurses-examples. 2445 2446 20131014 2447 + fix new typo in CF_ADA_INCLUDE_DIRS macro (report by Roumen Petrov). 2448 2449 20131012 2450 + fix a few compiler warnings in progs and test. 2451 + minor fix to package/debian-mingw/rules, do not strip dll's. 2452 + minor fixes to configure script for empty $prefix, e.g., when doing 2453 cross-compiles to MinGW. 2454 + add script for building test-packages of binaries cross-compiled to 2455 MinGW using NSIS. 2456 2457 20131005 2458 + minor fixes for ncurses-example package and makefile. 2459 + add scripts for test-builds of cross-compiler packages for ncurses6 2460 to MinGW. 2461 2462 20130928 2463 + some build-fixes for ncurses-examples with NetBSD-6.0 curses, though 2464 it lacks some common functions such as use_env() which is not yet 2465 addressed. 2466 + build-fix and some compiler warning fixes for ncurses-examples with 2467 OpenBSD 5.3 2468 + fix a possible null-pointer reference in a trace message from newterm. 2469 + quiet a few warnings from NetBSD 6.0 namespace pollution by 2470 nonstandard popcount() function in standard strings.h header. 2471 + ignore g++ 4.2.1 warnings for "-Weffc++" in c++/cursesmain.cc 2472 + fix a few overlooked places for --enable-string-hacks option. 2473 2474 20130921 2475 + fix typo in curs_attr.3x (patch by Sven Joachim, cf: 20130831). 2476 + build-fix for --with-shared option for DragonFly and FreeBSD (report 2477 by Rong-En Fan, cf: 20130727). 2478 2479 20130907 2480 + build-fixes for MSYS for two test-programs (patches by Ray Donnelly, 2481 Alexey Pavlov). 2482 + revert change to two of the dpkg format files, to work with dpkg 2483 before/after Debian #700177. 2484 + fix gcc -Wconversion warning in wattr_get() macro. 2485 + add msys and msysdll to known host/configuration types (patch by 2486 Alexey Pavlov). 2487 + modify CF_RPATH_HACK configure macro to not rely upon "-u" option 2488 of sort, improving portability. 2489 + minor improvements for test-programs from reviewing Solaris port. 2490 + update config.guess, config.sub from 2491 2492 2493 20130831 2494 + modify test/ncurses.c b/B tests to display lines only for the 2495 attributes which a given terminal supports, to make room for an 2496 italics test. 2497 + completed ncv table in terminfo.tail; it did not list the wide 2498 character codes listed in X/Open Curses issue 7. 2499 + add A_ITALIC extension (prompted by discussion with Egmont Koblinger). 2500 2501 20130824 2502 + fix some gcc 4.8 -Wconversion warnings. 2503 + change format of dpkg test-scripts to quilted to work around bug 2504 introduced by Debian #700177. 2505 + discard cached keyname() values if meta() is changed after a value 2506 was cached using (report by Kurban Mallachiev). 2507 2508 20130816 2509 + add checks in tic to warn about terminals which lack cursor 2510 addressing, capabilities or having those, are marked as hard_copy or 2511 generic_type. 2512 + use --without-progs in mingw-ncurses rpm. 2513 + split out _nc_init_termtype() from alloc_entry.c to use in MinGW 2514 port when tic and other programs are not needed. 2515 2516 20130805 2517 + minor fixes to the --disable-overwrite logic, to ensure that the 2518 configured $(includedir) is not cancelled by the mingwxx-filesystem 2519 rpm macros. 2520 + add --disable-db-install configure option, to simplify building 2521 cross-compile support packages. 2522 + add mingw-ncurses.spec file, for testing cross-compiles. 2523 2524 20130727 2525 + improve configure macros from ongoing work on cdk, dialog, xterm: 2526 + CF_ADD_LIB_AFTER - fix a problem with -Wl options 2527 + CF_RPATH_HACK - add missing result-message 2528 + CF_SHARED_OPTS - modify to use $rel_builddir in cygwin and mingw 2529 dll symbols (which can be overridden) rather than explicit "../". 2530 + CF_SHARED_OPTS - modify NetBSD and DragonFly symbols to use ${CC} 2531 rather than ${LD} to improve rpath support. 2532 + CF_SHARED_OPTS - add a symbol to denote the temporary files that 2533 are created by the macro, to simplify clean-rules. 2534 + CF_X_ATHENA - trim extra libraries to work with -Wl,--as-needed 2535 + fix a regression in hashed-database support for NetBSD, which uses 2536 the key-size differently from other implementations (cf: 20121229). 2537 2538 20130720 2539 + further improvements for setupterm manpage, clarifying the 2540 initialization of cur_term. 2541 2542 20130713 2543 + improve manpages for initscr and setupterm. 2544 + minor compiler-warning fixes 2545 2546 20130706 2547 + add fallback defs for <inttypes.h> and <stdint.h> (cf: 20120225). 2548 + add check for size of wchar_t, use that to suppress a chunk of 2549 wcwidth.h in MinGW port. 2550 + quiet linker warnings for MinGW cross-compile with dll's using the 2551 --enable-auto-import flag. 2552 + add ncurses.map rule to ncurses/Makefile to help diagnose symbol 2553 table issues. 2554 2555 20130622 2556 + modify the clear program to take into account the E3 extended 2557 capability to clear the terminal's scrollback buffer (patch by 2558 Miroslav Lichvar, Redhat #815790). 2559 + clarify in resizeterm manpage that LINES and COLS are updated. 2560 + updated ansi example in terminfo.tail, correct misordered example 2561 of sgr. 2562 + fix other doclifter warnings for manpages 2563 + remove unnecessary ".ta" in terminfo.tail, add missing ".fi" 2564 (patch by Eric Raymond). 2565 2566 20130615 2567 + minor changes to some configure macros to make them more reusable. 2568 + fixes for tabs program (prompted by report by Nick Andrik). 2569 + corrected logic in command-line parsing of -a and -c predefined 2570 tab-lists options. 2571 + allow "-0" and "-8" options to be combined with others, e.g.,"-0d". 2572 + make warning messages more consistent with the other utilities by 2573 not printing the full pathname of the program. 2574 + add -V option for consistency with other utilities. 2575 + fix off-by-one in columns for tabs program when processing an option 2576 such as "-5" (patch by Nick Andrik). 2577 2578 20130608 2579 + add to test/demo_forms.c examples of using the menu-hooks as well 2580 as showing how the menu item user-data can be used to pass a callback 2581 function pointer. 2582 + add test/dots_termcap.c 2583 + remove setupterm call from test/demo_termcap.c 2584 + build-fix if --disable-ext-funcs configure option is used. 2585 + modified test/edit_field.c and test/demo_forms.c to move the lengths 2586 into a user-data structure, keeping the original string for later 2587 expansion to free-format input/out demo. 2588 + modified test/demo_forms.c to load data from file. 2589 + added note to clarify Terminal.app's non-emulation of the various 2590 terminal types listed in the preferences dialog -TD 2591 + fix regression in error-reporting in lib_setup.c (Debian #711134, 2592 cf: 20121117). 2593 + build-fix for a case where --enable-broken_linker and 2594 --enable-reentrant options are combined (report by George R Goffe). 2595 2596 20130525 2597 + modify mvcur() to distinguish between internal use by the ncurses 2598 library, and external callers, preventing it from reading the content 2599 of the screen which is only nonblank when curses calls have updated 2600 it. This makes test/dots_mvcur.c avoid painting colored cells in 2601 the left margin of the display. 2602 + minor fix to test/dots_mvcur.c 2603 + move configured symbols USE_DATABASE and USE_TERMCAP to term.h as 2604 NCURSES_USE_DATABASE and NCURSES_USE_TERMCAP to allow consistent 2605 use of these symbols in term_entry.h 2606 2607 20130518 2608 + corrected ifdefs in test/testcurs.c to allow comparison of mouse 2609 interface versus pdcurses (cf: 20130316). 2610 + add pow() to configure-check for math library, needed since 2611 20121208 for test/hanoi (Debian #708056). 2612 + regenerated html manpages. 2613 + update doctype used for html documentation. 2614 2615 20130511 2616 + move nsterm-related entries out of "obsolete" section to more 2617 plausible "ansi consoles" -TD 2618 + additional cleanup of table-of-contents by reordering -TD 2619 + revise fix for check for 8-bit value in _nc_insert_ch(); prior fix 2620 prevented inserts when video attributes were attached to the data 2621 (cf: 20121215) (Redhat #959534). 2622 2623 20130504 2624 + fixes for issues found by Coverity: 2625 + correct FNKEY() macro in progs/dump_entry.c, allowing kf11-kf63 to 2626 display when infocmp's -R option is used for HP or AIX subsets. 2627 + fix dead-code issue with test/movewindow.c 2628 + improve limited-checking in _nc_read_termtype(). 2629 2630 20130427 2631 + fix clang 3.2 warning in progs/dump_entry.c 2632 + drop AC_TYPE_SIGNAL check; ncurses relies on c89 and later. 2633 2634 20130413 2635 + add MinGW to cases where ncurses installs by default into /usr 2636 (prompted by discussion with Daniel Silva Ferreira). 2637 + add -D option to infocmp's usage-message (patch by Miroslav Lichvar). 2638 + add a missing 'int' type for main function in configure check for 2639 type of bool variable, to work with clang 3.2 (report by Dmitri 2640 Gribenko). 2641 + improve configure check for static_cast, to work with clang 3.2 2642 (report by Dmitri Gribenko). 2643 + re-order rule for demo.o and macros defining header dependencies in 2644 c++/Makefile.in to accommodate gmake (report by Dmitri Gribenko). 2645 2646 20130406 2647 + improve parameter checking in copywin(). 2648 + modify configure script to work around OS X's "libtool" program, to 2649 choose glibtool instead. At the same time, chance the autoconf macro 2650 to look for a "tool" rather than a "prog", to help with potential use 2651 in cross-compiling. 2652 + separate the rpath usage for c++ library from demo program 2653 (Redhat #911540) 2654 + update/correct header-dependencies in c++ makefile (report by Werner 2655 Fink). 2656 + add --with-cxx-shared to dpkg-script, as done for rpm-script. 2657 2658 20130324 2659 + build-fix for libtool configuration (reports by Daniel Silva Ferreira 2660 and Roumen Petrov). 2661 2662 20130323 2663 + build-fix for OS X, to handle changes for --with-cxx-shared feature 2664 (report by Christian Ebert). 2665 + change initialization for vt220, similar entries for consistency 2666 with cursor-key strings (NetBSD #47674) -TD 2667 + further improvements to linux-16color (Benjamin Sittler) 2668 2669 20130316 2670 + additional fix for tic.c, to allocate missing buffer space. 2671 + eliminate configure-script warnings for gen-pkgconfig.in 2672 + correct typo in sgr string for sun-color, 2673 add bold for consistency with sgr, 2674 change smso for consistency with sgr -TD 2675 + correct typo in sgr string for terminator -TD 2676 + add blink to the attributes masked by ncv in linux-16color (report 2677 by Benjamin Sittler) 2678 + improve warning message from post-load checking for missing "%?" 2679 operator by tic/infocmp by showing the entry name and capability. 2680 + minor formatting improvement to tic/infocmp -f option to ensure 2681 line split after "%;". 2682 + amend scripting for --with-cxx-shared option to handle the debug 2683 library "libncurses++_g.a" (report by Sven Joachim). 2684 2685 20130309 2686 + amend change to toe.c for reading from /dev/zero, to ensure that 2687 there is a buffer for the temporary filename (cf: 20120324). 2688 + regenerated html manpages. 2689 + fix typo in terminfo.head (report by Sven Joachim, cf: 20130302). 2690 + updated some autoconf macros: 2691 + CF_ACVERSION_CHECK, from byacc 1.9 20130304 2692 + CF_INTEL_COMPILER, CF_XOPEN_SOURCE from luit 2.0-20130217 2693 + add configure option --with-cxx-shared to permit building 2694 libncurses++ as a shared library when using g++, e.g., the same 2695 limitations as libtool but better integrated with the usual build 2696 configuration (Redhat #911540). 2697 + modify MKkey_defs.sh to filter out build-path which was unnecessarily 2698 shown in curses.h (Debian #689131). 2699 2700 20130302 2701 + add section to terminfo manpage discussing user-defined capabilities. 2702 + update manpage description of NCURSES_NO_SETBUF, explaining why it 2703 is obsolete. 2704 + add a check in waddch_nosync() to ensure that tab characters are 2705 treated as control characters; some broken locales claim they are 2706 printable. 2707 + add some traces to the Windows console driver. 2708 + initialize a temporary array in _nc_mbtowc, needed for some cases 2709 of raw input in MinGW port. 2710 2711 20130218 2712 + correct ifdef on change to lib_twait.c (report by Werner Fink). 2713 + update config.guess, config.sub 2714 2715 20130216 2716 + modify test/testcurs.c to work with mouse for ncurses as it does for 2717 pdcurses. 2718 + modify test/knight.c to work with mouse for pdcurses as it does for 2719 ncurses. 2720 + modify internal recursion in wgetch() which handles cooked mode to 2721 check if the call to wgetnstr() returned an error. This can happen 2722 when both nocbreak() and nodelay() are set, for instance (report by 2723 Nils Christopher Brause) (cf: 960418). 2724 + fixes for issues found by Coverity: 2725 + add a check for valid position in ClearToEOS() 2726 + fix in lib_twait.c when --enable-wgetch-events is used, pointer 2727 use after free. 2728 + improve a limit-check in make_hash.c 2729 + fix a memory leak in hashed_db.c 2730 2731 20130209 2732 + modify test/configure script to make it simpler to override names 2733 of curses-related libraries, to help with linking with pdcurses in 2734 MinGW environment. 2735 + if the --with-terminfo-dirs configure option is not used, there is 2736 no corresponding compiled-in value for that. Fill in "no default 2737 value" for that part of the manpage substitution. 2738 2739 20130202 2740 + correct initialization in knight.c which let it occasionally make 2741 an incorrect move (cf: 20001028). 2742 + improve documentation of the terminfo/termcap search path. 2743 2744 20130126 2745 + further fixes to mvcur to pass callback function (cf: 20130112), 2746 needed to make test/dots_mvcur work. 2747 + reduce calls to SetConsoleActiveScreenBuffer in win_driver.c, to 2748 help reduce flicker. 2749 + modify configure script to omit "+b" from linker options for very 2750 old HP-UX systems (report by Dennis Grevenstein) 2751 + add HP-UX workaround for missing EILSEQ on old HP-UX systems (patch 2752 by Dennis Grevenstein). 2753 + restore memmove/strdup support for antique systems (request by 2754 Dennis Grevenstein). 2755 + change %l behavior in tparm to push the string length onto the stack 2756 rather than saving the formatted length into the output buffer 2757 (report by Roy Marples, cf: 980620). 2758 2759 20130119 2760 + fixes for issues found by Coverity: 2761 + fix memory leak in safe_sprintf.c 2762 + add check for return-value in tty_update.c 2763 + correct initialization for -s option in test/view.c 2764 + add check for numeric overflow in lib_instr.c 2765 + improve error-checking in copywin 2766 + add advice in infocmp manpage for termcap users (Debian #698469). 2767 + add "-y" option to test/demo_termcap and test/demo_terminfo to 2768 demonstrate behavior with/without extended capabilities. 2769 + updated termcap manpage to document legacy termcap behavior for 2770 matching capability names. 2771 + modify name-comparison for tgetstr, etc., to accommodate legacy 2772 applications as well as to improve compatbility with BSD 4.2 2773 termcap implementations (Debian #698299) (cf: 980725). 2774 2775 20130112 2776 + correct prototype in manpage for vid_puts. 2777 + drop ncurses/tty/tty_display.h, ncurses/tty/tty_input.h, since they 2778 are unused in the current driver model. 2779 + modify mvcur to use stdout except when called within the ncurses 2780 library. 2781 + modify vidattr and vid_attr to use stdout as documented in manpage. 2782 + amend changes made to buffering in 20120825 so that the low-level 2783 putp() call uses stdout rather than ncurses' internal buffering. 2784 The putp_sp() call does the same, for consistency (Redhat #892674). 2785 2786 20130105 2787 + add "-s" option to test/view.c to allow it to start in single-step 2788 mode, reducing size of trace files when it is used for debugging 2789 MinGW changes. 2790 + revert part of 20121222 change to tinfo_driver.c 2791 + add experimental logic in win_driver.c to improve optimization of 2792 screen updates. This does not yet work with double-width characters, 2793 so it is ifdef'd out for the moment (prompted by report by Erwin 2794 Waterlander regarding screen flicker). 2795 2796 20121229 2797 + fix Coverity warnings regarding copying into fixed-size buffers. 2798 + add throw-declarations in the c++ binding per Coverity warning. 2799 + minor changes to new-items for consistent reference to bug-report 2800 numbers. 2801 2802 20121222 2803 + add *.dSYM directories to clean-rule in ncurses directory makefile, 2804 for Mac OS builds. 2805 + add a configure check for gcc option -no-cpp-precomp, which is not 2806 available in all Mac OS X configurations (report by Andras Salamon, 2807 cf: 20011208). 2808 + improve 20021221 workaround for broken acs, handling a case where 2809 that ACS_xxx character is not in the acsc string but there is a known 2810 wide-character which can be used. 2811 2812 20121215 2813 + fix several warnings from clang 3.1 --analyze, includes correcting 2814 a null-pointer check in _nc_mvcur_resume. 2815 + correct display of double-width characters with MinGW port (report 2816 by Erwin Waterlander). 2817 + replace MinGW's wcrtomb(), fixing a problem with _nc_viscbuf 2818 > fixes based on Coverity report: 2819 + correct coloring in test/bs.c 2820 + correct check for 8-bit value in _nc_insert_ch(). 2821 + remove dead code in progs/tset.c, test/linedata.h 2822 + add null-pointer checks in lib_tracemse.c, panel.priv.h, and some 2823 test-programs. 2824 2825 20121208 2826 + modify test/knight.c to show the number of choices possible for 2827 each position in automove option, e.g., to allow user to follow 2828 Warnsdorff's rule to solve the puzzle. 2829 + modify test/hanoi.c to show the minimum number of moves possible for 2830 the given number of tiles (prompted by patch by Lucas Gioia). 2831 > fixes based on Coverity report: 2832 + remove a few redundant checks. 2833 + correct logic in test/bs.c, when randomly placing a specific type of 2834 ship. 2835 + check return value from remove/unlink in tic. 2836 + check return value from sscanf in test/ncurses.c 2837 + fix a null dereference in c++/cursesw.cc 2838 + fix two instances of uninitialized variables when configuring for the 2839 terminal driver. 2840 + correct scope of variable used in SetSafeOutcWrapper macro. 2841 + set umask when calling mkstemp in tic. 2842 + initialize wbkgrndset() temporary variable when extended-colors are 2843 used. 2844 2845 20121201 2846 + also replace MinGW's wctomb(), fixing a problem with setcchar(). 2847 + modify test/view.c to load UTF-8 when built with MinGW by using 2848 regular win32 API because the MinGW functions mblen() and mbtowc() 2849 do not work. 2850 2851 20121124 2852 + correct order of color initialization versus display in some of the 2853 test-programs, e.g., test_addstr.c 2854 > fixes based on Coverity report: 2855 + delete windows on exit from some of the test-programs. 2856 2857 20121117 2858 > fixes based on Coverity report: 2859 + add missing braces around FreeAndNull in two places. 2860 + various fixes in test/ncurses.c 2861 + improve limit-checks in tinfo/make_hash.c, tinfo/read_entry.c 2862 + correct malloc size in progs/infocmp.c 2863 + guard against negative array indices in test/knight.c 2864 + fix off-by-one limit check in test/color_name.h 2865 + add null-pointer check in progs/tabs.c, test/bs.c, test/demo_forms.c, 2866 test/inchs.c 2867 + fix memory-leak in tinfo/lib_setup.c, progs/toe.c, 2868 test/clip_printw.c, test/demo_menus.c 2869 + delete unused windows in test/chgat.c, test/clip_printw.c, 2870 test/insdelln.c, test/newdemo.c on error-return. 2871 2872 20121110 2873 + modify configure macro CF_INCLUDE_DIRS to put $CPPFLAGS after the 2874 local -I include options in case someone has set conflicting -I 2875 options in $CPPFLAGS (prompted by patch for ncurses/Makefile.in by 2876 Vassili Courzakis). 2877 + modify the ncurses*-config scripts to eliminate relative paths from 2878 the RPATH_LIST variable, e.g., "../lib" as used in installing shared 2879 libraries or executables. 2880 2881 20121102 2882 + realign these related pages: 2883 curs_add_wchstr.3x 2884 curs_addchstr.3x 2885 curs_addstr.3x 2886 curs_addwstr.3x 2887 and fix a long-ago error in curs_addstr.3x which said that a -1 2888 length parameter would only write as much as fit onto one line 2889 (report by Reuben Thomas). 2890 + remove obsolete fallback _nc_memmove() for memmove()/bcopy(). 2891 + remove obsolete fallback _nc_strdup() for strdup(). 2892 + cancel any debug-rpm in package/ncurses.spec 2893 + reviewed vte-2012, reverted most of the change since it was incorrect 2894 based on testing with tack -TD 2895 + un-cancel the initc in vte-256color, since this was implemented 2896 starting with version 0.20 in 2009 -TD 2897 2898 20121026 2899 + improve malloc/realloc checking (prompted by discussion in Redhat 2900 #866989). 2901 + add ncurses test-program as "ncurses6" to the rpm- and dpkg-scripts. 2902 + updated configure macros CF_GCC_VERSION and CF_WITH_PATHLIST. The 2903 first corrects pattern used for Mac OS X's customization of gcc. 2904 2905 20121017 2906 + fix change to _nc_scroll_optimize(), which incorrectly freed memory 2907 (Redhat #866989). 2908 2909 20121013 2910 + add vte-2012, gnome-2012, making these the defaults for vte/gnome 2911 (patch by Christian Persch). 2912 2913 20121006 2914 + improve CF_GCC_VERSION to work around Debian's customization of gcc 2915 --version message. 2916 + improve configure macros as done in byacc: 2917 + drop 2.13 compatibility; use 2.52.xxxx version only since EMX port 2918 has used that for a while. 2919 + add 3rd parameter to AC_DEFINE's to allow autoheader to run, i.e., 2920 for experimental use. 2921 + remove unused configure macros. 2922 + modify configure script and makefiles to quiet new autoconf warning 2923 for LIBS_TO_MAKE variable. 2924 + modify configure script to show $PATH_SEPARATOR variable. 2925 + update config.guess, config.sub 2926 2927 20120922 2928 + modify setupterm to set its copy of TERM to "unknown" if configured 2929 for the terminal driver and TERM was null or empty. 2930 + modify treatment of TERM variable for MinGW port to allow explicit 2931 use of the windows console driver by checking if $TERM is set to 2932 "#win32con" or an abbreviation of that. 2933 + undo recent change to fallback definition of vsscanf() to build with 2934 older Solaris compilers (cf: 20120728). 2935 2936 20120908 2937 + add test-screens to test/ncurses to show 256-characters at a time, 2938 to help with MinGW port. 2939 2940 20120903 2941 + simplify varargs logic in lib_printw.c; va_copy is no longer needed 2942 there. 2943 + modifications for MinGW port to make wide-character display usable. 2944 2945 20120902 2946 + regenerate configure script (report by Sven Joachim, cf: 20120901). 2947 2948 20120901 2949 + add a null-pointer check in _nc_flush (cf: 20120825). 2950 + fix a case in _nc_scroll_optimize() where the _oldnums_list array 2951 might not be allocated. 2952 + improve comparisons in configure.in for unset shell variables. 2953 2954 20120826 2955 + increase size of ncurses' output-buffer, in case of very small 2956 initial screen-sizes. 2957 + fix evaluation of TERMINFO and TERMINFO_DIRS default values as needed 2958 after changes to use --datarootdir (reports by Gabriele Balducci, 2959 Roumen Petrov). 2960 2961 20120825 2962 + change output buffering scheme, using buffer maintained by ncurses 2963 rather than stdio, to avoid problems with SIGTSTP handling (report 2964 by Brian Bloniarz). 2965 2966 20120811 2967 + update autoconf patch to 2.52.20120811, adding --datarootdir 2968 (prompted by discussion with Erwin Waterlander). 2969 + improve description of --enable-reentrant option in README and the 2970 INSTALL file. 2971 + add nsterm-256color, make this the default nsterm -TD 2972 + remove bw from nsterm-bce, per testing with tack -TD 2973 2974 20120804 2975 + update test/configure, adding check for tinfo library. 2976 + improve limit-checks for the getch fifo (report by Werner Fink). 2977 + fix a remaining mismatch between $with_echo and the symbols updated 2978 for CF_DISABLE_ECHO affecting parameters for mk-2nd.awk (report by 2979 Sven Joachim, cf: 20120317). 2980 + modify followup check for pkg-config's library directory in the 2981 --enable-pc-files option to validate syntax (report by Sven Joachim, 2982 cf: 20110716). 2983 2984 20120728 2985 + correct path for ncurses_mingw.h in include/headers, in case build 2986 is done outside source-tree (patch by Roumen Petrov). 2987 + modify some older xterm entries to align with xterm source -TD 2988 + separate "xterm-old" alias from "xterm-r6" -TD 2989 + add E3 extended capability to xterm-basic and putty -TD 2990 + parenthesize parameters of other macros in curses.h -TD 2991 + parenthesize parameter of COLOR_PAIR and PAIR_NUMBER in curses.h 2992 in case it happens to be a comma-expression, etc. (patch by Nick 2993 Black). 2994 2995 20120721 2996 + improved form_request_by_name() and menu_request_by_name(). 2997 + eliminate two fixed-size buffers in toe.c 2998 + extend use_tioctl() to have expected behavior when use_env(FALSE) and 2999 use_tioctl(TRUE) are called. 3000 + modify ncurses test-program, adding -E and -T options to demonstrate 3001 use_env() versus use_tioctl(). 3002 3003 20120714 3004 + add use_tioctl() function (adapted from patch by Werner Fink, 3005 Novell #769788): 3006 3007 20120707 3008 + add ncurses_mingw.h to installed headers (prompted by patch by 3009 Juergen Pfeifer). 3010 + clarify return-codes from wgetch() in response to SIGWINCH (prompted 3011 by Novell #769788). 3012 + modify resizeterm() to always push a KEY_RESIZE onto the fifo, even 3013 if screensize is unchanged. Modify _nc_update_screensize() to push a 3014 KEY_RESIZE if there was a SIGWINCH, even if it does not call 3015 resizeterm(). These changes eliminate the case where a SIGWINCH is 3016 received, but ERR returned from wgetch or wgetnstr because the screen 3017 dimensions did not change (Novell #769788). 3018 3019 20120630 3020 + add --enable-interop to sample package scripts (suggested by Juergen 3021 Pfeifer). 3022 + update CF_PATH_SYNTAX macro, from mawk changes. 3023 + modify mk-0th.awk to allow for generating llib-ltic, etc., though 3024 some work is needed on cproto to work with lib_gen.c to update 3025 llib-lncurses. 3026 + remove redundant getenv() cal in database-iterator leftover from 3027 cleanup in 20120622 changes (report by Sven Joachim). 3028 3029 20120622 3030 + add -d, -e and -q options to test/demo_terminfo and test/demo_termcap 3031 + fix caching of environment variables in database-iterator (patch by 3032 Philippe Troin, Redhat #831366). 3033 3034 20120616 3035 + add configure check to distinguish clang from gcc to eliminate 3036 warnings about unused command-line parameters when compiler warnings 3037 are enabled. 3038 + improve behavior when updating terminfo entries which are hardlinked 3039 by allowing for the possibility that an alias has been repurposed to 3040 a new primary name. 3041 + fix some strict compiler warnings based on package scripts. 3042 + further fixes for configure check for working poll (Debian #676461). 3043 3044 20120608 3045 + fix an uninitialized variable in -c/-n logic for infocmp changes 3046 (cf: 20120526). 3047 + corrected fix for building c++ binding with clang 3.0 (report/patch 3048 by Richard Yao, Gentoo #417613, cf: 20110409) 3049 + correct configure check for working poll, fixing the case where stdin 3050 is redirected, e.g., in rpm/dpkg builds (Debian #676461). 3051 + add rpm- and dpkg-scripts, to test those build-environments. 3052 The resulting packages are used only for testing. 3053 3054 20120602 3055 + add kdch1 aka "Remove" to vt220 and vt220-8 entries -TD 3056 + add kdch1, etc., to qvt108 -TD 3057 + add dl1/il1 to some entries based on dl/il values -TD 3058 + add dl to simpleterm -TD 3059 + add consistency-checks in tic for insert-line vs delete-line 3060 controls, and insert/delete-char keys 3061 + correct no-leaks logic in infocmp when doing comparisons, fixing 3062 duplicate free of entries given via the command-line, and freeing 3063 entries loaded from the last-but-one of files specified on the 3064 command-line. 3065 + add kdch1 to wsvt25 entry from NetBSD CVS (reported by David Lord, 3066 analysis by Martin Husemann). 3067 + add cnorm/civis to wsvt25 entry from NetBSD CVS (report/analysis by 3068 Onno van der Linden). 3069 3070 20120526 3071 + extend -c and -n options of infocmp to allow comparing more than two 3072 entries. 3073 + correct check in infocmp for number of terminal names when more than 3074 two are given. 3075 + correct typo in curs_threads.3x (report by Yanhui Shen on 3076 freebsd-hackers mailing list). 3077 3078 20120512 3079 + corrected 'op' for bterm (report by Samuel Thibault) -TD 3080 + modify test/background.c to demonstrate a background character 3081 holding a colored ACS_HLINE. The behavior differs from SVr4 due to 3082 the thick- and double-line extension (cf: 20091003). 3083 + modify handling of acs characters in PutAttrChar to avoid mapping an 3084 unmapped character to a space with A_ALTCHARSET set. 3085 + rewrite vt520 entry based on vt420 -TD 3086 3087 20120505 3088 + remove p6 (bold) from opus3n1+ for consistency -TD 3089 + remove acs stuff from env230 per clues in Ingres termcap -TD 3090 + modify env230 sgr/sgr0 to match other capabilities -TD 3091 + modify smacs/rmacs in bq300-8 to match sgr/sgr0 -TD 3092 + make sgr for dku7202 agree with other caps -TD 3093 + make sgr for ibmpc agree with other caps -TD 3094 + make sgr for tek4107 agree with other caps -TD 3095 + make sgr for ndr9500 agree with other caps -TD 3096 + make sgr for sco-ansi agree with other caps -TD 3097 + make sgr for d410 agree with other caps -TD 3098 + make sgr for d210 agree with other caps -TD 3099 + make sgr for d470c, d470c-7b agree with other caps -TD 3100 + remove redundant AC_DEFINE for NDEBUG versus Makefile definition. 3101 + fix a back-link in _nc_delink_entry(), which is needed if ncurses is 3102 configured with --enable-termcap and --disable-getcap. 3103 3104 20120428 3105 + fix some inconsistencies between vt320/vt420, e.g., cnorm/civis -TD 3106 + add eslok flag to dec+sl -TD 3107 + dec+sl applies to vt320 and up -TD 3108 + drop wsl width from xterm+sl -TD 3109 + reuse xterm+sl in putty and nsca-m -TD 3110 + add ansi+tabs to vt520 -TD 3111 + add ansi+enq to vt220-vt520 -TD 3112 + fix a compiler warning in example in ncurses-intro.doc (Paul Waring). 3113 + added paragraph in keyname manpage telling how extended capabilities 3114 are interpreted as key definitions. 3115 + modify tic's check of conflicting key definitions to include extended 3116 capability strings in addition to the existing check on predefined 3117 keys. 3118 3119 20120421 3120 + improve cleanup of temporary files in tic using atexit(). 3121 + add msgr to vt420, similar DEC vtXXX entries -TD 3122 + add several missing vt420 capabilities from vt220 -TD 3123 + factor out ansi+pp from several entries -TD 3124 + change xterm+sl and xterm+sl-twm to include only the status-line 3125 capabilities and not "use=xterm", making them more generally useful 3126 as building-blocks -TD 3127 + add dec+sl building block, as example -TD 3128 3129 20120414 3130 + add XT to some terminfo entries to improve usefulness for other 3131 applications than screen, which would like to pretend that xterm's 3132 title is a status-line. -TD 3133 + change use-clauses in ansi-mtabs, hp2626, and hp2622 based on review 3134 of ordering and overrides -TD 3135 + add consistency check in tic for screen's "XT" capability. 3136 + add section in terminfo.src summarizing the user-defined capabilities 3137 used in that file -TD 3138 3139 20120407 3140 + fix an inconsistency between tic/infocmp "-x" option; tic omits all 3141 non-standard capabilities, while infocmp was ignoring only the user 3142 definable capabilities. 3143 + improve special case in tic parsing of description to allow it to be 3144 followed by terminfo capabilities. Previously the description had to 3145 be the last field on an input line to allow tic to distinguish 3146 between termcap and terminfo format while still allowing commas to be 3147 embedded in the description. 3148 + correct variable name in gen_edit.sh which broke configurability of 3149 the --with-xterm-kbs option. 3150 + revert 2011-07-16 change to "linux" alias, return to "linux2.2" -TD 3151 + further amend 20110910 change, providing for configure-script 3152 override of the "linux" terminfo entry to install and changing the 3153 default for that to "linux2.2" (Debian #665959). 3154 3155 20120331 3156 + update Ada95/configure to use CF_DISABLE_ECHO (cf: 20120317). 3157 + correct order of use-clauses in st-256color -TD 3158 + modify configure script to look for gnatgcc if the Ada95 binding 3159 is built, in preference to the default gcc/cc (suggested by 3160 Nicolas Boulenguez). 3161 + modify configure script to ensure that the same -On option used for 3162 the C compiler in CFLAGS is used for ADAFLAGS rather than simply 3163 using "-O3" (suggested by Nicolas Boulenguez) 3164 3165 20120324 3166 + amend an old fix so that next_char() exits properly for empty files, 3167 e.g., from reading /dev/null (cf: 20080804). 3168 + modify tic so that it can read from the standard input, or from 3169 a character device. Because tic uses seek's, this requires writing 3170 the data to a temporary file first (prompted by remark by Sven 3171 Joachim) (cf: 20000923). 3172 3173 20120317 3174 + correct a check made in lib_napms.c, so that terminfo applications 3175 can again use napms() (cf: 20110604). 3176 + add a note in tic.h regarding required casts for ABSENT_BOOLEAN 3177 (cf: 20040327). 3178 + correct scripting for --disable-echo option in test/configure. 3179 + amend check for missing c++ compiler to work when no error is 3180 reported, and no variables set (cf: 20021206). 3181 + add/use configure macro CF_DISABLE_ECHO. 3182 3183 20120310 3184 + fix some strict compiler warnings for abi6 and 64-bits. 3185 + use begin_va_copy/end_va_copy macros in lib_printw.c (cf: 20120303). 3186 + improve a limit-check in infocmp.c (Werner Fink): 3187 3188 20120303 3189 + minor tidying of terminfo.tail, clarify reason for limitation 3190 regarding mapping of \0 to \200 3191 + minor improvement to _nc_copy_termtype(), using memcpy to replace 3192 loops. 3193 + fix no-leaks checking in test/demo_termcap.c to account for multiple 3194 calls to setupterm(). 3195 + modified the libgpm change to show previous load as a problem in the 3196 debug-trace. 3197 > merge some patches from OpenSUSE rpm (Werner Fink): 3198 + ncurses-5.7-printw.dif, fixes for varargs handling in lib_printw.c 3199 + ncurses-5.7-gpm.dif, do not dlopen libgpm if already loaded by 3200 runtime linker 3201 + ncurses-5.6-fallback.dif, do not free arrays and strings from static 3202 fallback entries 3203 3204 20120228 3205 + fix breakage in tic/infocmp from 20120225 (report by Werner Fink). 3206 3207 20120225 3208 + modify configure script to allow creating dll's for MinGW when 3209 cross-compiling. 3210 + add --enable-string-hacks option to control whether strlcat and 3211 strlcpy may be used. The same issue applies to OpenBSD's warnings 3212 about snprintf, noting that this function is weakly standardized. 3213 + add configure checks for strlcat, strlcpy and snprintf, to help 3214 reduce bogus warnings with OpenBSD builds. 3215 + build-fix for OpenBSD 4.9 to supply consistent intptr_t declaration 3216 (cf:20111231) 3217 + update config.guess, config.sub 3218 3219 20120218 3220 + correct CF_ETIP_DEFINES configure macro, making it exit properly on 3221 the first success (patch by Pierre Labastie). 3222 + improve configure macro CF_MKSTEMP by moving existence-check for 3223 mkstemp out of the AC_TRY_RUN, to help with cross-compiles. 3224 + improve configure macro CF_FUNC_POLL from luit changes to detect 3225 broken implementations, e.g., with Mac OS X. 3226 + add configure option --with-tparm-arg 3227 + build-fix for MinGW cross-compiling, so that make_hash does not 3228 depend on TTY definition (cf: 20111008). 3229 3230 20120211 3231 + make sgr for xterm-pcolor agree with other caps -TD 3232 + make sgr for att5425 agree with other caps -TD 3233 + make sgr for att630 agree with other caps -TD 3234 + make sgr for linux entries agree with other caps -TD 3235 + make sgr for tvi9065 agree with other caps -TD 3236 + make sgr for ncr260vt200an agree with other caps -TD 3237 + make sgr for ncr160vt100pp agree with other caps -TD 3238 + make sgr for ncr260vt300an agree with other caps -TD 3239 + make sgr for aaa-60-dec-rv, aaa+dec agree with other caps -TD 3240 + make sgr for cygwin, cygwinDBG agree with other caps -TD 3241 + add configure option --with-xterm-kbs to simplify configuration for 3242 Linux versus most other systems. 3243 3244 20120204 3245 + improved tic -D option, avoid making target directory and provide 3246 better diagnostics. 3247 3248 20120128 3249 + add mach-gnu (Debian #614316, patch by Samuel Thibault) 3250 + add mach-gnu-color, tweaks to mach-gnu terminfo -TD 3251 + make sgr for sun-color agree with smso -TD 3252 + make sgr for prism9 agree with other caps -TD 3253 + make sgr for icl6404 agree with other caps -TD 3254 + make sgr for ofcons agree with other caps -TD 3255 + make sgr for att5410v1, att4415, att620 agree with other caps -TD 3256 + make sgr for aaa-unk, aaa-rv agree with other caps -TD 3257 + make sgr for avt-ns agree with other caps -TD 3258 + amend fix intended to separate fixups for acsc to allow "tic -cv" to 3259 give verbose warnings (cf: 20110730). 3260 + modify misc/gen-edit.sh to make the location of the tabset directory 3261 consistent with misc/Makefile.in, i.e., using ${datadir}/tabset 3262 (Debian #653435, patch by Sven Joachim). 3263 3264 20120121 3265 + add --with-lib-prefix option to allow configuring for old/new flavors 3266 of OS/2 EMX. 3267 + modify check for gnat version to allow for year, as used in FreeBSD 3268 port. 3269 + modify check_existence() in db_iterator.c to simply check if the 3270 path is a directory or file, according to the need. Checking for 3271 directory size also gives no usable result with OS/2 (cf: 20120107). 3272 + support OS/2 kLIBC (patch by KO Myung-Hun). 3273 3274 20120114 3275 + several improvements to test/movewindow.c (prompted by discussion on 3276 Linux Mint forum): 3277 + modify movement commands to make them continuous 3278 + rewrote the test for mvderwin 3279 + rewrote the test for recursive mvwin 3280 + split-out reusable CF_WITH_NCURSES_ETC macro in test/configure.in 3281 + updated configure macro CF_XOPEN_SOURCE, build-fixes for Mac OS X 3282 and OpenBSD. 3283 + regenerated html manpages. 3284 3285 20120107 3286 + various improvements for MinGW (Juergen Pfeifer): 3287 + modify stat() calls to ignore the st_size member 3288 + drop mk-dlls.sh script. 3289 + change recommended regular expression library. 3290 + modify rain.c to allow for threaded configuraton. 3291 + modify tset.c to allow for case when size-change logic is not used. 3292 3293 20111231 3294 + modify toe's report when -a and -s options are combined, to add 3295 a column showing which entries belong to a given database. 3296 + add -s option to toe, to sort its output. 3297 + modify progs/toe.c, simplifying use of db-iterator results to use 3298 caching improvements from 20111001 and 20111126. 3299 + correct generation of pc-files when ticlib or termlib options are 3300 given to rename the corresponding tic- or tinfo-libraries (report 3301 by Sven Joachim). 3302 3303 20111224 3304 + document a portability issue with tput, i.e., that scripts which work 3305 with ncurses may fail in other implementations that do no parameter 3306 analysis. 3307 + add putty-sco entry -TD 3308 3309 20111217 3310 + review/fix places in manpages where --program-prefix configure option 3311 was not being used. 3312 + add -D option to infocmp, to show the database locations that it 3313 could use. 3314 + fix build for the special case where term-driver, ticlib and termlib 3315 are all enabled. The terminal driver depends on a few features in 3316 the base ncurses library, so tic's dependencies include both ncurses 3317 and termlib. 3318 + fix build work for term-driver when --enable-wgetch-events option is 3319 enabled. 3320 + use <stdint.h> types to fix some questionable casts to void*. 3321 3322 20111210 3323 + modify configure script to check if thread library provides 3324 pthread_mutexattr_settype(), e.g., not provided by Solaris 2.6 3325 + modify configure script to suppress check to define _XOPEN_SOURCE 3326 for IRIX64, since its header files have a conflict versus 3327 _SGI_SOURCE. 3328 + modify configure script to add ".pc" files for tic- and 3329 tinfo-libraries, which were omitted in recent change (cf: 20111126). 3330 + fix inconsistent checks on $PKG_CONFIG variable in configure script. 3331 3332 20111203 3333 + modify configure-check for etip.h dependencies, supplying a temporary 3334 copy of ncurses_dll.h since it is a generated file (prompted by 3335 Debian #646977). 3336 + modify CF_CPP_PARAM_INIT "main" function to work with current C++. 3337 3338 20111126 3339 + correct database iterator's check for duplicate entries 3340 (cf: 20111001). 3341 + modify database iterator to ignore $TERMCAP when it is not an 3342 absolute pathname. 3343 + add -D option to tic, to show the database locations that it could 3344 use. 3345 + improve description of database locations in tic manpage. 3346 + modify the configure script to generate a list of the ".pc" files to 3347 generate, rather than deriving the list from the libraries which have 3348 been built (patch by Mike Frysinger). 3349 + use AC_CHECK_TOOLS in preference to AC_PATH_PROGS when searching for 3350 ncurses*-config, e.g., in Ada95/configure and test/configure (adapted 3351 from patch by Mike Frysinger). 3352 3353 20111119 3354 + remove obsolete/conflicting fallback definition for _POSIX_SOURCE 3355 from curses.priv.h, fixing a regression with IRIX64 and Tru64 3356 (cf: 20110416) 3357 + modify _nc_tic_dir() to ensure that its return-value is nonnull, 3358 i.e., the database iterator was not initialized. This case is needed 3359 to when tic is translating to termcap, rather than loading the 3360 database (cf: 20111001). 3361 3362 20111112 3363 + add pccon entries for OpenBSD console (Alexei Malinin). 3364 + build-fix for OpenBSD 4.9 with gcc 4.2.1, setting _XOPEN_SOURCE to 3365 600 to work around inconsistent ifdef'ing of wcstof between C and 3366 C++ header files. 3367 + modify capconvert script to accept more than exact match on "xterm", 3368 e.g., the "xterm-*" variants, to exclude from the conversion (patch 3369 by Robert Millan). 3370 + add -lc_r as alternative for -lpthread, allows build of threaded code 3371 in older FreeBSD machines. 3372 + build-fix for MirBSD, which fails when either _XOPEN_SOURCE or 3373 _POSIX_SOURCE are defined. 3374 + fix a typo misc/Makefile.in, used in uninstalling pc-files. 3375 3376 20111030 3377 + modify make_db_path() to allow creating "terminfo.db" in the same 3378 directory as an existing "terminfo" directory. This fixes a case 3379 where switching between hashed/filesystem databases would cause the 3380 new hashed database to be installed in the next best location - 3381 root's home directory. 3382 + add variable cf_cv_prog_gnat_correct to those passed to 3383 config.status, fixing a problem with Ada95 builds (cf: 20111022). 3384 + change feature test from _XPG5 to _XOPEN_SOURCE in two places, to 3385 accommodate broken implementations for _XPG6. 3386 + eliminate usage of NULL symbol from etip.h, to reduce header 3387 interdependencies. 3388 + add configure check to decide when to add _XOPEN_SOURCE define to 3389 compiler options, i.e., for Solaris 10 and later (cf: 20100403). 3390 This is a workaround for gcc 4.6, which fails to build the c++ 3391 binding if that symbol is defined by the application, due to 3392 incorrectly combining the corresponding feature test macros 3393 (report by Peter Kruse). 3394 3395 20111022 3396 + correct logic for discarding mouse events, retaining the partial 3397 events used to build up click, double-click, etc, until needed 3398 (cf: 20110917). 3399 + fix configure script to avoid creating unused Ada95 makefile when 3400 gnat does not work. 3401 + cleanup width-related gcc 3.4.3 warnings for 64-bit platform, for the 3402 internal functions of libncurses. The external interface of courses 3403 uses bool, which still produces these warnings. 3404 3405 20111015 3406 + improve description of --disable-tic-depends option to make it 3407 clear that it may be useful whether or not the --with-termlib 3408 option is also given (report by Sven Joachim). 3409 + amend termcap equivalent for set_pglen_inch to use the X/Open 3410 "YI" rather than the obsolete Solaris 2.5 "sL" (cf: 990109). 3411 + improve manpage for tgetent differences from termcap library. 3412 3413 20111008 3414 + moved static data from db_iterator.c to lib_data.c 3415 &nb
https://ncurses.scripts.mit.edu/?p=ncurses.git;a=blob;f=NEWS;h=27e2f56a70d00f059be5a8ac62d210c82a2c1132;hb=31418a0e4a6f75ceffc9fee20ddbe390209a4ef4
CC-MAIN-2022-33
refinedweb
25,836
65.83
Error in my first Qt5 program Hi all, I have installed Qt5 and python 3.6.0. I am unable to run a simple hello world program. See below my error: from PyQt5.QtWidgets import QApplication, QLabel Can someone please help. I think there is a problem with my Qt5 Install on my Mac OS X El Capitan. Can someone please help me with the right commands to install Qt5 or Qt4? Appreciate your help! :) Hi and welcome to devnet, How did you install both ? Since you are using Python and PyQt, the most simple way is to create a virtual environment using python's virtualenv, activate it and then call pip install PyQt5. Hi Thanks for your help! Yes I did create a venv folder and I think I ran the above command to install PyQt5. Do I have to place my .py file inside that folder and run it? Nitin. No, you have to ensure that you properly activated the virtual environment before installing anything in it and also before running your application. From the looks of it, you have rather installed PyQt5 system wide. I tried to install PyQt5 all over again, activate it and when I tried to run the program I got the following error: (qtproject) (base) Nitins-MacBook-Pro:pluralsight Nitin$ python3 structure.py Traceback (most recent call last): File "structure.py", line 1, in <module> from PyQt5.QtWidgets import * ModuleNotFoundError: No module named 'PyQt5.QtWidgets' Do you know how I can import these modules? Nitin - jsulm Qt Champions 2018 @Mikenitin92 said in Error in my first Qt5 program: from PyQt5.QtWidgets import * Works for me (I installed PyQt5 using pip3 system wide), if it does not for you then you either did not install PyQt5 correctly or you're not using the virtual environment where you installed PyQt5. Did you consider what @SGaist wrote in hes last post in this thread? Hi all, I have done the following steps: - I already have Python 3.6.0 installed system wide. - Created a new virtual environment and activated it - pip install virtualenv - virtualenv nitin_venv - cd nitin_venv - source bin/activate - Install PyQt5 - pip install PyQt5 - Placed a . py file in my virtual environment(nitin_venv folder) and tried to execute it - python3 ~/.nitin_venv/sample.py Then I received the import error, not sure where I am doing it wrong. Might be a silly question but did you check that python3is really the one from your virtual environment ? Run which python3in the terminal you use to execute your script. That gave me ~/.nitin_venv/bin/python. So, I think python is from my virtual environment. Also, Do I have to run the my python program from my virtual environment? The file doesn't need to be in there, the virtual environment is there to provide you with the dependencies you need in a controlled fashion. Can you show the code you are using to test that ? Sure. Here it is! from PyQt5.QtWidgets import * import sys app = QApplication([]) label = QLabel('Hello world!') label.show() app.exec_() @Mikenitin92 If your problem seems to be something about not being to find libraries such that Qt apps can't be run then this probably has nothing to do with it. But I don't think you can write a Qt app to just "display a label nowhere" as per your code (you need a window or a dialog etc.). Did you get this code from somewhere/do you have a problem when it runs, or are you still at the ImportError just trying to get going? Hi, I have tested with a new sample file which is: print ("Hi") from PyQt5.QtWidgets import * And this is the output: Hi Traceback (most recent call last): File "/Users/Nitin/PycharmProjects/pluralsight/nitin_venv/lib/test.py", line 2, in <module> from PyQt5.QtWidgets import * @Mikenitin92 said in Error in my first Qt5 program: import sys app = QApplication([]) Unrelated but to be clean, it should be sys.argvas parameter of QApplication. What version of PyQt do you have installed ? Did you try to uninstall your system version of PyQt and re-install it in your virtual environment ? Hello, I have PyQt5. I have deleted the virtual folder and created it again, activated and installed PyQt5. Did I do it right? Yes you did, however PyQt5 is the package name, not its version. However since you just now installed it, it should be the latest version available. Did you also uninstall the version you have installed system wide ? I don't think I have installed PyQt5 system wide. Do you know how I can check if it is installed system wide? @Mikenitin92 said in Error in my first Qt5 program: /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/PyQt5/QtWidgets.so That path makes me think that it is since it's the OS provided Python framework.
https://forum.qt.io/topic/103273/error-in-my-first-qt5-program/1
CC-MAIN-2019-30
refinedweb
814
74.9
Abstract classes are classes that are not fully implemented because some of their methods represent abstract concepts. For example, if I had a Geometry class that calculated the area and perimeter of different shapes, the methods would be specific to each different shape (calculating the area of a circle is different than calculating the area of a square). Therefore, the Geometry class would be an abstract class that had subclasses representing the different shapes (circles, triangles, squares, etc). Below is an example: public abstract class Geometry { private String shape; public Geometry(String shape) { this.shape = shape; } // not all methods in abstract classes must be abstract public String getShapeName() { return shape; } // abstract methods have no implementation code public abstract double perimeter(); public abstract double area(); } /* classes which extend abstract classes must implement all of their abstract methods */ public class Square extends Geometry { public double sideLength; public Square(double sideLength, String name) { super(name); this.sideLength = sideLength; } public double perimeter() { return 4 * sideLength; } public double area() { return Math.pow(side, 2); } } Abstract classes have a key few rules: If a class has any abstract methods, it must be declared an abstract class (by using the abstract keyword). Any subclass of an abstract class must implement all of the superclass’s abstract methods. Instances of abstract classes cannot be created (because they are incomplete). Constructors are optional in abstract classes. In order to avoid rule #3, create an object with the type of the abstract class and assign it to an instance of the subclass, as shown below: Geometry squareProperties = new Square(5, "square"); Overall, abstract classes are very useful when creating classes/methods that cannot be fully defined without more specific information. Lesson Quiz 1. Which of the following is not a feature of abstract classes? 2. If Car is an abstract class, what must be wrong with the below code? Car myCar; // variable declaration, line 1 myCar = new Car("Toyota"); // variable assignment, line 2 Written by Chris Elliott Notice any mistakes? Please email us at [email protected] so that we can fix any inaccuracies.
https://teamscode.com/learn/ap-computer-science/abstract-classes/
CC-MAIN-2019-04
refinedweb
343
50.36
bind - bind a name to a socket #include <sys/types.h> #include <sys/socket.h> int bind(int sockfd, struct sockaddr *my_addr,.) Binding a name in the UNIX domain creates a socket in the file system that must be deleted by the caller when it is no longer needed (using unlink(2)). The rules used in name binding vary between communication domains. Consult the manual entries in section 4 for detailed information.. The following errors are specific to UNIX domain (AF_UNIX) sockets: EINVAL The addr_len was wrong, or the socket was not in the AF_UNIX family. EROFS The socket inode would reside on a read-only file system. EFAULT my_addr points outside your accessible address space. ENAMETOOLONG my_addr is too long. ENOENT The file does not exist. ENOMEM Insufficient kernel memory was available. ENOTDIR A component of the path prefix is not a directory. EACCES Search permission is denied on a component of the path prefix. ELOOP my_addr contains a circular reference (i.e., via a symbolic link) The bind function call appeared in BSD 4.2. accept(2), connect(2), listen(2), socket(2), getsock- name(2)
http://www.linuxonlinehelp.com/man/bind.html
crawl-001
refinedweb
188
61.12
Go, Docker, Google Cloud: A Microservice HOWTO Saying that software engineers today enjoy MicroServices (MS) ‘a little bit’ is like saying people enjoy chocolate covered bacon ‘a little bit’. MicroServices does for internet systems what function calls do for assembly: abstraction without losing functionality. A confluence of fortunate technologies arrived in the last few years that can make MS possible or at least much more easier. Docker is the biggest one. The others can start holy wars so I’ll just remain neutral. I write what I know, OK? We’re going to use a simple MS example that generates ascii art from an uploaded image using Docker, Go, and Google Cloud Platform. Go fork the (), and let’s get started! :D Go is made for MicroServices Writing C on UNIX is what God intended but Go on a Docker image is both fun and minimally unorthodox so you only need to pay a minimal penance. Let’s go for it! Go was written by Google for a lot of the kind of problems a place like Google would face: lots of scalable software that is easy to build and deploy. Building Go programs is waaay easier than it was with C/C++. No complex linking. And co-routines are a dream. Here is a very basic, simplistic microservice. Serve up a path and output a result while listening on port 8080. package main import ( "fmt" "net/http" "image" _ "image/jpeg" _ "image/gif" "image/color" "github.com/nfnt/resize" "bytes" "reflect" "log" "strconv" ) func handler(w http.ResponseWriter, r *http.Request) { if r.Method == "POST" { dimension, err := strconv.Atoi(r.URL.Path[1:]) if err != nil { dimension = 80 } if (dimension > 256) || (dimension < 0) { dimension = 256 } file, _, err := r.FormFile("uploadfile") if err != nil { fmt.Println(err) return } defer file.Close() img, _, err := image.Decode(file) if err != nil { log.Print(err) return } fmt.Fprintf(w, "%s", Convert2Ascii(ScaleImage(img, dimension))) } } // var ASCIISTR = "MND8OZ$7I?+=~:,.." // func ScaleImage(img image.Image, w int) (image.Image, int, int) { sz := img.Bounds() h := (sz.Max.Y * w * 10) / (sz.Max.X * 16) img = resize.Resize(uint(w), uint(h), img, resize.Lanczos3) return img, w, h } // func Convert2Ascii(img image.Image, w, h int) []byte { table := []byte(ASCIISTR) buf := new(bytes.Buffer) for i := 0; i < h; i++ { for j := 0; j < w; j++ { g := color.GrayModel.Convert(img.At(j, i)) y := reflect.ValueOf(g).FieldByName("Y").Uint() pos := int(y * 16 / 255) _ = buf.WriteByte(table[pos]) } _ = buf.WriteByte('\n') } return buf.Bytes() } func main() { http.HandleFunc("/v1", handler) http.ListenAndServe(":8080", nil) } Building the Docker Image You should note the github repository is arranged like this. . ├── Dockerfile ├── README.md └── image2asciiart.go Building the docker image is as simple as this docker build -tus.gcr.io/goasciiart-171107/my-golang-app . Typically a directory structure for a docker build would have a Dockerfile in it’s own directory. This is by design The <src>path must be inside the context of the build; you cannot ADD ../something /something, because the first step of a docker buildis to send the context directory (and subdirectories) to the docker daemon. You can use the -f option to point to another directory. . ├── README.md ├── build │ ├── Dockerfile │ ├── asdf.exe │ └── data/ ├── node.py └── tests You can run the docker image locally: docker run -it -p 8080:8080 --rm --name my-running-appus.gcr.io/goasciiart-171107/my-golang-app And test it out, issue a curl command like so: $ curl -F "uploadfile=@wilder.jpg" localhost:8080/ I=77$I$7$Z$$ZZZI:.:=77$OZ8DNN8O88 $+7$$777$Z$$OOZ$?,,+7$ODNM88DOO88 OZOOOOZZ$ZOO8OZZ$$$7$O8D888D8OON8 OZZZ$$77$$$I???+++++??II77$$$$OND ++++++=IODNI+?+??IIIII77$$$ZZZO8D I???????ZOOIII????III777777$$$Z$$ ?++?+?++I8D8$?+=IOZ????III777$$$Z IIIIIIII7OMMN$IZDNZI77IIII7$7$$77 II77III7I$$$7I$ZZOO7Z$?I7I7??I777 77I$I77777777$$ZOOZ77777$$77$ZZ$7 7$77777777777I777$7777777I777$$$$ $$77$77777777$$7777$77$777777$$$Z 77777$Z$$$$$$$777$$7$$7777$ZZ$ZZZ $ Note that the -F option is used to submit a form object with a parameter called uploadfile. Google Compute Cloud AWS feels like a Chinese place that also sells friend chicken and pizza. The menu is all over the place; it was fun at first but half a score years later, it’s overwhelming. AWS is the place that you recommend to everyone else except your self. AWS: a platform that both is and isn’t technically obtuse until observed. I look at the Google Compute Cloud environment and…and I think the future is going to be OK. gcloud Command Line Tool First thing’s first: install the gcloud utility. gcloud makes it easier to interface with GCP compared to the rainbow of other cli tools that we’ve come to be used to. GCP works in ‘projects’. This keeps resources split. If you upload a docker image to the wrong project, the other projects won’t necessarily see it. Eventually you’ll get a project built. Do you see the highlighted img2ascii-171905 code? Make note of it. There are a few more moving parts we’ll need. Docker Compute Registry Remember back when we built the docker image? We need to tag it in a particular way. GCP wants it that way. docker build -t us.gcr.io/img2ascii-171905/my-golang-app . We need to now push the docker image to the Google cloud gcloud docker — push us.gcr.io/goasciiart-171107/my-golang-app Kubernetes Kubernetes is the main way to get clusters of Docker images running in the cloud, either Google’s cloud or not. Google’s offering is called Google Container Engine. Creating a Container Engine Cluster Creating a cluster is super easy with gcloud. gcloud config set compute/zone us-central1-b Creating a default-configured container cluster will result in 3 new instances of VMs running. These will cost you money. gcloud container clusters create img2ascii gcloud auth application-default login kubectl run img2ascii-node --image=gcr.io/google-samples/node-hello:1.0 --port=8080 Be forewarned that the LoadBalancer can actually cost you extra money kubectl expose deployment img2ascii-node --type="LoadBalancer" kubectl get service img2ascii-node You should see an external IP listed under EXTERNAL-IP after a few seconds. Extras Q: My API doesn’t get exposed to the external environment. A: If you try to re-run the curl command and get no output or a hung response, what has probably happened is you told kubernetes to run an image it can’t find. Run glcoud projects list to see if you have other projects created and then use gcloud config set project img2ascii-171905to set the project you want as the default. You should be able to re-run the kubectl run command. Q: How Can I see the Kubernetes console? A: Run the following gcloud containers get-credentials img2ascii kubectl proxy You should be able to browse over to localhost:8001/ui and see the dashboard Q: What about security? A: This was a demo. Just don’t get hacked, ok?
https://medium.com/google-cloud/go-docker-google-cloud-a-microservice-howto-c4f3b50910f
CC-MAIN-2019-04
refinedweb
1,175
60.92
I learned a little more about stack traces in .NET today… in a very painful manner… but, lesson learned! Hopefully someone else will be able to learn this lesson without having to spend 4 hours on it like I did. Take a look at this stack trace that I was getting in my Compact Framework app, today: 1: System.NullReferenceException 2: Message="NullReferenceException" 3: StackTrace: 4: at TrackAbout.Mobile.UI.CustomControls.TABaseUserControl.<EndInit>b__8(Object o, EventArgs e) 5: at System.ComponentModel.Component.Dispose(Boolean disposing) 6: at System.Windows.Forms.Control.Dispose(Boolean disposing) 7: at TrackAbout.Mobile.UI.Views.BaseForms.TAForm.Dispose(Boolean disposing) 8: at TrackAbout.Mobile.UI.Views.GeneralActions.SetExpirationDateView.Dispose(Boolean disposing) 9: at System.ComponentModel.Component.Dispose() 10: etc. 11: etc. 12: ... In this stack trace, on line 4, is one very important detail: an anonymous method signature and the parent method that defines it. After several hours of debugging and finally turning on the “catch all” feature for CLR exceptions in Visual Studio, I discovered that line 4 actually translates to this code: 1: public virtual void EndInit() 2: { 3: ParentForm = FormUtils.GetParentFormOf(this) as TAForm; 4: if (ParentForm == null) return; 5: 6: ParentForm.Closing += FormClose; 7: ParentForm.Activated += (o, e) => ParentActivatedHandler(o, e); 8: ParentForm.Deactivate += (o, e) => ParentDeactivateHandler(o, e); 9: ParentForm.Disposed += (o, e) => ParentDisposedHandler(o, e); 10: 11: if (ControlEndInit != null) 12: { 13: ControlEndInit(this, EventArgs.Empty); 14: } 15: } Let me translate this line stack trace into this method… the namespace in the stacktrace is obvious… so is the username. The first part to note is the <EndInit>. Apparently this means that the EndInit method contains the code that is throwing the exception, but is not actually firing the code that is causing the exception. The next part is where we find what is throwing the exception. Apparently b__8(Object o, EventArgs e) tells me that the failing code in question is an anonymous method. The CLR naming of this method seems cryptic, but also seems like it might be something useful… Examining the entire method call: TrackAboutControl.<EndInit>b__8(Object o, EventArgs e) what I understand this to be saying is “The EndInit method is defining an anonymous method with a standard event signature at line 8 of the method.” Now I’m not entire sure that “line 8 of the method” is what this anonymous method name means… but it fits in this case… it matches up to the line that was causing the problem. The problem in this specific case was that this line had a null reference: ParentForm.Disposed += (o, e) => ParentDisposedHandler(o, e); The ParentDisposedHandler is defined as an event earlier in the class, and since it had no subscribers, it was null. That was easy to fix… just add a null ref check or define the event with a default value of “= delegate{ }”. So… 4 hours into debugging this issue, it turned out to be 1 line of anonymous method calls. The stack trace was cryptic and confusing to me at first. I hope to retain this lesson and hope to be able to pass this on to someone else that sees a cryptic stack trace such as this, and same someone the same heartache and headache that I went through today. Get The Best JavaScript Secrets! Get the trade secrets of JavaScript pros, and the insider info you need to advance your career! Post Footer automatically generated by Add Post Footer Plugin for wordpress.
http://lostechies.com/derickbailey/2010/03/19/net-stack-traces-and-anonymous-methods/
CC-MAIN-2015-06
refinedweb
582
56.55
I'm trying to write a python script which will traverse through a directory recursively and create files of different sizes inside all of them. So far I have reached here. Well I haven't written any mechanism for creating files with different sizes but I need it. I very well know there's something wrong with the file creation logic I have written. Any help is highly appreciable. My code: #!/usr/bin/python import os import uuid for dirs in os.walk('/home/zarvis'): print dirs filename = str(uuid.uuid4()) size = 1000000 with open(filename, "wb") as f: f.write(" " * size) Don't use a fixed size. Use random.randint to create a random size. Use os.path.join to build the full path to a file. import os import uuid import random for dirs in os.walk("/home/zarvis"): d = dirs[0] filename = str(uuid.uuid4()) size = random.randint(1, 100) with open(os.path.join(d, filename), "w") as f: f.write(" " * size)
https://codedump.io/share/QNTchkWwuKgq/1/create-files-of-different-sizes-inside-directories-recursively-in-python
CC-MAIN-2018-09
refinedweb
166
79.67
Python Contents Accessing Open Babel with Python There are two ways to access the Open Babel library using Python: - The openbabelmodule, a direct wrapper of the Open Babel C++ library, created using the SWIG package. - The pyopenbabelmodule, a Pythonic wrapper around the openbabelmodule. The openbabel module The openbabel module provides direct access to the C++ Open Babel library from Python. This wrapper. The pyopenbabel module The motivation behind the pyopenbabel module is to provide a more Pythonic wrapper.) The API for pyopenbabel will soon be available here. Until then, here are some examples of its use: from pyopenbabel import * mymol = readstring("smi","C1=CC=CS1") print "The number of atoms is %d" % len(mymol.atoms) print "These atoms have the following atomic numbers:" for atom in mymol: print "\t%d" % atom.atomicnum Note on Compiling the SWIG wrapper If you need to recompile the SWIG wrapper for the library, make sure you have the latest version of SWIG installed and run 'configure' as follows: ./configure --enable-maintainer-mode Running 'make' as usual should recreate the SWIG wrappers.
https://openbabel.org/w/index.php?title=Python&oldid=1430
CC-MAIN-2022-33
refinedweb
177
52.6
Welcome to Core Java Quiz. Java is an object-oriented programming language. Core Java Quiz In this quiz, you will be tested on Core Java basics and OOPS concepts. There are some code snippets too to test your basic Java coding skills. Some of the questions have multiple answers. You can click on the “Reveal Answer” button for the correct answer and explanation. Give it a try and share it with others if you like it. 1. Which of the below is valid way to instantiate an array in java? A. int myArray [] = {1, 3, 5}; B. int myArray [] [] = {1,2,3,4}; C. int [] myArray = (5, 4, 3); D. int [] myArray = {“1”, “2”, “3”}; Click to Reveal Answer Correct Answer: A int [] myArray = {“1”, “2”, “3”}; is invalid because String can’t be converted to an int. int [] myArray = (5, 4, 3); is invalid because array elements should be defined in curly braces ({}). int myArray [] [] = {1,2,3,4}; is invalid because myArray is a two-dimensional array whereas in this case it’s being defined as a one-dimensional array. The compiler will complain as Type mismatch: cannot convert from int to int[]. 2. Which of the below are reserved keyword in Java? A. array B. goto C. null D. int Click to Reveal Answer Correct Answer: B, D The goto and int are reserved keywords in java. array and null are not keywords in java. 3. What will happen if we try to compile and run below program? interface Foo{ int x = 10;} public class Test { public static void main(String[] args) { Foo.x = 20; System.out.println(Foo.x); } } A. Prints 10 B. Prints 20 C. Compile Time Error D. Runtime error because Foo.x is final. Click to Reveal Answer Correct Answer: C By default, any field of the interface is public, static, and final. So we can’t change is, hence compile-time error at the statement Foo.x = 20;. 4. What will be the output of the below program? public class Test { public static void main(String[] args) { char c = 65; System.out.println("c = " + c); } } A. Compile Time Error B. Prints “c = A” C. Runtime Error D. Prints “c = 65” Click to Reveal Answer Correct Answer: B Java compiler tries to automatically convert int to char. Since 65 gets converted to A, hence output will be “c = A”. The char values range is from u0000 to uffff. So char c = 65535; is valid but char c = 65536; will give compile time error. 5. What will be output of below program? public class Test { public void main(String[] args) { int x = 10*20-20; System.out.println(x); } } A. Runtime Error B. Prints 180 C. Prints 0 D. Compile-time error. Click to Reveal Answer Correct Answer: A Runtime error because main method is not static. The error message will be Main method is not static in class Test, please define the main method as: public static void main(String[] args) 6. What are the valid statements for static keyword in Java? A. We can have static block in a class. B. The static block in a class is executed every time an object of class is created. C. We can have static method implementations in interface. D. We can define static block inside a method. Click to Reveal Answer Correct Answers: A, C We can have static block in a class, it gets executed only once when class loads. From java 8 onwards, we can have static method implementations in interfaces. 7. Select all the core concepts of OOPS. A. Abstraction B. Inheritance C. Interface D. Polymorphism E. Generics Click to Reveal Answer Correct Answers: A, B, D OOPS core concepts are; - Abstraction - Encapsulation - Polymorphism - Inheritance - Composition - Association - Aggregation Read more at OOPS Concepts 8. Which of the following statements are true for inheritance in Java? A. The “extend” keyword is used to extend a class in java. B. You can extend multiple classes in java. C. Private members of the superclass are accessible to the subclass. D. We can’t extend Final classes in java. Click to Reveal Answer Correct Answer: D Inheritance is one of the core concepts in Java. You should be familiar with it. Please read the following articles to learn more about the answer choices – Inheritance in Java, Multiple Inheritance in Java. 9. What will be the output of below program? package com.journaldev.java; public class Test { public static void main(String[] args) { Super s = new Subclass(); s.foo(); } } class Super { void foo() { System.out.println("Super"); } } class Subclass extends Super { static void foo() { System.out.println("Subclass"); } } A. Compile time error B. Super C. Subclass D. Runtime error Click to Reveal Answer Correct Answer: A Subclass foo() method can’t be static, it will give compile time error This static method cannot hide the instance method from Super. 10. What will be the output of below program? package com.journaldev.java; public class Test { public static void main(String[] args) { Subclass s1 = new Subclass(); s1.foo(); // line 6 Super s = new Subclass(); s.foo(); // line 8 } } class Super { private void foo() { System.out.println("Super"); } } class Subclass extends Super { public void foo() { System.out.println("Subclass"); } } A. Compile time error at line 6 B. Compile time error at line 8 C. Compile time error at both line 6 and 8 D. Works fine and prints “Subclass” two times. Click to Reveal Answer Correct Answer: B Compile time error at line 8 because Super class foo() method is private. The error message is The method foo() from the type Super is not visible. 11. What will be the output of below program? import java.io.IOException; public class Test { public static void main(String[] args) { try { throw new IOException("Hello"); } catch (IOException | Exception e) { System.out.println(e.getMessage()); } } } A. Compile-time error B. Prints “Hello” C. Runtime Error Click to Reveal Answer Correct Answer: A Compile-time error as The exception IOException is already caught by the alternative Exception. 12. What will be the output of below program? public class Test { public static void main(String[] args) { String x = "abc"; String y = "abc"; x.concat(y); System.out.print(x); } } A. abcabc B. abc C. null Click to Reveal Answer Correct Answer: B x.concat(y); will create a new string but it’s not assigned to x, so the value of x is not changed. 13. Which of the below are unchecked exceptions in java? A. RuntimeException B. ClassCastException C. NullPointerException D. IOException Click to Reveal Answer Correct Answer: A, B, C RuntimeException and its subclasses are unchecked exceptions. Unchecked exceptions do not need to be declared in a method or constructor’s throws clause. 14. What will be the output of below program? package com.journaldev.java; import java.io.IOException; public class Test { public static void main(String[] args) { try { throw new Exception("Hello "); } catch (Exception e) { System.out.print(e.getMessage()); } catch (IOException e) { System.out.print(e.getMessage()); } finally { System.out.println("World"); } } } A. Compile-time error B. Hello C. Hello World D. Hello Hello World Click to Reveal Answer Correct Answer: A Compile-time error Unreachable catch block for IOException. It is already handled by the catch block for Exception. 15. Which of the following statement(s) are true for java? A. JVM is responsible for converting Byte code to the machine-specific code. B. We only need JRE to run java programs. C. JDK is required to compile java programs. D. JRE doesn’t contain JVM Click to Reveal Answer Correct Answer: A, B, C For a complete explanation, read JDK, JRE, and JVM. 16. Can we have two main methods in a java class? A. Yes B. No Click to Reveal Answer Correct Answer: A This was a tricky question. We can have multiple methods having name as “main” in java through method overloading. 17. Which of the following statements are true about annotations in java? A. @interface keyword is used to create custom annotation B. @Override is a built-in annotation in java C. Annotations can’t be applied to fields in a class. D. @Retention is one of the meta annotation in java. E. Java annotation information gets lost when class is compiled. Click to Reveal Answer Correct Answer: A, B, D For a complete explanation, read Java Annotations. 18. Which of the following statements are true about Enum in java? A. All java enum implicitly extends java.lang.Enum class. B. Java enum can implement interfaces. C. We can create instance of enum using new operator. D. Enums can’t be used in switch statements. E. Enum constants are implicitly static and final. Click to Reveal Answer Correct Answer: A, B, E Read more at Enum in Java. 19. Which of the below are built-in class loaders in java? A. Bootstrap Class Loader B. Extensions Class Loader C. Runtime Class Loader D. System Class Loader Click to Reveal Answer Correct Answer: A, B, D Read more at Classloaders in Java. 20. What will be the output of below program? package com.journaldev.util; public class Test { public static String toString() { System.out.println("Test toString called"); return ""; } public static void main(String args[]) { System.out.println(toString()); } } A. “Test toString called” B. Compile-time error C. “Test@7fh2bd8” (Object class toString() method is being called) Click to Reveal Answer Correct Answer: B We will get a compile-time error because we can’t have an Object class method overridden with the static keyword. The Object class has toString() method. You will get a compile-time error as “This static method cannot hide the instance method from Object”. 21. What will be the output of below program? public class Test { public static void main(String[] args) { String s1 = "abc"; String s2 = "abc"; System.out.println("s1 == s2 is:" + s1 == s2); } } A. s1 == s2 is:true B. false C. s1 == s2 is:false D. true Click to Reveal Answer Correct Answer: B The given statements output will be “false” because in java + operator precedence is more than == operator. So the given expression will be evaluated to “s1 == s2 is:abc” == “abc” i.e false. Conclusion I hope you liked the Core Java Quiz. If you think I have missed some important areas, let me know and I will add some more tricky quiz questions here. Next Quiz: Java String Quiz The last question was the final nail in the coffin. Extremely good questions sir ,Keep making more!! Really nice que’s. please update more tricky que’s great work, thanks LOL , at first question , answer is wrong The correct will be int[] array={1,2,3}; Not int array[] = {1,2,3}; Did you ever try to run it? I did and here it is from the Shell. the page shows “There is no question” for me, in all the quizzes! why? There was some issue, which has been fixed now. Thanks, for Question 5, there is no main method in the code, that be static or not Ah, I mistakenly removed it while doing some editing. I have fixed it. The JRE includes the JVM, which is what actually interprets the byte code and runs your program. To do this the JVM uses libraries and other files provided by the JRE. in question 4 i have copy your code and getting out is ‘c = A’ i have selected that option only but it says wrong option Sorry about that, some error happened when I was editing the question. I have fixed it. Thanks for the quiz. 15th question blew my mind! I’m not sure what java version this was written against, but you most certainly can use Enums in switch statements. You couldn’t use strings in switch statements before Java 7, but even before that you could use Enums. Even the link in the description for why “Enums can’t be used in switch statements.” says that they can be used in switch statements. Yes, you are right and so does the question. You have to select statements that are true for Enum. Java Runtime Environment (JRE) contains JVM, class libraries, and other supporting files. Do you have a source code when making this quiz, did you use php for this? Hello Pankaj, Your site has some problem. I have attempted only 5 questions, and finished my quiz.but it showing all the questions are attempted. with incorrect answer. Yes, when you finished the quiz. Any question you didn’t attempted will be considered as incorrectly answered. Just like any exams, if you won’t provide answer to a question, you won’t get any marks for it. Are you sure about question 8? I just copied and paste your code on IntelliJ and I got compilation error. Question 6>> WRONG>> My output is Super! I get an error, too, but the question was >> What will be the output of below program? Did you run the code in Eclipse, use command line and you will see that output is correct? Check this thread to understand why you got the output. Looks like Pankaj sir has made some changes to this set of questions. Earlier I was completely correct, but now the marked answers are showing as the wrong answer but explanation is correct. I also did google and tried output code in eclipse. I am double sure about this mistake. Pankaj sir plz cross check this issue. The explanation shows correct answers and I have marked same answer but it’s highlighted by red color. One of the questions were to select java core concepts from the options. One of the options were ‘Generics’ which was actually a link to Generics page. When I accidentally clicked on it, it took me to another page. Due to this, I could not complete the quiz. Please remove that link so that it won’t happen again for others. Thanks for letting us know, i have fixed it. This is a good warm up quiz. I realised I still have so many things to do It was very good quiz!! 🙂 Awesome work This was an interesting quiz for me. I just found out I need more practice in Java. Very instructive Good questions Thanks a lot for the effort put to make this quiz. Really helped refresh all the basics. Now that I have got a taste for a quality quiz, I would love to see similar quiz for more advanced topics like Collections and Threads. Once again, Great work! Thanks. Good questions. The best part was the explanation of the quiz answers at the end for review. Nice to learn via Quiz! Where to start quiz. I am not able to see any link I was editing the Quiz questions, so it was unavailable for some time. It’s back up again now, please give it a try. Thanks. Good questions! Thanks for your quiz. Thanks for this great test! It showed me a lot of gaps in my knowledge! It would be great to have some more ! 🙂 Greetings from Venezuela, good job doing good job sir Hi I need SQL program like many to one, one to one, one to many on different different kind. who has been asked in interview … Description of answer to question 11 about multiple exceptions handling depends on language level, although it’s сompile time error in any case. java multi-catch statement is not supported in -source 1.6 Hi Alex, Any programming test always assume the latest version. For example, if you have a lambda program, you shouldn’t say that output depends on whether you are on java 8 or lower. Good job! Thanks. Only one remark: question ” Can we have two main methods in a java class?” The answer no is incorrect. Because yes, we can have 2 methods, for example: public class A { public static void main( Stting [] args) {} public void main( int[] args) {} } Why not?) I think you didn’t checked the question properly, you are iterating the same thing in the question explanation. good job…a very good medium for begineers . Excellent JAVA Core quiz. I realized that I need to practice more the basic topics, We apreciate all your efforts. Thanks Regards The quiz is very good but IMO it contains mistakes. “null” cannot be used as a name of variable.Therefore, it is a reserved word in Java. This is output from javac. test.java: error: expected String null; ^ null is not a reserved keyword, please check below link. true, false, and null might seem like keywords, but they are actually literals; you cannot use them as identifiers in your programs. Hi Pankaj, Goto statement is not applicable in JAVA so how goto is keyword for JAVA excelent Even if you use a multiple choice approach, the answer may not be true or false. Example given: You asked for java keywords, and rated my answer incorrect. But null is no keyword, nbut the null literal. I noticed several of such things but did’nt took the time to write everything down. I’ll visit again and try to give more comments. Thanks for your efforts, it helps in preparing very simple tasks. But they’re far away from what I excpect fromwhat I expect students at my university to master once they have terminated their bachelor courses. The question and answers for java keywords are correct, let me drop you an email for this.
https://www.journaldev.com/15161/core-java-quiz
CC-MAIN-2021-21
refinedweb
2,915
76.52
it enables the user to show off and tutorial anything in the viewport without the need to tell about every tool he/she is using it also looks at personal hotkeys and shows which command is used even when the default of maya is overwritten a small frame in the right side of the tool allows the user to drag and drop their own logo to personalise the tutorial even more to install: extract the rar, Copy the "KeyBoardInputUI.py" together with "KeyBoardInputUI.ui" and the Icon folder to your Maya scriptsdirectory: MyDocuments\Maya\scripts\ use this text as a python script within Maya: import KeyBoardInputUI KeyBoardInputUI.StartUI()' Please use the Feature Requests to give me ideas. Please use the Support Forum if you have any questions or problems. Please rate and review in the Review section.
https://jobs.highend3d.com/maya/script/keyboard-input-ui-for-maya
CC-MAIN-2022-05
refinedweb
137
57.81
I run this version of gcc $ gcc --version gcc (GCC) 3.4.5 20051201 (Red Hat 3.4.5-2) My program uses a custom written library that has a function named basename with its own set of parameters. My question is, if I want to use the GNU version of basename, how can I do it? I tried including this in my header #define _GNU_SOURCE #include <string.h> and I get this compiler error: x.h:80: error: conflicting types for 'basename' /usr/include/string.h:387: error: previous declaration of 'basename' was here Is there a way I can tell gcc to ignore the custom version of basename? Sam
http://cboard.cprogramming.com/c-programming/93773-error-conflicting-types-%27basename%27.html
CC-MAIN-2016-07
refinedweb
111
75.81
Also published on Microsoft’s MSDN Network at Applies to: - Microsoft ASP.NET 2.0 - Microsoft Visual Studio 2005 - Microsoft Internet Information Services Link To Part 1: Security and Configuration Contents Introduction Technologies Used The Application and Project The ObjectDataSource in Detail The Return Value of the Select Method (Type Collection) The Select Method Itself The Custom Sort Criteria ObjectDataSource In GridView (Data Control) Conclusion Introduction Figure 1. Membership Editor. The tiers of this solution are defined as follows. The first tier, the ASP.NET page (also known as the presentation layer), interfaces with two business objects through the object data source. These business objects function as the middle tier, and they are wrappers for members and roles. The third tier, or back end, consists of the Membership and Role Manager APIs provided by ASP.NET. The middle tier objects can easily be dropped into any ASP.NET 2.0 project and used directly, with almost no changes. This article explains in depth the implementation of the middle tier—that is, the data objects, as well as the ObjectDataSource that is associated with them. It then explains how to use these objects in an ASP.NET Web project that uses Microsoft SQL Server Express 2005, which comes bundled with Visual Studio 2005. However, the Membership API provided by Microsoft uses their provider technology; therefore, the solution presented here is database independent. Membership and role information could just as easily come from LDAP, SQL Server, or Oracle. Technologies Used The ObjectDataSource There are two ObjectDataSource instances defined. One is for Membership Data (User Names, Creation Date, Approval, and so on), and the other is for Roles (Administrator, Friends, and so on). Both of these data sources are completely populated with all of the data access methods—that is, they both have Member functions that perform inserts, updates, deletes, and selects. Both ObjectDataSource instances return a Generic List type, which means that in the GridView, the column names are automatically set to the property value names of the ObjectDataSource. In addition, custom sorting is implemented so that users can click the column headers in the GridView in order to sort the data forwards or backwards, as desired. SQL Server Express 2005 and Web.Config The data provider source for the Membership and Role databases is SQL Server Express 2005. The appropriate entries are set in the web.config file in order to make this happen. A short discussion is given later in this article of how to set up a new project from scratch. The connection string for SQL Server Express 2005 is not mentioned in the web.config file, because it is already defined in the Machine.Config file that is included as a default part of the Microsoft .NET 2.0 Framework. IIS (5.1 and 6.0) Compatible The Web server can be either version 5.1 or 6.0. In order to do any testing of multiple users logged in to your Web app, you must use IIS. The built-in development Web server does not correctly maintain state of the different users who are logged in. Although the Asp.net Web config tool could be made to work with IIS, the additional security work necessary in order to enable this was not done. The GridView Control The GridView is used to present the data for both membership and roles. As mentioned earlier, because of the use of a Generic type for the ObjectDataSource, the column names of the GridView are automatically named after the property values of the ObjectDataSource. Without the use of Generics, the column names revert to meaningless default values and must each be edited by hand. The Application and Project The project necessary in order to run this utility is very simple and self-contained. The project files, which are available for download, contain a full working example. Because there is no direct database access to the users and roles, all that is needed is to grab the three data objects (MembershipDataObject.cs, MembershipUserSortable.cs and RoleDataObject.cs: see Figure 2). Figure 2. Membership Editor project In the SamplePages folder there are several other samples that demonstrate the use of the previously mentioned modules. As one example, Membership.aspx is the example shown in Figure 1. It can be used for selecting, updating, inserting, and deleting Members and Roles, as well as for assigning roles to members. With a working ASP.NET 2.0 application that already has a working membership module, these pages should need no external configuration beyond what has already been done. These files can be copied directly into a project and they will just work. If this is the first implementation of Membership and Role Management in an application, the process to follow to create a solution using these objects is as follows: - Using Visual Studio 2005, create a new Web project of the type ASP.NET Web Site. - Click Website / ASP.NET Configuration on the menu. - Follow the wizard steps (1 to 7) to create some sample users and roles. This will effectively create a valid web.config file in the current project that has enough information to have Member Management up and running. By default, it will use SQL Server Express 2005 in its default configuration. - Include the three .cs files in the project, and then include the sample .aspx pages as samples. The ObjectDataSource in Detail The ObjectDataSource technology enables the creation of a datasource that behaves very similarly to the SqlDataSource—that is, it exposes interfaces that allow for selecting, updating, inserting, and deleting records (or record-like objects) from a persistent data store (such as a database). The next several sections of this article will discuss the object (or class file) that the ObjectDataSource uses to manipulate membership. Its name in the project is MembershipUserODS.cs. The Class (MembershipUserODS) Because the data is retrieved from the Microsoft Membership API, an ObjectDataSource is used to solve the problem. The first step in doing this is to create a stand-alone class that wraps MembershipUser so that it can be associated with the ObjectDataSource. The example below shows a typical set of methods that need to be implemented, and the next several sections of this article will discuss the implementation of each member function. Many of the details are left out of the article, but they are included in the source code provided with this article. [DataObject(true) public class MembershipUserWrapper { [DataObjectMethod(DataObjectMethodType.Select, true)] static public Collection<membershipuserwrapper> GetMembers(string sortData) { return GetMembers(true, true, null, sortData); } [DataObjectMethod(DataObjectMethodType.Insert, true)] static public void Insert(string UserName, bool isApproved, string comment, DateTime lastLockoutDate, ...) { } [DataObjectMethod(DataObjectMethodType.Delete, true)] static public void Delete(object UserName, string Original_UserName){ Membership.DeleteUser(Original_UserName, true); } [DataObjectMethod(DataObjectMethodType.Update, true)] static public void Update(string original_UserName,string email,...){ } } </membershipuserwrapper> The Class Declaration The class declaration shown above is special because of the attribute [(DataObject(true)]. This attribute tells the the Visual Studio 2005 ObjectDataSource Creation Wizard to look only for members with this special attribute when searching for DataObjects in the data class. See the example in the section showing where this class is assigned to a GridView component. The Insert Method The details of each section involve a very straightforward use of the Membership API provided by Microsoft. For example, here is what might be a typical Insert method in more detail. [DataObjectMethod(DataObjectMethodType.Insert,true)] static public void Insert(string userName, string password,) { MembershipCreateStatus status; Membership.CreateUser(userName, password,); } This class Insert is polymorphic, which means there can be multiple Insert methods used for different purposes. For example, it may be necessary to dynamically decide whether a created user should be approved depending on the circumstances. For example, a new user created in an admin screen may want to create users defaulted to approved, whereas a user register screen might default to not approved. To do this, another Insert method is needed, with an additional parameter. Here is what an Insert method that would achieve this goal might look like. [DataObjectMethod(DataObjectMethodType.Insert,false)] static public void Insert(string userName, string password, bool isApproved) { MembershipCreateStatus status; Membership.CreateUser(UserName, password, isApproved, out status); } As with the other methods listed here, the examples shown are not what will actually be found in the accompanying source. The examples here are meant to be illustrations of typical uses. More complete and commented uses are included in the source. The Update Method The Update method is a very straightforward implementation of the Membership API. Just like the Insert method, there can be multiple implementations of Update. Only one implementation is shown here. In the code available for download, there are more polymorphic implementations of Update, including one that just sets the IsApproved property (shown in the following example). [DataObjectMethod(DataObjectMethodType.Update,false)] static public void Update(string UserName,bool isApproved) { bool dirtyFlag = false; MembershipUser mu = Membership.GetUser(UserName); if (mu.isApproved != isApproved) { dirtyFlag = true; mu.IsApproved = isApproved; } if (dirtyFlag == true) { Membership.UpdateUser(mu); } } The Delete Method The Delete method is the simplest, and it takes one parameters, UserName. <h2>The Delete Method</h2> static public void Delete(string UserName) { Membership.DeleteUser(UserName,true); } The Select Method with a Sort Attribute The Select method—GetMembers, in this case—has multiple components, each of them worthy of discussion. First, what it returns is discussed, and then the actual method itself, and finally, how it sorts what it returns. The Return Value of the Select Method (Type Collection) The return value of the Select method (which also is referred to as Get) is a Generic Collection class. Generics are used because the ObjectDataSource ultimately associated with the class uses reflection to determine the column names and types. These names and types are associated with each row of data that is returned. This is the same way that a SqlDataSource uses the database metadata of a table or stored procedure to determine the column names of each row. Since the return type of the Select method is MembershipUserWrapper, which inherits from MembershipUser, most of the properties of this class are the same properties that are associated with MembershipUser. Those properties include: - ProviderUserKey - UserName - LastLockoutDate - CreationDate - PasswordQuestion - LastActivityDate - ProviderName - IsLockedOut - LastLoginDate - IsOnline - LastPasswordChangedDate - Comment Jumping ahead of ourselves a little, one very nice feature of property values is that they can be Read-only (no set method), Write-only (no read method), and of course, Read/Write. The ObjectDataSource Wizard recognizes this and builds the appropriate parameters so that when the datacontrol is rendered (using the ObjectDataSource), just the fields that are updatable (read/write) are enabled for editing. This means that you can not change the UserName property, for example. If this does not make sense now, it will later, when we discuss the ObjectDataSource and the data components in more detail. The Select Method Itself Just like Insert and Update, the Select method is polymorphic. There can be as many different Select methods as there are different scenarios. For example, it may be desiable to use the Select method to select users based on whether they are approved, not approved, or both. Typically, there is one Get method that has the most possible parameters associated with it, and the other Get methods call it. In our case, there are three Get methods: one to retrieve all records, one to retrieve based on approval, and one to retrieve an individual record based on a select string. In the following example, the method that returns all users is being called. By setting both Booleans to true, all users will be returned. [DataObjectMethod(DataObjectMethodType.Select, true)] static public List<membershipdata> GetMembers(string sortData) { return GetMembers(true,true,null,null); } </membershipdata> The next example shows a more detailed Get method. This example shows only the beginning of the method. The details of the method not shown include finishing the property assignments, filtering for approval status and rejecting the records not meeting the criteria, and applying the sort criteria. Following this example is more discussion about the sort criteria. (Note that calling GetAllUsers on a database with more than a few hundred users [the low hundreds] is quickly going to become an expensive operation.) [DataObjectMethod(DataObjectMethodType.Select, true)] static public List<membershipdata> GetMembers(bool AllApprUsers, bool AllNotApprUsers, string UserToFind, string sortData) { List</membershipdata><membershipdata> memberList = new List</membershipdata><membershipdata>(); MembershipUserCollection muc = Membership.GetAllUsers(); foreach (MembershipUser mu in muc) { MembershipData md = new MembershipData(); md.Comment = mu.Comment; md.CreationDate = mu.CreationDate; </membershipdata> The Custom Sort Criteria Notice that, in the preceding code, a parameter string named sortData is passed into GetMembers. If, in the ObjectDataSource declaration, a SortParameterName is specified as one of its attributes, this parameter will be passed automatically to all Select methods. Its value will be the name specified by the attribute SortExpression in the column of the datacontrol. In our case, the datacontrol is the GridView. The Comparer method is invoked based on the parameter sortName coming into the GetMembers method. Since these ASP.NET Web pages are stateless, we have to assume that the direction of the current sort (either forward or backwards) is stored in the viewstate. Each call reverses the direction of the previous call. That is, it toggles between forward sort and reverse sort as the user clicks the column header. Assuming that a GridView is used, the parameter that gets passed into GetMembers(sortData) has in it the data from the SortExpression attribute of the GridView column. If a request for sorting backwards is being made, the word "DESC" is appended to the end of the sort string. So, for example, the first time the user clicks on the column Email, the sortData passed into GetMembers is "Email." The second time the user clicks on that column, the parameter sortData becomes "Email DESC," then "Email," then "Email DESC," and so on. As a special note, the first time the page is loaded, the sortData parameter is passed in as a zero-length string (not null). Below is the guts of the GetMembers method that retrieves and sorts the data so that it is returned in the correct order. [DataObjectMethod(DataObjectMethodType.Select, true)] static public List<membershipdata> GetMembers(string sortData) { List</membershipdata><membershipdata> memberList = new List</membershipdata><membershipdata>(); MembershipUserCollection muc = Membership.GetAllUsers(); List<membershipuser> memberList = new List</membershipuser><membershipuser>(muc); foreach (MembershipUser mu in muc) { MembershipData md = new MembershipData(mu); memberList.Add(md); } ... Code that implements Comparison â�¦ memberList.Sort(comparison); return memberList; } </membershipuser></membershipdata> In the next section, when this is incorporated into a GridView, it will become more clear. The ObjectDataSource Declaration The easiest way to declare an ObjectDataSource is to drag and drop one from the datacontrols on the toolbar, after first creating an empty ASP.NET page with the Visual Studio 2005 wizard. After creating the ObjectDataSource, a little tag in the upper-right corner of the newly created ObjectDataSource can be grabbed; then, clicking Configure Data Source opens a wizard saying "Configure Data Source—ObjectDataSource1" (see Figure 3). Figure 3. Configuring ObjectDataSource At this point, two classes that are available for associating with an ObjectDataSource will be seen. MembershipUserODS is the primary subject of this article. RoleDataObject is basically the same thing, but it encapsulates Membership Roles. Also, remember that what is shown here are just the objects that are declared with the special class attribute [DataObject(true)] that was described in "The Class Definition." After choosing MembershipUserODS, a dialog box with four tabs appears. The methods to be called from the MembershipUserODS class will be defined on these tabs. Methods for Select, Update, Insert, and Delete will be associated with member functions in the MembershipUserODS. In many cases, there will be multiple methods available in the class for each of these. The appropriate one must be chosen, based on the data scenario desired. All four tabs are shown in Figure 4. By default, the members that are marked with the special attribute [DataObjectMethod(DataObjectMethodType.Select, false)] will be populated on the tabs. Of course, however, this particular attribute is the default for Select. Changing the expression DataObjectMethodType.Select to DataObjectMethodType.Insert, DataObjectMethodType.Update, and DataObjectMethodType.Delete will make the defaults appropriate for the different tabs. The second parameter, a Boolean, signifies that this method (remembering that it may be defined polymorphically) is the default method, and that it should be used in the tab control. The Select Method As mentioned earlier, in the section describing the MembershipUserODS class, the GetMembers function returns a Generic Collection class. This enables the ObjectDataSourceMembershipUser control defined here to use reflection and ascertain the calling parameters associated with this GetMembers call. In this case, the parameters used to call GetMembers are returnAllApprovedUsers, returnAllNotApprovedUsers, userNameToFind, and sortData. Based on this, the actual definition of the new ObjectDataSource will be as follows. Figure 4. Assigning the Select> The Insert Method The Insert method, in this case, is assigned to the member function Insert(). Notice that this method is called with only two parameters: UserName and Password (see Figure 5). The number of parameters must equal the number of parameters declared in the ObjectDataSource. The parameter declaration from the ObjectDataSource is shown below. There is a second Insert Member function defined that adds a third parameter: approvalStatus. If the functionality of this ObjectDataSource is to include inserting while setting the approvalStatus, then the other insert method should be chosen from the drop-down list. That would cause the following InsertParameters to be inserted into your .aspx page. If the one with two parameters is chosen, the block would not include the asp:Parameter with the name isApproved in it. Again, keep in mind that this example may not agree with the source code enclosed, and that it is here only as an example. The source enclosed is much more complete. Figure 5. Assigning the Insert> Also, keep in mind that using an Insert method with minimal parameters will require a default password to be set in the method. In a production system, this would be a bad idea. See the attached source code for a better example of how to handle inserts. Specifically, see the page Membership.aspx for this functionality. The Update Method The Update method, in this case, is assigned to the member function Update(). Notice that this method is called with multiple parameters: UserName, Email, isApproved, and Comment (see Figure 6). In addition, there is another Update method that has all the updatable parameters. This is useful for creating a control that has the most possible update capabilities. Just like Insert, the appropriate Update method is chosen for this ObjectDataSource. When the wizard is finished, it will automatically create UpdateParameters, as shown below. Figure 6. Assigning the Update method <asp:ObjectDataSource <updateparameters> <asp :Parameter <asp :Parameter <asp :Parameter <asp :Parameter </updateparameters> ... ... The Delete Method The Delete method, in this case, is assigned to the member function Delete(). There is, of course, only one Delete method necessary (see Figure 7). Below is the declaration of the ObjectDataSource that supports this Delete method. Figure 7. Assigning the Delete method <asp:ObjectDataSource <deleteparameters> <asp arameter <asparameter Name="UserName" /> <asp arameter </deleteparameters> ...arameter </deleteparameters> ... The Class (RoleDataObject) Just like Membership, Roles are set up with their own DataObject. Since there is nothing special about Roles, there are no details regarding their setup in this article. An understanding of how the Membership DataObjects are set up is transferable to how Roles are set up. In Membership, the Microsoft C# object that encapsulates the Membership API is MembershipDataObject.cs. The analogous class for encapsulating the Role API is RoleDataObject.cs. ObjectDataSource In GridView (Data Control) Class declarations for Membership Users and Roles have been established in the previous sections of this article. Also, a complete ObjectDataSource object has been placed on an ASP.NET page. The final step is to create the user interface, also known as the user-facing tier of the application or the presentation layer. Because so much of the work is done by the objects created, all that is necessary is to create a simple GridView and associate it with the ObjectDataSource. The steps are as follows: - In visual mode of the ASP.NET page designer, drag and drop the GridView data component onto the page associated with the ObjectDataSource created earlier. - Enable selecting, deleting, updating, inserting, and sorting. Figure 8 shows the dialog box associated with configuring the Gridview. Figure 8. Configuring GridView A special mention should be made here that DataKeyNames in the GridView control shown below is automatically set. This is because the primary key has been tagged in the MembershipUserSortable class with the attribute [DataObjectField(true)] , as shown below. Notice also that since UserName is a property of the MembershipUser class, it was necessary to provide a default property in the class extending MembershipUser. Since this is a Read-only property, only a Get method is declared. (UserName is public virtual on MembershipUser.) [DataObjectField(true)] public override string UserName { get { return base.UserName; } There is one attribute in the GridView that must be set by hand: the primary key must be set in the control. To do this, associate the attribute DataKeyName with UserName. The GridView declaration is shown below. <asp:GridView <Columns> ... ... Conclusion To wrap things up, you should now be familiar with how to build your own three-tier architected ASP.NET application. In addition, you now have two objects that you can freely use that encapsulate Members and Roles. You could now, for example, use the DetailView control, and in only a few minutes build a complete DetailView interface to Members that performs Navigation, Inserting, Updating, and Deleting of Members. Give it a try! I have specifically not gone into the implementations of adding, updating, and deleting Members or Roles. If you look at the source code, you will find that I have used the APIs in a very straightforward way. Not much will be gained by describing those calls in much detail here, because I’m sure that if you are still reading this, you, like me, are probably learning this material as you go. I was fortunate enough to be at MS TechEd in Orlando and PDC in LA this year, and was able to ask many questions of the ASP.NET team. In particular, I would like to thank Brad Millington and Stefan Schackow for putting up with my many questions during those weeks, and Jeff King and Brian Goldfarb for all their help in making this a better article. In some way, this article is payback, so that hopefully they won’t have to answer as many questions in the future.. Thanks, Peter. Saved me lots of time. The only issue I had is that I allowed user names with spaces, and the role management fails badly in this case because you’re splitting the button text on spaces. I modified Membership.aspx.cs to use single-smart-quote characters not generally included in role or user names: // Modified in ShowInRoleStatus result = “Unassign ‘” + userName + “’ From Role ‘” + roleName + “’”; result = “Assign ‘” + userName + “’ To Role ‘” + roleName + “’”; // Modified in ToggleInRole_Click char[] seps = new char[] { ‘‘’, ‘’’ }; string[] buttonTextArray = buttonText.Split(seps); string roleName = buttonTextArray[3]; Excellent Work.. Tons of time saved. Thanks for sharing Like someone above said, it is difficult to implement this kind of system, especially if the work is done by a begginer (like I am). Without any knowledge, even if a copy paste tutorial would seem dificult Thanks Pete, this helped a lot with a project I’m working on! Thanks Peter! It’s already the 5.5th year now and your article still saves OUR vital hours all around the world!!! Great stuff, any ideas where I can get a guideon how to utilize the WebAdmin pages within an asp.net app outside of the dev environment (for example, adding them to the app and then establishing the necessary links afterwards). thanks, troy. ! Have been postponing this for a long time but always have had a need in all my applications. Finally a good easily solution in which you’ve done all the heavy lifting. Works perfectly in VS2008 with SQL2005. Thanks Works perfect! Have beed looking for these for many weeks! Regards Hans Classic ASP was so much simpler to manage in IIS6. ! Hello there, just browsing for information for my Georgia 4g site. Truly more information that you can imagine on the web. Looking for something else, but very nice site. Have a good day. Fantastic! Thanks a bunch for the write-up! This information and facts actually helped me, I am sharing with a couple of friends. I will probably be checking back regularly to look for updates. Intimately, the post is really the greatest subject on this associated problem. I agree along with your conclusions and will thirstily appear forward to your approaching updates. Just saying thanks is not going to just be sufficient, for the extraordinary lucidity within your writing. I will at as soon as grab your rss feed to stay informed of any updates. You need to update more you do a good job Thank you so much for this code! It was unbelievably easy to implement and would have taken weeks for me to get this working on my remote site on my own! Much Thanks! In my page Object Datasource return Dataset.So how to sorting in that method.Which doesn’t return Collection. great piece of code, saves a lod of ground work. was wondering if there was a quick way to filter the output of the grids using a related table to the users. eg i have a profile table related by userid, i would like to filter the users by country which is a field on the profile table. How is this easily plugged in? Tx Thanks for sharing this important article… Thanks, about – ObjectDataSourceRoleObject I got the same problem but solved it (after 3 ___ days!) I soved it when I added the designer code using the convert to web application but for each individual file – not the whole project I love the example you’ve created, but I’ve run into an issue and I’m not sure of the cause. I cannot delete Roles. When I try, I get the following error: ObjectDataSource ‘ObjectDataSourceRoleObject’ could not find a non-generic method ‘Delete’ that has parameters: RoleName, original_RoleName. In RoleDataObject.cs, if I changed the parameter for the Delete method from string roleName to string original_roleName, then it works correctly. Anyone have any ideas? I’ve used this before in a Web Site project model site before with no trouble but I’m trying to convert it to a Web Application project model and I just can’t seem to get it to work. “The type or namespace name ‘ProfileCommon’ could not be found (are you missing a using directive or an assembly reference?)” I tried nicki’s advice above with no success. Is the ProfileCommon class generated from the App_Code files and not available to the Web Application? Ok, I got the answer from another website: right-click and click Convert to Web application. I have an issue getting the samples to compile, it seems the samples are missing the .designer.cs files, as the objects defined on the .aspx page are not defined as properties in the .cs file. VS2005 is complaining at compile time. Error 1 The name ‘ObjectDataSourceRoleObject’ does not exist in the current context C:\Projects\Procurement.Site\Procurement.Web\Admin\SecurityAdmin\Membership.aspx.cs 66 4 Procurement.Web Am I missing something? when i edit email addresses it changes the loweredemail field and not the email field in the db??????? You rock. I spent all day trying to figure out why I couldn’t use the Membership class directly. Not only does this work, but I learned a thing or two. Thanks. thanks a lot mustafa This is great. Thank for the code. I spent few days looking for a solution and it works perfect. The downtime is that I am not good in C# and had to redo my project from VB to C# . Having say this it will be good is there is an example in VB code. Thanks again Hi, I a Martin here. Just picked up few stones of Microsot.Net 2.0. I just explored the Membership APIs and relized the we couldnt sort the grid if we are returning the collection ‘MembershipUserCollection’ to the ObjectDataSource of the GridView. For sorting purpose insted of using custom sorting why cant we use the default sorting of the GridView by returning DataTable to the ObjectDataSource. And we could still keep the custom Paging of the object datasouce. The code will be like this. public static DataTable GetAllMembers(int maximumRows, int startRowIndex) { //TODO: should try to avoid sessions reference. //startRowIndex/PageSize – if we are taking from the gridview startRowIndex param of object data source. //But here we are taking the gridview page index from the session to sort the current selected page and not to reset from the begining. if (HttpContext.Current.Session[“PageIndex”] == null || string.IsNullOrEmpty(HttpContext.Current.Session[“PageIndex”].ToString()) || !(int.TryParse(HttpContext.Current.Session[“PageIndex”].ToString(), out startRowIndex))) { // PageIndex session variable is not found/set . startRowIndex = startRowIndex / int.Parse(GetConfigValue(“GridViewPageSize”)); } MembershipProvider mp = Membership.Provider; MembershipUserCollection muCollection = mp.GetAllUsers(startRowIndex, maximumRows, out totalMembersCount); //moving the data to data table. max records will be the GridView PageSize. DataTable dt = new DataTable(“Users”); dt.Columns.Add(“UserName”); dt.Columns.Add(“Email”); dt.Columns.Add(“IsApproved”); dt.Columns.Add(“IsLockedOut”); dt.Columns.Add(“IsOnline”); foreach (MembershipUser mu in muCollection) { DataRow dr = dt.NewRow(); dr[“UserName”] = mu.UserName; dr[“Email”] = mu.Email; dr[“IsApproved”] = mu.IsApproved; dr[“IsLockedOut”] = mu.IsLockedOut; dr[“IsOnline”] = mu.IsOnline; dt.Rows.Add(dr); } return dt; } public static int GetTotalMembersCount(int maximumRows, int startRowIndex) { return totalMembersCount; } .aspx this was good but role management classes are not working properly when we publish the website.we are using the oracle as a database and provider classes are written by us. the classes are working fine when we are using the the default visual studio environment. Thank you very much Peter! This was incredibly simple to install and use! Peter, this is brilliant, thank you so much for providing this. Your follow up articles on MDSN are even better – The article about membership with profiles () is a god send, as is your ODS generator () Andrew Lot of work saved! Thanks. But I have a question. I have a requiement where I need to get users given a starting letter when the user presses the letter hyperlink. Example I need to pass ‘a%’ to the database and get all userid starting with a. do you have any suggestions? Thank you for your help. Hi Peter, I am new to ASP.NET but this looks like a fantastic piece of Code saves lot of headache… But how does this run with Oracle… Anyone here tried it…please mail me at chirag_97@yahoo.com Hi Peter, Thanks, for your great code! Just what I was looking for – you saved me a lot of time… Hi Peter, I plugged your code into my project and it worked perfectly, thanks! I have two questions, not really related to Membership, more to the GridView component. 1. Instead of ‘edit’, ‘delete’ and ‘select’ (and ‘update’ and ‘cancel’) hyperlinks, I want to show my own images. Is that possible? 2. I want to be able to disable or hide the ‘delete’ / ‘update’ hyperlinks per user. For example, my users database table is related to a couple of other tables. If the user is still used in one of those tables, I want to disable or hide the delete link. Similarly, I want to disable deletion of some fixed system user accounts that come with my application. Can this be done, and how? I can’t really find an answer, I was hoping you could help me out. Thanks, Guido Do u have a sample of this with vb language ? Cos i don know how to Implement the app code for vb language it will be a big help if u can help anyway thanks for the sample code My understanding is that converting the webadmin pages to an asp.net app causes security concerns and is not a good idea (though I understand it is very doable). Excellent article and code. They saved me a lot of time and google searching. I’m surprised no one has written an article describing how to utilize the WebAdmin pages within an asp.net app outside of the dev environment (such as adding them to the app and establishing the necessary links). Great code! you save a lot of my time. I am very pleased to you.
http://peterkellner.net/2006/01/09/microsoft-aspnet-20-memberrole-management-with-iis/
CC-MAIN-2015-22
refinedweb
5,451
56.35
The question and answer are locked and cannot be edited. How can you legally escape taxes? Escaping Taxes: Fact or Fiction? Escaping taxes is a rather taboo subject, and not one that is openly discussed. Just ask Willie Nelson or Wesley Snipes. Chances are you won't hear people secretly whispering about it while riding on the subway and it certainly won't be preached to you in church. So you're left wondering: "Can you legally escape taxes?" And the answer is, "Not really."If you were to attempt it, your best bet would be not to work. If you earn less than the minimum ($3,300) you don't have to file. Note that the $3,300 figure is for money earned as an employee and listed on your W2, not self-employment. If you get married and one of you works, then file separately and only that person will have to file. That will avoid the majority of tax (i.e. income tax). You could also move to a state that doesn't have sales tax. And forgo owning a home.But seriously, taxes pay the salaries of your cities public workers and the folks that bravely defend our nation (i.e. armed forces). Taxes are what we pay to be part of a civilized society. Consider them your dues. Yes, it hurts to give up that hard earned money, but if you have a full-time job you likely have benefits included and those affect your pay even though you don't see them. There are tons of ways to cut down your taxes, but don't drive yourself crazy trying to get out of them all together. Fact is, look at the statistics and you'll see A LARGE percentage of people actually don't pay tax, but get $$ back (through credit features like the EIC), from the Feds. Hence, for many with low incomes it PAYS to file! And even if you avoid income taxes you will still be paying taxes on many purchases as well as other taxes such as real estate, etc. Tax Protestor Arguments You may find a number of different suggestions on how you can accomplish paying no tax. Things like "opting out of...", filing 0 based returns, claiming wages aren't income, taxes are voluntary, Federal tax is only applicable to residents of D.C., etc., etc. These are certainly attractive arguments to escape tax liability/responsibility. These are frivolous, protestor-type arguments and have all been found not only baseless, but have been found so in all courts and proceeding for so many reasons, that there are now even special penalties for anyone that tries to, apparently without bothering to investigate the positions, use them.Below is a link to an agreeably IRS site, that lists many of these arguments and brief reasons why they fail. If you are not comfortable relying on the IRS for advice, do your own research and look at the independent court cases, etc. Maybe even consider that many, many intelligent people, who make substantial incomes, and have devoted their working lives and interest to tax/law and reducing their own or others taxes, wouldn't and don't suggest these arguments. (Generally, someone trying to get $29.95 for their "amazing discovery" that everyone wants to keep secret, or such, is).Finally... wouldn't you be much happier to go down in history as the US citizen that paid the MOST taxes ever! (Lots of people make nothing of their lives (and in financial value), while taking more of everything than they produce...that seems to be easy).The whole subject of taxes is a very legitimate discussion because it involves the whole community and most importantly your money! You worked for it!! Therefore you should at least be aware of what you are getting out of what's being spent. And of course, you will find, this is the crux of the issue. Is the money being spent well? Is it all accounted for? Can the tax issue be reformed to better suit the needs of the general public?So, basically, it's obvious there will much conflict over such an intimate subject. Not only is a percentage of your labor being spent for you, it's being spent in the name of the community or nation as a whole. This may benefit some while not benefiting others. It is a very moral issue. This is why those that favor taxes, especially high taxes, claim it is a citizen's duty to pay taxes. [Remember too that someone who agrees with paying taxes, especially those that want to pay lots of taxes, are generally not going to encourage you to pay less or no taxes. It is against 'their' interest. Just as paying taxes may not be in 'your' interest.]Most importantly, be involved. If you want taxes have a good strong stance on your position. Set a good example and act on your idea of what needs to happen in society and how to accomplish these goals. It's not just the duty of a citizen to adhere to the laws but to uphold and/or repeal them. 271 people found this useful Was this answer useful? Thanks for the feedback! How do you legally escape taxes? It is impossible to escape taxes because everyone MUST file taxes. Whether you pay out a lot of your own money is a different story. Taxes cannot be avoided, however depending… on where you are in the income brackets you may not have to pay a ton of cash to the IRS. Ben Franklin said two things are guarantees in life, death and taxes. Another answer: Ah, at last! A question on WikiAnswers that is WORTHY of being answered! First of all, nothing that is man created is "impossible" to avoid. This is a "polite fiction" that is indulged in by those who lack the interest to find solutions to their "problems". As far as the misinformation given about "everyone MUST file taxes", well, I can only say that the IRS has very specific guidelines about WHO MAY LEGALLY AVOID FILING, and the list is far from trivial! Look it up for yourself and decide what the truth of the matter is! Many presidents have availed themselves of some of the more egregious tax "loopholes" that are designed specifically for those who created the laws. It is NOT up to congress to start a huge educational campaign to show every Tom, Dick and Harry how to avoid paying taxes, otherwise, said congressperson might have to start chipping in and carrying some of the load THEMSELVES, after all... So, the FIRST thing you can do to "legally avoid taxes", is to move to a state that doesn't have STATE INCOME tax. A couple come to mind, Nevada (where the gambling casinos pay the income tax for the rest of the citizens, so that they don't have to), and Texas, where EVERY president in recent memory resides for AT LEAST ONE DAY A YEAR in order to qualify as a "resident". Texans don't pay state income tax. If you were as smart as a president, you'd copy what THEY do, and set yourself up a sweet deal and LIVE IN TEXAS for one day a year. Who knows, perhaps you wouldn't even have to suffer THAT long, check out the rules regarding "residency" for yourself! Next, you want to whack that pesky Federal Income Tax. Who doesn't have to pay any Federal Income Tax? Well, if you work for a job, and make less than $600 per month, you won't have to pay any Federal Income Tax. Why would you want to do a thing like this? Well, how would I know? I am just pointing out what you would need to do. If you have a genius mind, you might find a way to accomplish this and the next few things, without my having to POINT IT OUT TO YOU in black and white. There is a nifty thing called a Roth IRA, that is America's 2nd best kept secret way of avoiding paying income tax LEGALLY! Yep! If you pay income taxes on some income, and then stash some of it in a Roth IRA account, you 1: Don't pay any income taxes on the growth of the investments you make in that account. This is exactly the same treatment as the normal IRA, so it is no big deal, all by itself, but it IS pretty important! 2: You don't pay any income taxes on the withdrawals that you make from this account, as long as it is the money that you put into the account in the first place. That is, you can withdraw your contributions (since you ALREADY paid income tax on them in the first place), without any penalty, interest OR tax, and you may do so at any time that you need or want to! This would be a foolish thing to do, however, but it IS possible! 3: When you reach retirement age (59 1/2), and the account has been open for 5 years, you can WITHDRAW any amount of money (or no amount of money, if you want it all to keep growing, for as long as you are alive, unlike the standard IRA account), AND LEGALLY PAY NO INCOME TAXES! That's right, folks! If you can figure out a way to make a million dollars in your Roth IRA account, you won't have to pay uncle sugar a single, rotten nickel in Income Taxes Legally! Get yourself a "self-directed Roth IRA" so that you can invest in anything legally allowable by the IRS (real estate, notes, the usual junk from a brokerage house or bank, but stick with the things that actually pay you something, and that YOU have control over!), which does NOT include "collectibles", such as Persian rugs, stamps and coins (except for bullion type coins with little numismatic value, think pre '65 USA coins, marked 1964 and earlier and which contained 90% silver), and you can't invest in anything you ever owned or lived in, or that your family ever owned, (with the notable exception of things owned by your brothers and sisters, apparently the IRS thinks that siblings will rat on each other, and they specifically PERMIT you to do this), so always buy stuff from 3rd party strangers, and keep your tax exempt status on your account safe. You DON'T want to lose this over a trifle, such as a "sweetheart deal" your brother will give you on his condo in Florida! Thus, if you have the slightest bit of imagination whatsoever, you now have a 'TAX FREE INVESTMENT ACCOUNT"! Next, there is a lovely provision in the IRS tax code that allows you to receive something called "gifts". You may receive up to $10,000 per person (per year), from ANYBODY and neither you, nor the giver, have to pay any income tax on that money. I don't know about you, but if all you folks reading this decide to follow some advice and all send me a gift of 10 cents each, I'll be rich enough to quit working, AND neither you nor I will have to pay any more Federal income taxes! Leave a note on my message board if you want more details on this or other subjects too long to go into here. Next, we have to deal with the issue of sales taxes. These are commonly escaped, (but not legally), by purchasing things on the Internet. There are currently no laws requiring people in one state to collect sales tax from people OUT OF STATE. So, buy all your goodies from people OUT OF YOUR STATE, and you won't have to pay any sales tax. Now, some places, such as California, actually have a law somewhere that says that you have to declare all purchases made "out of state" and pay your fair share of the sales taxes on them. I've yet to see anybody INCLUDING THE PEOPLE WHO WORK FOR THE BOARD OF EQUALIZATION follow this rule, and if THEY can ignore it, why should YOU be the first one to set a good example? Oregon doesn't charge sales tax. People over the border from Oregon often go for a "holiday" to their friendly neighboring state and purchase things for far less than they can in their "home" state. Is this legal? Of course, there is NO law against traveling and you can hardly be expected to eat nothing but air! Again, your own conscious must dictate whether or not you think paying 10% sales tax to your state government is "the right thing to do" when they can't even balance the budget on time, and waste all the money you've given them to date on stupid mistakes and frivolous social experiments! Now, the issue of property taxes is a bit more difficult, and I don't have all the answers here by a mile. It seems to me that various forms of property are exempt from taxation at the county level if they are owned by a church, and are USED FOR CHURCH SERVICES. So, if you have an intense aversion to paying property taxes, you can go through the work of starting up your own church, (land of religious freedom, remember?), and create your own form of worship worthy of your creator, and if you are so poor that in the beginning that you have to hold worship services in each other's homes (home worship groups are pretty common, actually), you might want to check out what percentage of use qualifies your residence for a property tax exemption in your local county. Don't take the first answer as gospel, as each tax official will be pained to the extreme to think that they are cutting their own throat (and pocketbook) by answering your questions truthfully, and completely, and accurately! Far better to say some negative sounding thing that isn't QUITE an open lie, and have you go away and forget all about LEGALLY AVOIDING PAYING TAXES! Now, as to the MORALITY and PATRIOTIC DUTY of a citizen when LEGALLY AVOIDING PAYING TAXES, allow me to conclude with a quote from a famous judge, who was quite respected in his time. It is HIS opinion (and he was HIRED SPECIFICALLY to give his opinion on law all the time), that: The classic description of tax avoidance was written by Judge Learned Hand in Helvering v. Gregory, 69 F. 2d 809, 810 (2nd Cir, 1934), aff'd 293 U.S. 465 (1935). ; here is not even a patriotic duty to increase one's taxes. How can you escape taxes? YOU CANT WHY? cause our governments gay How can you escape the united kingdom taxes? maybe by leaving the united kingdom and live other country which dont have a collection of tax. How can you legally escape end a timeshare contract? If you have recently purchased the timeshare membership in the United States you can rescind the transaction in the first few days in most states. Each set of purchase documen…ts papers accompanying a timeshare sale will include a section explaining how to rescind. The right of rescission is controlled by the laws of the jurisdiction in which the time share is purchased. The longest is 15 days in Alaska. You need to check the laws. If you are past your rescission period you can also contact Timeshare Mortgage Relief, LLC who is a timeshare consumer advocacy company and they can get you out of your contract if you are a victim of fraud or deception. If you have a timeshare that is paid in full you can contact Property Donation Group who will accept your timeshare as a donation or offer a guaranteed title transfer. If you are the owner of a timeshare then you will need to read the contract. Will your commitment and membership terminate automatically after a specific number of years? If you fail to pay your annual fees what steps can be taken by the property owner? Are you legally able to resell your membership? Does the property owner have a right to buy or first right of refusal? Once you understand your rights you can market or offer for sale your membership. You will receive only what someone else will be willing to pay. The Internet is one way to find buyers. In some destinations there will be local sales agents who can market the membership and they will be able to show it to people who are looking in the area. Owning a timeshare is usually a contract of a considerable number of years. You can wait for the contract to end or you can transfer the ownership to someone else. You can also sell it. See related link for state rescission periods. Another name for a duckHow can you legally escape taxes? if you're like berlusconi, you not only can escape taxes , but do almost what you want, because you make the law. easy. What is Legally escape taxes by not earning enough to qualify to pay them? you speaka da english? How can you legally escape inheritance tax? Generally this is done by creating a Living Trust or other Trust entity to pass your assets through to a beneficiary. How Can you legally escape credit card dept? Two possible ways are to pay the bills regularly (preferably the full amount due every month) or to go through bankruptcy. Another strategy is to stop using credit cards …altogether and use debit cards instead. How can you legally escape income taxes? Do not work. How can you legally escape murder? by claiming your mentally ill. Even by claiming that you are ill, will not allow you to escape prosecution. You may have to spend the rest of your life in a facility for …mentally impaired. It may not be prison, but could be worse depending. How can you legally escape taxes if you withdraw from 401K and transfer to son? Many plans allow employees to take from their 401(k) to be repaid with after-tax funds at pre-defined. . Loans are paid back by post-tax monies, so there are substantial tax implications in taking a loan from pre-tax monies. Virtually all employers impose severe restrictions on withdrawals while a person remains in service with the company and is under age 59½. Any withdrawal that is permitted before age 59½ is subject to an). The tax code legally defines hardship as: # Purchase of a primary residence (specifically excludes mortgage payments) # To avoid foreclosure of, or eviction from, primary residence # Payment of post-secondary education expenses for the next 12 months for the employee, his/her spouse, or dependent(s) or beneficiaries # Medical expenses not covered by insurance for employee, their spouse, or dependent(s), or beneficiaries which would be deductible on a federal tax return (e.g. non-essential cosmetic surgery would not be acceptable) # Funeral expenses for the employee's deceased parent(s), spouse, child(ren), or dependent(s) or beneficiaries (as of,) # Home repairs due to a deductible casualty loss (as of,) ½ years of age. Money that is withdrawn prior to 59 ½ typically incurs a 10% penalty tax unless a further exception applies. [1] This penalty is of course, and for deductible medical expenses (exceeding the 7.5% floor). This does not apply to the similar. Answered How can you not pay taxes but legally? Not really. You can give up owning your house, or not work. If your income is less than minimum, ($3,300) You do not have to file. If you get married, and only your spou…se works, file seperatly so only one of you has to pay. This way you escape most taxes(i.e. income tax). Answered In State Laws Is it a legal to carry knife in taxes? Its a legal as liking a butten in Wyoming! Hey, fabergastic! Answered Pay taxes on legal herb? legal herbs Answered Is tax legal or lawful? Taxes are entirely lawful, with one borderline exception . Income taxes were authorized by the l6Th Amendment in I believe l9l2 ( this may explain the traditional April l5 dea…dline which coincides with the Titanic disaster of that year.) The exception oddly- is not widely discussed, least of all by politicians- that is- The individual states of the United States ( this is stated early in the constitution proper)- are forbidden to charge what amount to Border Taxes for commerce between say, New York and New Jersey/ However, there are tolls on all manner of bridges and tunnels which cross state lines- a de facto border tax. As far as I know this little but factual argument- and it is in the actual constitution, not amendments- ( so is on more solid ground than say Gun control versus the 2nd amendment)- has never reached the center of Washington politics- let alone the High Court! Of course it can be stated that tolls on bridges and tunnels ( which are interstate) are merely for the maintenance and upkeep of the structures, but look it over. Answered What is the tax for a Ford Escape car? Depends on the model year and where you live.
http://www.answers.com/Q/How_can_you_legally_escape_taxes
CC-MAIN-2018-09
refinedweb
3,576
69.62
See also: IRC log <Chris_IAB> I will be joining the call today, probably via Skype in about 15-min. <aleecia> Great, Chris! <aleecia> Ok, we should be all set. <schunter1> thanks aleecia! <schunter1> It worked for me (you are the 1st participant). <schunter1> The passcode is only valid 10min before the start (AFAIR). <aleecia> Yes. <aleecia> Uh, yes on first 10 minutes, not yes on having issues <aleecia> I've run into that a few times :-) <aleecia> hi (muted) <rvaneijk> will be joining the call in about 15 minutes... <aleecia> Please mute <aleecia> thank you <aleecia> Who called in via Skype or similar? <schunter1> Nick: Do you want to do the de-anonymisation procedure? <Chris_IAB> just joined via Skype <aleecia> (perhaps Chris?) <aleecia> great <Chris_IAB> fyi- am on mute, as I'm joining from an off-site meeting <aleecia> Chris, so noted. We'll want an update on the action item you have due. <BrendanIAB> BrendanIAB just joined via Skype, but I didn't see me scroll by. <aleecia> I don't see you either, Brendan <Chris_IAB> Aleecia, which action item do I have due? <David> zakim - its actually MacMillan (with an 'a' in Mac) <aleecia> Wrong Chris, sorry <Chris_IAB> np <efelten> Zakim DavidMcMillan is DavidMacMillan <aleecia> Yes, none of that made any sense - need coffee. <npdoty> schunter: sent out a list of issues I think are resolved in the draft <aleecia> scribenick: aleecia <npdoty> ... haven't seen any comments on the issues planning to close Matthias: Listed issues to close based on the document, no comments. <schunter1> scribe anybody? I can scribe again if needed But did last time :-) <schunter1> Brendan? <BrendanIAB> I annot scribe today <JC> I will thanks, JC <schunter1> Thanks a lot! <scribe> scribenick: JC <npdoty> scribenick: JC shcunter: Looking at overdue action items, there are 4 ... action 225 Heather? Heather: I'm not finished yet <npdoty> action-225? <trackbot> ACTION-225 -- Heather West to propose an alternative definition of first party (based on ownership? alternative to inference?) -- due 2012-08-01 -- OPEN <trackbot> Heather: will finish next week or we can drop it. <aleecia> updated. Schunter: action 229 Rigo? <npdoty> action-229? <trackbot> Getting info on ACTION-229 failed - alert sysreq of a possible bug <WileyS> I only got comments to Chris last night so I think we need another week <aleecia> I'll send email to ping. <WileyS> Thank you <aleecia> Shane, thanks for the info Schunter: will send reminder on Action 229 ... action 232 David <aleecia> Getting it out by Friday would let people read it in time for the next call dwainberg: will finish next week <aleecia> I'll see what Chris thinks & cc you Schunter: that closes action items. Any other issues? <npdoty> trackbot, reload Schunter: Callers identified? Npdoty: Still checking a couple numbers. <damiano> Damiano Fusco from Nielsen, on Google Talk Are we fully confirmed on next f2f? <efelten> 212 is New York <chapell> 917 is chapell Schunter: Next agenda item is TPE changes <fielding> Fielding: I sent around the changes earlier. Major changes in section 4.3 & 5 ... enables JS to ask for an exception or to enable APIs to ask for exception ... section 5 is big change ... holds tracking status value. N none 1 first part 3 third party ... claim by origin server stating this is how I operate ... doesn't indicate how it is used because it may not be known <jmayer> We discussed this on the last call, and I thought we had agreement it's a Compliance issue. <schunter1> What does "this" in your sentence refer to? Fielding: the actual choice will be in header field or tracking resouce <johnsimpson> apologies was stuck in LA traffic <jmayer> Consent != first party. There are some limits on first parties, and there may be limits to the consent. Fielding: other response is consent. If consent is answer then a link to consent controlling resource is necessary ... another response could indicate that a consent may have changed for monitoring cache changes ... I also moved some text around. ... section 5.4 is about the same. <npdoty> regarding "C", consent, the current spec says sites SHOULD provide a control URI in such a case. (I had thought earlier we had agreed on MUST, but would have to check.) Fielding: changed partner array to third-party array for clarity and consistency. ... received and response member has been removed. <WileyS> Nick, we stayed with a "SHOULD" in discussion as a full out-of-band experience wouldn't require a control URI (meaning the entire experience occurs outside of the DNT context - consent and control - and this only serves as a reminder to the user) Fielding: qualifiers nobody liked so they have been removed. <jmayer> Could you say what that just meant? <dsinger> (all the qualifiers indicating claims of permissions, etc. are gone) Fielding: section 5 the section on status codes, <jmayer> npdoty, I thought it was a MUST too - that was the compromise. <WileyS> Jmayer, how is consent a compromise? Schunter: lets take questions before moving to Dsinger ... you have one week to respond to issues <npdoty> schunter: reminder to raise any issues with closing the list of issues by the 20th; let schunter know if you need more time Jmayer: Could you clarify the removal of qualifiers? <aleecia> It seems to me that it's very premature to drop things for lack of expected implementations. Fielding: I couldn't find anyone who wanted to define them for every resource <schunter1> The main justification was that we discussed and agreed in seattle. Fielding: the only person who wanted it on the client was Tom, but if no one implements why bother. <aleecia> I'd expect post-LC to be a time we'd find out about implementations at earliest Jmayer: How do we manage issues that are important, but no one wants to work on it? <jmayer> Um, no JC. <fielding> right, chair called it in seattle <jmayer> Jmayer: Maybe this stays in the spec, maybe it doesn't. But some people care about it. So we should have more process than a unilateral decision by an editor. Schunter: Roy implemented based on Seattle discussions <aleecia> I believe you're hearing sustained disagreement with that approach, Matthias <fielding> and the text was a proposal from me, not consensus from the group Dwainberg: was is the tracking status of n and how to state that no tracking is occurring <aleecia> We've been reviewing the text from Ninja on that. <aleecia> On the compliance side. <npdoty> I heard agreement in Seattle that we would want a definition of such a term. <aleecia> We talked about that 2-3 calls ago <adrianba> ACTION-110? <trackbot> ACTION-110 -- Ninja Marnau to write proposal text for what it means to "not track" -- due 2012-02-10 -- PENDINGREVIEW <trackbot> <tl> +q to point out that this is not what we agreed. <aleecia> Or, Adrian can find it - thanks! Schunter: there are three levels of tracking N not tracking 1 first party 3 third parthy <Chris_IAB> for better :) Ifette: We spent a lot of time defining DNT 0 & 1, exceptions a questions was asked about implementation and no one said yes <aleecia> Quite. <jmayer> Stay on topic... Ifette: from a process standpoint is it worth spending time on issues if no one is willing to implement things ... that makes me worry <dsinger> for us, the devil is in the details, indeed <sidstamm> yes, agreed dsinger Schunter: I hope people consider what is likely to be implemented or not. But for now it is just hearsay ... we should try to reach consensus <Chris_IAB> yes, but how does that affect compliance? <WileyS> If there is no exception framework I don't see why industry would implement this standard Schunter: we should not automatically kill an idea because some people say they won't implement it ... Ifette what did you mean no one implements dnt:0 <BrendanIAB> There is a difference between "nobody will use" vs "nobody will implement" <Chris_IAB> Mozilla did say they were going to implement DNT:0 Ifette: No one agreed to implement it or have currently <aleecia> Ian is asking specifically about browsers, and it *has* been implemented <dsinger> no-one really explained why a *general preference* for dnt:0 makes sense. dnt:0 for exceptions does make sense <jmayer> Actually, I have implemented a prototype of exceptions, and Mozilla said they're looking into it. Ifette: let's see what happens when Aleecia sends out poll <aleecia> It's built into b2g, and it's on the roadmap for FF <Chris_IAB> should we survey all the browser makers on this? Schunter: Let's not kill the feature unless all browser vendors say no <Zakim> dsinger, you wanted to ask about my email <fielding> WileyS, to implement DNT you only need DNT and any consent mechanism -- it is far easier for us to use cookies as a consent mechanism than cookies for 90% of browsers and a half-baked API for the other 10% <dsinger> Dsinger: End of July I sent out questions using WKR and others, but no one responded ... what do we need resource and tracking header to answer? Schunter: Dsinger still wants answers to email? <johnsimpson> David, can you resdend the email? Dsinger: I would like to encourage peole to respond otherwise it is hard to design it <dsinger> archived here, johnsimpson <Zakim> tl, you wanted to point out that this is not what we agreed. <fielding> dsinger, I would like to move those questions and answers to section 5.6 <npdoty> ACTION: schunter to follow-up re: David, regarding purposes of the WKR [recorded in] <trackbot> Created ACTION-238 - Follow-up re: David, regarding purposes of the WKR [on Matthias Schunter - due 2012-08-22]. <Chris_IAB> Schunter1, re: Ian's point, I would suggest that this working group survey (even privately) if major browsers and UAs will implement DNT:0, so as to avoid unnessesary work on this... TL: I want to reiterate point about procedure. Maybe Roy is right or perhaps not, but in Seattle we agreed to a specific format and had consensus <WileyS> Roy, if cookies were enough then the current opt-out structure is just fine and DNT is not needed TL: it would make more sense to have a document that reflects our consensus <npdoty> from the Bellevue minutes: <aleecia> AGREED: fields become part of optional member of tracking status resource TL: if there are changes lets have that discussion rather than having editor drop it on floor <ifette> +1 fielding <rvaneijk> I had an interest as well, tl was not alone :) Ifette: we never had consensus on that issue Fielding: of Ifette <tl> +q <aleecia> Nick, can you grab additional context to note what "fields" these are? Fielding: if you want something in the document create an issue and we can add it back TL: we had it in the document based on a whiteboarding session ... after the 25 minute session we had consensus <jmayer> One year in, we still don't have a clear process for accepting edits. How wonderful. Schunter: We should look at the minutes and make a decsion ... if you disagree with the proposal then make a counter proposal <dsinger> sounds like Roy may be mistaken in his perception of what the consensus was on qualifiers; maybe we should re-confirm that. The question is, is the onus on those who want them out, or on those who want them in? Schunter: we may have changed our mind or missed a consensus. In the end we should have text we call all live with <aleecia> what? TL: we had a process where we discussed what we were going to do. Reproposing things is not a good approach. <justin_> Wait, editors can decide whose opinion matters? Awesome. <npdoty> aleecia, I believe we're referring to the list of qualifiers for permitted uses (which would need to be updated) Dsinger: Is the onus on the editor or the people who don't want text removed. <WileyS> David, you weren't at the meeting but I believe the consensus was to remove the fields Fielding: let's work with chair on issue <fielding> I was told to remove the fields by the CHAIR Schunter: Let's repropose as needed. I would look at minutes and see what I can find. <npdoty> I thought we had agreed to drop them (the permitted use qualifier fields) from the header and make them optional in the WKR <WileyS> +1 to Nick <amyc> agree with nick and shane Schunter: if not in minutes let's work together to fix text <WileyS> that's exactly my memory as well <aleecia> With sustained objections <dsinger> for the record, I was disturbed to see them completely gone, but I was not in Seattle ??? <fielding> Then propose text to make them optional in the resource -- I have no such text and am not going to waste my time on it any further. <WileyS> David, not completely gone - moved to an optional element <rvaneijk> Minutes: matthias: we have consensus to remove the tokens except for p <rvaneijk> Schunter: I will go through minutes to see what I can find. Nick will add actoin. <fielding> p is now C Schunter: any question on Fieldings update? ... David provide update <npdoty> ACTION: schunter to review minutes regarding permitted use qualifiers [recorded in] <trackbot> Created ACTION-239 - Review minutes regarding permitted use qualifiers [on Matthias Schunter - due 2012-08-22]. Dsinger: minor change to reconfirmation of exceptions <vincent> what if he reject the exception request, shoudl we ask again? Dsinger: big change resolving tention between people who want explicit list of third parties and giving peole ability to modify list ... is this mechanism operational or not. Can user agent deal with explicit list or deal with them as a site-wide exception. this should be reviewed ... what do we tell the first party. It could add itself to third-party list and get DNT:0, but seems like bad idea. Maybe modify header to handle. ... for remove call I simplified it by making it a general removal to clean state and put back needed exceptions ... web-wide exception not changed. Added section on API for user's general tracking preference. ... what if exception request is rejected? vincent: User agent must know when exceptions are granted Dsinger: also must be able to know when exceptions are removed ... the return callback indicates if the exception was granted or not <npdoty> I think vincent is perhaps noting that the user agent might remember that the user has rejected this request before and not bother the user? <vincent> yes that's it :) <jmayer> +q <vincent> thx npdoty, ifette <npdoty> sites can use cookies and other mechanisms to remember what happened the last time they did something Ifette: How does user agent know when to ask if exception is still granted? Cookies don't work very well <jmayer> -q scribe: how do we track when an exception is not granted <WileyS> Nick, if cookies were enough then the current opt-out approach would be fine and DNT would not be needed <ifette> it's not about how the UA handles it, it's whether there's any way for the site to handle it Schunter: do we want to change protocal or place requirements on UA? Ifette: The question is whether the site can know if it needs to ask for exception Schunter: according to spec it is okay to cache response <npdoty> WileyS, I'm not suggesting use of cookies for opt-out, just if a site wanted to remember a rejected request from a past interaction, the way sites will continue to use cookies to remember other preferences <WileyS> Its up to the site to determine how many times it wants to request an exception Dsinger: is not clear on cookieing the user. It is not suggest not forbidden <WileyS> They can use any mechanism they desire <npdoty> +1, up to the site's design Dsinger: this is a site design question that could be a rathole for us ... do we need an issue? <WileyS> +q <jmayer> Yep. I don't think a cookie like "HaveAskedForException=True" would raise objections. <BrendanIAB> If the UA can cache the user response, and the site cannot determine if it has received a cached response or a direct user response, there is the possibility of problem with regards to server response. <aleecia> +1 WileyS: We should speak to it directly to idicate server can implement mechanism of it choice to remember user choices <jmayer> We should also be explicit about browsers limiting excessive requests. WileyS: if a site wants to ask user everytime that should be a fair outcome though not suggested. <dsinger> ACTION: dsinger to insert a note on how sites can avoid repeatedly asking the user for an exception [recorded in] <trackbot> Sorry, couldn't find user - dsinger Dsinger: I will drop a note to that effect <jmayer> And that there are limits on the designs that might be allowed. <efelten> Non-normative text giving some example implementation approaches? <WileyS> jmayer, use can leave site if they feel requests are excessive <npdoty> ACTION: singer to insert a note on how sites can avoid repeatedly asking the user for an exception [recorded in] <trackbot> Created ACTION-240 - Insert a note on how sites can avoid repeatedly asking the user for an exception [on David Singer - due 2012-08-22]. <WileyS> Jmayer, "user" can... <jmayer> WileyS, requests might not originate from a site. <jmayer> *first-party site. <npdoty> issue-116? <trackbot> ISSUE-116 -- How can we build a JS DOM property which doesn't allow inline JS to receive mixed signals? -- pending review <trackbot> Schunter: Issue 116 is there an agreement on status <WileyS> jmayer, if a 3rd party is the source of the request then the first party will manage the issue if the requests are excessive (aka - kick the 3rd party off of their site) <rvaneijk> Wiley, leaving a site because of excessive requests contradicts the element of free choice. It will definitely become a problem in EU. <schunter1> Not if we permit user agents to cache decisions. <WileyS> Rob, I disagree with the thought that free choice can be applied in this context from a EU legal perspective Npdoty: We have the JS property. the value will be one was sent to the first party. third party should only use it if there not expecting an exception <fielding> <rvaneijk> I know we disagree Schunter: what was disagreement and how we come to agreeable conclusion <WileyS> rvaneijk, can you provide any case law that supports your position? :-) Fielding: I don't know how to describe disagreement <jmayer> WileyS, you are endlessly entertaining. We all know that many first parties have very little control over the third parties on their website. <rvaneijk> see my presentation on consent in brussels Dsinger: what is problem Npdoty: difference between text and what was sent on ML <WileyS> jmayer, not true. 1st parties have complete control. Any tag "initially" placed on a page is done so by the 1st party. Its my assumption it would be possible to track the source of excessive requests to its source and backtrack and take appropriate action as a 1st party. <fielding> trying to find Nick's message <WileyS> jmayer, allow the free market to manage itself in this context versus building arbitrary definitions of "excessive" Npdoty: header should be per sight and not general value <WileyS> rvaneijk, I have reviewed it - not meaningful case law in this area Npdoty: it should reflect the value of the header originating the page request Dsinger: can't there be a cross site scripting problem <justin_> If I'm a publisher, and a third party is spamming my users, I'm going to find a way to put a stop to it. I don't see how adding "excessive" to a W3C spec is helpful. Schunter: is there a need for feature? <ifette> also, should it be off of navigator or window? Ifette: Should that be off Navigator or Window? Npdoty: if top level page Window, otherwise Navigator <sidstamm> +1 to npdoty … global setting should hang off navigator <fielding> npdoty, I can't find your text on list -- did you send it just to editors? <jmayer> Hanging from window and pegging to the frame location seems the most reasonable approach to me. <schunter1> There is no concept of a "general preference" defined yet. User agents may use heuristics (reflecting user preference) to determine DNT;0 vs. DNT;1 Adrianba: we put things on Navigator because Window is the global namespace, and can cause conflicts with other names <npdoty> fielding, my original proposal is at: and regarding our particular differences I sent just to you and dave, I think Ifette: I understand name conflicts, I don't know how we solve, but I prefer it not on Navigator <adrianba> agree with ifette - makes sense <fielding> to be clear, the current text does not have the top-level origin part <ifette> ifette: if it's a property of the origin and changes depending on what site Schunter: Do we need this feature and for which use case? Fielding: for js runing on a page <ifette> ifette: depending on what site i'm on, then it's not really a property of the navigator but rather of the window. especially if an iframe on a different origin can discover something about the parent, that seems suboptimal Dsinger: What is the use case for understand general preference Fielding: so it can avoid sending header to sites that do not implement dnt Npdoty: It can be valuable to know what value was received to avoid a call Dsinger: It should be careful with interactions with sites that do not implement DNT Schunter: a user can use a mechanism to indicate prefence, but do not want to obligate UA Fielding: we have the concept <npdoty> schunter: we don't have a defined concept of a general preference, user agent and user can use whatever heuristic they want <npdoty> fielding: we do have the concept of being "enabled" <dsinger> oh, a UA is allowed to say "european sites don't get DNT, Ugandan ones do" Schunter: a user can send what it wants to sites as long as it can prove it reflects user preference ... how do we move forward? <dsinger> propose that those who want to change something propose exact text changes? Schunter: we should reopen issue and collect use cases Dsinger: giving we have a proposal lets make changes pending reviews Schunter: so we should make proposals and counter proposals as needed <dsinger> to propose the changes you suggest... Npdoty: I will take action to make suggested changes : 137 is open : if service provide on page they should indicate they are part of first party or send something different ... this is not closed <dsinger> we sent a discussion document to the list, without reaction <fielding> Dsinger: hard to know where we are <fielding> Right, as it says in. Fielding: I placed resolution of our discussion in IRc <dsinger> discussion at Fielding: I explained why SP tag does not provide usefulness and it is an open issue. ... people should review text Dsinger: there is a difference between a hosting provider and a site acting on behalf of first party Schunter: If a site uses a service provider it must satisfy constraints and indicate it is first party otherwise third party Dsinger: the site can, but the user may disagree ... the site should indicate that it is acting as service provider <npdoty> well, yimg.com is part of the 1st party even though it's a different domain name than yahoo.com <aleecia> We've spent a long time talking about this and I thought we agreed that there is a difference between 1st party and acting as a 1st party but is a Service Provider <aleecia> or, 3rd party acting as a different 3rd party Schunter: That is a UA can not tell difference between 1P and SP <aleecia> Yes. Schunter: the question is how do we indicate to UA <aleecia> I thought we'd agreed to do so in Seattle Fielding: there could be dozens of SP on major web sites <jmayer> +q Schunter: I agree with David on this. Analytics provide all the rule so they are part of the 1P. ... that could be confusing to user Fielding: that is a different issue Schunter: how can a UA differentiation between first party and accidentaly included 3rd party <jmayer> I would prefer we resolve this now. <dsinger> am happy to write up the issue/question Schunter: I will work with David on how to resolve <dsinger> issue-137? <trackbot> ISSUE-137 -- Does hybrid tracking status need to distinguish between first party (1) and outsourcing service provider acting as a first party (s) -- pending review <trackbot> <jmayer> It's been in the backlog for awhile, we have the right participants on the call. <aleecia> SP can also be acting for a 3rd party Fielding: will SP need to indicate that it is not first party in tracking status resource ... I added requirement that a SP is acting as first party domain must be run by first party or tracking must be provided and point to first party ... must know when SP is acting as first party for main site or other site ... hard to describe but text is in spec <johnsimpson> Where in spec? Schunter: what is attribute <npdoty> fielding, you're saying the user agent would need to check the `policy` element and if it re-directs to the domain name of the responsible first party? Fielding: when acting as SP information is provided indicating who first party is <fielding> If the designated resource is operated by a service provider acting as a first party, then the responsible first party is identified by the policy link or the owner of the origin server domain. <dsinger> I assume 5.4.3, . <dsinger> " <fielding> Schunter: I will work with David to see how UA can make choice. New text should determine if flag is needed. <BrendanIAB> Is it absolutely necessary for the UA to be able to determine in-transaction the state (1P/3P/SP) of the server with which they are communicating? <fielding> it isn't an excpetion Jmayer: some people feel SP needs to be known. Need to know how exception will be used. Getting rid of this is not workable outcome <schunter1> Roy: In order to inform user agents whether another URL claims to be part of the 1st party (as service provider or for some other reason), then it either needs to be part of the 1st party domain or else be listed in the "same-party" attribtue at the well-known location. Jmayer: there is not a lot of controversy <dsinger> some sites might object to their providers effectively saying "I am Acme corp." vs. "I am acting solely on behalf of Acme corp." :-) Jmayer: three scnarions. 1 send http request as 3rd party, 2 send something as 1st party, send something as SP, but not know for whom ... need to indicate if acting as 1st or 3rd party. I would like to get this resolved know Schunter: Okay I will draft an outline with David and everyone can respond, ok? <aleecia> 7 minutes left Dsinger: please send response on ML jmayer Jmayer: so we cannot finish on call? <aleecia> But I agree with David: Jonathan, that was uncommonly lucid, and could really help as a quick post <jmayer> aleecia, well, at least we got a lot done in the prior 83 minutes. Dsinger: Only 7 mins left <fielding> <aleecia> I hear you. Schunter: Have new issues that came up that I would like to resolve <WileyS> Link please? Schunter: issue 158 effect of redirect <npdoty> <schunter1> <WileyS> Thank you Nick <WileyS> And Mr. Schunter :-) Dsinger: they are not considered. should be considered on top level domain and target <fielding> object because that effectively kills auctions, right? <WileyS> Site-wide vs. explicit-explicit exception? <WileyS> If site-wide, this isn't an issue is it? Npdoty: If DNT:0 needs to go with redirect needs to have site wide exception <fielding> okay, never mind Dsinger: yes, if you ask for site-wide exception you do not have problem <WileyS> But we've not solved explicit-explicit, have we? Do we need to solve that first? Schunter: what happens if you do nothing? Dsinger: we can drop corner case (auctions) for now <npdoty> WileyS, singer presented an updated version of the exception proposal today, including an option to include a list in addition to the site-wide option <npdoty> WileyS, in any case, you can ask for a site-wide exception if you need DNT:0 to be sent to all third parties, including re-directs related to auctions <npdoty> user-generated content is another case where you might not know/trust all third parties Dsinger: we should be fine with just asking for site-wide exceptions. Schunter: therefore we can close 158: <npdoty> fine to close 158 Schunter: closing ... leaving 159 and 160 and Raised f2f firm??????????? <npdoty> I think it makes sense to postpone 159, as suggested just now by singer <johnsimpson> more details on F2F? <dsinger> thx for your patience <npdoty> yes, we're confirmed on October 3-5 in Amsterdam, hosted by an IAB Netherlands member company <ifette> i'll get it one of these days :( This is scribe.perl Revision: 1.136 of Date: 2011/05/12 12:01:43 Check for newer version at Guessing input format: RRSAgent_Text_Format (score 1.00) Succeeded: s/???/vincent/ Succeeded: s/definately/definitely/ Found ScribeNick: aleecia Found ScribeNick: JC Found ScribeNick: JC Inferring Scribes: aleecia, JC Scribes: aleecia, JC ScribeNicks: aleecia, JC WARNING: No "Topic:" lines found. Default WARNING: No meeting title found! You should specify the meeting title like this: <dbooth> Meeting: Weekly Baking Club Meeting Got date from IRC log name: 15 Aug 2012 Guessing minutes URL: People with action items: doty dsinger]
http://www.w3.org/2012/08/15-dnt-minutes.html
CC-MAIN-2014-10
refinedweb
5,006
66.67
28 February 2012 06:44 [Source: ICIS news] SINGAPORE (ICIS)--?xml:namespace> The firm’s net profit for the October-December period was Malaysian ringgit (M$) 826m ($275.3m), compared with a restated gain of M$998m in the corresponding period a year earlier, the company said in a stock exchange filing. “This [decrease] follows lower contribution from our associates and jointly controlled entity as a result of lower production and full utilisation of tax benefits in one of the associate companies in the previous year,” it added. PCG re-stated its year-on-year profit and revenue numbers for 2010 after shifting its financial year-end from 31 March to 31 December, it said. Group revenue for the three months to the end of December 2011 increased by 0.23% year on year to M$3.9bn primarily driven by stronger prices, which offset lower sales volumes in the quarter, PCG said. “The Group achieved higher production with improved plant utilisation driven by the fertiliser and methanol business segment,” it said. Earnings before interest, tax, depreciation and amortisation (EBITDA) grew by 9% to M$1.4bn, it added. For the 9 months from April-December 2011, net profit rose by 26.7% to M$2.9bn, while revenue grew to M$11.9bn, from M$10.2bn, as compared to the same period the prior year, PCG said. “Favourable market conditions led to higher prices by 29% which cushioned the impact of lower sales volume and exchange rate movements,” it added. EBITDA for the nine months period increased by 40% to M$4.5bn, the firm said. “The Group delivered improved financial performance, leveraging on our strong market position in Asia Pacific and favourable prices,” said Adb Hapiz Abdullah, the president and CEO of PCG. PCG expects results of its operations for the next financial year ending 31 December 2012 to be satisfactory, subjected to sufficient availability of methane gas supply, it said. ($1 = M
http://www.icis.com/Articles/2012/02/28/9536339/malaysias-petronas-chemicals-oct-dec-net-profit-down.html
CC-MAIN-2013-48
refinedweb
326
56.96
Contributing to freud¶ Code Conventions¶ Python¶ Python (and Cython) code in freud should follow PEP 8. During continuous integration (CI), all Python and Cython code in freud is tested with flake8 to ensure PEP 8 compliance. Additionally, all CMake code is tested using cmakelang’s cmake-format. It is strongly recommended to set up a pre-commit hook to ensure code is compliant before pushing to the repository: pip install -r requirements/requirements-precommit.txt pre-commit install To manually run pre-commit for all the files present in the repository, run the following command: pre-commit run --all-files --show-diff-on-failure Documentation is written in reStructuredText and generated using Sphinx. It should be written according to the Google Python Style Guide. A few specific notes: The shapes of NumPy arrays should be documented as part of the type in the following manner: points ((:math:`N_{points}`, 3) :class:`numpy.ndarray`): Optional arguments should be documented as such within the type after the actual type, and the default value should be included within the description: box (:class:`freud.box.Box`, optional): Simulation box (Default value = None).. Doxygen docstrings should be used for classes, functions, etc. Code Organization¶ The code in freud is a mix of Python, Cython, and C++. From a user’s perspective, methods in freud correspond to Compute classes, which are contained in Python modules that group methods by topic. To keep modules well-organized, freud implements the following structure: All C++ code is stored in the cppfolder at the root of the repository, with subdirectories corresponding to each module (e.g. cpp/locality). Python code is stored in the freudfolder at the root of the repository. C++ code is exposed to Python using Cython code contained in pxd files with the following convention: freud/_MODULENAME.pxd(note the preceding underscore). The core Cython code for modules is contained in freud/MODULENAME.pyx(no underscore). Generated Cython C++ code (e.g. freud/MODULENAME.cxx) should not be committed during development. These files are generated using Cython when building from source, and are unnecessary when installing compiled binaries. If a Cython module contains code that must be imported into other Cython modules (such as the freud.box.Boxclass), the pyxfile must be accompanied by a pxdfile with the same name: freud/MODULENAME.pxd(distinguished from pxdfiles used to expose C++ code by the lack of a preceding underscore). For more information on how pxdfiles work, see the Cython documentation. All tests in freud are based on the Python pytestlibrary and are contained in the testsfolder. Test files are named by the convention tests/test_MODULENAME_CLASSNAME.py. Benchmarks for freud are contained in the benchmarksdirectory and are named analogously to tests: benchmarks/benchmark_MODULENAME_CLASSNAME.py. Benchmarks¶ Benchmarking in freud is performed by running the benchmarks/benchmarker.py script. This script finds all benchmarks (using the above naming convention) and attempts to run them. Each benchmark is defined by extending the Benchmark class defined in benchmarks/benchmark.py, which provides the standard benchmarking utilities used in freud. Subclasses just need to define a few methods to parameterize the benchmark, construct the freud object being benchmarked, and then call the relevant compute method. Rather than describing this process in detail, we consider the benchmark for the freud.density.RDF module as an example. The __init__ method defines basic parameters of the run, the bench_setup method is called to build up the RDF object, and the bench_run is used to time and call compute.. Steps for Adding New Code¶ Once you’ve determined to add new code to freud, the first step is to create a new branch off of master. The process of adding code differs based on whether or not you are editing an existing module in freud. Adding new methods to an existing module in freud requires creating the new C++ files in the cpp directory, modifying the corresponding _MODULENAME.pxd file in the freud directory, and creating a wrapper class in freud/MODULENAME.pyx. If the new methods belong in a new module, you must create the corresponding cpp directory and the pxd and pyx files accordingly. In order for code to compile, it must be added to the relevant CMakeLists.txt file. New C++ files for existing modules must be added to the corresponding cpp/MODULENAME/CMakeLists.txt file. For new modules, a cpp/NEWMODULENAME/CMakeLists.txt file must be created, and in addition the new module must be added to the cpp/CMakeLists.txt file in the form of both an add_subdirectory command and addition to the libfreud library in the form of an additional source in the add_library command. Similarly, new Cython modules must be added to the appropriate list in the freud/CMakeLists.txt file depending on whether or not there is C++ code associated with the module. Finally, you will need to import the new module in freud/__init__.py by adding from . import MODULENAME so that your module is usable as freud.MODULENAME. Once the code is added, appropriate tests should be added to the tests folder. Test files are named by the convention tests/test_MODULENAME_CLASSNAME.py. The final step is updating documentation, which is contained in rst files named with the convention doc/source/modules/MODULENAME.rst. If you have added a class to an existing module, all you have to do is add that same class to the autosummary section of the corresponding rst file. If you have created a new module, you will have to create the corresponding rst file with the summary section listing classes and functions in the module followed by a more detailed description of all classes. All classes and functions should be documented inline in the code, which allows automatic generation of the detailed section using the automodule directive (see any of the module rst files for an example). Finally, the new file needs to be added to doc/source/index.rst in the API section.
https://freud.readthedocs.io/en/latest/reference/development/howtoadd.html
CC-MAIN-2021-21
refinedweb
990
55.44
I made a python program on Raspberry Pi able to connect in classic bluetooth (not BLE) with sensors. To do this, I used socket programming. I can perfectly connect to several sensors simultaneously and exchange data (receive/transmit) between the Raspberry Pi and the sensors. Overall, the most important lines in my code are the following: The problem I can't solve is when one of the sensors is out of range of the Raspberry Pi, it ends up disconnecting. I would like it if when the sensor is within range of the Raspberry Pi again, the python script is able to automatically reconnect to the sensor. Code: Select all import bluetooth import socket addr_sensor1 = xx:xx:xx:xx:xx:xx port_sensor1 = 1 sock_sensor1=bluetooth.BluetoothSocket(bluetooth.RFCOMM) sock_sensor1.connect((addr_sensor1, port_sensor1)) sock_sensor1.send("Message\n") while True : while char != '\n' : char = str(sock_sensor1.recv(1).decode("utf-8", "ignore")) data = data + char print(str(data)) Do you know of any method to solve this problem? Even another method with other libraries? Thanks in advance
https://www.raspberrypi.org/forums/viewtopic.php?f=32&p=1879731&sid=bece6756cea30514b599e897ee78a755
CC-MAIN-2021-31
refinedweb
175
50.23
DataKnowledgeEngJour.. - School of Computing Each function group of wrappers is implemented as a public Java class; they extend the JESS Userpackage class. The various wrapper functions are created as private classes and added into the JESS inference engine. Sample code: public class ExprFunctions implements Userpackage { public void Add(Rete engine) { engine.AddUserfunction(new exprRemoveStop()); engine.AddUserfunction(new exprStem()); : : } } The above code shows how the class ExprFunctions implements the group of wrapper functions for the Expression Module. Other groups are implemented similarly. Each wrapper function is implemented as a private class extending from the JESS Userfunction class. The latter contains a private attribute _name to store the name the programmer use for invoking the function in the JESS script. The public method Call is then used to define the operations to be performed when the function is called in the JESS script. Sample code: class exprRemoveStop implements Userfunction { Expression ex = new Expression(); int _name = RU.putAtom( "exprRemoveStop" ); public int name() { return _name; } } public Value Call(ValueVector vv, Context context) throws ReteException { String expr = ""; } if ((vv.size() == 2) && (vv.get(1).type() == RU.STRING)) { expr = vv.get(1).StringValue(); expr = ex.removeStop(expr); } return new Value(expr, RU.STRING); 21 This code shows how the class ExprRemoveStop is used to wrap the Java function expr.RemoveStop of the Expression Module into the JESS function exprRemoveStop. All other Java functions are wrapped in the same way. e. Network Interface Module This module sets up the connection between the client and the proxy. Search requests issued by the client are submitted to the proxy through this module. The search result as returned by the proxy is collected by this module before it is displayed to the user. All networking functions are implemented via the Socket class in Java. 3.4 Proxy Modules Design and Implementation a. Proxy Controller Module As the name implies, this module controls all the activities and transactions that are carried out in the proxy. It accepts connections from E-Referencer client applets, and establishes connection with the selected Z39.50 server on behalf of the clients. The Z39.50 Interface module is invoked for the connection. If a client applet requests for subject headings that are associated with the keywords it submits, the Keyword-Subject Association Module will be invoked by the controller to retrieve the relevant subject headings. If logging is required at a later stage, it can be implemented in this module since this module handles all transactions. The Proxy Control Module is implemented using Java Threads. When the proxy starts up, a controller thread is created to listen to client requests. Each time a new client’s connection request is received, the controller thread would instantiate two new threads to handle all future requests from that client. One thread will handle all activities between the client and the proxy while the other thread will handle all activities between the proxy and the Z39.50 server the client is connecting to. With two separate threads, there is continuous communication since the blockage of one communication channel will not affect the other. When the connection to the client dies, the two threads will also be killed and reclaimed. 22
https://www.yumpu.com/en/document/view/6817980/dataknowledgeengjour-school-of-computing/23
CC-MAIN-2018-34
refinedweb
530
57.27
Sep 19, 2012 12:36 PM|MTVK|LINK I have the following class public class StController:apicontroller { public void PostBodyMethod() { HttpRequestMessage request=this.request; //How to read the header and body parameters } } The applet sends both the header and body parameters to the post method of webapi controller method i.e.,PostBodyMethod. How to retrieve the information which is sent along with post method inside the webapi controller using the HttpRequestMessage object?</div> Sep 19, 2012 04:59 PM|jitheshb|LINK You can access the header information new HttpRequestMessage().Content.Headers Content body can be accessed through strongly typed model through model binding. new HttpRequestMessage().Content will give u access to the request content. 1 reply Last post Sep 19, 2012 04:59 PM by jitheshb
http://forums.asp.net/t/1844619.aspx
CC-MAIN-2014-10
refinedweb
126
55.54
Another_Darren wrote:For starters VB.NET usually needs more lines of code to achieve the same result that C#. And VB.NET is not as nice at handling certain logic operators or statements without additional checks in you code. Right, so c# biggots criticise VB for introducing the My namespace on the grounds that its dumbing-down, and then criticise because it takes more lines of code to achieve something? One, you cant have it both ways. Two, thats rubbish as in both you are basicly writing code to target framework classes which takes the same number of lines. And exactly which logic operators or statements are not as nice? What additional checks do you need exactly? I think all the things you are attributing to the language are in fact due to lazy code.
http://channel9.msdn.com/Forums/Coffeehouse/190070-Learning-VBNET/f7f9bd92724a453781819deb01636113
CC-MAIN-2014-15
refinedweb
135
73.58