Visiting points on a number line while minimizing a cost not related to distance

I need some help on this ACM ICPC problem. My current idea is to model this as a shortest path problem, which is described under the problem statement. **Problem** There are `N = 1000` nuclear waste containers located along a 1-D number line at _distinct_ positions from `-500,000 to 500,000`, except `x=0`. A person is tasked with collecting all the waste bins. Each second that a waste container isn't collected, it emits 1 unit of radiation. The person starts at `x = 0` and can move `1` unit every second, and collecting the waste takes a negligible amount of time. We want to find the minimum amount of radiation released while collecting all of the containers. **Sample Input:** `4` Containers located at `[-12, -2, 3, 7]`. The best order to collect these containers is `[-2, 3, 7, -12]`, for a minimum emitting of `50` units. Explanation: the person goes to `-2` in 2 seconds and during that time `2 units` of radiation are emitted. He then goes to `3` (distance: `5`) so that barrel has released `2 + 5 = 7` units of radiation. He takes `4` more seconds to get to `x = 7` where that barrel has emitted `2 + 5 + 4 = 11` units. He takes `19` seconds to get to `x = -12` where that barrel has emitted `2 + 5 + 4 + 19 = 30` units. `2 + 7 + 11 + 30 = 50`, which is the answer. **Notes** There is an obvious `O(N!)` solution. However, I've explored greedy methods such as moving to the closest one, or moving to the closest cluster but those haven't worked. I've thought about this problem for quite a while, and have kind of modeled it as a graph search problem:   1. We insert `0` in as a baseline position (This will be the initial state)   2. Then, we sort the positions from least to greatest.   3. We then do a BFS/PFS, where the `state` consists of      * Two integers `l` and `r` that represent a contiguous range in the sorted position array that we have visited already     * An integer `loc` that tells us whether we're on the left or right endpoint of the range     * An integer `time` that tells us the elapsed time     * An integer 'cost' that tells us the total cost so far (based on nodes we've visited)   4. From each state we can move to [l - 1, r] and [l, r + 1], tweaking the other 3 integers accordingly   5. Final state is [0, N], checking both ending positions. However, it seems that `[L, R, loc]` does not uniquely define a state, and we have to store `L, R, loc, and time`, while minimizing `cost` at each of these. This leads to an exponential algorithm, which is still way too slow for any good. Can anyone help me expand on my idea or push my into the right direction? **Edit:** Maybe this can be modeled as a dynamic programming optimization problem? Thinking about it, it has the same issues as the graph search solution - just because the current `cost` is low doesn't mean it is the optimal answer for that sub problem, since the `time` also affects the answer greatly. Greedy doesn't work: I have a greedy selection algorithm that estimates the cost of moving to a certain place (e.g. if we move right, we double the distances to the left barrels and such). Could you do a Priority-first search, with a heuristic? The heuristic could combine the cost of the current trip with the amount of time elapsed.


How to integrate google search results in a spring mvc app

Here's what am trying to do (and searching for similar hasn't shown any results anywhere): On my website - provide an input box which will search google for results. I want to display those results on my page and customize the URL of those search results. So whenever a user clicks on the displayed result, my application will (internally search for profile pages and) provide the future course of action. The only integration of google is, providing the search results (and probably the map coordindates) Env: Spring mvc, jsp, hibernate. Can some one please advise on how can I achieve this ?   I dont where to begin but I have read about the Google custom search, but I think that is only for searching within your site or to redirect users to relevant sites found from the result.


How do handle developer keys that are supposed to be non human readable in your app? (example: specific conflict with twitter api and twitter gem)

How do handle developer keys that are supposed to be non human readable in your app? From twitter's developer page, under My Access Token it says: "Keep the oauth_token_secret a secret. Along with your OAuth consumer secret, these keys should never be human readable in your applications." However, the awesome twitter gem ( https://github.com/jnunemaker/twitter ) says to make an initializer with this:               Twitter.configure do |config|       config.consumer_key = YOUR_CONSUMER_KEY       config.consumer_secret = YOUR_CONSUMER_SECRET       config.oauth_token = YOUR_OAUTH_TOKEN       config.oauth_token_secret = YOUR_OAUTH_TOKEN_SECRET      end      What do you do about this type of conflict? You can't just reset the oauth_token and oauth_token_secret, as far as I know you have to create a whole new twitter app. I concerned as I am going to begin working with some freelancer programmers and to begin with I wouldn't want to trust them my apps private keys/tokens. Thanks.


What is the logic behind filtering/sanitizing input?

I have always found it more logic to validate input instead of filtering it. How to appropriately filter data depends on the situation, so IMO it should be done in output or when saving to a database. But I see that some frameworks provide automatic XSS filters for incoming POST and GET data. What is the logic behind this solution? I can't see any advantages in doing this except providing a quick and easy solution to "lazy" developers. Or is there some specific security reason I don't understand?


Maintain a web application once the only developer is gone

I have a terminal disease and there is a very high chance that I will no longer be in this world by the end of the year. I have developed a web application that it is extensively used in my family’s business (a small hairdressing shop). No member of my family has neither programming nor system administration skills. I have neither close friends with those skills. The business makes at most 10k in net profits per year. In fact, the business profits can only afford to pay the salaries of its 3 employees (father, mother and sister) and those are quite low and decreasing each year due to the financial crisis. In fact, I am not an employee of my family’s business, I work for a normal software development company. I developed the application during my free time in order to help them. So far I do not care if another business also uses my application or even if the application itself loses my ownership. I just want that my family’s business can continue using it, which means system administration support if something goes wrong and development for new features/bugs. I would like to ask you if you could give me the measures you think I could take in order to guarantee as much as possible the continuity of the application. The technologies of the application are: Platform: Tomcat (Java), MySQL and Linux Frameworks: mainly JPA and ZK


How can I effectively explain technical concepts to a non technical boss when I'm not a good talker?

## Preface I work as web developer for a big retail company, which sells goods to smaller retails through its e-commerce web site, developing both for the e-commerce and intranet. The main source of profits is made through the sales through the e-commerce, followed by the ad-hoc customer management by the marketing department. Our department (web development) report directly to the top managment (AD, CEO, etc). ## My problem Even though my direct manager is an ex developer who understands the various programming issues, the department head is a marketroid who doesn't understand a thing about programming. He thinks that everything that doesn't yield benefits in a short span is a waste of time and not worthy, and his behaviour is hurting us developers. The main problem is I'm unable to explain technical concepts or issues to non technical people, so I fail to persuade him about what I should do or not do or what would make my work easier and more efficient. ## My questions Reading the similar questions I understood that I should   * Not make him feel stupid.   * Not look like I'm insubordinating.   * Not look like I'm trying to skip my work. But how the hell can I do that?   * How can I cross this "cultural" gap?   * How can I speak his language?   * What's the best way to convey him that thing X should be done Y way, that thing W is not a good idea and that tool Z is something really useful for us?   * Is there any good material on how to deal with non technical managers? Some of the answers around are suggesting examples he can understand, but I find these answers a little vague, I fail to come up with anything decent. Lately I'm starting to think that maybe we should take marketing classes or buy Mitnick's social engineering book... :\ ## Beware Let me stop those who are starting to scream "let your manager handle him". When my manager fails to handle him, the ones who will pay the consequences are us, the developers. So, helping my boss getting the point through is helping myself keeping my sanity around, and certainly something worth the trouble. ## Some examples   * Both the password for the intranet user and the e-commerce customers are saved in clear text in the database and must be changed every sixty days. This is a nonsense to me: aside from all the implications of not encrypting passwords before saving them, forcing the user to change their password every two month is begging them for using weak passwords. (He thinks the first is not an issue and that changing password frequently is more secure.)   * When a customer log in, all the user informations are saved into a cookie and using HTTPS everywhere is only a burden. This too doesn't make sense to me: we're bouncing arounk 75 KiB of cookies with every request instead of looking up user details from database, and by sniffing the cookie (e.g. unprotected WiFi) you can impersonate the user and buy stuff (even really expensive things) under his name yet only the login process is encrypted. (The former is not worth refactoring, and the latter is a non issue to him.)   * A colleague handles trouble tickets quickly because he's been working for the company for twelve years, many of the tools he's been "entrusted" have been developed by him and tells the user "don't do X" instead of fixing the problem in the code, and we who have been working here for one or two years, are managing tools written by former employees and go digging through the code to fix the problem get chewed for out higher mean resolution times. (He tells us we should be quicker, like him, because the time spent dealing with trouble tickets is not profitable, yet he won't allow the rebuild of the most crappy tools which would save time in the long run.)   * An issue tracking a la Redmine is seen only as a time sink because it does not "produce" any tangible benefit, yet we're stuck on taking note of to dos and problems on paper or .txts and keeping spreadsheets of the modifications as reference.


XSLT and possible alternatives

I had a look at XSLT for transforming one XML file into another one (HTML, etc.). Now while I see that there are benefits to XSLT (being a standardized and used tool) I am reluctant for a couple of reasons   * XSLT processors seem to be quite huge / resource hungry   * XML is a bad notation for programming and thats what XSLT is all about. It do not want to troll XSLT here though I just want to point out what I dislike about it to give you an idea of what I would expect from an alternative. Having some Lisp background I wonder whether there are better ways for tree- structure transformations based upon some lisp. I have seen references to DSSSL, sadly most links about DSSSL are dead so its already challenging to see some code that illustrates it. Is DSSSL still in use? I remember that I had installed openjade once when checking out docbook stuff. Jeff Atwood's blog post seems to hint upon using Ruby instead of XSLT. Are there any sane ways to do XML transformations similar to XSLT in a non-xml programming language? I would be open for input on   * Useful libraries for scripting languages that facilitate XML transformations   * especially (but not exclusively) lisp-like transformation languages, or Ruby, etc. A few things I found so far:   * A couple of places on the web have pointed out Linq as a possible alternative. Quite generally I any kind of classifications, also from those who have had the best XSLT experience.   * For scheme http://cs.brown.edu/~sk/Publications/Papers/Published/kk-sxslt/ and http://www.okmij.org/ftp/Scheme/xml.html


How long should someone take classes in a language they don't plan to work professionally in?

I was late in my signing up for classes at the start of last term, so I signed up for the only programming class I could find C++. After doing well in that class I was allowed into intermediate C#, which I learned was what I needed to be in for my major. I also took intermediate C++ thinking that taking both would make them both easier. I was right. I will be moving on to ASP.NET next term, and while I really like C++, I'm not sure that it will help me overall with my future education in C#. I also have the option to move into java, so I would be taking ASP.NET and java at the same time. So do I take C++, Java, both, or neither? and why?


Why were short, int, and long invented in C?

I'm having trouble understanding, what were the exact purposes of creating the `short`, `int`, and `long` data types in C? The reason I ask is, it doesn't seem like their sizes are bounded -- they could be of any size, so long as `short` is smaller than an `int`, for example. In which situations, then, should you use an `unsigned int` or `unsigned long`, for example, instead of a `size_t`, when doing so offers no hope of binary compatibility? (If you don't know the size, then how would you know when to choose which?)


Who should support and maintain development infrastructure?

I am interested to know what other peoples' experiences are with managing development infrastructure are. I am talking about things like the build server, the central git repo etc etc. Any infrastructure which end users would probably not even know existed, but which are essential for the development team.   1. Do your dev/devops/ops teams consider them to be as important as 'true' production systems?   2. What happens when one goes down (both in terms of ramifications and recovery processes)?   3. Who should be responsible for managing them? Note: to complicate things (especially (3) above, our "teams" are small, about five or six devs and only the one sys admin. Hence, there is a lot of crossover of us devs in to ops, especially with the advent of the "devops" movement and technologies. Disclaimer - I am the author of this blog post about the subject.


Where are programming languages published?

I have read that a number of new programming languages are created each year, however I have never seen a single one. Where exactly are these things published? Is there some site out there that keeps track of them? (I don't have any intention to learn such languages - I am only interested)


Should I care about Junit redundancy when using setUp() with @Before annotation?

Even though developers have switched from junit 3.x to 4.x I still see the following 99% of the time:               @Before     public void setUp(){/*some setup code*/}          @After     public void tearDown(){/*some clean up code*/}      Just to clarify my point... in Junit 4.x, when the runners are set up correctly, the framework will pick up the `@Before` and `@After` annotations no matter the method name. So why do developers keep using the same conventional junit 3.x names? **Is there any harm keeping the old names while also using the annotations** (other than it makes me feel like devs do not know how this really works and just in case, use the same name AND annotate as well)? **Is there any harm in changing the names** to something _maybe_ more meaningful, like `eachTestMethod()` (which looks great with @Before since it reads 'before each test method') or `initializeEachTestMethod()`? **What do you do and why?** I know this is a tiny thing (and may probably be even unimportant to some), but it is always in the back of my mind when I write a test and see this. I want to either follow this pattern or not but I want to know why I am doing it and not just because 99% of my fellow developers do it as well.


Technical interview and programmer ability

What I will say might be a tad controversial in nature but I am very disheartened today - and so I will ask this. I just had an interview with a major tech firm for an internship position, where I was asked a lot of typical algorithm oriented interview questions. Now, given my background, I consider myself to be strong in algorithms (I have also got good grades in graduate level algorithms -stuff involving NP- completeness and beyond (approximation and randomized algorithms), but unfortunately I flunked the interview. I could not think of a very efficient method of solving a string problem in approximately ~10 minutes. Once the interview was over, I had a glass of water, ate a banana and relaxed for a while and tried the problem again. And vola! there is the answer I could arrive in under 5 minutes. And the worst of it all - I was actually on that track and the interviewer did hint about it, but too much pressure cooked me. My entire experience got me thinking about tech interviews. I had some questions and I wanted to pose them in this forum -   1. Is it really possible to judge someone's technical ability in half an hour? Honestly? Or is it just a throw of dice?   2. Do technical interview questions measure problem solving ability? This point is very debatable? As a PhD student I know that Mathematical problem solving involves solving something that you have never heard about before. On the other hand questions like - merging two linked lists in sorted order, or printing all the elements of a binary tree in the kth level become "mere exercises" once someone has seen the solution or solved the problem beforehand?   3. Do people who come out with flying colors in these interview go on to become great programmers? Do they go on and design a sleek game engines, graphics libraries, write fast fork-join frameworks? Is there any evidence to point to a positive co-relation between doing well in technical interviews and actual programming ability? Or are these interviews more geared towards finding "getting things done" type of person (Spolsky)? I can bet that lots of academics publishing ground breaking ideas in - ICML, VLDB, Mobicom - will flunk these interviews. But I can assure you that they are some of the smartest people you will find on this planet. I am mainly in academia (grad student) - so I will greatly appreciate some perceptive from someone in the other side of the fence. Someone who actually conducts these interviews? [Ok everyone. Thanks for all the nice and thoughtful responses. Since I do not want to ask another question, I will ask you to answer this question for me. Suppose candidate X has a good public portfolio of works where he has contributed to some known open source project where - you can actually go and verify his patches, verify the bugs he has closed and take a look at the designs he has created. In that case, the question is how much weightage are you willing to give to his publicly available/verifiable work versus how well he does in answering some very contrived binary tree interview question in under 15 minutes?]


Simple questions about apache and cgi

I'm just learning about using cgi in html files. I've read a lot of stuff on the web, but most of it is all about the trees and not enough about the forest. I'm a top-down learner and I'm having trouble understanding what's going on with cgi, apache, and html. At the moment I'm using python as my cgi scripting language, but if you'd care to answer using perl, I can handle that. Here's a MWE for a failed test I ran. HTML: (file is getname.html)                              <form method="POST" action="./test.py">
Your First Name: <input type="text" name="firstname">
Click here to submit form: <input type="submit" value="Submit">       <input type="hidden" name="session" value="1f9a2">     </form>                  Python: (file is test.py)               #!/usr/bin/python     import sys, os, os.path, shutil, string, fileinput     import cgi, cgitb          print "Content-type: text/html\n"     form = cgi.FieldStorage()     f = open('./testOutput', 'w')     if form.has_key("firstname"):         f.write(form["firstname"])     else:         f.write("Failure")     f.close()      So, it _looks_ like what's happening is that the info the user enters into the form is put into a variable called 'firstname' (actually it's a key-value pair put into a hash-like thing in the scripting language. In python it's a dictionary). This variable is then sent as input to the cgi script (test.py), and the script is run. But, that isn't what's happening. When I hit the 'Submit' button in the html file, the test.py script is displayed in the browser and the script isn't run. BTW, the reason that I have the script write to a file is so I can see whether it gets run. When I run test.py from the command line, it works fine. The fact that test.py is displayed in my browser indicates, I think, that apache isn't running or is misconfigured or has permission problems. As far as I can see, none of those things is true, but I could be wrong. So here are my questions: 1) why is apache involved at all? Is it needed to send the variables gathered in the html form to the script? If so, why? I know that html is just a markup language, but I thought the 'form' tag had the ability to send a variable to a script and run the script. 2) Is there a way to test an apache configuration? Is it possible for apache to use 127.0.0.1 as the 'ServerName' (i.e. ServerName 127.0.0.1:80 in my httpd.conf file) Basically, I just want to write cgi scripts for some webpages I'm hand-coding and test them on my home laptop. I don't seem to know how to do that and I could use some help. TIA.


Can resizing images with css be good?

After reading Is CSS resizing of images still a bad idea?, I thought of a similar question. (too similar? should this be closed?) Lets say you need to use 10 different product image sizes throughout your website and you have 20k-30k different product images, should you use 10 different files for each image size? or maybe 5 different files and use css to resize the other 5? Would there ever be combination that would be good? Or should you always make separate image files? If you use css to resize them, you will save on storage (in GBs) but you will have slight increase in bandwidth and slower loading images(but if images are cached, and you show both sizes of the image would you use less bandwidth and have faster loads?) (But of course you wouldn't want to use css to resize images for mobile sites.)


In Functional Programming, should domain-relevant simple functions (e.g., sorts) be reified?

In a functional application, should you wrap common higher-level functions in domain-meaningful names or should you leave them "bare"? For instance, if you have a list of Addresses, and "sorted by zipcode" is a common domain-meaningful ordering (targeted mailers, etc.), is it preferable to write:               val sortedCustomers = customers.sort((a,b) => (a.zipCode compareTo b.zipCode) < 0)       Or is it better to create a function `sortedByZip(cs : Iterable[Customer]) : Seq[Customer]`? Creating the function has the advantage of being (minutely) more abstract, but has the disadvantage of being opaque, creating a name to remember, etc. I'm asking in the context of a significant professional codebase, one that you intend to live for years, be as maintainable as possible, be "true" to the expectations of functional programmers, etc.


Are developers more productive at night?

I personally stay awake late at night, coding and enjoying working on personal projects. My other colleagues also feel the same and like coding at night. However, it's not about being passionate about personal hobbies, rather, I really feel that I'm more productive at night. I think that there is something about night, maybe its darkness, maybe its silence, maybe another attribute that makes developers become more productive. Is there some truth to this? Why do some developers believe that they are more productive at night? Is there any scientific proof to justify this proposition? Maybe something like "in night, monitor light is less harmful" or "the natural air in night has more oxygen, thus is more suitable for thinking process", or anything like that. > ### Moderator Note: > > The question is asking for **scientific proof** and otherwise cited > information on this subject. Answers that do not provide supporting > references will be removed. This is _not_ a poll where you should share when > you wake up and what parts of the day you personally are productive.


When they say its open source it means i can take their pictures?

when they say that a project is open source (i.e. LifeRay) does it mean that I can take anything I want from that project? I want to use some of the icons used in LifeRay portal for my own (commercial) apps. Is this legal?


Is there a way to prevent others to steal your open source project and use it to make a profit?

This might seems like a silly question to ask, but I can't really figure out the answer. The title pretty much says it all. Let's say you have an open source music player, along comes someone, copies it, adds features, modifies the interface, etc and sells it. Nobody would find out. So how does it work? Related: I'm working in some projects myself to make me more employable, so employers can take a look at my code but with some of them I don't feel like uploading them to an online repository, ie sourceforge, and make them visible for the general public.


Why text editors are recommended over IDEs for beginners in books like Head First Java?

I am a programmer with some experience in C++ and I am learning Java. In most of the Java books (like Head First Java) authors ask readers to stay away from IDEs and recommend using a good text editor, but I could not find a convincing reason apart from the fact that a beginner might be overwhelmed by many options being thrown at once. However I started using Eclipse after writing a couple of small programs and I think that tools like auto-completion, inbuilt help debugging etc makes learning a better experience. I would like to know which approach is better and if I am missing out anything by using an IDE rather than a text editor.


Succinct Lazy Initialization Pattern

# Background I often use the following lazy initialization pattern:               public class Clazz {       private Object object;            private Object getObject() {         Object object = this.object;              if( object == null ) {           object = createObject();           setObject( object );         }              return object;       }            public Object setObject( Object object ) {         this.object = object;       }            protected Object createObject() { return new Object(); }     }      Member variables are only ever used directly twice (in the accessors), which includes internal calls. This also allows subclasses to inject new behaviour by overriding `createObject()`. # Problem This is a lot of code to ensure every member variable is always initialized. # Question What Java mechanism (syntactic sugar) can simplify the code? For example, Scala has the `lazy` keyword. # Ideas Ideally I would like to code:               public class Clazz {       @lazypolymorph       private Object object;            public Clazz() {         // Uses the object...         System.out.println( getObject().toString() );       }     }      The compiler would then expose a public mutator, a private value accessor, and a protected polymorphic creation method (used by the value accessor), following the typical Java naming conventions introduced in the background section.


Programmer Timeliness vs Effort

The engineering team I am on has a very laid back approach to work hours. People come in at 6am and at 11am, and work until things are done when necessary. Engineers will routinely work very late, on weekends, etc as pressing issues arise (and deadlines loom). Recently, the company has decided to implement a "core business hours" initiative, which is fundamentally incompatible with the Engineering Team's "get it done" approach. What would be a good way to expose the nature of the hard work the team does to the rest of the company, in such a way that: a) It does not come off as self congratulatory bragging b) It does not encourage the development of a no work-life balance culture


How to find number of points with same minimal distances on matrix

I'm trying to find the number of points in a matrix with the same minimal distances. Start with a MxN matrix, where M and N < 50000\. There is given a set of fixed points, with their respective coordinates.   The problem is to find the number of points in the matrix such as the minimal distance from any point in the set can be reached for at least two point in the set. The distance is measured by moving one units a time horizonatally or vertically. You can't move diagonally. An example would make things clearer.   Let's say we have 3 fixed point: (1,3), (3,1) and (3,6). Here the point (3,3) would be one point since the minimal distance is 2 units and it can be reached for the first two fixed points in the set. However, the point (4,4) doesn't satisfy the requirements. Although the distance from (1,3) and (3,1) is same, 4 units, the minimal distance is 3 units. My idea was to use any point with integer coordinates that lies on the bisector of a segment joining each par as a point that would fill our requirements. But I find a lot of false positives were a point satisfies the requirements, but doesn't lie on the perpendicular bisector. Brute-force methods won't work, because we need too check a billion of distance for each point and that one heck of a job to do. How should I go about solving this problem?


Finding a definition for this anti-pattern

Working on a large and multi-tiered software project, I just found a recurring anti-pattern to be occurring in the code. I coulnd't find its definition in Wikipedia or other sources after a quick search, so I would like to ask you if there is a known anti-pattern for our current situation. I'll explain it both in the general way and by providing you an example. In general, this anti-pattern could be called like the Italian expression "scaricabarile" (lit. _passing the buck_ , avoiding your responsibility and giving it to someone else under you). ![Funny image describing this](http://i.stack.imgur.com/Td3JI.png) If there are several people on a [sub]project, and they are organized in a chain of responsibility, someone on the upper levels could decide to deliberately avoid resolving a design problem and leave it resolution to the person next to him, who could repeat this and ultimately "leave the last developer in a mess of development complexity". The anti-pattern appears when it's discovered that if the person on top of the chain resolved the problem on his own, much less work and rework would have been done by people under him. Real world situation (in general): you are developing a middle-tier service which handles calls from front-end and has to perform several calls to different back-end services (a DB, a web service, a file storage, outsourced services...) which are not very well documented. When you get an input field you immediately can't handle on your own, instead of asking further information you simply put it in your front-middle-end interface and require the front-end guy to supply you with this parameter that will be passed unprocessed to the back-end. The front-end guy may have to perform several calls to services to get a single value that could be else obtained by the middle-tier with few calls/instructions. In my case (assuming that in the middle-back-tier interface all values are considered to be `string`, and please don't comment on that becuase there are reasons), I discovered that the back-end services require fields such as `order`, `flagDescription` which can be thought to be respectively an enumeration of `ascending`, `descending`, and a `boolean`. One of the problems is to encode the enumeration. What does the service accept as values? `ASC`/`DESC`? `A`/`D`? `0`/`1`? Only BE developers know. In fact, we **ultimately** discovered that the original ME developer was too lazy to ask for detailed information about the possible values of these fields. He instead put them in the front-middle-end interface as two `string`s, leaving the FE guys angrily questioning "where do we pick values these fields?". I'll describe another case with a fictional example: suppose an outsourced back-end service define an operation as `doSomethingOnAPerson(string socialSecurityNumber, string phoneNumber, Date birthdate)`, your `Persons` DB table identifies people by a unique ID and contains all of these information. At a certain time, FE knows only person ID and a bunch of information insufficient to make a complete call. However, the middle tier exposes the same signature as the back-end instead of a simpler `doSomethingOnAPerson(long personID)` which can be implemented as a DB call followed by a service call. Since ME is already deployed, this forces the FE guys to request a rework for a new service to retrieve the missing information to call the middle end services, or in other cases request that the service is re-developed to change the signature and perform the missed operation. In general words, _the original developer didn't take the time to resolve the [very simple/simplified] problem of obtaining the required information from the smallest information of data available, but decided to **pass the buck** to the FE_ In a few words, a better design and much more attention could have prevented **both** situations. In fact, the first also led to troubles when switching from a mocked environment to **integration testing**. I would like to explain the team that we did wrong by passing the buck between ourselves rather than solving problems. ## Do you find a popular definition for what I have descripted so far? Can you help me find _articles_ about this, if it has been documented yet?


Utterly Confused with OOP - How do I overcome a beginner's hurdle?

I have been reading and working through the exercises of Steve Lott's book _Building Skills in Python_. However, on the very **first** exercise dealing with OOP I have gotten completely stuck. **The problem set is here** : http://www.itmaybeahack.com/book/python-2.6/html/p03/p03c01_class.html#class- definition-exercises **My attempt** (sourcecode):               # Stock Valuation OOP     class StockBlock(object):         def __init__(self, purchdate =0, purchprice =0, shares=0):             self.date = purchdate             self.price = purchprice             self.shares = shares         def __str__(self):             return "Price: %2f \tDate: %s \tShares: %d" % (self.price, self.date,                                                        self.shares)         def getpurchvalue(self):             return self.price * self.shares         def getsalevalue(self, saleprice):             return saleprice * self.shares         def getroi(self, saleprice):             return (self.getsalevalue() - self.getpurchvalue()) / self.getpurchvalue()     blocksGM = [         StockBlock(purchdate = "25-Jan-2001", purchprice = 44.89, shares = 17),         StockBlock(purchdate = "25-Apr-2001", purchprice = 46.12, shares = 17),         StockBlock(purchdate = "25-Jul-2001", purchprice = 52.46, shares = 15),         StockBlock(purchdate = "25-Oct-2001", purchprice = 37.73, shares = 21),         ]     blocksEK = [         StockBlock(purchdate = "25-Jan-2001",purchprice = 35.86, shares = 22),         StockBlock(purchdate = "25-Apr-2001",purchprice = 37.66, shares = 21),         StockBlock(purchdate = "25-Jul-2001",purchprice = 38.57, shares = 20),         StockBlock(purchdate = "25-Oct-2001",purchprice = 27.61, shares = 28),         ]     class Position(object):         def __init__(self, name, symbol, *blocks):             """Accept collection of StockBlock instances."""             self.name = name             self.symbol = symbol             self.blocks = blocks         def __str__(self):             return "Symbol: %s \tTotal Shares: %d  \tTotal Price: %d " % (self.symbol,                                                                            self.blocks[1],                                                                            self.blocks[2])         def getpurhvalue(self):             value = 0             for stock in self.blocks:                 value += stock.getpurchvalue()             return value         def getsalevalue(self, saleprice):             value = 0             for stock in self.blocks:                 value += stock.getsalevalue(saleprice)             return value         def getroi(self, saleprice):             (self.getsalevalue() - self.getpurvalue()) / self.getpurchvalue()          portfolio = [         Position("General Motors", "GM", blocksGM),         Position("Eastman Kodak", "EK", blocksEK),         Position("Caterpillar", "CAT",                  [StockBlock(purchdate = "25-Oct-2001",                              purchprice = 42.84, shares = 18)])         ]     # display individual blocks purchased, and purchase value of the block     def main():         for position in portfolio:             StockBlock(position)          main()      There is no solution in the book, so I cannot check that way. It seems that I totally do not understand OOP? It's just so frustrating and I don't know what I should do to continue... My question is, when I get this utterly stuck learning programming, what strategies can help me overcome the problem? I think this is an important question because I am learning programming by myself. I cannot ask a teacher or friend for help (because I don't have any that are programmers.)


Correctly value a development?

I started a discussion on StackOverflow earlier this week about one of my work project and how to lead it correctly. But it seems that this stack is a more appropriate place to ask those sort of questions, so here is my last question about my project: **How do you value your work? / How do you rate it in a financial way?** I'm working on a quite cool project with two other friends and people that we know ask us for an earlier access and how many it would cost per month for us to access it. Unfortunately, I was not able to answer this simple question due to the fact that I'm not agree with my friends on this specific topic. For me a bill of 80$/month/contract seems to be reasonable and appropriate for our targeted market (Institutions and Corporations) but my partner would rather count a charge of 500$/month/contract. Our project is an asset manager in SAAS mode, and I don't really think that our potential clients would be ready to pay more than 90$/month/contract even if they have a lot of money due to their situation. So, I would really like to have some opinions and advices on this kind of question. PS: If my post is not on the appropriate stack, feel free to tell me. PS2: I'm quite sorry if I'm not totally crystal clear, I'm not a native english, if you do not understand something, as above, feel free to notice me and I'll rephrase.


Always keeping 2 people expert on any one chunk of code

I interviewed for a job at a company where they said their policy is to make sure that at least 2 people understand any piece of code, just in case one of them "goes on vacation". They also said that some people don't last more then a few months at this company, although many have stayed for years. I think I get the message: They are inclined to fire people right away who don't like the work culture or who don't integrate into their cliques. But is there another interpretation? Thanks.


What are the principles of open source projects?

Although its generally agreed by organisations like the OSI and the FSF what is and isn't an open source software (basically, the the terms of the source code license) what are the guiding principals for open source projects? Other software movements have principals like the Agile Manifesto. It seems as though open source share some common values (such as transparency, collaboration, etc.). Are these documented somewhere?


Which stages of the requirements analysis process in mobile requirements engineering are the most challenging ones?

I'm doing a research on formulating a requirements analysis model as a stage of requirements engineering for mobile-application development by considering the limitations and the needs of it ( agility and etc.. .), what I'm trying to figure out is that which parts of this process (requirements analysis for mobile development) are the most challenging ones ( so i can focus more on) , and if there is any stage that u think I need to include or exclude (exp. some may think a quality plan may or may not be necessary and etc.) to make it more clear below is the list of few of the areas in which I can focus on ( by the way your suggestions can be anything out of the below list.) -Requirements specification -Prototyping -Requirements Prioritization -Focusing on quality functions


Was API hooking done as needed for Stuxnet to work? I don't think so

Caveat: I am a political science student and I have tried my level best to understand the technicalities; if I still sound naive please overlook that. In the Symantec report on Stuxnet, the authors say that once the worm infects the 32-bit Windows computer which has a WINCC setup on it, Stuxnet does many things and that it specifically hooks the function `CreateFileA()`. This function is the route which the worm uses to actually infect the .s7p project files that are used to program the PLCs. ie when the PLC programmer opens a file with .s7p the control transfers to the hooked function `CreateFileA_hook()` instead of `CreateFileA()`. Once Stuxnet gains the control it covertly inserts code blocks into the PLC without the programmers knowledge and hides it from his view. However, it should be noted that there is also one more function called `CreateFileW()` which does the same task as `CreateFileA()` but both work on different character sets. `CreateFileA` works with ASCII character set and `CreateFileW` works with wide characters or Unicode character set. Farsi (the language of the Iranians) is a language that needs unicode character set and not ASCII Characters. _I'm assuming that the developers of any famous commercial software (for ex. WinCC) that will be sold in many countries will take 'Localization' and/or 'Internationalization' into consideration while it is being developed in order to make the product fail-safe_ ie. the software developers would use `UNICODE` while compiling their code and not just 'ASCII'. Thus, I think that `CreateFileW()` would have been invoked on a WINCC system in Iran instead of `CreateFileA()`. Do you agree? My question is: If Stuxnet has hooked only the function `CreateFileA()` then based on the above assumption there is a significant chance that it did not work at all? I think my doubt will get clarified if: my assumption is proved wrong, or the Symantec report is proved incorrect. Please help me clarify this doubt. Edit: For more clarity of my question and what I'm looking for. Is it possible that the WinCC STL Editor be programmed in the following way?               //Pseudocode Begins     if (locale == ASCII Dependent) //like US, UK, Australia etc.     {          CreateFileA(); //with appropriate parameters     }     else if (locale == UNICODE Dependent) //like Middle East, China, Japan etc     {          CreateFileW(); //with appropriate parameters     } //Pseudocode ends      If it is possible then does it follows that Stuxnet would work appropriately in the US but not in China or Japan or Iran?


How do programs like JAVA and C++ store variables in a database , does it still use MySQL like in PHP?

I imagine they have to have some sort of query to goes to a database , or maybe I'm wrong and they can just store it to their computer? Is MySQL for server - side scripting only?


When do you 'speak' C++ fluently?

I see that many companies require the same skill. This skill is often described as following: > _"Applicants are required to speak C++ fluently."_ I never really understand what _fluent_ meant for programming. So, my question is: When do you speak a programming language fluently?


What has been learned about making variance part of the type?

In Java, the variance of parameterized types is indicated depending on how it's used:               <A extends B,B> void store(ArrayList<B> list, A elem) {         list.add(elem);     }      Whereas in Scala it is indicated in the class declaration with a `+` or `-`. What I want to know is, now that Scala has been around awhile, what has been people's experience with making variance a property of the type? Is it generally flexible enough for what you want to do? Are there aspects you would have done differently, knowing what you know now?


When developing a piece of software, when do you start thinking/designing the concurrent sections?

Following along with the principle of not optimizing too early, I'm wondering at what point in the design / development of a piece of software do you start thinking about the concurrency opportunities? I can well imagine that one strategy would be to write a single threaded application, and through profiling identify sections that are candidates to run in parallel. Another strategy I've seen a little of is to consider the software by groups of tasks and to make the independent tasks parallel. Part of the reason for asking is that of course, if you wait until the end and only refactor the software to operate concurrently, you may structure things in the worst possible way and have a major task on your hand. What experiences have helped to determine when you consider parallelization in your design?


What are some common algorithm optimization opportunities - mathematical or otherwise

What are some common algorithmic optimization opportunities that everyone should be aware of? I have recently be revising/reviewing some code from an application, and noticed that it appeared to be running considerably slower than it could. The following loop turned out to be the culprit,               ...         float s1 = 0.0;         for (int j = 0; j < size; ++j) {             float diff = a[j] - b[j];              s1 += (diff*diff * c[j]) + log(1.0/c[j]);         }     ... This is equivalent to, ∑j { (aj-bj)2*cj \+ log(1/cj) } Each time the program is run, this loop is called perhaps over 100k times, thus the repeated calls to log and divide result in a very large performance hit. A quick look at the sigma representation makes it pretty clear that there is a trivial fix - assuming you remember your logarithm identities well enough to spot it, ∑j { (aj-bj)2*cj \+ log(1/cj) } = ∑j { (aj-bj)2*cj } + ∑j { log(1.0/cj) } = ∑j { (aj-bj)2*cj } + log(1.0/(Πjcj)) and leads to a much more efficient snippet,               ...         float s1 = 0.0;         float s2 = 1.0;         for (int j = 0; j < size; ++j) {             float diff = a[j] - b[j];              s2 *= c[j];             s1 += (diff*diff * c[j]);         }         s1 += log(1.0/s2);     ... this lead to a very large speed-up, and should have made its way into the original implementation. I assume it did not because the original developer(s) either weren't aware, or weren't 'actively aware' of this simple improvement. This made me wonder, what other, similar, common opportunities and _I_ missing out on or overlooking, and how can I learn to better spot them? I'm not so much interested in complex edge cases for particular algorithms, but rather examples like the one above that involve what you might think of as 'obvious' concepts that crop up frequently, but that others may not.


Function like C# properties?

I've been thinking about how C# properties work and could work. I know the purpose that C# properties were originally designed for, which is certainly useful. However instead in this question I'm comparing them more abstractly to functions and other programic elements. Firstly, I wondered, if it were possible, and if so why not, to have a function like C# property. For example:               byte n = 4;          byte test // property     {         get         {             return n;         }         set         {             n = value;         }         func         {             n++;         }     }      To use as follows:               // n is 4     byte n2 = test; // get     test = 2; // set     // n is now 2     test; // function     // n is now 3      The 'n++' in this example being used only as a simple demonstration. I also noticed that there is room for more polymorphism than just in function parameter types. For example having overload resolution by return type, get/set and private/public as well.               public test     {         get         {         }         get byte         {         }         private get byte         {         }         get bool         {         }         get myType         {         }         set byte         {         }         set myType         {         }         func         {         }         func(bool)         {         }         func(byte, myType)         {         }         // etc...     }      The above example defines "test" along with reasonably fine detail involving different implementations for using test in various different ways. More examples: Read only:               byte test     {         get         {         }     }      Function like:               test     {         func         {         }     }      Function like with parameter polymorphism, returns a byte:               byte test     {         func(bool)         {         }         func(myType, Int16)         {         }     }      Behaves differntly depending on the type assigned to it:               test     {         set bool         {         }         set myType         {         }     }      Function like and could return a value or not, depending on the context it is used:               test     {         byte get         {         }         func(bool)         {         }         func(byte, byte, myType)         {         }     }      The additional possibility for expression and code tidiness should be apparent. However I have been challenged to find specific uses. One example of how this could be used is equality. Where a bool is expected, for example in an 'if' statement, the behaviour could be defined as being '==', however where there was either nothing to return to, or the return to was other than bool, the behaviour would instead be '='.               if (n.equals(4)) // if n == 4         n.equals(2); // n = 2      Another example is as follows:               class my_list<T>     {         List<T> store;         public count         {             get             {                 // unless otherwise apparent,                 // use the Int32 version.                 return (Int32)count;             }                  get byte             {                 byte n = 0;                 ForEach(var e in store)                     n++;                 return n;             }                  get Int32             {                 Int32 n = 0;                 ForEach(var e in store)                     n++;                 return n;             }                  private get             {                 // An implmentation of "count get" that only                 // occurs when count is used from inside the                 // my_list class.             }                  func             {                 print store.Count();             }                  set int             {                 if (value == 0)                     list.Clear();             }         }     }


At what point should developers become involved in a triangular relationship among the client, the design agency, and the developers themselves?

Imagine that there is a project to be completed. This project involves three parties: client, a development organisation (a one that you work for), and a design agency. The design agency is a subcontractor of the client. The role of the design agency are largely responsible for doing styling; however in the past these designers have produced substandard work such as extensive use of id targetting in css instead of class targetting, etc. At what point should developers become involved in a triangular relationship among client, design agency, and themselves? What meetings or communication would you expect to take place at this point?


Is there any legislation requiring how we store passwords?

Given the Sony data breach and other events recently, is there any actual laws or regulation regarding how to store passwords? I think there are with credit cards, you're not allowed to store the 3 digit key or something. Is it illegal to actually store plaintext passwords without warning the user? Or it there a level of encryption that has to be used? Are there any standard guidelines that anyone can point me to?


Number of semi-random combinations / permutations given a set of constraints

### Background: There are around 60 students at the boarding school I work for. The counselor asked my colleague and me to come up with a better way to come up with seating arrangements for dinner than by hand. He would like assignments for the rest of the school year. He also asked us to try to solve some of the issues he has hearing about from students and faculty. ### Constraints:   * Most of the students are not from the US, so when they are surrounded by people of the same nationality (i.e., at the dinner table), they speak the language they are fluent in, instead of practicing English,   * Complaints are made when students have sat at a certain table "too many" times overall,   * or if they sit at the same table more than twice in a row,   * and some of the students do not get along, so they cannot sit together. ### Input: At run time, the program is supplied with:   * A set of people,   * A set of tables, and   * Each table has a different number of seats (repetition is allowed) The size of both sets, and the size of each table does not change between each assignment. ### Tests: I am using 18 people of different nationalities, and 4 tables of size 3 through 6, inclusive. I picked numbers that I thought made sense for that data set:   * No more than 3 people of the same nationality can sit together at a time   * No person can sit at a table more than 4 times ### Results: I have run the generator around 15 times without changing the input data. Each time, it comes with anywhere from 6 to 12 "weeks" of assignments. ### Questions: (least to most important)   1. Why do I get a different number of generated assignments every time I run the program? The data set isn't changing between runs.   2. How do I find the...      * minimum number of people of the same nationality that can sit at a given table,     * minimum number of overall times they sit at a given table, all while     * maximizing the number of generated assignments?   3. How do I guarantee that these actually are the correct numbers? ### Edit: Each time I generate a new assignment, I call `Collections.shuffle(List)` on the list of people to randomize their order. I then pass the list of tables and people to a backtracking method based off of kapilid's eight queens implementation on github to assign people to tables.


How do open-source projects grow?

I know of lots of software that is open-source. For at least some of it, someone, somewhere must have written the first version alone. How does good open-source software become well known? I'm most interested in the first steps. How does software written by one person gain its first new contributors? I'm looking for practical advise. I've started a project here, called aodbm. What steps can I take to give it the best possible start?


Component Diagram, what's next?

I'm working on an iPhone application and I created a component diagram. I defined interfaces for each component. For example I have an AI component and I have made some interfaces for it. How should I carry on? Should I create a class diagram to go into details, should I go into details of each interface or should I just start implementing my interfaces? I am a bit confused on how to proceed.


How do I create a .NET WebService for File Upload

I need to create a web service using the .NET platform for accepting file uploads. What are the options available for doing this in C#? What is the best approach to use? Can please you provide me with blogs/code samples/references for further reading?


Do you do any validation on directories when recursively deleting them?

How do you recursively delete paths of the data that your app created? The deleting process itself is trivial. The question is, do you do extra validation? And if so, what kind? From one point of view, maybe it's simply an uncomfortable task to do, but on the other, imagine if the program has a bug and something passes "c:\" to the recursive function, or if there is a memory overflow and some data becomes corrupt, causing paths you work on to be truncated etc. Is there even a way to do a clean validation?


In pseudo code what does := mean?

The section entitled Algorithmic Implementation has the following code:               // Return RC low-pass filter output samples, given input samples,      // time interval dt, and time constant RC      function lowpass(real[0..n] x, real dt, real RC)        var real[0..n] y        var real α := dt / (RC + dt)        y[0] := x[0]        for i from 1 to n            y[i] := α * x[i] + (1-α) * y[i-1]        return y      what does := mean?


Why are references rarely used in PHP?

I have some C++ knowledge and know that pointers are commonly used there, but I've started to look at PHP open source code and I never see code using references in methods. Instead, the code always uses a return value instead of passing the reference to the variable to the method, which then changes that variable's value and just returns it. I have read that using references uses less memory, so why aren't they used in PHP?


Object oriented versus function oriented for backend design in PHP?

I am curious as I am currently using functions exclusively in my webpages. The MVC pattern is very interesting, and I know Code Igniter utilizes classes which works very well. I want to be able to keep my code as clean as possible, and I thought about trying to move my functions into classes. Currently I am separating the files by logic, so I have functions that output the html with arguments that pass any dynamic content, and the functions which handle the user input. I also have functions that interact with the database. I require and include the necessary files between them. As one can tell, there are a lot of arguments being passed around. So that leads me to wanting to try a style of OOP in PHP that I can do the same without having any html inside of the actual class. I really don't want to hear anything about frameworks as the point is to learn and incorporate these ideas into my own website. That being said, I am fairly new at web development, so I do not understand the many different styles in setting up the logic of websites. I would like to get some insight on how to best clean up my code in OOP? EDIT: It is fairly obvious people have strong feelings about frameworks. So I decided to make this very clear; MY WEBSITE IS A PROJECT FOR LEARNING. I WISH ONLY TO LEARN FROM IT. THEREFORE I do not wish to use a framework as it makes more sense for me to learn how it all works before making my life easier and actually use a framework. A FRAMEWORK FOR MORE ROBUSTS PROJECTS. Thank you.


Reducing Valgrind Findings (uninitialised value)?

I'm trying to run some code though Valgrind. The code depends on OpenSSL, and OpenSSL is making Valgrind useless due to uninitialised values. I know where the use lies in OpenSSL's PRNG, but I'm getting hundreds more at the moment. I'd like to try an run a tool over the OpenSSL sources that initializes values. So:               int* p;     int n;      is changed to:               int* p = NULL;     int n = 0;      **Question** : Is anyone aware of a tool to perform bulk initialization on declarations of primitives? I'm more than happy to perform an un-needed initialization and have the optimizer remove it later. That's the optimizers job. For completeness, "speed" has never been a top concern for me. I'm more interested in "correctness" and assuring it. To me, it does not matter how fast someone arrives at the answer if its wrong.


How can resolve an URL on a specific DNS server

I'm currently facing a issue on a project. I'm resolving URL's on multiple DNS servers using a node.js server. Until here, everything is fine. But some ISP restrict the incoming requests from IPs outside their IP range. So how could I modify my request to those specific DNS servers to make it look like I'm one of their clients? If I understand DNS request correctly, there are no such things as x-forwarded-for header as an HTTP request would have. So can it be achieve ? Or am I facing a real blocker ? (I hope I am on the correct stackexchange for this question)


Am I potentially hurting my career by taking a dev test position?

Background: If you haven't read much of what I've written here, then:   * I'm a sole developer   * I've developed professionally for ~3 years, personally for 13   * I love my work   * Top-to-bottom, I find the whole process of developing software interesting, fun and exciting (with the slight exception of marketing)    * I hate the environment I'm in now and had to leave Now: I've applied for a position as a Software Development Engineer in Test which potentially pays significantly more than I'm making now (~70%), is located somewhere I'd really like to be and looks like a company I'd really like to work for (interesting product, good tools, smart people - I was referred by an existing employee). So obviously, I'm really hoping that I get the position. I don't want to get pigeonholed as a test developer, however, because they can sometimes have a bad reputation as not being good 'production' developers (not sure why... and this could be wrong, but that's the vibe I've gotten). I'd prefer my career path to end up at a senior dev/lead dev position in 5-10 years. If I'm offered** the position, is there a possibility of hurting this desired path? ** I'm getting ahead of myself. I know. I haven't even had the interview yet. I'm anxious. Still, I interview well and I think that I have the knowledge/experience for the position.


What would the role of a "Software Engineer in Test" be?

> **Possible Duplicate:**   >  Microsoft SDET position   >  How difficult is it to transition from a software test engineer to a > software development engineer? I interviewed for a Software Engineering role, but unfortuantely wasnt offered the position. The company said there were impressed with me and Inwas close behind the other cadidate and that they wanted me to go in and talk to about another role, Software Engineer in Test. So my question is as per the title really, What is the role of a Software Engineer in Test? What do you envisage the type of work would be involved in a role like this? Would taking a role like this limit me to moving into regular software engineering?


Does any software come with a warranty?

> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, [blah blah > blah]. It's everywhere. **Is there any software which expressly comes with warranties** which can be taken seriously? That is:   * Provided by a group/company which has the **resources** to handle warranty claims, not uncle Bob.   * Assures something " **useful** ," such as ACID or ISO-whatever compliance, not protection from meteor impacts.


How to improve the training of students regarding maintainability?

Maintainability is a major stake of professional software development. Indeed, maintenance is nearly always the longest part of a software life cycle, as it lasts from the project release until basically the end of times. Moreover, projects being in maintenance represent a large majority of the overall number of projects. According to http://www.vlegaci.com/298/interesting-statistics-%E2%80%93-numbers-of- programmers-in-maintenance-vs-development/, the proportion of projects being in maintenance is about 2/3. I recently came across this question, where the guy looks pretty surprised discovering that his job is mainly about maintenance. I then decided to open a discussion (french) on the main site of the French community of software development professionals (http://www.developpez.com/). The discussion is entitled "Are students well-enough trained to the reality of professional software development?" and is mainly about **maintainability**. It was pointed out that, at least in France, people are not well-enough prepared to face maintenance in both aspects of it:   * maintain existing code   * make maintainable code My question here echoes to this discussion and aims at finding a good way to teach maintainability.   * How can we teach maintainability?   * What kind of exercise would you suggest?   * If you have been well-trained regarding maintainability, what particular kind of courses did you take? [edit] After some misunderstanding, I think I must clarify my question. As a project leader and software developer, I often work with trainees or freshly graduated students. I once was freshly graduated myself. The thing is that students are usually unfamiliar with principles such as SOLID that increase the maintainability of a project. We often end up having important difficulties making projects evolve (low maintainability). What I am looking for here is a concrete academical example of successful teaching about the importance of maintainability and how to make better code regarding this particular point; or possible suggestions to improve the way students are trained.


OOP technology death

I've heard many times about the aspect-oriented programming, mostly that it is the "next generation" technology in programming and is going to 'kill' OOP. Is it right? Is OOP going to die or what can be reason for that?


Is code duplication a necessary evil in C?

I'm rather new to C, and I'm wondering if code duplication is a necessary evil when it comes to writing common data structures and C in general? I could try to write a generic implementation for a `hash map` for example, but I'm always finding the end result to be messy. I could also write a specialized implementation just for this specific use case, keep the code clear and easy to read and debug. The latter would of course lead to some code duplication. Are generic implementations a norm, or do you write different implementations for each use case?


How to Release to the App Store as an Individual

I've written an iOS app, and I'd like to release it on to the App Store. I'm an individual so it's not being released via a company or anything, just me. Is it typical to just release a free app under your own name? If so, what would be appropriate copyright information to submit?


How can I obtain feedback from external developers?

One of our external devs is leaving after successfully completing a **short (1 month) project** which he was contracted for. I'd like to get some feedback from him by doing an exit interview to find out what could be better in our organization and development process. What sort of questions can I ask to get detailed feedback from him, and not just vague responses?


I want to master ASP.NET - What concepts should I focus on/What concepts do you most value?

I start a job this summer doing work in ASP.NET 4 (C#). I plan on working with some legacy code as well as MVC. I want to get a running start. I have good understanding of HTML/CSS/Javascript, and pretty good understanding of C# itself, Design principles, Design Patterns, and understand masterpages, basic MVC2, and code behinds for web forms.   * In your opinion what aspects of ASP.NET are the most important to master for web applications?    * What do you value most in your usage of ASP.NET?    * Do you have a recommendation for understanding the internals of ASP.NET itself?


Converting from web to PhoneGap

I was going through the `PhonGap Documentation` about how to package your `HTML/JS/CSS` to a platform specific `"native app"`. They have maintained separate documentations for the separate `Cordova` versions which seems fine. I essentially understand most of the things there. But the confusion I have is the disparity or the loss of information in the documentation from the older ones to the newer ones. For an instance, if you take a look at this documentation for the version `2.1.0` about setting up the android project and scroll a bit down, they have mentioned such things:   * In the root directory of your project, create two new directories:       * /libs     * assets/www   * Copy cordova-2.0.0.js from your Cordova download earlier to assets/www   * Copy cordova-2.0.0.jar from your Cordova download earlier to /libs   * Copy xml folder from your Cordova download earlier to /res ....   * Change the class's extend from Activity to DroidGap   * Replace the setContentView() line with super.loadUrl("file:///android_asset/www/index.html"); ... and so on which clearly mentions the steps to follow while migrating or creating an app for a specific platform. But upwards from the `version 2.1.0`, these information are missing. Like in the newer documentations, all they have is just the `regular android setup stuffs and android hello world` which we can obviously find on the official android documentation. I tried searching the whole documentation for that version and I could not find any information regarding the steps I mentioned above in the older documentation. Otherwise how are the readers supposed to know those steps? Am I missing something here or have they provided?


Cache While Developing or Finish Development then Cache?

I'm new to cache and haven't used it on my projects. I would like to know about what is best practice in caching. Should caching be done while developing or finish development then cache everything?


Is 'process debt' a term people work with

As a result of a retrospective we were uncovering worse ways of developing software. We had a idea we though was great and tried it. We stayed with it during the development of a major update which took 3 months. After a retrospective with the maintenance engineers it turn out our idea does not work for them (we had discussions with them before we tried the idea and the also thought it was a great idea). We came to the agreement we better get back to the old situation. The team for the update is dismantled and the maintenance engineers don't have time to do so (although their project manager has agreed to invest the time). We're now in the situation the maintenance engineers pay the interest each time a minor release has to be made. This is very much like technical debt but has nothing to do with the product itself. Is this called process debt or is this put under the term technical debt? And what would be a good way of dealing with it? (Any other or concrete ideas to make it visible to product managers?) PS The idea was migrating a 4 product VSS database to SVN. The database heavily leans on shared files and is a mess to untangle and pour in a usable SVN structure. It's very counter intuitive but is seems some things are better kept in VSS.


What are some good resources for debugging/disassembling proprietary software?

From time to time, I experience different bugs with proprietary software that I need to interact with. In order to get through these bugs, I need to develop various workarounds. Is there a good book for debugging/disassembling proprietary software to write better workarounds?


Quantify value for management

We have two different legacy systems (window services in this case) that do exactly the same thing. Both of these systems have small differences for the different applications they serve. Both of these system's core functionality lies within a shared library. Most of the time, the updates occur in the shared library and we simply deploy the updated library to both of these systems. The systems themselves rarely change. Since both of these systems do essentially the same thing, our development team would like to consolidate these two systems into a single service. What can I do to convince management to allocate time for such a task? Some of the points I've noted are:   * Easier maintenance   * Decrease testing/QA time Unfortunately, this isn't enough. They would like us to provide them with hard numbers on the amount of hours this will save in the future and how this will speed up future development. Since most of the work is done in the shared library and the systems themselves never change, it's hard for us to quantify how many hours this will save. What kind of arguments can I make to justify the extra work to consolidate these systems?


Continuous Integration using Docker

One of the main advantages of Docker is the isolated environment it brings, and I want to leverage that advantage in my continuous integration workflow. A "normal" CI workflow goes something like this:   * Poll repository for changes   * Pull from repository   * Install dependencies   * Run tests In a Dockerized workflow, it would be something like this:   * Poll repository for changes   * Pull from repository   * Build docker image   * Run docker image as container   * Run tests   * Kill docker container My problem is with the "run tests" step: since Docker is an isolated environment, intuitively I would like to treat it as one; this means the preferred method of communication are sockets. However, this only works well in certain situations (a webapp, for example). When testing different kind of services (for example, a background service that only communicated with a database), a different approach would be required. What is the best way to approach this problem? Is it a problem with my application's design, and should I design it in a more TDD, service-oriented way that always listens on some socket? Or should I just give up on isolation, and do something like this:   * Poll repository for changes   * Pull from repository   * Build docker image   * Run docker image as container   * Open SSH session into container   * Run tests   * Kill docker container SSH'ing into the container seems like an ugly solution to me, since it requires deep knowledge of the contents of the container, and thus break the isolation. I would love to hear SO's different approaches to this problem.


How do you validate critical input that cannot be vetted?

How does one prevent users from creating erroneous input sets, when there is no practical way to vet the input? ### The scene I modify a small ERP package written in Visual FoxPro. One part of the package concerns itself with printing truck manifests and invoices to be sent with the drivers on their delivery routes. The print routine, when fed nothing as an input, will attempt to print everything, resulting in reams and reams of printer paper being wasted on a high-speed printer. I am not in a position to re-write any of the GUI interface elements, nor can I adapt any frameworks, tool kits, or other outside code to be used in this situation. The reasons are related to office politics, please do not suggest that I can override the existing ERP framework, as it is not an option for me. ### The issue The users are in a high-pressure, time-critical environment. Each process is measured in minutes or even seconds, which means that I have to minimize processing time as much as possible. Because of this environment, and possible distractions, users _frequently_ ignore the dialogs, pressing the [Enter] key which causes the focus to rapidly move through the form and eventually landing on the action button for the input dialog, resulting in them triggering an automatic printout. The input consists of a date range, route range, and sales order range. The input for date range cannot be auto-set to "today's date", as frequent back-printing is required. Also, the end-users work during midnight, i.e. date rollover makes this impractical without rigging a routine that auto-detects the change, etc. The input for routes cannot be hard-coded, nor can it be deduced from routes that have already been shipped, because re-prints are required (see above). The input for sales orders only has meaning when printing single orders or specific ranges. So, frankly, _there is no practical way to validate input_. The action button that triggers printing cannot be blocked. Any suggestions that a blocking dialog be placed in front of the user will be ignored. I am not at liberty to discuss why this is not an option, other than the concept has been already discussed elsewhere on the site (from a different vantage point) and was rejected. Blocking printouts when all inputs are empty was rejected as a design decision as the software _must_ accommodate this as a feature. ### The users The users have been repeatedly asked not to do this. They frequently ignore this advice. Triggering this unfortunate event is not something that their foremen/managers will address, so there is no pressure to end the behavior. ### The organization I do not have a say in the workflow involved, only the modification of existing software components affected by that workflow. ### The vendor The vendor second-sources the package as a custom installation from the original software vendor. The vendor requires that all code changes be sent back to them for integration into their codebase. Significant changes to architecture will result in increased future costs during version migrations due to the extensive customization involved; in some cases, the programmers have even told me that they will completely ignore such large changes and will do as they please. ### The software I have no say in the selection or installation of the software, so changing the platform is out of the question. Regarding the environment of the software, each invoice printed is a single call. There isn't a batch printing facility, and because of how the print facility is integrated into the system (and some language quirks as well) it isn't feasible to make a batch wrapper around that API. Topping this off, this part of the program calls another program that does the invoice print, which in turn calls the print-a-report API, which prints a single invoice. Horrid design, I know. Input forms are a weird combination of a form header that is devoid of input boxes, but can contain other GUI elements. Input boxes are defined at runtime. ### The objective The software will prevent the users from erroneously printing all paperwork. How would you solve this issue?


Is going to grad school going to hurt your engineering career?

I study software engineering and have every intention to become one and stay one. However, I also love logic, computability theory, automata theory, and similar computer sciency math topics, and would love to do at least a Masters degree _at some point_ after I graduate to study these topics more in depth. This is really something I want to do for myself, and not because it will contribute something to my career as a software engineer (and let's face it- it won't either), but I'm worried that a few years of absence from the field will be frowned upon, and will make it harder for me to get back on the horse, so to speak. Is that true? How _do_ employers react to such absence?


interview for an internship but I think I may be unprepared

I have an interview for a C++ internship position. Now, the thing is I've taken two out of three quarters of the basic CS classes (in C++) at my community college and we covered the basics up to arrays, pointers, linked lists, recursion, etc (basically all of Walter Savitch's Absolute C++ book). I spoke to the interviewer on the phone and he said the interview will include technical questions on trees, hashes, probably some sorting algorithms, and other stuff like that. I have less than a week to prep for the interview. What can I do to familiarize myself with the absolute, bare, essentials of the aforementioned interview question topics? Or, is it just a waste of time for me until I take the next class that covers all of those things?


Design strategies for storing and validating serial numbers

We are writing software to track Foo Widgets. Each Foo Widget has a serial number. The serial number is an 32-character alphanumeric string. The string is separated into five sets. Each set is separated by a dash (so the s/n is 32-characters NOT including dashes). So for example: 11111111-1111-1111-1111-111111111111. But this may change, since our software isn't actually creating the serial numbers. I'd like to learn about different strategies for storing the serial number and doing user validation of the serial number in the UI. To start with, I'd like get talk about strategies for storing the the serial number in our system. This issue came up at Foo Widgets Incorporated, and there was a disagreement about whether we should store each serial numbers with or without the dashes. I think the most flexible way of doing this (but maybe not most simple) would be to store the serial number without the dashes, store the schema of the serial number (as a regular expression), and then create an identifier that is used to track which schema is used (so later if the manufacturer changes it we can support that and perhaps both schemas at the same time). The counter argument to this was that the dashes "are a part of the data" and that it's "not like a phone number". I'm having some trouble understanding this point of view.


How to store record statuses (like pending, complete, draft, cancelled...)

Quite a lot of applications require records in their tables to have a status, such as 'complete', 'draft', 'cancelled'. What's the best way of storing these statuses? To illustrate what i'm getting at here is a *very short) example. I have a simple Blog application and each post has a status one of: published, draft or pending. The way i see it there are 2 ways to model this in the database.   1. The Post table has a text field that includes the status text.   2. The Post table has a status field that contains the ID of a record in the PostStatus table The Blog example here is a very simple example. Where an enum (if supported) might suffice. However i'd like responses to the question to take into account that the list of statuses could change at any time, so more could be added or removed. Can anyone explain the advantages/disadvantages of each? Cheers! My initial optnion on this is that its better to use another table and look up the status as its better for normalisation and i've always been taught that normalisation is good for databases


Separation of Concerns when adding new types

I have a system I've been working on this week where I'm having a hard time balancing separation of concerns with easy extensibility. I'm adding new types to the system, and it feels like shotgun surgery. The basic idea is that data is collected (polled) from a remote system and then made available to a number of different kinds of clients. To support their interface type (protocol), I'm doing a lot of translation. I'm going to try to simplify this so I can fit it in a question box. There's a FruitService out in the world with an SNMP interface. My publisher's job is to collect that data and then publish it.   1. So for each kind of new Fruit we decide to publish, I create a class that knows how to pull the attributes for that fruit via SNMP.   2. Internally Fruit is translated to DTOs (the same objects used to talk to client #1 (RMI)).   3. A cache is updated and checked for changes to trigger async notifications.   4. A class to translate the fruit into the xml schema used by another client (#2).   5. A class to translate the fruit into simple attribute/value pairs used by another client (#3). In the end I create 5 classes and edit 8 more to plug in a new type. It's not a lot of work; couple hours to write code, test, and check-in for a simple type. Note that there isn't a lot of commonality in the fruit types (e.g.: pear and coconut), so most of the common abstractions are based around the process of updating the data and not the data itself. My design concerns are:   1. The SNMP interface changes 2-3 times a year   2. The xml schema (client 2) changes 10 times a year.   3. Adding new types happens less frequently, generally when someone gets around to it. But maybe if it was easier... So the notional goal with the design was to handle those external changes easily. This lead to all the separation in the translation layers. But adding types feels harder than I'd like. Is there a technique or example I might look into? An idea I'm missing? Am I applying SRP wrong and there should be an Apple type that speaks SNNP, xml schema, DTO, etc? ![alt text](http://imgur.com/IaAEU.png) EDIT: Client #1, the RMI client, is custom written when a new fruit is added, to take advantage of all the fruit's capabilities. So if we decide to pull banana information from the FruitService we will also write a client that allows you to peel the banana, get a notification when it's ripe, and tell you which bunch it belongs to - along with the basic fruit attributes like size, weight, color, time till rotten, etc.


What are the disadvantages of a "simple factory"?

I am reading the book »Head First Design Patterns« from O'Reilly. Before explaining the Factory Method Pattern, they introduce a Simple Factory first. They are using the example of a pizzeria. In a first step they show the problem:               Pizza orderPizza(string type) {       Pizza pizza;       if (type.equals("Pepperoni") { pizza = new PepperoniPizza(); }       else if (type.equals("Salmon") { pizza = new SalmonPizza(); }       // ... and so on            pizza.Prepare();       pizza.Bake();       pizza.Cut();       pizza.Pack();       return pizza;     }      The obvious problem is that you had to change Pizzeria whenever you add or remove a Pizza.   Hence they introduce a "Simple Factory Idiom" first. They move the creating part into a class "SimplePizzaFactory". Now you don't need to modify Pizzeria anymore when adding or removing a Pizza. Then they say that this approach isn't that good, when you have more than one pizzeria (in several towns).   I don't really understand their reasoning. They give the following example code and then they say that each pizzeria wouldn't be using the procedure as implemented above but were using different methods in order to "bake", "cut" and "pack" the pizza.               BerlinPizzaFactory berlinFactory = new BerlinPizzaFactory();     Pizzeria berlinPizzeria = new Pizzeria(berlinFactory);     berlinPizza.Order("Pepperoni");      Instead of using the Simple Factory, they suggest using the Factory Method Pattern. First, I don't see why the BerlinPizzeria is supposed to not using the procedure. It's still a Pizzeria and when you call Order, you're using the same procedure. My best guess is that they are implying that you are able to implement, let's say, a cafeteria (I'm deliberately using something entirely different to make my point) and use the factory (as it is independent of the pizzeria) and prepare the pizza in a way you want to. But even when using the Factory Method Pattern, nobody forces you to use the default procedure. It's even simpler to "hide" that you're doing it differently. Their code examples are given in Java and Java methods are virtual by default. So I would be able to implement BerlinPizzeria and override Order (or had to explicitly declare the method as final). The client, however, wouldn't notice that my BerlinPizzeria is doing things differently. In conclusion I don't see any significant difference between a Simple Factory and the Factory Method Pattern. The only advantage of the Factory Method Pattern I'm seeing is that you would save a few classes (namely, the 'outsourced' factories). So, what is really the disadvantages of a Simple Factory and why isn't is a good idea to 'outsource' the creating part?   Or what is really the advantage of the Factory Method pattern and why is it a good idea to force the creating part being implemented in the subclass?


Open .doc file from my website in browser

What's the best way to give the end-user of my web application the ability to open, edit and save (via browser) word documents that are stored in my database? I have this working by doing an html conversion of the file (via Aspose Words) but this method seems not even close to flawless and i'm trying to improve this. Is integrating with google docs possible/good? Their edition seems awesome and very powerful. I can't use any Microsoft Word objects (and this is even discouraged by MS). EDIT: The application is developed in .NET and currently uses the .NET framework 2.0. However, as this is fairly obsolete the idea is to restart from scratch and therefore use the 4.0 framework and C# or VB.


Wolfram is out, any alternatives? Or how to go custom?

We were originally planning on using wolfram alpha api for a new project but unfortunately the cost was entirely way to high for what we were using it for. Essentially what we were doing is calculating the nutrition facts for food. (http://www.wolframalpha.com/input/?i=chicken+breast+with+broccoli). Before taking the step of trying to build something that may work in its place for this use case is there any open source code anywhere that can do this kind of analysis and compile the data? The hardest part in my opinion is what it has for assumptions and where it gets that data to power the calculations. Or another way to put it is, I cannot seem to wrap my head around building something that computes user input to return facts and knowledge. I know if I can convert the user input into some standardized form I can then compare that to a nutrition fact database to pull in the information I need. Does anyone know of any solutions to re-create this or APIs that can provide this kind of analysis? Thanks for any advice. I am trying to figure out if this project is dead in the water before it even starts. This kind of programming is well beyond me so I can only hope for an API, open source, or some kind of analysis engine to interpret user input when I know what kind of data they are entering (measurements and food).


Complex fetching of Domain Objects

Usually whenever I want to fetch an aggregate root by ID I just use some type of Repository::findByID(...) function Whenever I started with DDD I thought factories where just a pattern to build _new_ objects, but after meeting some aggregates needing one or two extra queries to load, I realized that Factory::objectWithID(...) were useful to also create instances of objects already existing in the database. Now I have a tree relationship of entities, like **Project->Task**. The number of relations is huge and I have no framework providing lazy loading. Since Tasks can be nested, have complexity of their own, and should not be fully retrieved in one query, I made **Project** and **Task** different aggregate roots How should I retrieve and persist **Tasks**?. It seems that a **ProjectFactory** is not the solution this time because a **Project** does not contain the whole **Task** tree. I still want some aggregate root like features for my **Project** , and since I am avoiding queries inside my entities, I decided to write the relationships inside a Project-Service-Aggregate. Now I can retrieve a single **Project** with a Repo::findByID() function, but fetching a **Task** looks like               ProjectAggregationService *service = ProjectAggregationService.new(SomeProject)     Task task_1 = service.findTask(...)     Task task_1_child_2 = service.findTaskChild(task_1,2)      I am puzzled at this point because:   1. I have a service to represent entity relationships.    2. I am declaring many instances of a service, whereas before, services tended to be quite unique objects.   3. Not having a clear object tree like Project.tasks[1].subtask[3] make the code above look like more complex than necessary. Basically I could summarize my question to: Did I take the right approach? I would greatly appreciate any comment on my reasoning. I am mostly concerned about degenerating my code with overblown complexity, but I still think that keeping references to queries and repos outside my entities implementation is a good goal.


How to detect root cause of problem or bug

Often in coding, I find it very slow and difficult to detect the root cause of a bug and sometimes I end up going to wrong point in my code. It's painful. I know that to detect the root cause of a bug is a very important skill for programmers. Does anybody have a trick or technique to suggest a good way of finding the root cause?


Confused About Virtual Memory for All Processes

I hope this is the right place. This is a homework assignment for my Operating Systems course and I have to implement a working virtual memory system in C++ so programming is directly involved. I've read some sources about Paging and Virtual Memory now (Tanenbaum, What Every Programmer Should Know About Memory, etc) and noticed that everybody starts off with the phrase `Every process gets its own virtual memory.` Then off they go into a detailed analysis about page size, page replacement algorithms, the MMU and TLB, etc. Those things are actually quite fine in my mind, what doesn't make sense is the concept of virtual memory. If I have four processes running simultaneously and each process uses it's own virtual address space, how is the physical memory protected? The MMU translated the virtual address 0 the same whether it comes from process one, two, three or four. Let me give an example: Every process has a 32-bit virtual address space that it can use. Every process starts off the same way               MOVI 10, 0  // r10 = 0      LOAD 11, 10 // r11 = MEM[r10]; value at address 0x00000000      I just don't understand this concept of distinct virtual address space if every process tries to call the same virtual address which will be translated the same way by the MMU. So all four processes will receive the same data? We have a page table which keeps an index of every mapped and unmapped page to a page frame. If each page entry is unique, then how can it account for the duplicated virtual address space that each process has? I'm at the point where I have written design drafts for the MMU, TLB and the Page Table, but I can't continue until I properly understand how the heck virtual space is defined and used for each process.


Is Clojure a 3GL or a 4GL?

A bit of background (in case I'm mistaken)... I think I understand that (it's an oversimplification):   * manually entering codes into memory (or on a punchcard) is "first generation language"   * using mnemonics corresponding to CPU instructions would be a 2GL (like assembly language)   * C/C#/Java/Objective-C are all 3GLs   * SQL is a 4GL Where would Clojure stand in such a classification? I'm particularly confused by this Wikipedia sentence: > The archetypical example of a declarative language is the fourth generation > language SQL, as well as the family of functional languages and logic > programming. This sentence seems to imply that all functional languages are declarative. Is that correct? Then Clojure can be used in a functional way (and it is probably recommended to use it "as much as possible" in a FP style), so is Clojure a declarative language ? Also, I can see that Clojure make it really easy to create 4GLs (e.g. as embedded DSLs, like core.logic reproducing logic programming in about 200 lines of code) but is Clojure itself a 4GL?


What are the requirements for an open-source license inside an open-source license?

If I include an open source library in my project that is licensed under the MIT license, but contains BSD-licensed code that requires attribution (correctly attributed inside the project), is it my responsibility to attribute it again if I decide to use that library? Normally this is not a problem (I would just credit everyone regardless of the license) but on a mobile platform there is not a lot of real estate or efficient ways to show / bundle these licenses.


Polymorphism versus authorization

I have something bother me in the understanding of polymorphism (vs role):   Note: I am using rails (but it's a general question) I have **4 models** :   * User   * Pro   * Customer   * Company There is a **polymorphic association (profileable)** between Pro/Customer and User [because Pro has many more fields for the registration process than Customer]. User is used for the session (I am using the devise gem) Basically something very similar to this writing is used: http://jeffsaracco.com/blog/2012/03/04/ruby-on-rails-polymorphic-user-model/ ### Company association   * Now, I want to create my association with Company.   * By now, only **Pro has one Company** (but I figure it could be other profileable_type which can also have a Company).   * Customer doesn't have a Company. In that case which association is preferable: ### Approach 1   * User has_one Company   * Company belongs_to User   * and manage authorization (with a gem like cancan) to permit company creation only for Pro (with my profileable_type field in the user table) or: ### Approach 2   * Pro has_one Company   * Company belongs_to Pro   * So in that case I don't need any authorization management anymore (User (and by extension Customer) cannot create company by default) Looking for pros/cons of the 2 approaches. I am pretty sure the first one is the best solution as I have a user_id in my company table which would be more generic and expandable than having a pro_id.. I would be pleased to be sure. Thanks!