title: How to completely decouple Model from View/Controller in Java Swing

text: Is there a collection of commonly-agreed-upon design guidelines for separating the Model classes from the View/Controller classes in a Java Swing app? I'm not so concerned that the View/Controller know nothing about the Model as the other way around: I'd like to design my Model to have no knowledge of anything in javax.swing. Ideally it should have a simple API enabling it to be driven by something as primitive as a CLI. It should be, loosely speaking, an "engine." Communicating GUI events to the model isn't too hard -- the Action Performers can call the model's API. But what about when the model makes its own state changes that need to be reflected back to the GUI? That's what "listening" is for, but even "being listened to" is not entirely passive; it requires that the model know about adding a listener. The particular problem that got me thinking involves a queue of Files. On the GUI side there's a `DefaultListModel` behind a `JList`, and there's some GUI stuff to choose files from the file system and add them to the JList. On the Model side, it wants to pull the files off the bottom of this "queue" (causing them to disappear from the JList) and process them in some way. In fact, the Model code is already written -- it currently maintains an `ArrayList<File>` and exposes a public `add(File)` method. But I'm at a loss as to how to get my Model working with the View/Controller without some heavy, Swing-specific modifications to the Model. I'm very new to both Java and GUI programming, having always done "batch" and "back-end" programming up to now -- hence my interest in maintaining a strict division between model and UI, if it's possible and if it can be taught.


title: Constants vs public properties for configuration

text: My application has a few high level configuration options such as directories which will be used for various things, database connection information and a few other settings which are required for the application to run. I'm debating with myself whether or not constants are better than variables for this purpose and would like some input. By having:                $config = new Config;      new Whatever($config->foo, $config->bar);      Instead of:               new Whatever(Config::FOO, Config::BAR);      I get the power of polymorphism, I can quickly swap between configuration settings by instantiating $config as a different class with the same class members. There's obviously a trade-off here. Anything which needs the config options must instantiate a $config object, using memory and creating extra code as well as making it so the config options are no long immutable. The immutability problem could by solved with a method e.g. $config->get('Foo'); so that is potentially a non-issue, although it does add to verbosity and a method call is more expensive than reading a constant or variable.


title: Is this proper OO design for C++?

text: I recently took a software processes course and this is my first time attempting OO design on my own. I am trying to follow OO design principles and C++ conventions. I attempted and gave up on MVC for this application, but I am trying to "decouple" my classes such that they can be easily unit-tested and so that I can easily change the GUI library used and/or the target OS. At this time, I have finished designing classes but have not yet started implementing methods. The function of the software is to log all packets sent and received, and display them on the screen (like WireShark, but for one local process only). The software accomplishes this by hooking the send() and recv() functions in winsock32.dll, or some other pair of analogous functions depending on what the intended Target is. The hooks add packets to SendPacketList/RecvPacketList. The GuiLogic class starts a thread which checks for new packets. When new packets are found, it utilizes the PacketFilter class to determine the formatting for the new packet, and then sends it to MainWindow, a native win32 window (with intent to later port to Qt).1 ![UML Class Diagram](http://i.stack.imgur.com/dtPwP.png) Full size image of UML class diagram Here are my classes in skeleton/header form (this is my actual code):               class PacketModel     {     protected:         std::vector<byte> data;         int id;     public:         PacketModel();         PacketModel(byte* data, unsigned int size);         PacketModel(int id, byte* data, unsigned int size);         int GetLen();         bool IsValid(); //len >= sizeof(opcode_t)         opcode_t GetOpcode();         byte* GetData(); //returns &(data[0])         bool GetData(byte* outdata, int maxlen);         void SetData(byte* pdata, int len);         int GetId();         void SetId(int id);         bool ParseData(char* instr);         bool StringRepr(char* outstr);         byte& operator[] (const int index);     };          class SendPacket : public PacketModel     {     protected:         byte* returnAddy;     public:         byte* GetReturnAddy();         void SetReturnAddy(byte* addy);     };          class RecvPacket : public PacketModel     {     protected:         byte* callAddy;     public:         byte* GetCallAddy();         void SetCallAddy(byte* addy);     };          //problem: packets may be added to list at any time by any number of threads     //solution: critical section associated with each packet list     class Synch     {     public:         void Enter();         void Leave();     };          template<class PacketType> class PacketList     {     private:         static const int MAX_STORED_PACKETS = 1000;     public:         static const int DEFAULT_SHOWN_PACKETS = 100;     private:         vector<PacketType> list;         Synch synch; //wrapper for critical section     public:         void AddPacket(PacketType* packet);         PacketType* GetPacket(int id);         int TotalPackets();     };          class SendPacketList : PacketList<SendPacket>     {          };          class RecvPacketList : PacketList<RecvPacket>     {          };          class Target //one socket     {         bool Send(SendPacket* packet);         bool Inject(RecvPacket* packet);         bool InitSendHook(SendPacketList* sendList);         bool InitRecvHook(RecvPacketList* recvList);     };          class FilterModel     {     private:         opcode_t opcode;         int colorID;         bool bFilter;         char name[41];     };          class FilterFile     {     private:         FilterModel filter;     public:         void Save();         void Load();         FilterModel* GetFilter(opcode_t opcode);     };          class PacketFilter     {     private:         FilterFile filters;     public:         bool IsFiltered(opcode_t opcode);         bool GetName(opcode_t opcode, char* namestr); //return false if name does not exist         COLORREF GetColor(opcode_t opcode); //return default color if no custom color     };          class GuiLogic     {     private:         SendPacketList sendList;         RecvPacketList recvList;         PacketFilter packetFilter;         void GetPacketRepr(PacketModel* packet);         void ReadNew();         void AddToWindow();     public:         void Refresh(); //called from thread         void GetPacketInfo(int id); //called from MainWindow     };      I'm looking for a general review of my OO design, use of UML, and use of C++ features. I especially just want to know if I'm doing anything considerably wrong. From what I've read, design review is on-topic for this site (and off-topic for the Code Review site). Any sort of feedback is greatly appreciated. Thanks for reading this.


title: What are invariants, how can they be used, and have you ever used it in your program?

text: I'm reading _Coders at Work_ , and in it there's a lot of talk about invariants. As far as I've understood it, an invariant is a condition which holds both before and after an expression. They're, among other things, useful in proving that loop is correct, if I remember my Logic course correctly. Is my description correct, or have I missed something? Have you ever used them in your program? And if so, how did they benefit?


title: On-site interview without phone interviews - meaning?

text: I recently applied to work at a tech company which - to the best of my knowledge - usually does two rounds of phone screening before bringing applicants in for the on-campus interview. They contacted me and want to bring me up without doing a phone interview. I know this isn't much to go on, but should I take this at face-value or should I read something into this? Call me an optimist, but it seems like a positive thing. Maybe somebody on the inside recommended me without my knowing? Or They found something on my resume/online they liked the look of? Or maybe there's some sort of interview quota they had to fill? Any insights from hiring managers/HR people would be greatly appreciated. If this is a common thing that means something specific, knowing what it is might be to my advantage. Thanks! EDIT: Since a few people seem to indicate that it might depend on the company in question, let's say that it's a large national company (not Google or Microsoft, though), and that I don't live anywhere near the headquarters (it's about as far away as two places can be in the continental US).


title: Are there problems with using Reflection?

text: I don't know why, but I always feel like I am "cheating" when I use reflection - maybe it is because of the performance hit I know I am taking. Part of me says, if it is part of the language you are using and it can accomplish what you are trying to do, then why not use it. The other part of me says, there has to be a way I can do this without using reflection. I guess maybe it depends on the situation. What are the potential issues I need to look out for when using reflection and how concerned should I be about them? How much effort is it worth spending to try to find a more conventional solution?


title: How can I capture an incoming email with ASP.net-mvc?

text: I would like to write a web system that can capture and parse incoming emails, traditionally the web system I write are asp.net-mvc, running in a cloud hosted environment like AppHarbour or Azure. How can I leverage those (and potentially my DNS) to acheive this?


title: Learning PHP with a Rails/Django/Lift background

text: While I have been at university studying a CS degree I have been picking up web development on the side. As I started in the last couple of years, I have mainly been using Rack/Ruby based frameworks such as Rails and Sinatra but I have also looked at - and occasionally used - Web.py, Django and Lift. I realised that I have never used or seen PHP used for web development. This might seem strange but, as a young twenty something, learning PHP doesn't seem like the most fun/hip route to take. Given this background (which I am sure is relevant to many people my age). What is the best way to approach learning PHP web development? What are the key differences/similarities? Also, what frameworks are widely used and/or respected?


title: Why does Resharper prefer "as" to "is"?

text: When I write code like this, where obj is a local variable:               if (obj is IMyInterface)     {        var result = (IMyInterface)obj;        // ....     }      Resharper offers to change it into code like this:               var result = obj as IMyInterface;     if (result != null)     {        // ...     }      I prefer the former, as it offers no opportunity for accidental null reference exceptions. What reasons are there for preferring the other form? Why does Resharper recommend this?


title: What are the pros and cons of Inter process communication done via sockets vs shared memory?

text: I understand that two of the many more options for inter process communication can be :   1. Shared memory   2. Sockets  Actually I saw these two options being exposed by Intellij Idea for debugging a Java application . I want to know what are the pros and cons of each approach .


title: How to avoid repetitively logging in to web site?

text: While developing web sites it can be annoying that I have to login to the site. Every time the session runs out I have to go through a flow like...   Open logon page -> enter username/password -> click link to navigate to my page. I sometimes use Selenium to record this flow, and then automate it. But Selenium doesn't work in all browsers, and it still takes too long to load etc.   I would like to be able to just refresh the page, exactly like I would if the site didn't have a login page. Does anyone use any strategies to achieve this? Any way to disable login during development? Or other tools which can help improve the situation?


title: Aggregate Root and Lots of Data Efficiency

text: It's more of a scenario, but it isn't far fetched at all. Let's say I have an Aggregate Root (AR) Warehouse which it's used to manage product stock. The Product itself is an AR in a different bounded context (BC) but in this BC is represented only by an id. In the Warehouse I can add a new product (must be unique), Ican remove it and i can update stock. Of course, I can communicate the stock for a product and maybe even keep the in/out flow for a product. THe problem is you can easily reach hundreds or thousands of products. So, for any wareohuse action you'll have to load everything even if that action won't use all that info. It's highly inefficient. A solution I could think of is to pretty much 'break' the warehouse AR in specialiazed objects for different actions. But this means we no longer have an AR and we're back to a CRUD like solution. Even more so, the AR was split not becasue the Domain need it, but because the technical details need it. It looks like you can do DDD until a certain point, after that you go CRUD or buy a MUCH BIGGER and expensive server. What do you think? Can we have both DDD and efficiency when lots of data is involved?


title: Avoid GPL violation by moving library out of process

text: Assume there is a library that is licensed under GPL. I want to use it is closed source project. I do following:   1. Create small wrapper application around that GPL library that listens to socket, parse messages and call GPL library. Then returns results back.   2. Release it's sources (to comply with GPL)   3. Create client for this wrapper in my main application and don't release sources. I know that this adds huge overhead compared to static/dynamic linking, but I am interested in theoretical way.


title: Rails engine testing - use dummy app or real parent app?

text: I'm using Rails engines to break up a big app into smaller pieces. The parent app mostly handles users and authentication. In one of my engine tests I want to log in a user before each test. How should I access this user log in functionality, which exists in the parent app, from the engine? It seems there are two options: 1) Build user authentication into the dummy app. When you run `rails plugin new app_name --mountable` a "dummy app" - just a plain Rails app - is created in your test folder. During tests the engine is mounted on to this dummy app. For feature (integration, acceptance, what-have-you) tests, I thought it would be good to use real objects whenever possible. So I was planning on using a factory to create a real user and then log in that user. To do this with the dummy app, I would need to build that user functionality in. This seems like a pain because if the real parent app changes, I need to change this dummy app as well. 2) Put all my tests in the parent app. This will work fine, I think, but it seems fishy. I feel like I should put my engine tests in the engine.


title: Recommended Reading for Polishing JavaScript coding style?

text: I've been coding in JavaScript for a while now and am fairly familiar with some of the more advanced coding features of the language (closures, self- executing functions, etc). So my question is, what advanced books/blogs/or anything else would be recommended to help tighten up my coding style? For example, recently I was coding something similar to:               var x = ['a', 'b', 'c'];     var exists = false;     for(var i = 0; i < x.length; i++){         exists = x[i] === 'b' ? true : exists;     }      But found that the following condensed code would work better:               var y = {'a':'', 'b':'', 'c':''};     var exists = 'b' in y;      Both store the same value in 'exists', but the second is less common, but much cleaner. Any suggestions for where I should go to learn more tricks like this? Edit: I recently found this blog with a lot of good detail on the intricacies of JavaScript: http://javascriptweblog.wordpress.com/


title: Do you own your tools?

text: A colleague of mine wrote a post a while ago asking Do you own your tools. It raises an important question. Do you? I answered way down in the comments. As an independent, I do own my tools. Even when I wasn't independent, I had my own (fully licensed) tools that I used for personal development. I don't think buying your own tools are something to puff your chest up about (just because you can buy a $100 pair of basketball sneakers they won't make you as good as Michael Jordan), but it IS an investment in yourself that shouldn't be taken lightly. What do you think good people?


title: Why hill climbing is called anytime algorithm?

text: From wikipedia, Anytime algorithm > In computer science an anytime algorithm is an algorithm that can return a > valid solution to a problem even if it's interrupted at any time before it > ends. **The algorithm is expected to find better and better solutions the > more time it keeps running.** Hill climbing > Hill climbing can often produce a better result than other algorithms when > the amount of time available to perform a search is limited, such as with > real-time systems. It is an **anytime algorithm** : it can return a valid > solution even if it's interrupted at any time before it ends. Hill climbing algorithm can stuck into local optima or ridge, after that even if it runs infinite time, the result won't be any better. Then, why hill climbing is called anytime algorithm?


title: PHP rand function (or not so rand)

text: I was testing PHP rand function to write on a image. Of course the output shows that it's not so random. The code I used:               <?php      header('Content-Type: image/png');     $lenght = 512;     $im = imagecreatetruecolor($lenght, $lenght);     $blue = imagecolorallocate($im, 0, 255, 255);     for ($y = 0; $y < $lenght; $y++) {         for ($x = 0; $x < $lenght; $x++) {             if (rand(0,1) == 0) {                 imagesetpixel($im, $x, $y, $blue);             }         }     }            imagepng($im);     imagedestroy($im);     ?>      My question is, if I use image width/lenght (variable $lenght in this example) number like 512, 256 or 1024, it is very clear that it's not so random. When I change the variable to 513 for an example, it is so much harder for human eye to detect it. Why is that? What is so special about these numbers? 512: ![512 pixels](http://i.stack.imgur.com/T0qjD.png) 513: ![513 pixels](http://i.stack.imgur.com/vDzXS.png) **Edit: I'm running xampp on Windows to test it.**


title: How to store a list of Objects that might change in future?

text: I have set of Objects of the same class which have different values of their attributes. and I need to find the best match from a function under given scenarios out of these objects. In future these objects might increase as well. Quite similar to the way we have Color class in awt. we have some static color objects in the class with diff rgb values. But in my case say, I need to chose the suitable color out of these static ones based on certain criteria. So should I keep them in an arrayList or enum or keep them as static vars as in case of Colors. because I will need to parse through all of them and decide upon the best match. so I need them in some sort of collection. But in future if I need to add another type I will have to modify the class and add another list.add(object) call for this one and then it will violate the open-close principle. How should I go about it ? **EDIT:** To be more precise I have a roughly 7-8 branches of restaurants which wont increase that much..may be by 3-4 in few years and I need a function that will return the nearest Restaurant satisfying few other criteria. and For that I need to parse through all of them to decide which one suits the customer the most.


title: How to use Open Source Licenses and what do you recommend to me

text: I have a code that I'd like to share, but I'd like to publish it using an open source license. But I don't know how you have to use that licenses. How do you have to activate an open source license? Just including the text of the license in all files? What else do I have to do? Do I need to buy some right? Include a readme.txt in all the directories? I mean, what do I have to do if I want my code is protected by the legal test of a license? The second question is what it is the better license for this conditions:   * I don't care what people do with my code, educational purposes, to make money, I don't mind whatever they want to do with it.   * But I want people don't delete my name from the code, and If they use my code force them to mention me. If they change my code and someone ask for those modifications, they give the code with the modifications.   * But I don't want to force people to publish the code of they applications, even if they are using my code. What is the best license to that purposes?


title: FOSS licensing decision: What to read? What factors to consider?

text: Which reasoning would you follow to choose one license over another? Which literature would you expect someone to read, if he wants to make a meaningful decision about licensing? I specifically don't go too much into detail about my current project, because I am looking to learn how to make this decision correctly without getting a degree in law first.


title: Questions about software licensing

text: I've been having a discussion about licensing and open source software. Basically - the other guy is saying that licensing is easy, if you're going to build a product you can use an (any) open source project and make money by selling that code. My issue is that say I create a website or app with a project that uses a GPL license the restrictions aren't so straight forward - correct me if i'm wrong on each of these scenarios: 1 - i create an iPhone app using GPL code and put that app into the appstore - the code must be freely available to people buying that app. 2 - i create a website that my client hosts - they must have access to the code. 3 - i create a website as SaaS that my client "leases" but does not own - though it is hosted on their infrastructure - they must have access to that code Am i right on each of those assumptions? Are there any other issues i should be aware of under any other licensing terms for other licenses?


title: How can I control Visual Studio's window creation behavior?

text: I have recently installed Visual Studio 2010. By default it has a nice layout, and when I open files, the tabbed windows for those files appear where I like them to appear: source code on the upper half of the screen, compiler output, test status, trace windows on the bottom half. But, after a period of using it, I fat finger something, and then the window positioning logic goes haywire. One of the tabs gets undocked, and then after I redock it, nothing else operates like it used to operate. So maddening! It opens source code on the bottom, it opens other windows in unpredictable places. I undock and redock the windows where I want them, and the next time I open them, they go to the wrong place again. WTF? Even the "start page" gets moved. This is what it looks like when I start up: ![enter image description here](http://i.stack.imgur.com/8sKDn.png) I know I can do the `devenv /resetsettings` thing to restore to the original, and I have done this (Several times), but really I would like to know:   1. How is this happening? What am I doing to cause this behavior? How can I avoid it?    2. Can I undo it - get it to behave sanely again - without stopping visual studio, and restarting with the /resetsettings switch? What are the magic mouse clicks to make it revert? I know it's challenging to describe UI gestures, but if you have hints, I'd love to hear them. Does anyone else have this problem?


title: Flowcharting and Method Calls

text: I am doing out some flow charts and am wondering if I am approaching this correctly. In essence, I have several method calls and I am flowcharting each separately. However, several of these methods make a method call for some info and then continue. See this example: ![enter image description here](http://i.stack.imgur.com/bmqBD.png) I have 3 other methods that also call GetQueue() and I am wondering if I am representing this correctly. The AddQueue() flow visually looks like it is broken. NOTE: Changes made in my flowchart: ![enter image description here](http://i.stack.imgur.com/pWa9Q.png)


title: How much programming should I know before looking for first job/internship in tech company?

text: Im in college and just started to learn programming. How much should I atleast know before I start to look for jobs/internship so that they wont laught me out of office. I just started to learn programming and CS and literally don't know anything about it before college.


The development team I'm in has been working on a VERY large project for months now and we recently started to implement a kanban board with agile practices into our process. We have seen MASSIVE improvement in our throughput! Its so exciting! But we have one struggle right now. We have a total ticket count for the project and our supervisor has given us incentive(candy and popcorn boxes) for when we get down to 100 and 50 tickets. It at first felt like a great idea but it feels like new tickets are created just as fast as we can resolve them, and its making the team feel worse about our progress. So heres my question: Should you reward based on overall project completeness or velocity? And if completeness how do you make that feel more reachable?


title: HTML + CSS or HTML5 + CSS3 or HTML5 + jQuery

text: I want to be a good UI Developer. I'm confused whether I should learn ( **I need some serious suggestions** ): 1) **HTML + CSS + JavaScript or HTML5 + CSS3 + JavaScript or HTML5 + CSS3 + jQuery** 2) Is it required to learn CSS first before learning CSS3 ??? 3) If the above technologies needs to be prioritize then what would be the order?


title: Randomly select from list with increased odds

text: I have a list of entities. Every entity contains a number that holds how many times the entity has been selected. I need to make a function that selects `n` (say 25%) of the entities, randomly. What I want to do is increase the odds for entities that have been selected the least times. Suppose after 5 runs the times the entities have been selected can be anywhere from 0 to 5. But I don't want to have such a spread. I want the times the entities are selected more or less to be equal. How can I write a function that increases the odds for entities that haven't been selected as often as others? One way I could think of is to make a list that has more occurrences of lesser selected entities, increasing the chance the randomizer selects that entity. Any hints, tips, ideas? **EDIT:** Wow. Closed as not being a real question and reopened again. For not being a real question it did get a lot of answers and comments. Thanks for that. I got exactly what i wanted from them. I got some nice ideas to work out and to test.


title: What's the best way to learn nature-inspired algorithms?

text: I completed the Machine Learning course (Stanford) and got very interested, also after some research, I decided that I'd like to learn nature-inspired algorithms. I've found some resources like:   * Clever Algorithms: Nature-Inspired Programming Recipes (Book)   * Wyss institute (Website)   * Programming Game AI by Example (Book) The first reference look good and complete with pseudocode (giving me the possibility to implement everything in Ruby, my prefered language), and also gives ruby implementations for every code. But it lacks of exercises to practice, which I think is a key feature. The second is something that inspired me a lot to start studying this area, but they don't have any course or material to study. The third one looks good too, but has only a little amount of exercises, and might be too focused (I do like games, but I also want to study everything else related to nature-inspired algorithms). Also it is focused on C++ (not that it is a hard language, but I don't like its limitation compared to ruby), and I'd prefere something in Ruby or pseudocode (although it is not my main priority). Does anyone know something that also have exercises to complement the theory? Is there anything better to learn, with a particular focus on exercises? (Maybe courses or video lectures).


title: Is it necessary to follow the standard , take the C standard for that matter?

text: May be this question is a duplicate and I am a dumb to ask it here, but I searched a bit and none of the titles suggested to answer my question exactly . There are some very experienced folks on SO who always talk about the C standard. People seem to not like non-portable solutions, even if they work for me. Ok, I understand that the standard needs to be followed , but doesn't it put shackles on programmer's creativity? What are the concrete benefits that come from following a standard? Especially since compilers may implement the standard slightly differently.


title: Tic tac toe class diagram

text: I'm in a software engineering class and I want to practice some skills on the most basic case possible : tic tac toe. I know this is overkill but I want to do it in "proper" OOP. I designed a class diagram for it but there is one point where I don't clearly see what would be the best design decision. ![enter image description here](http://i.stack.imgur.com/US5Er.jpg) ("Joueur" means "Player", "PlancheDeJeu" means "Game board") Given this diagram, according to the `Expert`, `Low coupling` and `Strong cohesion` design patterns (sorry if those are not the correct english terms, I am translating) the score should be kept by the user class (Joueur). However, since there is no direct relation between Joueur and Système I don't exactly know how the game could display the score in a clean way. In this diagram, Système would have to ask the PlancheDeJeu object about the score and it would itself have to get it from Joueur. This seems wrong. I am trying to think of how to design an intermediary object that would link Joueur and Système but I can't come up with a good idea. What would be the best way to go here ? Thanks !


title: Use case decomposition for class registration system

text: I am currently working on refactoring a summer camp registration system to include some new features and will also be using it as the basis for a new after-school class registration system. For this new version of the system, I want to start out by writing use case descriptions for the registration process (and ultimately I plan to document all the use cases). I understand that the purpose of a use case is to accomplish a user's goal, but I'm still not sure how the registration process should be divided into use cases. Here are the options I've been thinking about:   1. One big "Register Student(s) For Classes" use case   2. Divide it into separate use cases: "Enter Student Information", "Select Classes", "Pay for Registrations"   3. Have separate use cases but also have a "Register Student(s) For Classes" use case which "includes" the more granular use cases Another factor to consider is timing: parents may want to enter their students' basic information (name, age, etc.) prior to the time when registration begins, but of course some parents will complete the whole registration process in one sitting. Also, payment won't always immediately follow class selection; in some cases parents will be allowed to complete their payment later (within a 48 hour window). I read some articles about use cases on Alistair Cockburn's website but I'm still confused as to what the guidelines are for dividing up use cases in a case like this. My inclination is to go with option 3 since the system will have a wizard interface that could potentially guide the user through the registration from start to end, accomplishing the "user goal" of registering his/her student(s) for classes, but the "included" use cases could also be initiated on their own. I was also wondering if I should have a separate "Modify Class Selections" use case for the case when the parent logs back into the system later and changes class selections on behalf of the student, or whether that should just be an alternative scenario of the "Select Classes" use case. What would you recommend, and why? What guidelines should be used in general when analyzing use case boundaries, beyond the idea of a "user goal"? * * * **Update:** I found this quote from the first chapter of Alistair Cockburn's book to be helpful: > Depending on the level of view needed at the time, the writer will choose to > describe a multi-sitting or **summary** goal, a single-sitting or **user > goal** , or a part of a user goal, or **subfunction**. Communicating which > of these is being described is so important that my students have come up > with two different gradients to describe them: by height relative to sea > level (above sea level, at sea level, underwater), and by color (white, > blue, indigo). It seems to me that "Register Student(s)" is a summary level goal, since it could potentially take multiple sittings to complete. The line is blurred in this case, but I think this idea of a summary use case suggests that my approach #3 above is a reasonable one.


I'm writing a small program that I want to be able to link with other programs. I also intend to run it from a command line interface, and maybe later with a GUI interface. How could distribution and reuse flexibility be hurt by linking my program as a static or dynamic library? Distribute it as a library and   * Dynamically link for GUI and command line interfaces   * Statically link for a stand alone binary


title: Refactoring Tomcat webapp deployments

text: **Background** We have several webapps running on Tomcat 7.0.x (on Linux). For historical reasons, we have populated the "Common" lib (i.e. $CATALINA_HOME/lib) with many application jars. These jars include Spring, Jackson, and our own persistence-layer jars. As we deploy new persistence-layer jars, we are embroiled in a classpath hell: some jars are OK in ~/webapps/foo/WEB-INF/lib, but some must be excluded and placed in Common. Recent adventures show that some may have to be in _both places_. Our local (Windows) build is similarly messy: we have one folder filled with jars. We build with Eclipse (not Gradle, Ant, etc) and do not have an explicit list of jars used by the web applications. The Linux build does use Ant, but semi-selectively globs jars into the WAR files. **Question** I would like to white-board a strategy on how to extricate ourselves from this predicament. One approach is listed below, but I would appreciate any refinements, or alternative approaches. The goal is to correct the deploy process, not the local build. **Strategy** On local machine, use Gradle to compile each web application:   * add compile-time dependencies until compilation is OK   * locate Gradle's local cache (or observe output) to find transitive run-time dependencies   * add all jars to ~/WEB-INF/lib for the web app, with explicit references in the formal Ant build   * deploy into a fresh, pristine Tomcat install   * observe startup logs for any "ClassNotFound" exceptions, both for 3rd-party libraries and our application libraries   * add these libraries to the formal Ant build   * perform regression QA tests on application and monitor for "ClassNotFound"


title: LuaJit FFI and hiding C implementation details

text: I would like to extend an application using LuaJit FFI. Having seen http://luajit.org/ext_ffi_tutorial.html this is surprisingly easy when comparing this to the Lua C API. So far so good. However I do not plainly want to wrap C functions but provide a higher level API to users writing scripts for the application. Especially I do not want users to be able to access "primitives", i.e. the `ffi.*` namespace. Is this possible or will that ffi namespace be available to user's Lua scripts? On the issue of Sandboxing Lua I found http://lua-users.org/wiki/SandBoxes which is not talking about FFI though. Furthermore, the plan I have described above is assuming that the introduction of abstraction layers happens on the lua side of code. Is this an advisable approach or would you rather abstract functionality on the statically compiled code (on the C-side)?


title: Getting related foreign keys from parent entities

text: I'm thinking about a design issue which affects my project's data base. Supposing there are three diferent tables:   * CLIENT    * ORDER    * PACKING_SLIP * * * Each **order** has its **client** and different **packing slips**. So there are some foreign keys which are compulsory, there would be _clientId_ for the `ORDER` and _orderId_ for the `PACKING_SLIP` table. That makes full sense.            ![First diagram](http://i.stack.imgur.com/DLSEq.png) Now suppose in my logic I want to have access to the client from the packing slip. As I'm using an ORM tool as Hibernate, that involves firstly accessing the order from the packing slip and after getting the client from it. If I want to have access to the client directly, I should add the _clientId_ foreign key also to the `PACKING SLIP` table.                                  ![Second diagram](http://i.stack.imgur.com/7jwu0.png) My question is, is that a correct design if there's a possibility to get the client joining the `ORDER` table? Isn't it a bit redundant? I think it's a control problem and the data base part shouldn't take care about it...


title: Multivariable decisions

text: I am running into a situation where my program can have different outcomes depending on the state of some variables. 4 variables are involved and they can all have different ( 3 to 4 different states). All the possible combinations are leading me to about 48 different cases which would be resolved using a 4 level deep nested if/else structure. So, I have a couple of questions,   1. Is there a better technique to draw logic or decision tables or some other structure so that you can model a decision tree for this many outcomes? When a decision is dependent on only 2 variables you can easily model this on a spreadsheet which is two dimensional by its nature but how do you deal with a case like the one I mentioned?   2. Other than a 4 level deep nested if/else structure is there a better programming technique to deal with this?


title: What techniques/methodologies do you use to organize your own open source projects, and why?

text: Aside from using a specific tool such as JIRA or Bugzilla, what techniques or development methodologies do you use to keep your OSS development efforts organized? and more importantly, how do you prioritize which features to deliver when there really isn't any paying clients that decide which features are the most important to deliver?


title: HDD Failure Paranoia

text: HDD Failure Paranoia I tend to make small programs for myself. Whenever I make an application I use a database application like MS Access or MySQL. I can CRUD my data as I want. No problem in finishing a task. The problem is when I try exploring more into File IO. I have heard of HDD crashes due to high read/write operations. I used to think that these happened only on server machines. But then I came to know that it happens on desktop machines too! So I now I have this huge mental blockage. Whenever I try converting my former software into ones with raw FILE IO, I lose the "mental drive/motivation" and freeze. I get thoughts like "OMG this task will cause this many reads/writes to the disk". I fear for loosing my hard disk. My goodness! It has happened so many times that I wish that the computer engineers had redesigned the internals of the computer to fix the problem and so I curse them a lot. A lot of my time gets wasted remotivating myself and the projects never get completed. Ya, ya, I know that behind the scenes the database applications use raw File IO to do their work! But who thinks of that when using them. All you are mostly thinking of is SQL and the resulting table in the resultset/recodset. The database applications are like a black box to raw File IO. Does anyone else think the same? Are my fears valid? What should I do? Any views/ consolations? Help! This makes me mad and unproductive!


title: Should I persist notification before or after publishing it through Redis pub/sub?

text: I'm implementing a mechanism to notify a group of users about newly inserted blog comments. The architecture uses the Redis Pub/Sub mechanism. By definition, the pub/sub mechanism aims to propagate message to the right subscribers, without storing/persisting anything. Although blog comments are obviously persisted in DB, I also expect all notifications to be sent to be persisted in order to be retrieved at any time by an offline user that gets logged again. Of course, Redis could have persistent messages, but the cost for that is pretty high. I use a distinct main database, let's take for the example MySql. Currently, the workflow is:   1. A blog comment posted by a user is handled by my backend and firstly stored in DB.   2. An event is raised, let's call it "CommentedBlogEvent", that triggers a worker aiming to detect all the targeted user of the comment.   3. Assuming that 10 users are target of the comment, I insert 10 "notification rows" in my database associating the commentId and the targeted userId, each specific to a user since it would have a flag read/unread.   4. Then, once all notifications have been persisted, I use Redis Pub/Sub to trigger subscribers aiming to push results to the concerned online clients (through WebSockets for instance). **The "issue" is that the process could be slow because of the step 3.** Would it be tolerated to make the step 4 before the step 3, meaning before persisting it in DB, since a potential data loss isn't dramatic in my case (non-financial data etc)?   Advantage: Client gets result more quickly.   Drawback: User could receive a notification that failed to be stored in background, leading to a missing notification when user refreshes the page. What is the best way to handle this case, while keeping my main database as the notifications store?


title: how do you cope with long hours of coding?

text: I am just a high-school student but for a while now I have been coding for weeks (from early in the morning to late at night). I really enjoy it, however it can be really monotone. I usually listen to some webradios but they take my attention from coding sometimes. How do you cope with long hours of coding? How often do you take breaks how do you spend them? Do you have any kind of further advice?


title: Can PHP handle mouse events?

text: I'm a newbie in php and i want to know if php can handle mouse events such as upon mouseCicked, mouseDoubleClicked, mouseMoved, mouseHovered etc.. And can events like button click , like displaying alert after clicking the submit button If yes, how can it be done ? I know that this can be done in Javascript               <script>         window.onbeforeunload = "Are you sure you want to leave?";     <script/>      Are there any other ways to do it ? Thank You !


title: Should we live by using Suhosin with PHP?

text: A lot of my security experienced friends have told me that I need to code my web applications for working under the Suhosin PHP patch, Suhosin being _"an advanced protection system for PHP installations [...] designed to protect servers and users from known and unknown flaws in PHP applications"_. Sense stating that feat, I have had to rewrite quite a bit of of my functions and classes. Is this the new standard of making secure web applications so that it is harder to exploit and compromise? Is Suhosin now a _common_ requirement for web development in PHP?


title: What are the proper uses of the various "Sign-in" terminologies?

text: What are the preferred use cases for the following sets of terms:   1. Log in / Log out   2. Log on / Log off   3. Sign in / Sign out   4. Sign on / Sign off From what I can guess, "Logging in" should be used for a long-lived session (like a website), whereas "Sign in" should be for something that you will be attending to (like IM or a financial transaction). I'm a little fuzzy here...


title: Efficient way of evaluating an array of strings then add to an array in Ruby

text: I am looking for an efficient way of evaluating an array of strings against a series of rules and then adding them to another array. For example I have an array of strings:   1. something   2. a   3. 1234   4. #gohere I want to iterate through all the items in the array and evaluate them based on a series of rules. For example:   * Strings greater that 1 in length   * Strings that don't start with the # character I was thinking of either:   1. Nested loop of if statements evaluating the string for each rule and if they all pass then add to another array   2. Evaluating the string against rule 1 then adding to the array then performing another evaluation - I have discounted this since it requires lots of array read/write operations to evaluate the complete ruleset. Please note that I have kept the number of rules to two for brevity however I could be needing up to 10 rules. Additionally, I do not control the original array since the function I am calling returns an array of strings. I know I may have answered my own question with the nested loop however I wondered if anyone had any ideas for optimizing this type of situation. Also, I know I asked this question in the reference of Ruby but any pseudo- code would suffice.


title: What do you think of an interpreter written in Java?

text: I am currently working on the implementation of a new programming language, for fun. I realize that most languages never become popular, but I still want the language to have a high-quality implementation. The language is loosely lisp-like. It supports closures, first-class continuations, a homoiconic syntax, first-class functions, etc. In addition, I want my language to be able to have access to already established library code (specifically the Java Standard library, etc). Dynamically compiling to JVM byte-code is essentially out of the question, because of the difficulty of implementing the stated feature set (excluding first-class functions) using a virtual machine that is not designed to support it. On the other-hand, compiling to C/C++ or some other lower-level language will lead to an unwanted degree of platform-dependence and/or reduce/remove the ability to use the Java standard library via programs written in my language. My (largely-completed) approach to the implementation is to implement a custom p-code interpreter in Java. The high-level language simply compiles its code on-the-fly to essentially an array of instructions for this custom virtual machine. Each instruction is an object that implements a common interface. When executed, the instructions manipulate a stack-machine. Unfortunately, executing each instruction requires a virtual method call; whereas, the normal implementation of such interpreters does not use object based instructions. However, current micro-benchmarks and guess-based-estimates indicate that the completed implementation should match the speed of Python, given equivalent programs. **So do you think this method of implementation is crazy or amateurish, given the language's design goals?** **What would you do differently?**


title: Are there any tools for testing drag & drop Windows desktop applications?

text: I need to develop a Windows desktop application (win32 API) which will use drag & drop extensively in many formats, including my own. I need to test it, for example, with CF_TEXT dragging, CF_RTF, CF_DIB, CF_METAFILEPICT, and many others. The tool needs to have the following features:   1. Displaying the content of DataObject dragged into it with all available format viewers.   2. Allows preparation of a few samples of different clipboard formats together in a single DataObject, ready for dragging into my app.   3. Allows including my own format names into the formats list of the testing tool.


title: Company internal Android Market

text: i want to establish Android in our company. Since our company doesn't want our future internal Android Apps distributet to the Google Android Market i would need to setup an internal market. But i can't find any resources. Maybe someone here knows more!


title: Publishing VS2010 Web Solution to WordPress

text: I am wondering if it's possible to publish a website that I have created onto WordPress? If so, how? The site was created using VS2010. I've done some searching online, and all I've came up with are tutorials on WordPress on how to publish your Visual Studio site onto other things not related to WordPress. Thank you


title: How do you deal with people who ask you to fix their computer?

text: Because I'm a programmer, people constantly ask me to fix their computer. How do you handle this situation? Do you make exceptions for relatives, friends and coworkers? Do you charge people for it?


What server-side language(s) should be used for user-created information sites such as Facebook, SE, Blogs, etc.?


title: How to restrict the violation of an N-Tier Architecture

text: Recently we fitted a 4-Tier Architecture in our project composed by the following four main layers :   * User Interface Layer.   * Data Access Layer.   * Domain Layer.   * Business Layer. All the layers fulfill their usual roles in 4-Tier Architecture and interact which each one in the usual way. We use SVN to maintain our CVS. My problem is that we have many inexperienced programmers developing in a well formed architecture, and we have to be checking all the time the code to find violations of the architecture. For example:   * Sometimes include access to database in the User Interface Layer and not in the Business Layer which is where interact with the Data Access layer to read or save data in the database. Problems like the above occurs all the time. My question is: How to check the code before the programmers can submit his new changes to the repository and report violations of the architecture? How to avoid doing this manually?


title: How can I share a managed DBConnection across various objects?

text: I am implementing what I thought was a simple object wrapper around a database where one object "PartRecord" represents one row of a database table. I want a client to be able to request a given record and to receive an object that contains the data. The data read and exposed properties are all a piece of cake, but I am trying to share the MySqlConnection object in a coherent way. My initial naive implementation was to keep a private MySqlConnection object in a VB module and to have a functions that my classes can call. This would effectively be a singleton that any of my classes could share.               Private MySqlCn as MySqlConnection          Friend Function GetMySqlConnection() as MySqlConnection        If IsNothing(MySqlCn) then  MySqlCn = New MySqlConnection(cnstring)        if MySqlCn.State = ConnectionState.Closed then MySqlConnection.Open(cnstring)        Return MySqlCn     End Function          Friend Sub CloseMySqlConnection()        If Not IsNothing(MySqlCn) AndAlso (Not MySqlCn.State = ConnectionState.Closed) Then  MySqlCn.Close     End Function      With this method you can generally ensure that the objects will share a connection and that it will be open whenever the database is available, but you cannot guarantee that the connection gets closed until the program ends. Some alternatives that I have tried:   1. close connection after every read               'in PartRecord constructor:     Using MySqlCn as MySqlConnection = GetMySqlConnection       'read data     End Using     'this causes an open and close for every object you instantiate     'obviously bad        2. just leave it open              'in constructor:     Dim MySqlCn as MySqlConnection = GetMySqlConnection     'read data     'no close or dispose, open for the next guy     'we are sharing an open connection, but     'the connection won't really close until the program ends.     'I think it will close then, but I was a lot more certain of it     'in the COM days when I could wrap it in a class and     'close it in the Terminate event when the reference count hit zero        3. quit having public constructors and have a object factory that implements IDisposable to manage the connection              'maybe not as nice for the client code     'but does force a sharing of connections     'and the client can call PartFactory.Close or PartFactory.Dispose when they are done     'the PartFactory replaces the singleton     'even though you could have more than one if you wanted        4. your better idea . . . **I would like to know if I can keep my preferred style of public object constructors for a given record, but still manage the shared connection in a responsible way.** I think this might be impossible since the standalone publicly creatable objects do not know when the client is ever done. I think I must leak the "we are connecting to a database y'know" abstraction to the client or else cause open connections or unnecessary network traffic. Also, the documentation tells you that IDisposable is usually used for unmanaged things (files, handles, etc). Is is appropriate/necessary for holding a managed object like a .NET DBConnection object? I like that the client would have the Using syntax and that I am signalling that it needs closed in a standard way, but is the deterministic close that I am trying to get necessary and worth my effort in a garbage collected world? I am not comfortable saying "well the connection will close eventually when no one wants it" since this component will be eventually be used by many different clients in the organization. What if they crash, or we use it in a long- running server process? If it matters, this is the first of several DB wrapper classes. Whatever scheme I use here, I want to maintain across the entire component.


title: open source social network allowing advertising

text: I want to build up a social network, targeted to a specific interest. I want to generate revenues in form of ads. I first thought of building it from scratch, which will take a lot of time (even if it's something simple), then i remembered there are open source options like Diaspora or Friendica. I don't know if there are others... My question is, with these previously mentioned projects or any other, ¿is it possible to legally generate revenues? Diaspora license is: AGPLv3,[3][4] some parts dual-licensed under MIT License[5] as well Friendica: AGPL ¡Thank you!


title: Learning but then forgetting

text: I am teaching myself to program in C and have been for a few months. I recently took a one month break and came back a week ago, and it's all gone. I had to look up some things that I really put effort into understanding (see: pointers) and some others just stuck with me. Now learning about `malloc` and dynamically allocated memory is also getting a bit tough. What do you suggest for keeping it all retained? Will it just come with time and experience?


title: Using JDBC to asynchronously read large Oracle table

text: What strategies can be used to read every row in a large **Oracle** table, **only once** , but as fast as possible with JDBC & Java ? Consider that each row has non-trivial amounts of data (30 columns, including large text in some columns). Some strategies I can think of are:   * Single thread and read table. (Too slow, but listed for clarity)   * Read the id's into ConcurrentLinkedQueue, use threads to consume queue and query by id in batches.   * Read id's into a JMS queue, use workers to consume queue and query by id in batches. What other strategies could be used ? _For the purpose of this question assume processing of rows to be free._


title: online quiz app android

text: I'm interested in working on a project. The project involves a test taking app with 2 modules where there is one quizzer and multiple test takers. I want to make a web application which also has an android app for the same. How should i go along with making this project so that there are no issues as some user can be on the web app and some on the android app? How can i do it so that i don't have to write separate code for the web app and the android app? What should be my approach because i have never made an internet based android app? ( i only have some basic android programming experience, and i'm willing to learn more) but i have a fair experience with developing with jsp/servlets and frameworks. UPDATE: I do not want detailed answers. Just point me in the right direction.


title: Why should main() be short?

text: I've been programming for over 9 years, and according to the advice of my first programming teacher, I always keep my `main()` function extremely short. At first I had no idea why. I just obeyed without understanding, much to the delight of my professors. After gaining experience, I realized that if I designed my code correctly, having a short `main()` function just sortof happened. Writing modularized code and following the single responsibility principle allowed my code to be designed in "bunches", and `main()` served as nothing more than a catalyst to get the program running. Fast forward to a few weeks ago, I was looking at Python's souce code, and I found the `main()` function:               /* Minimal main program -- everything is loaded from the library */          ...          int     main(int argc, char **argv)     {         ...         return Py_Main(argc, argv);     }      Yay python. Short `main()` function == Good code. Programming teachers were right. Wanting to look deeper, I took a look at Py_Main. In its entirety, it is defined as follows:               /* Main program */          int     Py_Main(int argc, char **argv)     {         int c;         int sts;         char *command = NULL;         char *filename = NULL;         char *module = NULL;         FILE *fp = stdin;         char *p;         int unbuffered = 0;         int skipfirstline = 0;         int stdin_is_interactive = 0;         int help = 0;         int version = 0;         int saw_unbuffered_flag = 0;         PyCompilerFlags cf;              cf.cf_flags = 0;              orig_argc = argc;           /* For Py_GetArgcArgv() */         orig_argv = argv;          #ifdef RISCOS         Py_RISCOSWimpFlag = 0;     #endif              PySys_ResetWarnOptions();              while ((c = _PyOS_GetOpt(argc, argv, PROGRAM_OPTS)) != EOF) {             if (c == 'c') {                 /* -c is the last option; following arguments                    that look like options are left for the                    command to interpret. */                 command = (char *)malloc(strlen(_PyOS_optarg) + 2);                 if (command == NULL)                     Py_FatalError(                        "not enough memory to copy -c argument");                 strcpy(command, _PyOS_optarg);                 strcat(command, "\n");                 break;             }                  if (c == 'm') {                 /* -m is the last option; following arguments                    that look like options are left for the                    module to interpret. */                 module = (char *)malloc(strlen(_PyOS_optarg) + 2);                 if (module == NULL)                     Py_FatalError(                        "not enough memory to copy -m argument");                 strcpy(module, _PyOS_optarg);                 break;             }                  switch (c) {             case 'b':                 Py_BytesWarningFlag++;                 break;                  case 'd':                 Py_DebugFlag++;                 break;                  case '3':                 Py_Py3kWarningFlag++;                 if (!Py_DivisionWarningFlag)                     Py_DivisionWarningFlag = 1;                 break;                  case 'Q':                 if (strcmp(_PyOS_optarg, "old") == 0) {                     Py_DivisionWarningFlag = 0;                     break;                 }                 if (strcmp(_PyOS_optarg, "warn") == 0) {                     Py_DivisionWarningFlag = 1;                     break;                 }                 if (strcmp(_PyOS_optarg, "warnall") == 0) {                     Py_DivisionWarningFlag = 2;                     break;                 }                 if (strcmp(_PyOS_optarg, "new") == 0) {                     /* This only affects __main__ */                     cf.cf_flags |= CO_FUTURE_DIVISION;                     /* And this tells the eval loop to treat                        BINARY_DIVIDE as BINARY_TRUE_DIVIDE */                     _Py_QnewFlag = 1;                     break;                 }                 fprintf(stderr,                     "-Q option should be `-Qold', "                     "`-Qwarn', `-Qwarnall', or `-Qnew' only\n");                 return usage(2, argv[0]);                 /* NOTREACHED */                  case 'i':                 Py_InspectFlag++;                 Py_InteractiveFlag++;                 break;                  /* case 'J': reserved for Jython */                  case 'O':                 Py_OptimizeFlag++;                 break;                  case 'B':                 Py_DontWriteBytecodeFlag++;                 break;                  case 's':                 Py_NoUserSiteDirectory++;                 break;                  case 'S':                 Py_NoSiteFlag++;                 break;                  case 'E':                 Py_IgnoreEnvironmentFlag++;                 break;                  case 't':                 Py_TabcheckFlag++;                 break;                  case 'u':                 unbuffered++;                 saw_unbuffered_flag = 1;                 break;                  case 'v':                 Py_VerboseFlag++;                 break;          #ifdef RISCOS             case 'w':                 Py_RISCOSWimpFlag = 1;                 break;     #endif                  case 'x':                 skipfirstline = 1;                 break;                  /* case 'X': reserved for implementation-specific arguments */                  case 'U':                 Py_UnicodeFlag++;                 break;             case 'h':             case '?':                 help++;                 break;             case 'V':                 version++;                 break;                  case 'W':                 PySys_AddWarnOption(_PyOS_optarg);                 break;                  /* This space reserved for other options */                  default:                 return usage(2, argv[0]);                 /*NOTREACHED*/                  }         }              if (help)             return usage(0, argv[0]);              if (version) {             fprintf(stderr, "Python %s\n", PY_VERSION);             return 0;         }              if (Py_Py3kWarningFlag && !Py_TabcheckFlag)             /* -3 implies -t (but not -tt) */             Py_TabcheckFlag = 1;              if (!Py_InspectFlag &&             (p = Py_GETENV("PYTHONINSPECT")) && *p != '\0')             Py_InspectFlag = 1;         if (!saw_unbuffered_flag &&             (p = Py_GETENV("PYTHONUNBUFFERED")) && *p != '\0')             unbuffered = 1;              if (!Py_NoUserSiteDirectory &&             (p = Py_GETENV("PYTHONNOUSERSITE")) && *p != '\0')             Py_NoUserSiteDirectory = 1;              if ((p = Py_GETENV("PYTHONWARNINGS")) && *p != '\0') {             char *buf, *warning;                  buf = (char *)malloc(strlen(p) + 1);             if (buf == NULL)                 Py_FatalError(                    "not enough memory to copy PYTHONWARNINGS");             strcpy(buf, p);             for (warning = strtok(buf, ",");                  warning != NULL;                  warning = strtok(NULL, ","))                 PySys_AddWarnOption(warning);             free(buf);         }              if (command == NULL && module == NULL && _PyOS_optind < argc &&             strcmp(argv[_PyOS_optind], "-") != 0)         {     #ifdef __VMS             filename = decc$translate_vms(argv[_PyOS_optind]);             if (filename == (char *)0 || filename == (char *)-1)                 filename = argv[_PyOS_optind];          #else             filename = argv[_PyOS_optind];     #endif         }              stdin_is_interactive = Py_FdIsInteractive(stdin, (char *)0);              if (unbuffered) {     #if defined(MS_WINDOWS) || defined(__CYGWIN__)             _setmode(fileno(stdin), O_BINARY);             _setmode(fileno(stdout), O_BINARY);     #endif     #ifdef HAVE_SETVBUF             setvbuf(stdin,  (char *)NULL, _IONBF, BUFSIZ);             setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ);             setvbuf(stderr, (char *)NULL, _IONBF, BUFSIZ);     #else /* !HAVE_SETVBUF */             setbuf(stdin,  (char *)NULL);             setbuf(stdout, (char *)NULL);             setbuf(stderr, (char *)NULL);     #endif /* !HAVE_SETVBUF */         }         else if (Py_InteractiveFlag) {     #ifdef MS_WINDOWS             /* Doesn't have to have line-buffered -- use unbuffered */             /* Any set[v]buf(stdin, ...) screws up Tkinter :-( */             setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ);     #else /* !MS_WINDOWS */     #ifdef HAVE_SETVBUF             setvbuf(stdin,  (char *)NULL, _IOLBF, BUFSIZ);             setvbuf(stdout, (char *)NULL, _IOLBF, BUFSIZ);     #endif /* HAVE_SETVBUF */     #endif /* !MS_WINDOWS */             /* Leave stderr alone - it should be unbuffered anyway. */         }     #ifdef __VMS         else {             setvbuf (stdout, (char *)NULL, _IOLBF, BUFSIZ);         }     #endif /* __VMS */          #ifdef __APPLE__         /* On MacOS X, when the Python interpreter is embedded in an            application bundle, it gets executed by a bootstrapping script            that does os.execve() with an argv[0] that's different from the            actual Python executable. This is needed to keep the Finder happy,            or rather, to work around Apple's overly strict requirements of            the process name. However, we still need a usable sys.executable,            so the actual executable path is passed in an environment variable.            See Lib/plat-mac/bundlebuiler.py for details about the bootstrap            script. */         if ((p = Py_GETENV("PYTHONEXECUTABLE")) && *p != '\0')             Py_SetProgramName(p);         else             Py_SetProgramName(argv[0]);     #else         Py_SetProgramName(argv[0]);     #endif         Py_Initialize();              if (Py_VerboseFlag ||             (command == NULL && filename == NULL && module == NULL && stdin_is_interactive)) {             fprintf(stderr, "Python %s on %s\n",                 Py_GetVersion(), Py_GetPlatform());             if (!Py_NoSiteFlag)                 fprintf(stderr, "%s\n", COPYRIGHT);         }              if (command != NULL) {             /* Backup _PyOS_optind and force sys.argv[0] = '-c' */             _PyOS_optind--;             argv[_PyOS_optind] = "-c";         }              if (module != NULL) {             /* Backup _PyOS_optind and force sys.argv[0] = '-c'                so that PySys_SetArgv correctly sets sys.path[0] to ''                rather than looking for a file called "-m". See                tracker issue #8202 for details. */             _PyOS_optind--;             argv[_PyOS_optind] = "-c";         }              PySys_SetArgv(argc-_PyOS_optind, argv+_PyOS_optind);              if ((Py_InspectFlag || (command == NULL && filename == NULL && module == NULL)) &&             isatty(fileno(stdin))) {             PyObject *v;             v = PyImport_ImportModule("readline");             if (v == NULL)                 PyErr_Clear();             else                 Py_DECREF(v);         }              if (command) {             sts = PyRun_SimpleStringFlags(command, &cf) != 0;             free(command);         } else if (module) {             sts = RunModule(module, 1);             free(module);         }         else {                  if (filename == NULL && stdin_is_interactive) {                 Py_InspectFlag = 0; /* do exit on SystemExit */                 RunStartupFile(&cf);             }             /* XXX */                  sts = -1;               /* keep track of whether we've already run __main__ */                  if (filename != NULL) {                 sts = RunMainFromImporter(filename);             }                  if (sts==-1 && filename!=NULL) {                 if ((fp = fopen(filename, "r")) == NULL) {                     fprintf(stderr, "%s: can't open file '%s': [Errno %d] %s\n",                         argv[0], filename, errno, strerror(errno));                          return 2;                 }                 else if (skipfirstline) {                     int ch;                     /* Push back first newline so line numbers                        remain the same */                     while ((ch = getc(fp)) != EOF) {                         if (ch == '\n') {                             (void)ungetc(ch, fp);                             break;                         }                     }                 }                 {                     /* XXX: does this work on Win/Win64? (see posix_fstat) */                     struct stat sb;                     if (fstat(fileno(fp), &sb) == 0 &&                         S_ISDIR(sb.st_mode)) {                         fprintf(stderr, "%s: '%s' is a directory, cannot continue\n", argv[0], filename);                         fclose(fp);                         return 1;                     }                 }             }                  if (sts==-1) {                 /* call pending calls like signal handlers (SIGINT) */                 if (Py_MakePendingCalls() == -1) {                     PyErr_Print();                     sts = 1;                 } else {                     sts = PyRun_AnyFileExFlags(                         fp,                         filename == NULL ? "<stdin>" : filename,                         filename != NULL, &cf) != 0;                 }             }              }              /* Check this environment variable at the end, to give programs the          * opportunity to set it from Python.          */         if (!Py_InspectFlag &&             (p = Py_GETENV("PYTHONINSPECT")) && *p != '\0')         {             Py_InspectFlag = 1;         }              if (Py_InspectFlag && stdin_is_interactive &&             (filename != NULL || command != NULL || module != NULL)) {             Py_InspectFlag = 0;             /* XXX */             sts = PyRun_AnyFileFlags(stdin, "<stdin>", &cf) != 0;         }              Py_Finalize();     #ifdef RISCOS         if (Py_RISCOSWimpFlag)             fprintf(stderr, "\x0cq\x0c"); /* make frontend quit */     #endif          #ifdef __INSURE__         /* Insure++ is a memory analysis tool that aids in discovering          * memory leaks and other memory problems.  On Python exit, the          * interned string dictionary is flagged as being in use at exit          * (which it is).  Under normal circumstances, this is fine because          * the memory will be automatically reclaimed by the system.  Under          * memory debugging, it's a huge source of useless noise, so we          * trade off slower shutdown for less distraction in the memory          * reports.  -baw          */         _Py_ReleaseInternedStrings();     #endif /* __INSURE__ */              return sts;     }      Good God Almighty...it is big enough to sink the Titanic. It seems as though Python did the "Intro to Programming 101" trick and just moved all of `main()`'s code to a different function called it something very similar to "main". Here's my question: Is this code terribly written, or are there other reasons to have a short main function? As it stands right now, I see absolutely no difference between doing this and just moving the code in `Py_Main()` back into `main()`. Am I wrong in thinking this?


title: Term for Production Rollback

text: The firm I work at keeps a copy of the compiled source code on production. So basically on our Production server, we have two folders:               ProductionServer\SourceCode\          ProductionServer\SourceCodeRollback\      The Rollback folder always contains one version older code. This is done so that on deployment nights, if something is wrong with the new code, the deployer(who is not familiar with source control software) has the older version to revert back to. My question is: Is there an official computer science term/nomenclature for the Rollback folder? Or is "Rollback" itself the official term?


title: How do I approach this PHP/MYSQL query?

text: I have a reservation system that I have coded and my final task is to allow the user to enter a set of dates and then show them all available options. The reservation table is set up with `unit_id`, `check_in` and `check_out`. There are twelve different unit numbers. So I have to somehow iterate through them and find the units that have no taken dates during the date range the user has put in. Just having some trouble conceptualizing what needs to happen. Pseudo code               $units = array (all the units);          foreach($units as $key = $value){              Run a query searching through all reservations for that unit,          if the unit is available, add to our $available_units array for the view later          }      Checking availability has me stumped too though. What is the most efficient way to use the customers available date range and compare to the date ranges in the db?


title: Sort algorithms that work on large amount of data

text: I am looking for sorting algorithms that can work on a large amount of data, i.e. that can work even when the whole data set cannot be held in main memory at once. The only candidate that I have found up to now is merge sort: you can implement the algorithm in such a way that it scans your data set at each merge without holding all the data in main memory at once. The variation of merge sort I have in mind is described in this article in section **Use with tape drives**. I think this is a good solution (with complexity O(n x log(n)) but I am curious to know if there are other (possibly faster) sorting algorithms that can work on large data sets that do not fit in main memory. **EDIT** Here are some more details, as required by the answers:   * The data needs to be sorted periodically, e.g. once in a month. I do not need to insert a few records and have the data sorted incrementally.   * My example text file is about 1 GB UTF-8 text, but I wanted to solve the problem in general, even if the file were, say, 20 GB.   * It is not in a database and, due to other constraints, it cannot be.   * The data is dumped by others as a text file, I have my own code to read this text file.   * The format of the data is a text file: new line characters are record separators. One possible improvement I had in mind was to split the file into files that are small enough to be sorted in memory, and finally merge all these files using the algorithm I have described above.


title: How would I use a browser as a GUI for Emacs apps?

text: I've started using Emacs, and love it. Naturally, I'm thinking about ways of extending it. I' m particularly fascinated by the thought of creating browser based GUIs for some stuff I would otherwise do in emacs, particularly reviewing fairly static data. An example: I have a bunch of txt files (created and edited in Emacs) containing quotes and passages from my favorite books. It would be cool to present them in a more visually striking/engaging manner. For example with unique color schemes and typefaces for different authors, and several columns of text to use more screen real estate (like in Stanza, the .epub reader). Are there simpler ways of rendering HTML derived from plain text files that are open in Emacs than browsers?


title: Development Approach: User Interface In or Domain Model Out?

text: While I've never delivered anything using Smalltalk, my brief time playing with it has definitely left its mark. The only way to describe the experience is MVC the way it was meant to be. Essentially, all the heavy lifting for your application is done in the business objects (or domain model if you are so inclined). The standard controls are bound to the business objects in some way. For example, a text box is mapped to an object's field (the field itself is an object so it's easy to do). A button would mapped to a method. This is all done with a very simple and natural API. We don't have to think about binding objects, etc. It just works. Yet, in many newer languages and APIs you are forced to think from the outside in. First with C++ and MFC, and now with C# and WPF, Microsoft has gotten it's developer world hooked on GUI builders where you build your application by implementing event handlers. Java Swing development isn't so different, only you are writing the code to instantiate the controls on the form yourself. For some projects, there may never even be a domain model--just event handlers. I've been in and around this model for most of my carreer. Each way forces you to think differently. With the Smalltalk approach, your domain is smart while your GUI is dumb. With the default VisualStudio approach, your GUI is smart while your domain model (if it exists) is rather anemic. Many developers that I work with see value in the Smalltalk approach, and try to shoehorn that approach into the VisualStudio environment. WPF has _some_ dynamic binding features that makes it possible; but there are limitations. Inevitably some code that belongs in the domain model ends up in the GUI classes. So, which way do you design/develop your code? Why?   * GUI first. User interaction is paramount.   * Domain first. I need to make sure the system is correct before we put a UI on it. There's pros and cons for either approach. Domain model fits in there with crystal cathedrals and pie in the sky. GUI fits in there with quick and dirty (sometimes really dirty). And for an added bonus: How do you make sure the code is maintainable?


title: Where can I find interesting project to work on?

text: If I want to learn a new programming language, I cannot master it without digging it deeply. Maybe a project would be good, but I am lacking idea for them. Where can I find projects to work on, maybe some open-source project?


title: Is context inheritance, as shown by Head First Design Patterns' Duck example, irrelevant to strategy pattern?

text: In Head First Design Patterns it teaches the strategy pattern by using a Duck example where different subclasses of Duck can be assigned a particular behavior at runtime. From my understanding the purpose of the strategy pattern is to change **a single** object's behavior at runtime, yet they are using inheritance of Duck to change the behavior of various types of Duck. ![Strategy Pattern](http://i.stack.imgur.com/EIsOf.png) ## Relevance? **Is context inheritance of Duck irrelevant to the strategy pattern or is varying Duck types and also varying their behaviors a good reason to employ the strategy pattern?** Do situations where you need to vary both constitute a good reason to use strategy pattern? Why would they include this as the strategy pattern example? ## A Simpler Example Could I further simplify this example by just having a Duck class (no derived classes)? Then when implementing one duck object it can be assigned different behaviors based on certain circumstances that aren't dependent on its own object type. For example: FlyBehavior changes based on the weather or QuackBehavior changes based on the time of day or how hungry a duck is. I realize this would be solving a different problem than from the one in the book, but what I am looking for is a relevant strategy pattern example to fall back on. Would my example above constitute the strategy pattern as well? ## Edit: I was successful in finding 2 simpler strategy pattern examples that adhere more strictly to being just strategy patterns without context inheritance: Hunter.java and solver.py.


title: What would be the fastest way of storing or calculating legal move sets for chess pieces?

text: For example if a move is attempted I could just loop through a list of legal moves and compare the x,y but I have to write logic to calculate those at least every time the piece is moved. Or, I can store in an array [,] and then check if x and y are not 0 then it is a legal move and then I save the data like this [0][1][0][0] etc etc for each row where 1 is a legal move, but I still have to populate it. I wonder what the fastest way to store and read a legal move on a piece object for calculation. I could use matrix math as well I suppose but I don't know. **Basically I want to persist the rules for a given piece so I can assign a piece object a little template of all it's possible moves considering it is starting from it's current location** , which should be just one table of data. But is it faster to loop or write LINQ queries or store arrays and matrices?               public class Move     {         public int x;         public int y;     }          public class ChessPiece : Move     {             private List<Move> possibleMoves { get; set; }              public bool LegalMove(int x, int y){           foreach(var p in possibleMoves)           {              if(p.x == x && p.y == y)              {  return true;  }              }         }     }      Anyone know?


title: Subsumption architecture vs. perceptual control theory

text: I'm a new person to AI field and I have to research and compare two different architectures for a thesis I'm writing. Before you scream (homework thread), I've been reading on these two topics only to find that I'm confusing myself more.. let me first start with stating briefly what I know so far. **Subsumption** is based on the fact that targets of a system are different in sophistication, thus that requires them to be added as **_layers_** , each layer can suppress (modify) the command of the layers below it, and there are inhibitors to stop signals from execution lets say. **PCT** stresses on the fact that there are nodes to handle environmental changes ( ** _negative feedback_** ), so the inputs coming from an environment go through a comparator node and then an action is generated by that node, HPCT or (Hierarchical PCT) is based on nesting these cycles inside each other so a small cycle to avoid crashing would be nested in a more sophisticated cycle that targets a certain location for example. My questions, am I getting this the right way? am I missing any critical understanding about these two models? also any idea where I can find simplified explanations for each theory (so far been struggling trying to understand the papers from Google scholar). * * * **Edit:**   * The acceptable result would be to compare and contrast subsumption with PCT as alternative control structures in behaviour-based robotics.   * The experiments will be done on Mindstorm NXT 2.0 robot and the implementation will be done using PureData.   * I'm not seeking complex behavior, only several models that will demonstrate capabilities of PCT and Subsumption and come up with weaknesses and strengths about each approach.   * As for the other points 'rwong' mentioned, I don't believe they're part of my research scope. _**my main target here is to get he concepts fully understood as this is my critical phase to implement a fully correct solution that would allow the comparison_**


title: Entity framework and Eager loading and enterprise application with DDD aproach

text: We are trying to create an ASP.NET MVC 4 application using entity framework with domain driven development style pattern approach. As you can see in our part of domain layer, we have a complex design. We need to load entity with lazy as well as eager methods. Unfortunately we have big problem with these methods in entity framework. As we understand, for eager loading in EF we have to use the `Include` method and give string of properties and properties of properties etc. (In Hibernate and java we could use annotation top of member to load eagerly and it was so much easier than this approach). But the horrible problem is that we have inheritance structures and heavy polymorphism, in these states we don’t have that’s string we should given to include because we don’t know which derived class of class is selected to understand which properties should include. ![Our model](http://i.stack.imgur.com/b5OCM.png) For example as you can see a result has a collection of items and then decides to add some group to this collection and each of those groups have some groups and fields (like the composition pattern). Now imagine we want to load a result is like the one talked above. When I want to write a string of given include I don’t know what items of this result are groups. Because we can’t predict these items are groups and so these groups have collection of items which should load.               this.Items = new List<Item>                  {                     new Group(                         a,                         new List<Item>                         {                              new Field(b),                             new Field(c),                             new Field(d),      At last we have a critical question: is entity framework designed for Enterprise Applications with a complex domain and DDD approach? If not, how we follow the approach of Martin Fowler and Eric Evans in software engineering and enterprise application in C#?


title: Better way to train new hires

text: The team I currently am part of experiences fairly high turnover, with members typically moving to different projects within the same company. Currently our "training" for new members is to pair them with a primary contact (usually the most recent person to complete their training) who will provide them with hands-on experience and will ask more senior developers if the newer hire ask something the mentor doesn't know. It provides a chance for the new hire to get involved quickly, and challenges the mentor to improve his/her understanding of the system also. However, as you can imagine, this style of training is very time consuming, and doesn't provide a very good knowledge transfer (misconceptions propagate, gaps expand). I've been tasked with generating documentation and training materials for our future new hires. I already do technical writing occasionally, but it's for the end user and is highly specific with lots of screenshots and consumes a large amount of time to complete. Creating the new documentation for new hires is considered low priority and I've only currently got ~40 hours to work on it. Documenting the system the current way I write technical documentation would barely scratch the surface in 40 hours. Especially considering I have to document not only about the code base, but also about deployments and support. How can I quickly write documentation to get new hires up to date as quickly as possible without investing significant time in writing the documentation? **Additional Information:**   We currently have both a wiki, and some training documentation, however both are kind of sparse.


title: How to inform a colleague of .NET and C# coding guidelines without offending him?

text: I have a good colleague at work that I work often and he is pretty smart. He is not a .NET programmer but now is coding for a long time too, mainly C++, Python, etc. I see that he is using Python like guidelines in naming, etc, and in shared code, it looks non-uniform to have things like: getEffectById, etc and many other Python names, etc. How do you guys think I should tell this to him so he isn't offended or think I am looking down on his code or skills, because I don't.


title: Why should I choose Java, Flash, or HTML5 for an online game with server communication

text: I'm starting to design a game that is going to have the following characteristics, and I'm trying to decide how I should program it. I'll also give a bit of my experience after, to help make the decision a bit better.   1. The game should be able to support both Facebook integration, and a stand alone version.   2. I don't want to do it right away, but I am thinking it would be a good idea to port this to Android/ iPhone at some point in time.   3. The game will involve communication with a server. The method of communication is still opened, but I imagine most of it will be over HTTPS. I'm suspecting most of the work is going to be done on the server at this point in time, and that the client is mainly going to show the results of the previous frame, and select what to do for the next frame.   4. I suspect that at some point in time, I'm going to want to put in animations and the like, but this is not critical for the beginning of the game.   5. The game is essentially an online board game, complete with cards, a board, etc. I'm currently looking at Flash, HTML 5, and a Java applet. Some random pieces of information.   1. I have access to Adobe Flash, actually the whole Design Premium, CS5.   2. I have some experience with programming Android apps.   3. I have done work with HTML, but it has been quite a while. I've only done a little bit of Javascript, but I don't recall it being particularly hard.   4. I routinely program in C, C++, Matlab, and Android (Java). I fairly often program in Python, Perl, Shell, and I have programmed before in Basic, HTML, Javascript.


title: Is it bad practice to run Node.js and apache in parallel?

text: I have an idea in mind and would like to know if that's the way to go for my end application. Think of my application as a social networking system in which I want to implement chat functionality. For that, I'd like to push data from the server to the client. I have heard I could use Node.js for that. In the meanwhile, I want a 'regular' system for posting status updates and such, for which I'd like to use PHP and an apache server. The only way I can think of is having Node.js and apache running parallel. But is that the way to go here? I'd think there would be a somewhat neater solution for this.


title: How are OOP "objects" and "classes" organized in memory in terms of assembly language?

text: How are objects organized in memory? For instance, I know that a function is a piece of code in memory, that expects parameters via the stack and/or the registers and handles it's own stack frame. But objects are a much more complicated structure. How are they organized? Does each object have "links" to methods and passes address to itself to that method? It would be great to see a good explanation of this topic. UPD. I made the question more exact, and I'm mainly interested in statically typing languages.


title: How would I design an interface such that it's clear which properties may change their value, and which will remain constant?

text: I am having a design issue regarding .NET properties.               interface IX     {         Guid Id { get; }         bool IsInvalidated { get; }         void Invalidate();     }      **Problem:** This interface has two read-only properties, `Id` and `IsInvalidated`. The fact that they are read-only, however, is by itself no guarantee that their values will remain constant. Let's say that it were my intention to make it very clear that…   * `Id` represents a constant value (which may therefore be safely cached), while    * `IsInvalidated` might change its value during the lifetime of an `IX` object (and so shouldn't be cached). How could I modify `interface IX` to make that contract sufficiently explicit? **My own three attempts at a solution:**   1. The interface is already well-designed. The presence of a method called `Invalidate()` allows a programmer to infer that the value of the similarly-named property `IsInvalidated` might be affected by it. This argument holds only in cases where the method and property are similarly named.   2. Augment this interface with an event `IsInvalidatedChanged`:              bool IsInvalidated { get; }     event EventHandler IsInvalidatedChanged;      The presence of a `…Changed` event for `IsInvalidated` states that this property may change its value, and the absence of a similar event for `Id` is a promise that that property will not change its value. I like this solution, but it's a lot of additional stuff that may not get used at all.   3. Replace the property `IsInvalidated` with a method `IsInvalidated()`:              bool IsInvalidated();      This might be too subtle a change. It's supposed to be a hint that a value is computed freshly each time -- which wouldn't be necessary if it was a constant. The MSDN topic "Choosing Between Properties and Methods" has this to say about it: > _Do use a method, rather than a property, in the following situations. […] > The operation returns a different result each time it is called, even if the > parameters do not change._ **What kind of answers do I expect?**   * I am most interested in entirely different solutions to the problem, along with an explanation how they beat my above attempts.   * If my attempts are logically flawed or have significant disadvantages not yet mentioned, such that only one solution (or none) remains, I would like to hear about where I went wrong. If the flaws are minor, and more than one solution remains after taking it into consideration, please comment.   * At the very least, I would like some feedback on which is your preferred solution, and for what reason(s).


title: How to simulate events that cause exceptions to test try/catch blocks?

text: I understand how exceptions work and how to catch and handle them in C# but how can I simulate events that may cause an exception to ensure that it is caught correctly? For example, is it possible to run an application in a kind of test bed where it's possible to simulate network problems, database problems, etc? Exceptions by their nature seem hard to reproduce thus making it hard to ensure your code can cope with them. Although I mainly develop using C#/.NET/Visual Studio, answers or resources relating to other languages could be useful.


title: Pass ID or Object?

text: When providing a business logic method to get a domain entity, should the parameter accept an object or an ID? For example, should we do this:               public Foo GetItem(int id) {}      or this:               public Foo GetItem(Foo foo) {}      I believe in passing objects around, in their entirety, but what about this case where we're getting an object and we only know the ID? Should the caller create an empty Foo and set the ID, or should it just pass the ID to the method? Since the incoming Foo will be empty, except for the ID, I don't see the benefit of the caller having to create a Foo and set its ID when it could just send the ID to the GetItem() method.


title: Is there a way to compare and record changes to code without VCS?

text: I'm working for a client that has no version control system in place. I want to record changes to code without having to add all changes to a spreadsheet. I'm restricted to using Notepad++ so would a plugin or macro for this be another option?


title: Have you ever dealt with writing a spec late in the development lifecycle?

text: We have an existing code base which has been developed to meet the needs of most of our clients, which has accumulated features and bug fixes as they were needed and as projects developed universally useful features. Right now, we're running into the problem that there's no real documentation for its capabilities outside of the code itself, and on larger jobs it can mean that it's difficult to determine what should be included in the scope of work. How would you approach writing a defined spec for an existing application or framework?


title: Why has the PowerCollections C# library recently declined in popularity?

text: I just looked at the statistics for the PowerCollections C# library and noticed a sharp decrease in quantity of downloads. What may be the cause? Is there something better I should be using?


title: Representing a deck of cards in C (not C++)

text: So far my best ideas have been as fallows A) Represent a "card" in one structure and have a "deck" in another a deck being an array of 52 cards and a card being 2 chars one for and rank one for suit. B) The second seems like it might be easier to manage but less obvious in code. Creating an array of ints each with a different value ranging from 1-52. Then crating a conversion function that would translate the value to a card structure that would have a string for the suit and a string for the rank. The value of zero could indicate a card that has not been "dealt". Just trying to find a better way of doing this.


title: Is there a name for the number of values a variable can take?

text: For example, a bit or a boolean can be either 0 or 1 so the number 2 is associated with it. Similarly, for a byte which is 8 bits, the maximum number of different assignments would be 2^8. Is there a name for this number? When we pass everything through our system that has ECMAScript, Java and MySQL, then a boolean does not have only two possible assignments. For instance, a false boolean gets saved as a 0 and the boxed value could be null so a boolean suddenly can get true, false, 0, 1, null or even undefined or `<missing>`. I think it could get problematic in tests to guarantee that the values are not inconsistent. For instance, a value `boolean locked` could become `null` and then when a script or a layout template evaluates it then it will evaluate to `false` somewhere if the real value was `null` and similar problems. So why don't we always assert that a boolean has the same number of possible values (2 values) and similarly for other types? There is a mathematical term named "arity" that is something similar but not exactly, and statistics and probability theory also has the concept of "event space" that would be almost exactly what I mean. For instance, the event space for a boolean would be the set `{0,1}` which has cardinality 2 and that cardinality doesn't get preserved throughout the system, especially when data is passed as polyglots and/or serialized (json, jsonp, xml, yaml).