Best way to set sys.path for "hot library" development in Python?

I have my Python source structured as follows:               +-branchname/       +-dst/       +-src/       | +-library/       | | +-cleese/       | | | +-test/       | | | | +-__init__.py       | | | | +-test_cleese.py       | | | +-__init__.py       | | | +-cleese.py       | | +-palin/       | |   +-test/       | |   | +-__init__.py        | |   | +-test_palin.py        | |   +-__init__.py       | |   +-palin.py       | +-productline/       |    +-circus/       |    | +-test/       |    | | +-__init__.py       |    | | +-test_circus.py       |    | +-__init__.py       |    | +-circus.py       |    +-grail/       |      +-test/       |      | +-__init__.py       |      | +-test_grail.py       |      +-__init__.py       |      +-grail.py       +-branch_root_marker      Entry points are in circus/ and grail/, as well as (possibly) each of the test/ directories, depending on how testing is implemented. I have multiple copies of this source tree present on local storage at any one point in time (corresponding to various maintenance and feature branches), so I cannot set PYTHONPATH in my shell without some pain. (I would need to remember to change it each time I switched to work on a different branch, and I am very forgetful) Instead, I have some logic that walks up the file tree, starting at the "current" file location, moving from leaf towards root, looking for branch_root_marker. Once the root directory of the current working copy is found, it adds library/ and productline/ to sys.path. I call this function from each entry-point in the system.               """Add working copy (branch) to sys.path"""          import os     import sys               def _setpath():         """Add working copy (branch) to sys.path"""              markerfile = "branch_root_marker"         path = ""         if ("__file__" in locals() or globals()) and __file__ != "__main__":             path = __file__         elif sys.argv and sys.argv[0] and not sys.argv[0] == "-c":             path = sys.argv[0]         path = os.path.realpath(os.path.expandvars(path))         while os.path.exists(path):             if os.path.exists(os.path.join(path, markerfile)):                 break             else:                 path = os.path.dirname(path)             errormsg = " ".join(("Could not find", markerfile))             assert os.path.exists(path) and path != os.path.dirname(path), errormsg              path = os.path.join(path, "src")         (_, subdir_list, _) = os.walk(path).next()         for subdir in subdir_list:             if subdir.startswith("."):                 continue             subdir_path = os.path.join(path, subdir)             if subdir_path in sys.path:                 continue             sys.path.append(subdir_path)     _setpath()      Currently, I need to keep a separate but identical copy of this function in each entry point. Even though it is quite a short function, I am quite distressed by how fragrantly the DRY principle is being violated by this approach, and would love to find a way to keep the sys.path modification logic in one place. Any ideas? Note:- One thing that springs to mind is to install the sys.path modifying logic into a common location that is always on PYTHONPATH. Whilst this is not a terrible idea, it means introducing an installation step that needs to be carried out each time I move to a fresh environment; another thing to remember (or, more likely, forget), so I would like to avoid this if at all possible.


Why is CPU cache memory so fast?

What makes CPU cache memory so much faster than main memory? I can see some benefit in a tiered cache system. It makes sense that a smaller cache is faster to search. But there must be more to it.


What really is the "business logic"?

I'm working with web development since 2009, when I started with PHP. When I moved to ASP.NET I've heard a lot about DDD and OOAD where a lot of focus is given to this "business logic" and "business rules". The point is that all the apps I've developed until now were all about CRUD operations and I've never seem these things in practice. I simply can't imagine what those things can really be in practice. So, what really is this business logic and how this fits into an app? I know these are implemented as methods in domain models, but what those methods could possibly be, and where in the application they could possibly used?


How to document experimental or incomplete APIs like @deprecated?

Is there a good term that is similar but different than "deprecate" to mean that a method or API is in the code base but should not be used because its implementation is not complete or will likely change? (Yeah, I know, those methods shouldn't be public, yada yada yada. I didn't create my situation, I'm just trying to make the best of it.) What do people suggest? Experimental, Incomplete, something else? If I'm building javadoc documentation for this API that is still in flux, should I use the @deprecated tag or is there a better convention? To me @deprecated implies that this API is old and a newer preferred mechanism is available. In my situation, there is no alternative, but some of the methods in the API are not finished and so should not be used. At this point I cannot make them private, but I'd like to put clear warnings in the docs.


Is there anything in .NET that allows me to define a grammar and generate a programming language?

I have a course in which the proffesor has asked us to create a DSL for a our final project. He presented us in the first courses xText with Eclipse. This being a new course, I am still a bit fuzzy on what Domain Specific Languages means. This is my current understanding: a domain specific language is a language that is created for specific problems in software development. Examples of DSL's are PHP, SQL, JavaScript and on the opposite are languages like Java , C# , C++ , Ruby etc. Please feel free to correct me if I am wrong. What I would like to know: is there is any tool for .NET/Visual Studio that is similar to Xtext, that allows me to define a grammar and be allowed to generate a programming language based on that with an activity diagram?


What is SAP and where can I learn about it?

I've just inherited a code base that makes extensive use of SAP technologies. The project is written in C# if that makes a difference. I'm having trouble finding resources for learning more about SAP. Can anyone point me in the right direction?


ORM: Keep entities coherent in a cache or retrieve entities each time?

We have a tricky question in a project using Java & Hibernate, with a model containing bi-directional relationships. As it's a small project with few users, few entities, and few rows involved in relationships (not more than 100 in 1-n relationships), we don't really need a 2nd level cache. Operations done with entities are simple: inserting, removing and performing some computations with entities involving relationships loading. Let say we have two Java entities: `Room` and `Furniture`. An item of furniture is in one room and a room can have many items of furniture. So `Furniture` has a reference to `Room`, and `Room` has a list of `Furniture`. For the `Delete Furniture` action, the easiest thing to do is to retrieve the right `Furniture`, and tell the EntityManager to remove the `Furniture`. But, to ensure the Java instances remain coherent, we should also remove the `Furniture` instance in the list of `Furniture`s in the associated `Room`. Unfortunately, if the `Room` instance is not loaded, a request will be done to the database for nothing if we don't have a cache. So, what would be a better choice between: A) Keeping it simple   * In general, no preoccupation about bilateral relationships in java instances coherence, as we don't have 2nd level cache   * Well document the fact that there is a cache per-action, so if specific computations must be done requering bilateral relationships coherence within an action, this action must take care of the coherence   * No boilerplate code for bilateral relationships coherence management needed   * No overhead of loading non-necessary entites   * If a 2nd level cache must be added, then a big effort in refactoring has to be done B) Keeping it coherent   * Always maintain the bilateral relationship's coherence   * Enable 2nd level cache


C++ log every function and parameter values

I want to log every function call and parameter value in my C++ app. Is there a generic approach for this task ? (3rd part library, **VAR_ARGS** etc.)


JVM vs operating systems

Recently i was re-visiting the basic concepts of operating systems. Since I am a java developer, I have inherently started looking at everything from java point of view. I am also reading 'Inside the JVM fundamentals' from http://www.artima.com/insidejvm/ed2/jvm.html so when I see the basics of operating systems and JVM, I have begun to think that there are lot of similarities on an abstract level, i.e. both do the memory management, process scheduling, etc. So I want to ask SO programmers whether I am correct in my learning or assumptions?


what kind of functions and/or classes are impossible to unit test and why

Main excuse from the developer for not having a good unit testing is "Code is not designed in a unit testable fashion." I am trying to understand what type of design and code that can't be unit tested.


Where do service implementations fit into the Microsoft Application Architecture guidelines?

The guidelines discuss the service layer with its service interfaces and data/message/fault contracts. They also discuss the business layer with its logic/workflow components and entities as well as the 'optional' application facade. What is unclear still to me after studying this guide is where the implementations of the service interfaces belong. Does the application facade in the business layer implement these interfaces, or does a separate 'service facade' exist to make calls to the business layer and it's facade/raw components? (With the former, there would be less seemingly trivial calls to yet another layer, though with the latter I could see how the service layer could remove the concerns of translating business entities to data contracts from the business layer.)


How to find a job as a developer with a charity

Can anybody suggest the best way to go about finding software development jobs within charitable organisations? This comes from an experienced developer who dreams of working for a company he actually believes in :) The most obvious answer would be, of course, to check job listings for some of the larger charities. But how about the large number of smaller charities out there? Where would they advertise?


Do object-oriented programming languages exist that are not class-based?

Are there any object-oriented programming languages that are not based on the class paradigm?


Is there something a `Promise` can do that `async` cannot?

Recently, I've spent a lot of time trying to dive into, and understand, Javascript Promises, especially those adhering to the Promises/A+ spec. What I'm trying to understand is whether or not `Promises` actually give developers additional tools specifically when compared to CPS based `async`, or whether it is mostly syntactic sugar and a tool to reduce verbosity or streamline some behaviors. One argument I've heard for promises is error handling. In that case, using the `async` library it is very easy to execute a `async.waterfall` of functions, each waiting for the prior to complete, each wrapped in a try/catch to handle synchronous errors (since neither `Promises`, nor `async` handle async errors), passing caught errors to an error handler. In that situation `Promises` and `async` behave identically regarding error semantics (gist showing this behavior). Another argument I've heard for promises is future-proofing methods which are sync now, but asynchronous later on. The theory is that if the function returns a promise, it doesn't matter what if it is modified later. Since both sender and receiver have to modified to adhere to the promise contract, can't the same argument be stated for modifying both sender and receiver to use the CPS contract, even if it's synchronous, to future proof it? So with that in mind is there any use-case that you can think of which can only be solved optimally by `Promises` or is their usage really more a case of preference and the desire to reduce verbosity and reduce the chance of error?


Is it good to create static method at Visual Studio refactoring?

There are various refactoring options in Visual Studio to use at the time of coding. When we extract and create a new method. Then Visual Studio decide whether the new method will be static or instence depending on the usage inside the new method. If that method use some intence member of the class then it creates as instence method, if it does not use any instence member of the class then it creates the method as static. I can understand that if there is no instence member usage then it is better to declare that method as static to prevent initialization for every object. Static method initilize only once at the time of class load. ![Extract method in Visual Studio](http://i.stack.imgur.com/fEmyB.png) But the question is if there are many static methods inside various classes of a application, then performance will hurt? Because many object of that class will share same static method of that class? Should we do thread safety management to that static method? Or in this kind of setuation it is better to simplily create instence method if there are no usage of instence member of the class?


What is Global Delivery Model?

Many software companies preach in their Website Banners: "Global Delivery Model". Has it anything to do with Deployment?


Trying to grasp the idea of DI/Unity and possibly apply it to our simple application

Our app basically is a few forms that are filled out by people.. Then these forms are validated and reviewed and reports are created.. So I was thinking about DI and messing with a simple example of Unity + MVC http://netmvc.blogspot.com/2012/04/dependency-injection-in-aspnet-mvc-4.html So could it be useful for something or overkill ? It seems to me the idea behind DI is to dynamically grab objects of a different type.. So in my case maybe those can be a set of rules for validation of a form... Something like SyntaxRules1.dll, BusinessRules1.dll, CalculationRules1.dll... So then as time goes by maybe additional sets of rules would be created so I can drop another DLL like BusinessRules2.dll in a folder and DI would pick it up in the boot strapper.. But then again if it changes very little then using DI might be pointless and just be a layer of abstraction that is not needed.. Do I have the right idea? Is there any other ideas how DI could be useful for this type of app ? Could I make the entire view/controller/model or each form its own DLL ? That make sense ? I just read alot of theory and struggling to find some concrete examples of what DI can do.


GIS-based data visualization and maintenance tool

## Background Looking to leverage an existing GIS system for exploring organizational data. ## Architecture The following figure represents a high-level overview of the system's desired features: ![](http://i.imgur.com/SskPD.png) The most basic usage would be as follows:   1. The user visits a web site.   2. The system presents a map (having regions, cities, and buildings).   3. The user drills-down on the map to a particular building.   4. The system provides a basic CRUD interface.   5. The user can view and modify information about personnel (e.g., their assigned teams), equipment (e.g., network appliances), applications, and the building itself (e.g., contact and phone numbers). Ideally, all the components should be open-source (or otherwise free). ## Problem This must be a small project that needs a quick (but functional) prototype, mostly to confirm whether or not such a system would be useful in the long term. ## Questions   * What software components would you use to quickly develop a working prototype?   * What open-source solutions already exist, if any? ## Ideas Here is what I am thinking:   * PostGIS - Define the regions, cities, and sites   * Google Maps - Display an interactive, clickable map   * geoJSON - Protocol between PostGIS and Google Maps   * Seam - CRUD interface ## Custom Development For example, this would entail:   1. Installation and configuration      1. Configure SSH for remote logins     2. Subversion (or git)     3. PostgreSQL     4. PostGIS     5. Java     6. Tomcat     7. Seam     8. JasperReports   2. Enter GIS information into PostGIS   3. Aggregate data sources into PostgreSQL database   4. Develop starting page for map interface   5. Develop clickable Google Maps interface   6. Develop summary reports   7. Develop CRUD interface using Seam for data maintenance Surely something like this already exists? Thank you!


How to manage contextual objects without IoC container (session or passing around objects)?

I'm using asp.net (c#). I have a factory that uses a dictionary of keys that are mapped to objects types. I originally used a static variable to track the dictionary but realized it would be shared among all sessions. Then I'm left with the idea of passing the object map around everywhere, which seems messy. Should object maps or other contextual items get passed around, stored in the session, or should I just create a new instance each time I need one (in the case of non-contextual items)? I'm not using an IoC container. An example of a non-contextual item in my case would be mapping text commands that come in from the client to objects. In general it seems there is no good way to deal with contextual data without at least having a static object that pulls the values from a session. Otherwise I am stuck with passing tons of context objects around everywhere they are needed. Surely there is a good pattern for handling contexts, object maps, etc. without using session to store everything?


What is the alternative to an enterprise portal strategy in the Java space?

So, I got my wrist slapped by asking this question over on StackOverflow. I guess the previous iteration of the question was not one that gets resolved with a concise enough answer - hopefully some of the edits here will help. Anyways, one commenter, Perception, suggested that I reposted the question over here where some of the handsome and intelligent readership might be able to provide an answer. Here's the question as it was posted over at SO, but edited a bit to be more specific in focus. * * * I'm trying to garner insight from as many sources as I can, and I wanted to hear from the big brains at Stackoverflow (well, I guess it's now all about the big brains at stackexchange). **Disillusionment with the Portal Space** I'm seeing a disturbing number of large, enterprise clients who have become disillusioned with their enterprise Portal experience, especially those in the WebSphere Portal Server (WPS) space. Millions have been invested, yet the promise of personalized content with aggregation and integrated collaborative tools has never come to fruition. The move to WPS 7.x is a big rip and replace move, and clients are wondering if they should move somewhere else completely. **Portal Software: A horrible option, but what's the alternative** There are loads of Portal haters out there, and sometimes a portal solution is indeed overkill, but when you're talking about large, multi-national corporations, how would one recommend they architect a global solution without a portal server? Portals aren't always as fun to work with as Tomcat or JBoss AS, but when it comes to integrating multiple applications, managing content, updating individual applications that are deployed as individual war files, managing security down to the portlet level, proving a certain amount of personalization to users, and help with the overwhelming task of managing the thousands of pages large scale enterprises have as part of their internal and external websites, is there a better technology out there? **Garnering community insight and feedback** I've been trying to garner as much insight as possible. I wrote a little article on TSS about the issue: Which other alternatives to portal exists on market? I'm also resurrecting a thread at the CodeRanch to see if I can get any insight from that handsome crew. Updated Thread Asking for an Alternative to a Portal Software Stragety. Circa 2012 I'm also looking for some insight from the twitterati (@potemcam). It's not so much a cross-posting as much as it is an attempt to really gather some keen insight from the community. If I can get some solid responses and experiences, I'd like to aggregate them into an advice article over at TSS. **What is the right alternative to an enterprise Portal in the Java space** Looking forward to hearing your advice. By the way, I'll be cross-linking to this thread from the other sights as well so people with the same questions will be able to bounce back and forth and see what the community is saying on this topic. * * * Hopefully this iteration of the question will be well recevied by the programmers community at stackexchange.


Is it a code smell if you are frequently creating an object just to call a method on it

I inherited a code base where there is a lot of code that goes something like this:               SomeDataAdapter sda = new SomeDataAdapter();     sda.UpdateData(DataTable updateData);      And then sda is never used again. Is that a code smell that indicates that those methods should actually be static class methods instead?


It is bad practice to hard couple logging interface/implementation with business model classes?

Should we avoid using logging in business model classes and try to move logging to service/controller classes? In for example java context, logging in model classes will hard couple the code with dependencies on `slf4j` or `commons-logging` etc.


An alternative to an array of functions?

I'm programming an app (php) which requires a very long list of **similar yet different functions, which are being called by a set of keys** :               $functions = [         "do this" => function() {             // does this         },         "do that" => function() {             // does that         }     ]      etc.      I've chosen to place the similar functions in an array because they are not similar **enough** - getting the same result with one big function which is full of conditional statements isn't gonna work. And **I do need to be able to call them only by key** , for example:               $program = ["do this", "do that", "do this"];     foreach ($program as $k => $v) {         $functions[$v]();     }      Thing is this functions-array structure is causing many problems, for example I'm having a hard time **calling one array function from within another array function** , e.g. this doesn't work:               "do that" => function() {         $functions["do this"]();     }      nor this:               "do that" => function() {         global $functions;         $functions["do this"]();     }      or this:               "do that" => function($functions) {         $functions["do this"]();     }          $functions["do that"]($functions);      I guess I could have one giant function with a long **switch statement** :               function similar_functions($key) {         switch ($key) {             case "do this":                 // does this             break;             case "do that":                 // does that             break;         }     }      But that doens't really seem like good practice. Or maybe it is? **So, what are my alternatives?** Should I go with the switch structure? Or is there another, better solution?


Should I remove an 'embarrassing non-programming' project from my CV?

At a major IT company the project that I was working on got cancelled. The entire team was _benched_. Since the team size was large (>300) not everyone was immediately employable. To cover the losses the company took on a project that involved content cleaning. It involved reading 1000's of pages of documents and fixing the disparity between them i.e. fixing the English! We had to make sure the punctuation was correct, word spellings were consistent, sentence structure etc. We were given 3-5 pages of a checklist of the most common mistakes. This was NOT a programming job at all. It was just given to the folks who were _on bench_ and had them billable for some time. However, this project duration was about 6 months! There were no projects coming by or the talent pool had more resources IMO. Of course, I did quit the company but I still show the entire duration of my work at the organization on my CV. However, this 'English' (non-programming) project is a bit embarrassing (although I try to frame the English well so it doesn't feel so :) Should I just get rid of such a project altogether? It was quite a while back, but I'm only concerned about the authenticity of the duration - I did work from date A-B. Should I just indicate the primary project for the entire duration and drop the English one?


What is an Aguri tree?

Going through some old Hacker News items, I came across a post from a user that said > Aguri trees, which marry a bounded-size radix trie (like you'd use in a > software routing table) to an LRU list, and automatically synthesize > aggregates (like, 10.0.0.0/16 from 1,000 observations across all IPs) from > the pattern of insertion. They're best known in traffic analysis, but we've > used them on in runtime memory analysis as well. ~ tptacek So I decided to look it up,   * A quick Google Search leads me to a F1 driver.   * A search on Wikipedia leads to a agricultural caste in India and some items from Japan    * Stack Overflow hits 0 results http://stackoverflow.com/search?q=aguri `site:stackoverflow.com/questions aguri` So I have finally linked it back to the user see he has a link on his blog > http://www.matasano.com/log/1009/aguri-coolest-data-structure-youve-never- > heard-of/ But it's dead. _So, what is this Aguri data structure and if it is a real data structure, why is it not documented anywhere else?_


When to use weak references in .Net?

I have not personally come across a situation where I've needed to use WeakReference type in .Net, but the popular belief seems to be that it should be used in caches. Dr Jon Harrop gave a very good case against the use of WeakReferences in caches in his answer to this question. I've also often heard AS3 developers talk about using weak references to save on memory footprint but based on the conversations I've had it seems to add complexity without necessarily accomplishing the intended goal, and the runtime behaviour is rather unpredictable. So much so that many simply give up on it and instead manage the memory usage more carefully/optimize their code to be less memory intensive (or making the trade-off of more CPU-cycles and smaller memory footprint). Dr Jon Harrop also pointed out in his answer that the .Net weak references are not soft, and there's an aggressive collection of weak references at gen0. According to MSDN, long weak references gives you the potential to recreate an object, `but the state of the object remains unpredictable.`! Given these characteristics, I can't think of a situation where weak references would be useful, perhaps someone could enlighten me?


How Would I Start With Prolog?

If I wanted to start learning Prolog on Windows, is there any package that would integrate Prolog into Visual Studio 2010? That is, a compiler and templates and so forth for working with Prolog on Windows? Assuming there is no flavor of Prolog targeting the .Net platform, is there a GCC Prolog compiler for Windows?


Design pattern for object conversion (java)

I don't use design patterns very often, besides an occasional factory and MVC, and I want to start using them more. I have a concrete case at hand that I would like your opinion on the use of design patterns in this case. In my application I have to convert objects pretty often in different situations. I might have to convert a Hibernate POJO to a DTO, because I use GWT and Hibernate POJO's aren't serializable and can't be sent over the line. In another situation I might need to convert Java objects to SolrInputDocument's for indexing by Solr. I would like to know if I should use a design pattern for this. It seems that "object conversion" is a generic task that could be handled in a flexible/abstract way by a pattern, but I don't really see how. Without patterns I would just create a separate class for each type of conversion, for example CourseToSolrInputDocument (Course is a Hibernate entity in my application). Or CourseToCourseDTO. Each of these conversion classes might have a single static method called `convert()` that takes the source object as input and returns the output object. But that is not really a pattern, is it? So I started of on something with generics and created this class that implements the Converter interface. But is somehow feels silly tgo create a generic interface and I don't really see the advantage other than being able to congratulate myself on the use of generics.               public class CourseToSolrInputDocument implements Converter<Course, SolrInputDocument>         {         @Override         public void convert(Course source, SolrInputDocument destination) {             //To change body of implemented methods use File | Settings | File Templates.         }     }      So, the real question here is: is there a pattern that applies to generic object conversion and, what would be your approach and what are the advantages over using just a class-per-conversion type approach?


MVC - Isolating view and model logic

I understand that the model should generally consist of data manipulation and the view for data display from the model, but how do I keep my model and view layers decoupled? My simple view has a few tables that display data. Its associated model manipulates the data based on the view's type of `TableModel`. Most of its methods involve using the `TableModel` type. Should the view generally "breakdown" the data into a more generic type of integers and strings for the model? Therefore all the model handles are simple generic lists of data without needing to use `TableModel` in case the view is changed into another interface. The model should be "unaware" of the view for good programming practices, right? If I change my view to a command-line interface, the associated model should still be able to perform its functions, given the correct associated Lists of integers/strings/whatever.


Does it violate the license to use Windows XP Mode with Virtual Box?

I am working on a team developing a client-side application. We work in a Linux environment, but the server we work with can only be run from a Windows environment. As such, each developer is being set up with a virtual machine, running on Oracle VM Virtual Box. Would it violate the terms of use or licensing for the developers to use the virtual hard drive from Windows XP Mode with Oracle VM Virtual Box?


How can one manage thousands of IF...THEN...ELSE rules?

I am considering building an application, which, at its core, would consist of thousands of if...then...else statements. The purpose of the application is to be able to predict how cows move around in any landscape. They are affected by things like the sun, wind, food source, sudden events etc. How can such an application be managed? I imagine that after a few hundred IF- statements, it would be as good as unpredictable how the program would react and debugging what lead to a certain reaction would mean that one would have to traverse the whole IF-statement tree every time. I have read a bit about rules engines, but I do not see how they would get around this complexity.


Heuristics for absolutely-positioned GUI design - are multiples of 5 a good idea?

Disclaimer: I do not specialize in [desktop] GUI design, but have to do it on occasion. I have seen co-worker's dialogs worse than the once I created, and my major problem with them is that they can be unnecessarily big, and things do not line up. To be more specific, I mostly do it in .Net Winforms, but occasionally with MFC(C++) as well. My simple heuristic so far is: I try to make the sizes and positions divisible by 10 ... or 5 if I have to. Something like a Label would be an exception, for it knows its own size. I find that things mostly look OK after I am done (of course there are other considerations such as grouping things intelligently, etc.), and I am satisfied because I know that every control has non-random position, and my OCD can now go back to sleep. Somewhere at work I found a guide from MSFT about ideal spacing between things. Sorry, I do not have a source for it available. It has many rules, such as (for instance) 2 pixels between a button and a border, 3 pixels between two buttons horizontally, 4 pixels vertically, unless ... it is pretty complicated and not practical to remember. Additionally, I simply do not trust that MSFT knew much about GUI design, not until they hired an ex-apple person to help them design the ribbons for Office 2007, etc. What rules/heuristics do you follow? References to short articles and other links are welcome.


How to change careers

For the past 4 years I have worked in c# doing web development. I have really enjoyed it, learnt a lot and have a worked hard to get to a position where I am earning good money and enjoy the work. However lately - I have wanted a change. What with the "native renaissance" I would like to change my career from being high level application and web development to more down to the metal native development. I haven't done any c or c++ since Uni over 4 years ago and so I have begun reading text books and websites to brush up. However - one major issue I have is that I have no practical experience with C++ and although I am brushing up on it, there will be a lot I don't know. Most of the jobs I have seen in native code around me all require native experience. The only positions I can find that don't explicitly ask for native experience are junior level positions. In my current role I am a mid level developer and although there would be a lot to learn in a c++ position, I wouldn't class myself as a junior. I guess my question is, how do people solve this issue when changing programming languages for their profession and / or how would you approach this hurdle? Like I said, I would really like to try out native development professionally but I wouldn't want to move back to a junior role. Would employers consider years of managed development and native hobby projects enough experience?


Secure silverlight WCF calls

I have a Silverlight application that uses Entity Framework. The application are protected with a login made in ASP, so only valid users get the xap file. Have do I secure the WCF calls to the Entity Framework? I have to make the calls over https, but have can i make sure that only valid users can get data from the WCF service? Thanks Jakob


Committing https certificates to Github...is there ever a good reason for this?


Is Haskell appropriate for Signal Processing, Communication Systems and Information Theory?

I have been working on Software-Defined Radio projects for almost a year. This is an area which requires lots of signal processing (digital filters and FFTs), communication theory (modulation, equalization and synchronization) and information theory (specifically, coding theory, as Huffman, Linear and Convolutional codes). I program mostly in Matlab (for simulations) and C++ and Python (for practical applications using GNURadio and the USRP). As you can see, those areas require lots of mathematical concepts. As I've been studying Haskell, I see that it is a good programming language for applications that involve heavy math.It seemed a good idea to program in Haskell for problems in the area I have been working on. On the other hand, there doesn't seem to be a lot of people doing this. There seems to be a Haskell DSP library, but there aren't many projects using it available on the web. I've also found a thesis where Haskell was used to implement a Viterbi coder/decoder and it seems quite an elegant solution. But it seems to me that people in the communication industry and research still don't use a lot of Haskell in their codes. Maybe this coulde be because many of them still haven't heard about Haskell. What would be upsides and downsides of applying Haskell to those kind of problems? What will be key benefits of doing SDR in Haskell? What about Haskell would make it a bad choice for SDR? Should I expect severe pain points using Haskell for SDR (what are they?).


Which version of C should I learn?

It looks like _K &R "C Programming Language (2nd Edition)"_ covers ANSI C, but another book that I'm starting ( _Stephen G. Kochan "Programming in C"_) says that it uses C99. I'm coming from a C#/JavaScript/Python/PHP/Java background and looking to round out my skills. I'm currently using GCC, but I'm curious about Clang. Which version is used more in new and existing code? Does it even matter, or should I learn both?


How to avoid dragging arguments from function to function

When I do my code layout, I like to start with a rather high level view, and then start to delegate actual computation to class or functions that have a bit more detail. Then in these classes of functions, I do the same, layer by layer, until I get to the bottom where I have to do the 'real' action. Example:               def build_table():         legs = get_legs()         plate = get_plate()         return put_together(legs, plate)          def get_legs():         legs = []         for i in [0,1,2,3]:             legs.append(get_leg_from_warehouse())         return legs          def get_plate():         plate = get_plate_from_warehouse()         return finish_plate(plate)          def put_together(legs, plate):         table = Table()         for i in [0,1,2,3]:            table.mount(legs[i])         table.mount(plate)         return table          class Table:         self.component = []         def mount(self, item):             self.component.append(item)      In this way, I find it easy to think about the layout, and hide complexity. I mostly have short pieces of code that are easy to understand. The downside of this is, that when I discover I need a piece of information available at the top of the stack further down, I pass arguments from function to function. In the above example, I might gather 'screws' at the top, and then keep passing them down to a function where they are actually drilled into the wood. This makes it feel that it is not so easy to modify the code, and I wondered what I could do about this. In this example the modified code would look like this:               def build_table():         legs = get_legs()         plate = get_plate()         screws = get_screws()         return put_together(legs, plate, screws)          def get_legs():         legs = []         for i in [0,1,2,3]:             legs.append(get_leg_from_warehouse())         return legs          def get_plate():         plate = get_plate_from_warehouse()         return finish_plate(plate)          def get_screws():         drive_to_hardwarestore()         screws = buy_screws()         drive_home()         return screws          def put_together(legs, plate, screws):         table = Table()         for i in [0,1,2,3]:            table.mount(legs[i], screws)         table.mount(plate, screws)         return table          class Table:         self.component = []         def mount(self, item, screws):             self.component.append((item, screws.pop()))      So besides adding the code for getting screws, I had to modify 4 lines. This would increase linearly with the amount of layers. How can I refactor? On the other hand, how can I avoid this in the first place? Is my design process 'wrong'?


What software programming languages were used by the Soviet Union's space program?

I got interested in the Soviet space program and was interested to discover that the software on the Buran spacecraft circa 1988 was written in Prolog. Does anyone know what languages might have been used in earlier missions, especially the Mars PrOP-M rover missions of the early 1970s which were somewhat autonomous and could navigate obstacles? **Edit** My source for the Buran Prolog is this declassified document from the CIA site from May 1990. I couldn't find an OCR version, so here's the relevant quote from p. 0449: > According to open-source literature, the Soviets used the French-developed > programming language known as Prolog to develop on-board system software for > the Buran vehicle...


Source control workflow for managing a software platform

I'm in charge of a software platform, written in C, that is used to provide a variety of projects to clients. I am trying to improve the workflow for people using this platform, and looking at whether source code control (Mercurial being the most likely candidate) can help. The platform is only used internally for ~10 projects / year. It's got a wide range of functionality, and lots of bits that are unused on most projects. As a result, there are plenty of bugs hidden away. I'm wondering if anyone has similar experience, either managing or using a constantly updated platform in this way. **The current situation** Platform development is done with a mercurial repository, but the releases of the platform are not done through mercurial. For a release, the platform files are put into a tarball on a central server. For any system connected to the core, the start of the build process copies the updated tarball and unpacks it into the application source code. Application programmers can't edit the core files (various commands are aliased through shell scripts, and they get an error if they try). **What I'm after** It seems like it should be possible to somehow use Mercurial to manage this. We could easily maintain a release branch of the platform, and have projects clone the release branch as their starting points. But I'm not sure where it would go after that. On a project, the functionality is completely up to the client. If the core files are unlocked, people will immediately start editing them, even when there is a better way (this is what happened before the lockdown). This is going to mean merging in new core changes becomes difficult, and I suspect will result in a lot of teams not bothering. The draconian solution of locking the core files, and forcing automatic updates to all projects was really quite successful: we get more complaints and problems from the projects that are disconnected, than the ones receiving the forced updates. However, as soon as projects go into testing, they have to be disconnected. After that, short of manual merging, they get no more platform updates.


Are all security threats triggered by software bugs?

Most security threats that I've heard of have arisen due to a bug in the software (e.g. all input is not properly sanity checked, stack overflows, etc.). So if we exclude all social hacking, are all security threats due to bugs? In other words, if there were no bugs, would there be no security threats (again, excluding the faults of humans such as disclosing passwords and such)? Or can systems be exploited in ways not caused by bugs?


How can I best prepare for building Windows Phone 8 Apps

I'm interested in learning to develop for Windows Phone down the road a bit, and am mostly interested in developing Metro Apps for the Windows Phone. It seems like there is some basic info for Metro development now, but no guidance on what will be relevant when Windows Phone 8 releases. There seem to be two potential strategies: 1) Start coding for Mango/WP7.5 and then later attempt to convert the experience for use with WP8. I guess this would involve learning Silverlight for applications (as opposed to XNA for games)? 2) Write Windows 8 Metro apps now with the dev preview. This experience seems less likely to be deprecated but it also seems harder to test in a real world fashion. I'd normally lean towards option 1, but there are a few downsides with that route imo. First, I'd read elsewhere that Silverlight 5 was the last Silverlight release. I'm not completely clear on how much Silverlight experience will be useful for future iterations on their phone OS. Also, one thing I find interesting is the improved async/await setup and my understanding is that WP7 still relies heavily on callbacks for async operations. I'm pretty unfamiliar with Silverlight/WP7/etc so please be gentle if there are some flagrant misunderstandings on my part. Thanks!


Migrating from Python to Scala wise when a lot of work is already done in Python?

Me and my friend are developing a web-app in Python + Flask + PostgreSQL. We have been working on it for the past few months and have developed a lot of schema/use-cases specific to Python + Flask + PostgreSQL. Now, all of a sudden, we plan to move to another NoSQL database (Neo4j) because it somehow fits better to what the core of our web-app is going to be. Python supports Neo4j through embedded/rest api bindings, but uses a technology **JPype, which is rather unmaintained, to say the least**. So, this question of using Scala arose today. **Ours is going to be next-to- realtime application, so we can't afford to have the lag/overhead** of having intermediate steps of Python->Java requests (Neo4j standalone server is based on embedded Neo4j). So, whereas I am in favour of spending a month or two and learning Scala/Lift, he is in favour of carrying on with Python and porting to Scala whenever need arises, even though when we know that Python+bindings will be a bit slower as compared to the native Neo4j support for Java. In the past few months, we had done a lot of work in Python + Flask + PostgreSQL already. If we port to Scala, we will need to port all of it to Scala. Would it be wise to port now? Are there any personal experiences or advices from you all? Or is this just premature optimization? _P.S.: I am aware of the learning curve of Scala/Lift._


Agile development : How to design your code for an iteration / Sprint?

In Agile development you work on small user stories and produce a working iteration. But what happens when the next user story comes in and affects the design for the already done iteration? Sometimes it seems like re-doing the last iteration or another user story to incorporate the new user story in the last iteration! How to approach on this?


Do people use any tools to make Rich UI on Web Application?

As titled, take ASP.NET/Perl/PHP for example. Because I don't have chance to work with UI Designer/or know anyone like that, so I really wonder do they use any tools to do the UI design? I don't mean tools like PhotoShop or Flash to make the graphic, but I mean like writting CSS, Table layout/color, Div, JQuery animation etc. I know for ASP.NET Visual Studio have some support on UI design, but is very minimum compares to like ExpressionBlend for WPF/Silverlight. I have been still typing everything when I do the UI Design for ASP.NET. So I wonder do people use any tools to help doing UI Design? Or everyone take it like a man to type everything else like what we did back then with NotePad?


Patching open source software when upgrading is not an option?

I recently ran into a rather annoying (confirmed) bug in an open source software package that I have integrated into my application. According to the public issue tracker this bug has been resolved in the latest release of the software. Occasionally you NEED that bug fix to avoid an expensive refactor of a particular module, however for technical and/or political reasons, you will not be able to upgrade to the latest release. On inspecting the code changes made, the fix seems simple enough that I feel a viable option would be to patch the code myself and recompile my current approved version of the software, however detractors want to argue the case that this is nearly always a bad idea in that it is risky and introducing a troublesome complexity. In their eyes because this code change was done by us solely for our use, it must be part of our code base, meaning that rather than introducing the open source software as a third party dependency, we must introduce it as a new project and incorporate its automated build into our build process. To me I think this is wrong headed, as we would be pulling their code from their source control repository into ours, and we lose the history behind any code changes that came before that. Also it just seems like something that is far too complicated for such a small code change that needs to be made. Would it be a bad idea to do the above in this case? If so, then what is the ideal situation when open source needs to change, but only for your sole benefit in house?


How to count condition coverage

I am wondering, What would be the correct condition coverage test cases for the following condition:               if(A && E && (B || C || D))      Considering short circuiting, what cases would I need? EDIT: Sorry I put only a half of the expression


Is there an effective way to test XSL transforms/BizTalk maps?

Creating repeatable tests for BizTalk maps is frustrating. I can't find a way to handle testing them like I'd do unit testing, because I can't find ways to break them into logical chunks. They tend to be one big monolithic unit, and any change has the potential to ripple through the map and break a lot of unit tests. Even if I could break it up, creating XML test inputs is painful and error prone. Is there any effective way of testing these? I'd settle for recommendations for testing XSL transforms in general, but I specifically mention BizTalk maps primarily for the reason that when using the mapper, there really isn't any way to break your XSLT into templates (which I'd imagine you could use to break up your logic into testable chunks, but I've honestly never gotten that far with XSLT).


Should every git commit leave the project in a working state?

I'm curious to know what the prevailing best practice is about get commits are. Should they be enforced such that the project is in a working state (builds properly, all tests pass etc), or is committing broken code OK? If you waive the requirement, you can be more flexible with commits (use them as logical chunks, even though the app is not in a working state etc). But if you enforce it you gain the flexibility of being able to cherry-pick any given commit later on...


How to check robustness in a service that includes multiple points of failure in workflow, including FTP

As part of my workflow, I need to do all these steps in one transaction - I need to ftp files to 2 different FTP servers. - There is also a spreadsheet that gets generated which needs to be FTP'ed. Can this be streamed, instead of downloading and then pushed to FTP server. I am using Ruby Net::SFTP and Net::FTP libraries to send the files. I would like it to be robust. I am not sure if I need to do anything else or of this is good enough. Just to be clear, this is already working in production, I am not stuck, just looking to exchange design/architecture ideas on how to improve this.


How fast should a version number increment?

Some version numbers increase very quickly (like firefox and google chrome) and others don't (like cloudapp and the ubuntu kernel). I'm kinda thinking that the developer chooses how fast the number increments; it'd be silly to add a full +1 to the number if you fixed only minor stuff though....


How does working in a team (in an OO project) work?

I'm programming in Java, in a very OO style, by myself. Never had the chance to work with other programmers (I'm not a professional, at least yet). Out of curiosity, I wanted to ask: How does working with a team on a project work, especially when working on an OO project? How does splitting tasks work? **How do you develop something that will succesfully work with something another programmer developed?** How and when do programmers communicate? Thanks


Does it always require a lot of programming practice before you really master an algorithm?

I have programmed for several years. And I found it is always difficult to master an algorithm(What 'master' mean here is to understand how the algorithm works and could implement independently in some programming language). I could implement some easy algorithms(such as bubble sort, binary search, basic graph traversal algorithms such as DFS, BFS, basic dynamic programming problems such as ). But it is very difficult for me to master some advanced algorithms such as KMP, max-flow. I could understand the basic idea behind the algorithms. But I am usually stucked at implementation and forget the algorithm in a while. So my questions are:   1. what is a reasonable procedure to learn/master a new algorithm?    2. Do I need practice it again and again in platform such as USACO, topcoder to master it? Or is there any better way?


How much product value can be hurt if demo of product not working properly

I am just checking a java script framework . A universal JavaScript framework. To check how its really works i just checkout a demo of this product example site which is just normal todo list . I just start to playing with the `todo` list and i just notice that after click on `add` if i click on `cancel` in that dialog box, Its still add a blank `todo item` . I am sure this is bug . Here my point is not solve this bug or find this bug .My point is that if i have such products and there demo have bugs which can be easily noticed then **Are those bugs going to hurt my product reputation ? and how much ?**


Improve Bad testing

We have a large team of developers and testers. The ratio is one tester for every one developer. We have full bug tracking and reporting systems in place. We have test plans in place. Every change to the product, the testing team is involved in the design of the feature and are included in the development process as much as possible. We build in small iterative blocks, using scrum methodology and every scrum they are included in, including the grooming sessions etc. But every release of the product, they miss even the most simple and obvious defects. How can we improve this?


Keeping an enum and a table in sync

I'm making a program that will post data to a database, and I've run into a pattern that I'm sure is familiar: A short table of most-likely (very strongly likely) fixed values that serve as an enum. So suppose the following table called `Status`:                 Status       Id Description       --------------        0 Unprocessed        1 Pending        2 Processed        3 Error      In my program I need to determine a status Id for another table, or possibly update a record with a new status Id. I could hardcode the status Id's in an enum and hope no one ever changes the database. Or I could pre-fetch the values based on the description (thus hardcoding _that_ instead). What would be the correct approach to keep these two, enum and table, synced?


How to programmatically construct textual query

Here is a query language, more specifically, it's JQL, you can use it in Jira, to search for issues, it's something like SQL, but quite simpler. My case is that, I need to construct such queries programmatically, in my application. Something like:               JQLMachine jqlMachine = new JQLMachine()     jqlMachine.setStatuses("Open", "In Progress")     jqlMachine.setReporter("foouser", "baruser")     jqlMachine.setDateRange(...)     jqlMachine.getQuery() --> String with corresponding JQL query is returned      You get my point I hope. I can imagine the code for this, but it's not nice, using my current knowledge how I'd do that. That's why I'm asking. What you'd advice to use to create such thing. I believe some patterns for creating something like this already exist and there is already best practices, how to do that in good way.


What is a "complimentary license" for a software product?

I don't really understand the term. I got a survey about either getting gift card or a complimentary license for a SDK control set. But I really wonder what's complimentary license means? I tried to search in their official site but didn't say anything about it... Is it last for the life and I can use the controls in all my personal software and publish it?


What is the historical basis of using Javascript in web programming?

I come from a scientific biology background where we also use Python a lot. Now that I've begun to start with Web development, I've consistently found myself wondering just why it is that JavaScript is the primary client-side language on the Web. Is JavaScript's predominance a historical accident or something else? Also, I'm curious if there are any hurdles to integrating Python into client-side scripting?


Back button after doing posts on the same page

I have 3 pages to my site. The 1st page allows you to select a bunch of options. Those options get sent to the 2nd page to be displayed with some data about those options. From here I can click on a link to get to page 3 on 1 of the options. On page 3 I can create a new/edit/delete all on the same page where reloads come back to page 3. I want a "back" button on page 3 to go back to page 2, but retain the options it had from the original page 1 request. Page 1 has a bunch of check boxes which are passed to page 2 as arrays to the controller. My thought is that I have to pass these arrays (I converted them to lists) to page 3 (even thought page 3 directly doesn't need them) so that page 3 can use them in the back link to it can recreate the values page 1 sent to page 2 originally. I'm using asp.net MVC and when I pass the converted array it seems to convert it to the type instead of actually showing the values: "types=System.Collections.Generic.List" (where types is a List. **Is this what is needed or are there other options to getting a "back" button in this case to go back to page 2.** It's sort of a pain to pass information to page 3 that isn't really relevant to page 3 except the back button.


Please explain the benefit(s) of using an XML-based syntax (e.g. XAML) instead of normal source code (e.g. WinForms)?

First off, please note that this question is not about WPF vs. WinForms. What are the highest-ranking benefits that led Microsoft to invent XAML in favour of the “old” approach of generating compilable C# code? My impression is that other developers seem to find a lot of downsides to it, but Microsoft went with it regardless, which must mean that there is a benefit that I am not seeing. I would like you to explain to me what it is that I am missing.


Automated out going ACH transfers

Our team is working on a market place web application where the application will collect payments from individual users then deduct a small percentage fee before paying the balance to the users chosen service vendor. We've encountered problems finding a service provider that will allow outgoing ACH. We've asked both several merchant accounts and banks looking for a solution. Although out going ACH is possible through some banks, we are so far unable to find a bank that exposes an API for automating the process. We're hoping the community has found a viable solution for the redistribution of funds as described. We're certainly not stuck on any particular technology or method such as ACH. Your thoughts, idea or solutions are greatly appreciated.


learning on the clock

Some might argue this question is too general, but because keeping up seems especially relevant to programming, is anyone's experience that:   * do employers expect you to stay current? what is the "industry standard" of expected time a programmer should spend keeping up-to-date?    * is it generally acceptable that a programmer can spend some time during working hrs on meeting the expectation to keep skills current? If not, how do most programmers find the time?  -


Choosing the right branching strategy for releases

Starting with a new dev team on a new project and we have to define our Branching strategy for our source repository ( _e.g. Microsoft Team Foundation Server 2010_ ). We've run into a sticky discussion over whether or not to... **A**. Have one **Release** branch from which we do production builds and then **Label** when something is actually released OR **B**. Have a new **Release** branch for each new Release into production ( _Ex. Version 1, 2, 3, etc..._ ) Option **A** seems pretty straight-forward but we're not sure if this will lead to problems in the long run. Option **B** seems like it just creates lots of one-time long-lived branches that just pile up over time. Does anyone have any experience either way that could help us decide? Specifically, I'm looking to hear where the pain-points are for any one choice. Feel free to provide specific experience relative to TFS and/or Release-Management implications.


What does Software Engineer in Test do?

Normally unit tests were written by developer who write the code, i.e. Test Driven Development. So what does Software Engineer in Test do?


Should a developer adhere to the class diagrams produced during system design?

The class diagram is modeled on the system requirements, and it is important to create solutions based on those requirements. If I have said class diagram should I strictly adhere to it? What about refactoring? What if the diagram did not provide some design principle that I feel were left out?


How is a committer expected to behave?

In _open source projects_ there is typically a set of devs that have permissions to commit code - the committers -, and others that "pull request" or send patches, the "general public". I find a annoying when   1. the committer signs the commit with its own name, and writes in the commit message a "Thanks to ...".   2. the committer changes the patch before commit without asking if the original author agrees. Given this two annoyances, I'm compelled to think that I should put myself in the other side and ask how should a core committer behave. Are these two particular situations expected? I mean, is this the correct behaviour for building and maintaining an active community of "general public"? EDIT: I'm not asking if they have the right to do it or are legally obliged to do so. IMO a committer should not content himself to follow the law, but should be interested in building/maintaining the community within the project objectives constraints. That is what I'm asking for: how he should behave to accomplish this.


Website Internationalisation approaches

I'm currently working on a project that the client wants to deliver to different countries. The application is a website. We started out using resource files to change the text the user sees when visiting pages based on their locations. But this isn't enough. In the English version of the site we have a page that states "page x of y". In the Chinese version of the site, it's not enough to do " x y" The syntax for the language doesn't match the placeholders that were created for the English language. The only other option I can think of is to have a completely separate site, serving different content. Are there any other options to solve this issue?


Dealing with not knowing parameter names of a function when you're calling it

Here's a programming/language problem I'd like to hear your thoughts on. We have developed conventions that most programmers (should) follow that aren't a part of the languages syntax but serve to make code more readable. These are of course always a matter of debate but there's at least some core concepts that most programmers find agreeable. Naming your variables appropriately, naming in general, making your lines not outrageously long, avoiding long functions, encapsulations, those things. However, there's a problem that I have yet to find anyone commenting on and that just might be the biggest one of the bunch. It's the problem of arguments being anonymous when you call a function. Functions stem from mathematics where f(x) has a clear meaning because a function has a much more rigorous definition that it usually does in programming. Pure functions in mathematics can do a lot less than they can in programming and they are a much more elegant tool, they usually only take one argument (which is usually a number) and they always return one value (also usually a number). If a function takes multiple arguments, they are almost always just extra dimensions of the function's domain. In other words, one argument isn't more important than the others. They are explicitly ordered, sure, but other than that, they have no semantic ordering. In programming however, we have more freedom defining functions, and in this case I'd argue it isn't a good thing. A common situation, you have a function defined like this               func DrawRectangleClipped (rectToDraw, fillColor, clippingRect) {}      Looking at the definition, if the function is written correctly, its perfectly clear what's what. When calling the function, you might even have some intellisense/code completion magic going on in your IDE/editor that will tell you what the next argument should be. But wait. If I need that when I'm actually writing the call, isn't there something we're missing here? The person reading the code doesn't have the benefit of an IDE and unless they jump to the definition, they have no idea which of the two rectangles passed as arguments is used for what. The problem goes even further than that. If our arguments come from some local variable, there might be situations where we don't even know what the second argument is since we only see the variable name. Take for example this line of code               DrawRectangleClipped(deserializedArray[0], deserializedArray[1], deserializedArray[2])      This is alleviated to various extents in different languages but even in strictly typed languages and even if you name your variables sensibly, you don't even mention the type the variable is when you're passing it to the function. As it usually is with programming, there are a lot of potential solutions to this problem. Many are already implemented in popular languages. Named parameters in C# for example. However, all that I know have significant drawbacks. Naming every parameter on every function call can't possibly lead to readable code. It almost feels like maybe we're outgrowing possibilities that plain text programming gives us. We've moved from JUST text in almost every area, yet we still code the same. More information is needed to be displayed in the code? Add more text. Anyways, this is getting a bit tangential so I'll stop here. One reply I got to the second code snippet is that you would probably first unpack the array to some named variables and then use those but the variable's name can mean many things and the way it's called doesn't necessarily tell you the way it's supposed to be interpreted in the context of the called function. In the local scope, you might have two rectangles named leftRectangle and rightRectangle because that's what they semantically represent, but it doesn't need to extend to what they represent when given to a function. In fact, if your variables are named in the context of the called function than you're introducing less information than you potentially could with that function call and on some level if does lead to code worse code. If you have a procedure that results in a rectangle you store in rectForClipping and then another procedure that provides rectForDrawing, then the actual call to DrawRectangleClipped is just ceremony. A line that means nothing new and is there just so the computer knows what exactly you want even though you've explained it already with your naming. This isn't a good thing. I'd really love to hear fresh perspectives on this. I'm sure I'm not the first one to consider this a problem, so how is it solved?


Do .NET 4.0 Code Contracts have a role to play in solo-programmer projects?

I often find myself wondering what programming best practices apply to solo programming, since most of the time, I'm the only programmer on a project. I just started experimenting with C# 4.0 Code Contracts, and I thought I'd ask the community what utility they may have for a solo programmer. Here's where I'm coming from with this. Most of the time, when I encounter an exception, it means there's a bug in my code. There are definite exceptions (no pun intended) to this, such as when I'm dealing with something external, such as a text file, database, or service, but for the most part, exceptions mean _I_ did something wrong. Take this simple method:               public void MapEntity(PersonModel model, PersonEntity entity)     {         entity.Name = model.Name;         entity.Age = model.Age;         entity.Updated = DateTime.Now;     }      If either `model` or `entity` are null, this method will throw a `NullReferenceException`. As the only consumer of my code, I know that I shouldn't pass in a null reference, but if I somehow do, I _want_ an exception to be thrown, and I _want_ the debugger to jump right to the source of the error so I can see what happened. That said, I could write:               public void MapEntity(PersonModel model, PersonEntity entity)     {         Contract.Requires(model != null);         Contract.Requires(entity != null);         entity.Name = model.Name;         entity.Age = model.Age;         entity.Updated = DateTime.Now;     }      This has the advantage of explicitly indicating (to myself) that the two arguments are not allowed to be null. However, it's very unlikely I would make this mistake (because I know what the method does). Further, if I understand properly what `Requires()` does, the behavior at runtime if a null argument is encountered would be pretty much the same. So, I can't help but wonder, what have I gained besides two lines of code? As a counterpoint, here's a case where I see definite value in being explicit:               public User FindUser(string emailAddress)     {         if (string.IsNullOrWhiteSpace(emailAddress)) return null;         var users = DbContext.Users.Where(u => u.EmailAddress == emailAddress);         Contract.Assert(users.Count() <= 1,                         "The database appears to be corrupted:                         More than one user was found for the provided email address.                         Email addresses are supposed to be unique.");         return users.SingleOrDefault();     }      But in this case, the reason I see value in using a coding contract is to indicate that something that has gone wrong that is not a bug per se (though it could have resulted from a bug elsewhere in the system). I'd like to know if I'm on the right track with my thinking, or if there is more value in code contracts than I realize. Does it pay to use contracts when you can examine and debug the code yourself or only when the code is going to be used by a third party?


I'm a iOS developer and I want to learn game programming

I programmed for the iphone (and a bit for mac) for the last 1 or 2 years and now I want to learn Java. I know OOP and am also farmiliar with a bit of the c syntax! Are there any books like java for objective-c programmers or some stuff like that? If you think c++ would be a better idea than Java (for game programming) please also give me tips for that. I'd really like to stay in OOP.


Correlation between two curves

I am trying to solve a mathematical problem in two different ways and output is a curve in both the cases. I want to compare these output curves for similarity in python. Is there any function or framework which provides this functionality? Thanks.


Settle an Argument: String vs. Array?

True or False: A string is the same thing as an array. I had an interview the other day and the above question was asked. I said false, but the interviewer said it was actually true. I explained to her that a string is a data type and an array is an object that holds multiple instances of a variable, and that they aren't even similar concepts. But, she was an HR person who was just reading tech questions that were handed to her, so she couldn't elaborate or relate to my point. A coworker later explained the True answer by stating that a string is actually a character array... thus, a string is an array. Now, if a string is a character array, that doesn't mean that document arrays or integer arrays qualify as strings. Thus, a string is not the same thing as an array. But even so, (considering C#) a string isn't even a character array. In order to do character manipulation on a string (without using concatenation methods), you have to convert the string to a character array. Now, if a string was synonymous with a character array, why would you need to convert it? Wouldn't you just be able to call each character in the string implicitly as you would a character array? No! Why? Because a string is not a character array! I liken it to asking, "Is a primary key the same as a unique identifier?" The answer is false. Reason being: A primary key is a unique identifier, but you can have unique identifiers in a table without setting them as keys. What do you all think? Is a string (data type) the same thing as an array (object type)? If so, why?


Plugin Architecture: How to Handle Databases and Logging?

I am in the process of designing an architecture for a plugin based application and I have some questions about how to handle database access and logging. The goal of my application is to allow a device my company is manufacturing to send messages over any number of third-party protocols and to any number of third party devices. Because of the nature of my application, I need to log every message that is sent via my system in reasonable detail. Here's what I am thinking on the Database side: There will be a global message table which stores all of the implementation agnostic data we have, and then there will be a table (or set of tables) for each messaging plugin _as defined by the plugin writer_ which references the Global Message table via a foreign key. It is handling these other tables that I am having a hard time figuring out how to design safely. On the one hand, I don't particularly want to give the plugins full access to the database (I want them to have the fewest possible privileges), on the other hand I want the plugin developers to have full reign to log any data they need to tables that they define similarly to how plugins work in Wordpress. Additionally, I don't want logging to the Database to be optional at all: Good logging is crucial to my application. Things I have considered:   * Designing a logging infrastructure which allows a plugin to define (maybe in an XML file) the tables it needs in the DB and a mapping between those tables and objects that they will return, and using those mappings and table definitions to write to the DB the results from method calls.   * Making a naming convention for Stored Procedures in the DB that each plugin must define when defining their tables and automatically calling those stored procedures after sending a message.   * Allowing each plugin to implement a logging method which returns a String holding the proper SQL query. Each of the above solutions makes me a little uncomfortable, but I'm not sure what other approaches might exist. Any Suggestions? Implementation Details: I am writing my application in Java, and I am using a hand-rolled plugin solution, so I have a pretty decent amount of flexibility. Since none of the actual code has been written (other than some proof-of concept code which is really just for reference), I can make fairly major changes to my plan without great cost.


Algorithm to order array

Take for example this input array:               [2,7,1,4,9]      For this input, I need to produce an array of total 23 elements which contains two elements of 2, seven elements of 7, one element of 1, four elements of 4 and nine elements of 9. Example of output array:               [2,2,7,7,7,7,7,7,7,1,4,4,4,4,9,...]      However, this array **needs to be ordered in the way that minimizes the number of same elements appearing next to each other**. The example of such array would be something like this:               [7,2,9,4,9,1,7,...]      The primary goal is to minimize the number of the same adjacent elements. Secondary goal is to distribute elements unbiased across resulting array if possible. Any pseudo code or C#, java, ... would be helpful.


Nesting Linq-to-Objects query within Linq-to-Entities query –what is happening under the covers?

var numbers = new int[] { 1, 2, 3, 4, 5 };             var contacts = from c in context.Contacts                       where c.ContactID == numbers.Max() | c.ContactID == numbers.FirstOrDefault()                       select c;              foreach (var item in contacts) Console.WriteLine(item.ContactID);       Linq-to-Entities query is first translated into Linq _expression tree_ , which is then converted by Object Services into _command tree_. And if Linq-to- Entities query nests Linq-to-Objects query, then this nested query also gets translated into an _expression tree_. a) I assume none of the operators of the nested Linq-to-Objects query actually get executed, but instead _data provider_ for particular DB (or perhaps Object Services) knows how to transform the logic of Linq-to-Objects operators into appropriate SQL statements? b) _Data provider_ knows how to create equivalent SQL statements only for some of the Linq-to-Objects operators? c) Similarly, _data provider_ knows how to create equivalent SQL statements only for some of the non-Linq methods in the Net Framework class library? **EDIT:** I know only some Sql so I can't be completely sure, but reading Sql query generated for the above code it seems data provider didn't actually execute `numbers.Max` method, but instead just somehow figured out that `numbers.Max` should return the maximum value and then proceed to include in generated Sql query a call to **TSQL's build-in MAX function**. It also put all the values held by `numbers` array into a Sql query.                SELECT CASE              WHEN (([Project1].[C1] = 1)                    AND ([Project1].[C1] IS NOT NULL)) THEN '0X0X'              ELSE '0X1X'            END                      AS [C1],            [Extent1].[ContactID]    AS [ContactID],            [Extent1].[FirstName]    AS [FirstName],            [Extent1].[LastName]     AS [LastName],            [Extent1].[Title]        AS [Title],            [Extent1].[AddDate]      AS [AddDate],            [Extent1].[ModifiedDate] AS [ModifiedDate],            [Extent1].[RowVersion]   AS [RowVersion],            CASE              WHEN (([Project1].[C1] = 1)                    AND ([Project1].[C1] IS NOT NULL)) THEN [Project1].[CustomerTypeID]            END                      AS [C2],            CASE              WHEN (([Project1].[C1] = 1)                    AND ([Project1].[C1] IS NOT NULL)) THEN [Project1].[InitialDate]            END                      AS [C3],            CASE              WHEN (([Project1].[C1] = 1)                    AND ([Project1].[C1] IS NOT NULL)) THEN [Project1].[PrimaryDesintation]            END                      AS [C4],            CASE              WHEN (([Project1].[C1] = 1)                    AND ([Project1].[C1] IS NOT NULL)) THEN [Project1].[SecondaryDestination]            END                      AS [C5],            CASE              WHEN (([Project1].[C1] = 1)                    AND ([Project1].[C1] IS NOT NULL)) THEN [Project1].[PrimaryActivity]            END                      AS [C6],            CASE              WHEN (([Project1].[C1] = 1)                    AND ([Project1].[C1] IS NOT NULL)) THEN [Project1].[SecondaryActivity]            END                      AS [C7],            CASE              WHEN (([Project1].[C1] = 1)                    AND ([Project1].[C1] IS NOT NULL)) THEN [Project1].[Notes]            END                      AS [C8],            CASE              WHEN (([Project1].[C1] = 1)                    AND ([Project1].[C1] IS NOT NULL)) THEN [Project1].[RowVersion]            END                      AS [C9],            CASE              WHEN (([Project1].[C1] = 1)                    AND ([Project1].[C1] IS NOT NULL)) THEN [Project1].[BirthDate]            END                      AS [C10],            CASE              WHEN (([Project1].[C1] = 1)                    AND ([Project1].[C1] IS NOT NULL)) THEN [Project1].[HeightInches]            END                      AS [C11],            CASE              WHEN (([Project1].[C1] = 1)                    AND ([Project1].[C1] IS NOT NULL)) THEN [Project1].[WeightPounds]            END                      AS [C12],            CASE              WHEN (([Project1].[C1] = 1)                    AND ([Project1].[C1] IS NOT NULL)) THEN [Project1].[DietaryRestrictions]            END                      AS [C13]     FROM   [dbo].[Contact] AS [Extent1]            LEFT OUTER JOIN (SELECT [Extent2].[ContactID]            AS [ContactID],                                    [Extent2].[BirthDate]            AS [BirthDate],                                    [Extent2].[HeightInches]         AS [HeightInches],                                    [Extent2].[WeightPounds]         AS [WeightPounds],                                    [Extent2].[DietaryRestrictions]  AS [DietaryRestrictions],                                    [Extent3].[CustomerTypeID]       AS [CustomerTypeID],                                    [Extent3].[InitialDate]          AS [InitialDate],                                    [Extent3].[PrimaryDesintation]   AS [PrimaryDesintation],                                    [Extent3].[SecondaryDestination] AS [SecondaryDestination],                                    [Extent3].[PrimaryActivity]      AS [PrimaryActivity],                                    [Extent3].[SecondaryActivity]    AS [SecondaryActivity],                                    [Extent3].[Notes]                AS [Notes],                                    [Extent3].[RowVersion]           AS [RowVersion],                                    cast(1 as bit)                   AS [C1]                             FROM   [dbo].[ContactPersonalInfo] AS [Extent2]                                    INNER JOIN [dbo].[Customers] AS [Extent3]                                      ON [Extent2].[ContactID] = [Extent3].[ContactID]) AS [Project1]              ON [Extent1].[ContactID] = [Project1].[ContactID]            LEFT OUTER JOIN (SELECT TOP (1) [c].[C1] AS [C1]                             FROM   (SELECT [UnionAll3].[C1] AS [C1]                                     FROM   (SELECT [UnionAll2].[C1] AS [C1]                                             FROM   (SELECT [UnionAll1].[C1] AS [C1]                                                     FROM   (SELECT 1 AS [C1]                                                             FROM   (SELECT 1 AS X) AS [SingleRowTable1]                                                             UNION ALL                                                                       SELECT 2 AS [C1]                                                             FROM   (SELECT 1 AS X) AS [SingleRowTable2]) AS [UnionAll1]                                                     UNION ALL                                                               SELECT 3 AS [C1]                                                     FROM   (SELECT 1 AS X) AS [SingleRowTable3]) AS [UnionAll2]                                             UNION ALL                                                       SELECT 4 AS [C1]                                             FROM   (SELECT 1 AS X) AS [SingleRowTable4]) AS [UnionAll3]                                     UNION ALL                                               SELECT 5 AS [C1]                                     FROM   (SELECT 1 AS X) AS [SingleRowTable5]) AS [c]) AS [Limit1]              ON 1 = 1            LEFT OUTER JOIN (SELECT TOP (1) [c].[C1] AS [C1]                             FROM   (SELECT [UnionAll7].[C1] AS [C1]                                     FROM   (SELECT [UnionAll6].[C1] AS [C1]                                             FROM   (SELECT [UnionAll5].[C1] AS [C1]                                                     FROM   (SELECT 1 AS [C1]                                                             FROM   (SELECT 1 AS X) AS [SingleRowTable6]                                                             UNION ALL                                                                       SELECT 2 AS [C1]                                                             FROM   (SELECT 1 AS X) AS [SingleRowTable7]) AS [UnionAll5]                                                     UNION ALL                                                               SELECT 3 AS [C1]                                                     FROM   (SELECT 1 AS X) AS [SingleRowTable8]) AS [UnionAll6]                                             UNION ALL                                                       SELECT 4 AS [C1]                                             FROM   (SELECT 1 AS X) AS [SingleRowTable9]) AS [UnionAll7]                                     UNION ALL                                               SELECT 5 AS [C1]                                     FROM   (SELECT 1 AS X) AS [SingleRowTable10]) AS [c]) AS [Limit2]              ON 1 = 1            CROSS JOIN (SELECT MAX([UnionAll12].[C1]) AS [A1]                        FROM   (SELECT [UnionAll11].[C1] AS [C1]                                FROM   (SELECT [UnionAll10].[C1] AS [C1]                                        FROM   (SELECT [UnionAll9].[C1] AS [C1]                                                FROM   (SELECT 1 AS [C1]                                                        FROM   (SELECT 1 AS X) AS [SingleRowTable11]                                                        UNION ALL                                                                  SELECT 2 AS [C1]                                                        FROM   (SELECT 1 AS X) AS [SingleRowTable12]) AS [UnionAll9]                                                UNION ALL                                                          SELECT 3 AS [C1]                                                FROM   (SELECT 1 AS X) AS [SingleRowTable13]) AS [UnionAll10]                                        UNION ALL                                                  SELECT 4 AS [C1]                                        FROM   (SELECT 1 AS X) AS [SingleRowTable14]) AS [UnionAll11]                                UNION ALL                                          SELECT 5 AS [C1]                                FROM   (SELECT 1 AS X) AS [SingleRowTable15]) AS [UnionAll12]) AS [GroupBy1]     WHERE  [Extent1].[ContactID] IN ([GroupBy1].[A1], (CASE                                                          WHEN ([Limit1].[C1] IS NULL) THEN 0                                                          ELSE [Limit2].[C1]                                                        END))      Based on this, is it possible that Linq2Entities provider indeed doesn't execute non-Linq and Linq-to-Object methods, but instead creates equivalent SQL statements for some of them ( and for others it throws an exception )? Thank you in advance


What are some JavaScript selectors?

I was at an interview recently and although they knew that I was a beginner in javascript they asked me what selectors I used before? I didn't know what to say. I came back home and searched for it but can't find a clear definition. Isn't a selector something like a .class or #id?


Is Using Locking/Unlocking in Version Control an Anti-Pattern?

Recently I've started using Git at work. Previously I've only ever used VSS (which has some problems) and so far, Git is orders of magnitude better. The key differences here is that Git is distributed while VSS has a centralized "server" version, and that VSS uses a "checkout-lock-checkin" workflow while Git doesn't. The biggest problems we've had on working with code on our team relate to code being checked-out and unavailable to other people. This slows down work considerably, but I also know this isn't unique to VSS. Other source control systems like CVS apparently also lock files as part of their workflow. Is there any good reason for locking to be part of a version control system? Or even a development workflow? Or perhaps locking practices should be considered bad practice and discouraged?


success:/failure: blocks vs completion: block

I see two common patterns for blocks in Objective-C. One is a pair of success:/failure: blocks, the other is a single completion: block. For example, lets say I have a task that will return an object asynchronously and that task might fail. The first pattern is `-taskWithSuccess:(void (^)(id object))success failure:(void (^)(NSError *error))failure`. The second pattern is `-taskWithCompletion:(void (^)(id object, NSError *error))completion`. ### success:/failure:               [target taskWithSuccess:^(id object) {         // W00t! I've got my object     } failure:^(NSError *error) {         // Oh noes! report the failure.     }];      ### completion:               [target taskWithCompletion:^(id object, NSError *error) {         if (object) {             // W00t! I've got my object         } else {             // Oh noes! report the failure.         }     }];      Which is the preferred pattern? What are the strengths and weaknesses? When would you use one over the other?


What does "recursive" mean for a program which processes files and directories?

I know what recursion is in programming. I do understand the basics of version control systems (have used svn that is). But I have often wondered what the meaning of "recursion" or "recursive" is with respect to version control systems. What does a function calling itself have to do with working with files and directories in a version control system?


What use is a Business Logic Layer (BLL)?

In reading up on good practice for database applications I've frequently come across advocates of so-called "business logic layers" and I'm trying to decide if it's best for my project to use one (it's a small personal project). My issue lies in the fact that I can't think of anything for the BLL to do that the DAL can't already handle (executing queries and mapping results to objects), so my BLL just calls the DAL without doing anything itself. Maybe I'm wrong about exactly what the DAL should be doing too. But regardless, what sorts of functionality should be expected of a BLL in a database management application?


Are there benefits to deriving versions from SCM branch?

Currently, we have a versioning scheme following the major.minor.patch pattern. Development is done in a branch (i.e. - branches/b4_2); a release is a tag (tags/r4_2_0). To determine the version inside the code, we have a class which can parse the SCM URL (FooVersion.java). If the URL represents a branch, the SVN revision is appended (for QA builds). We're re-evaluating versioning and, more pointedly, what sort of environments we have up. The big change here is adding the concept of a beta environment for our "super users". Along with this, I'm rethinking this potentially over- engineered version derivation system. How do you determine, in the code, what the version of the software is? Creating a release is already a manual process (create tag, check in JARs for the related libraries we develop, etc.) which could probably be scripted, so is there a benefit to the way we do it over having a text file which is updated when a version is cut?


Filling a scene with cubes

I am trying to design a solution for simulating gaseous fluids in confined areas, I am using naiver-stokes equations for fluid dynamics but since it only covers incompressible fluids like liquid, i needed to find a way to simulate compression Recently, I came up with the solution which is, creating a field storing pressure data for each volumetric partition and I thought it would be a good idea to construct this field as a composition of cubes where each cube has homogeneous pressure value within itself. I tried to inflate a cube from a point and create other cubes from its surfaces recursively minding the collision with surfaces inside that scene, but this algorithm fails because there are lots of detailed cases involving complex holes and notches on the object. Is there a better way to construct this field?


Are there any subversion "dash board" web applications that can show me a list of recent commits from all my repositories?

I am looking for something like a subversion dashboard that at the very least can show me commits from across a group of repositories. Is there anything like this available? Since it could just as well be dead simple and I can't find anything immediately I am thinking if just scratching my own itch here, but I am hoping someone has wanted this before? Are there any subversion "dashboards" that an show me even a simple twitter-like list of commits from across my repositories?


Online Poker Game Programming

I am trying to write a massive online multiplayer client for a poker site, where one user can be on a Flash client and the other on say an iOS client (iPhone / iPad), and would like to know how can interaction between two users be visible on both clients. What would be better to use?   * Should I use MSMQ?    * AJAX?    * Something other?  I need the messaging layer (client interaction messages) to scale up to 100K+ online users to begin with. In other words; What scalable technology can I use to make game interactions between online users visible to all game participants?


A local/internal deployment of something like Campfire for developers

I've been looking at Campfire by 37Signals and it looks like a great tool for collaboration between developers but we need something that can be deployed internally. Any good options out there?


PHP, when to use iterators, how to buffer results?

1. When is it best to use Iterators in PHP, and how can they be implemented to best avoid loading all objects into memory simultaneously?   2. Do any constructs exist in PHP so that we can queue up results of an operation for use with an Iterator, while again avoiding loading all objects into memory simultaneously?      1. An example would be a curl HTTP request against a REST server   3. In the case of an HTTP request that returns all results at once (a la curl), would we be better off to go with streaming results, and if so, are there any limitations or pitfalls to be aware of?      1. If using streaming, is it better to replace curl with a PHP native stream/socket? My intention is to implement Iterators for a REST client, and separately a document ORM that I'm maintaining, but only if I can do so while gaining benefits from reduced memory usage, increased performance, etc. Thanks in advance for any responses :-)


How do I capture information from a website that doesn't provide an API?

Do you know any good tutorials, frameworks, anything that can help me to write code that captures information from a website that don't have a public API, or hasn't been written in a RESTful way? I've heard there's a Ruby gem that simulates a browser, but I forgot its name and couldn't find any information about it anymore.


How do you keep track of large projects?

When dealing with a project that has many different files, I always seem to loose track of how the parts interact with one another. I've never really had much of a problem understanding smaller components in isolation, but as the complexity of the project increases, I find myself unable to mentally construct an understanding of what is going on. I notice this especially with OOP projects, as the number of methods and source files increase. My background: I'm a self-taught web programmer. I've dealt mostly with python for quick and dirty scripts, but I've also done a few basic django projects. I like web frameworks such as flask, because in the simplicity of a single-file layout, I can easily keep track (mostly) of what is going on. I now find myself in a situation where I need to interact with a large Zend Framework PHP project that someone else developed, and I'm overwhelmed with trying to understand the code spread out to numerous files. **What techniques and processes have you found useful to understand a large code base that someone else has developed? Is there any particular diagram that you find helps you grasp the larger picture?**


What is the difference between a pointer pointing to 0x0 location and a pointer set to NULL?

Is a pointer pointing to 0x0000 the same as a pointer set to NULL? If NULL value is defined in the C language, then what location does it physically translate to? Is it the same as 0x0000. Where can I find more details about these concepts?


Name for use of methods that return rather than set

There exists a general OOP principle that methods should return local variables rather than set object fields. For instance, say I have the following piece of code (example in Java):               public class Number {         public int myNum;     }          public class Horrible {         public static void areYouSerious(Number num){             num.myNum = 47;         }     }          public class Test {         public int num = new Number();              public void doHorribleThings(){             Horrible.areYouSerious(num);         }              public static void main(String[] args){             Test test = new Test();             test.doHorribleThings();         }     }      Obviously this style of programming can go sideways very quickly, and becomes a massive headache for anyone attempting to maintain it. A more correct way of doing this would be the following:               public class Number {         public int myNum;     }          public class NotAsBad {         public static int getDefaultVal(){             return 47;         }     }          public class Test {         public int num = new Number();              public void doHorribleThings(){             num.myNum = NotAsBad.getDefaultVal();         }              public static void main(String[] args){             Test test = new Test();             test.doHorribleThings();         }     }      The first example is modifying a passed in reference, whereas the second is generalizing the static setting function, making it return a value which can be used to set the object field. **Is there a name for the principle that the second method should be preferred over the first? A sort of "modularity" principle?** Just as `encapsulation` is the term for restricting variable manipulation, I would like a term for limiting the scope of the effects of some piece of functionality. If there is no existing term, I am going to call it _consequence localization_.