Java Logfile Parsing Assistance

I'm writing a log parser that continuously looks for specific patterns and then fires off events to another system when it finds these matches. The firing of the event is time critical to catch errors or ensuing problems. This part is non-negotiable in terms of design. The log files belong to Applications and the Operating System; thus they can be rapid in logging, large in size and rotate based on time, or size. What is a better approach to reading these log files, detecting when they change, and reading from their last read location as I wrote code to do this using a RandomAccessFile which kept the last read location for every file. For dealing with large files and rapid logging I did this:   1. DataProducer - would get last read point in file and then find any changes then add to a Queue    2. DataConsumer - any changes to the Queue by way of size, would then cause this thread to wake and start parsing all the items in the Queue for that log file. Deleting what it has parsed. I am looking for some suggestions (in light of what I have done) that may improve the current way I manage reading a file, and picking up when there are changes, and parsing the file efficiently (considering size and rotation). Code or an API will do.


typical way to share database connection for open-source project, without revealing too much

I have an open source project for `mydomain.com` which requires connections to a database (...as is tradition). What is the standard practice for allowing others to work on the site, without giving them full access to the database's credentials? For example: If I have a `connect.php` page that connects to the database. I don't want someone to be able to read that file, or simply write `<?php include("http://mydomain.com/connect.php")` because then they will have full access to the database. If I put the file in my `.gitignore` file, sure the file won't be in the repo, but it'll still be visible in the source code. Do I just make a read-only user and give them access to that, and then put the full read-write connection file and follow the guidelines of this answer?: Making sure database connection information is secured What is standard practice here? or what can I research to learn more about this?


What is selection and what is projection

I am working on Android with the query() method of the ContentResolver class and it accepts 6 parameters, `(uri,projection,selection,selectionArgs,sortOrder,cancellationSignal)` for selection and projection parameters. I am little bit confused with the selection and projection part of query. In below example, what is selection and project part in the query?               select * from Person     where name='zeus';


Unit Testing DatabaseOpenHelper class in Android

I've written several unit tests for an already existing `DatabaseOpenHelper` class. I covered the creation scenario and migration from old schema to new one. Unfortunately, I don't feel that my tests are good. For example, for DB creation I check that `SQLiteDatabase. execSQL()` was called three times (we have three tables so far) and check that query string is in set of specified SQL strings. The issue so far - if someone changes order of columns the test will fail. Probably this is OK. But what are other ways of SQL schema unit testing? Or don't you have unit tests for that, and rely only on the integration one?


Using Exception Emails as a System Status Indicator

I'm working through our bug list today and I'm trying to clear up/fix issues that we commonly receive exception emails for. Although all the exceptions (so far) are handled, some don't actually represent an error in the code. For instance, if a third party service goes down temporarily, our code fails, handles the exception and sends us an email. This can be especially useful during business hours because it allows us to quickly see if something is down and react to it. However, there are also scheduled down times and the exception emails can quickly fill an inbox. My question is, is there a best practice for gaining insight into your system status? Is an exception email as I've outlined here an acceptable practice or should exception notifications only ever be unexpected?


How can I express recursive composition in UML class diagrams?

I have one class called "Institution" which represents a public institution (with properties like id_inst, name_inst, tel_inst, fax_inst...). The institution can have affiliated institutions, for example a university is composed of different faculties (which are also institutions with the same properties and methods). Theses faculties can also have affiliated institutions : laboratories, annexes, etc. How can I express this concept in a UML class diagram?


What is proper etiquette and recommended GitHub workflow for simultaneously contributing to and diverging from upstream repo?

I'm new to GitHub and VCS in general. I've been programming in various languages for years, but I've always worked solo on custom projects (no public releases). I recently started using a jQuery UI widget I downloaded from GitHub in a project I am working on. The repo is no longer maintained by the original author. Another fork has incorporated some of the original pull requests. This is the one I forked from. I found a couple of bugs and have come up with the fixes for them. I'd like to contribute these fixes, but I also have a whole lot of other changes I want to make, for our own use, that will break some of the existing features. Plus, I'd like to incorporate an idea from another fork. I'm still learning GIT and GitHub and I'm trying to figure out the best way to go about everything. I've done a lot of reading (here, SO, GitHub help pages, Pro Git) about different concepts/tasks: workflows, merging, pull requests, cherry picking, rebasing, branching. My grey matter is swimming and I need to start _doing_ so I can better understand what I've read. ### Main Issues:   1. I think I read (somewhere) that you can only have one pull request on a branch at a time. So does that mean I should have a separate branch for each bug and then do a separate pull request for each one?   2. I want to clean up whitespace issues and I seem to remember reading that it's best to do this in a separate commit. Should I do this in my master or a separate branch? I don't want to do a pull request for something so _trivial_ , but if I make whitespace changes before branching, will that affect the pull request for the bug fixes? Some forks did whitespace cleanup and it effectively made the diff pretty useless.   3. I was thinking of creating issues against my fork as a way of documenting the bugs even though I already have the fix for them. Is that a good idea? How do I go about linking together the issue, the commit, and the merge to master? If I do a pull request upstream, will my issue appear upstream as well or will that documentation link be lost? I can't open an issue against the upstream repo (there is no issue tab).   4. What's the best way to give credit to the other fork author for the idea of his that I want to use? I can't use his code exactly, especially since his change is applied against an older version of the upstream and is not compatible with my other changes as is. But I want to use the idea and I want to give credit where credit is due. Should I just link to his repo (or profile or specific commit) in my commit message?   5. What is the etiquette regarding changing the readme file and the DocBlock at the top of the main file? Is it ok to make changes, add my name, add links to my repo and demo, remove links to the original demo (since my fork will end up being incompatible with the original)? Of course, I will leave the original author name and license information. For the record, it's licensed under the MIT license. As a solo developer who's never used VCS, I am accustomed to _rewriting history_. I'm a perfectionist and like things to be neat and tidy. The idea of recorded history is making me a little nervous and I want to _do it right the first time_. I've created a new repo to play/learn with, but I am anxious to get moving on fixing up the jQuery UI widget so I can move on with my project.


Build a native dll or .net dll to be used independently in either set-up

Here's a simple question (kind of), but I'm having a hard time taking a decision. First, a history on how I came to have this problem. In my new job, we need to use a third party API to communicate with their proprietary database (this is manufacturing technologies). This API only comes with very simple c example (not simple syntax ;) ) on how to use this API. Functions have no documentations and the syntax is thick, since it was probably build sometime in the last century, so parameters have short non significant names same with the functions names. Very few help is found on the web and the company itself can't really help us. Over the web, the small crumb found are about people not able to translate it into simpler language call (like VB6). People before me here tried to use it, without success. The good news is I have been able to make the example work and modified them to fit our basic needs to send or read data. I have wrapped these new version in a c++/CLR assembly dll, to use it in c#, which is our almost current language(Yeah , it moves slow in this world) Depending on the version of the software we use (every client we have can have different setup, from legacy to brand new setup). This can have an influence an what language we use. So I was asked to try and make my dll available in native & managed setting. So, here lies my question. Should I leave my dll to have a managed signature and if it needs to be use in vb6, make sure it is understood how to make it work in native mode (which I need to learn), or should I make a native dll and make it P/Invoke in managed setting? Or should I build two distinct dll? IMO, I would keep it as a managed dll, but I was wondering if it's the best way to do it? On a last note, the current version is a v.1 build to showcase how we can use it,and start using it fast. Writing this makes me realize I need to build an interface!:). I plan to rebuild the whole program, but the API's calls will always be to their native dll, unless they have .net SDK coming, but no word about it yet.


managing a remote programmer

We have an opportunity to hire an awesome web dev for our team. Problem is, he is leaving for S. America in 6 months. We will still have him onsite for six months. We are thinking of having him work remotely after that, but we have our concerns. Ours is a 4 person Chicago-based team that uses scrum. Our office is a war room where we are in constant collaboration. How could we include a remote worker in such a process? What technologies and techniques can make this work? Or is it a lost cause? This thread lists some tools, but I'm hoping for some real world experiences.


How does MySQL blob actually work?

This is a question driven by curiosity. I am learning Oracle database and Oracle database handles Blob data in a separate tablespace, which I believe reduces overhead while trying to read large Blob data. I am wondering how MySQL handles Blob? I am actually planning to start a project and I wish to give a try on saving images in MySQL databases instead of standard approach of saving files in the file system. Thank you.


Unit testing: about easy- and hard-first strategies

I've never written a unit test. I'm reading _The art of Unit Testing_ by Osherove, and he explains a way to choose where to start when you're writing tests for legacy code. Basically you end up with two kinds of tests to write: **easy** (on components with few dependencies) and **hard** (on components with many dependencies). Then he says that starting from the hard ones you have to be more experienced, but that it lets you refactor and make testable a wide part of the system, making later work much easier. But isn't it true the way around too? I mean, if you start from easy tests, shouldn't you end up making hard tests easier?


Sort rectangles in a grid based on a comparison of the center point of each

If I have a grid of rectangles and I move one of the rectangles, say above and to the left of another rectangle, how would I resort the rectangles? Note the rectangles are in an array, so each rectangle has an index and a matching tag. All I really need to do is set the proper index based on the rectangles new center point position within the rectangle, as compared with the center point position of the other rectangles in the grid. Here is what I am doing now in pseudo code (works somewhat, but not accurate):               -(void)sortViews:myView {     int newIndex;     // myView is the view that was moved.     [viewsArray removeObject:myView];     [viewsArray enumerate:obj*view]{         if (myView.center.x > view.center.x) {             if (myView.center.y > view.center.y) {                 newIndex = view.tag -1;                 *stop = YES;             } else {                 newIndex = view.tag +1;                 *stop = YES;             }         } else if (myView.center.x < view.center.x) {             if (myView.center.y > view.center.y) {                 newIndex = view.tag -1;                 *stop = YES;             } else {                 newIndex = view.tag +1;                 *stop = YES;             }         }     }];     if (newIndex < 0) {         newIndex = 0;     } else if (newIndex > 5) {         newIndex = 5;     }     [viewsArray insertObject:myView atIndex:newIndex];     [self arrangeGrid];     }


Can I start with a passing unit test?

Uncle Bob's rules for TDD are specified here.   1. You are not allowed to write any production code unless it is to make a failing unit test pass.    2. You are not allowed to write any more of a unit test than is sufficient to fail; and compilation failures are failures.    3. You are not allowed to write any more production code than is sufficient to pass the one failing unit test. But, is it ok to write a bunch of tests that pass as soon as the test compiles? For example, a test that asserts null and the default impl of a method I'm testing returns null. Am I doing something wrong by doing this? Should I skip to the first test that will fail or is it ok to write tests that automatically pass first?


How to write comments to explain the "why" behind the callback function when the function and parameter names are insufficient for that?

How should I approach writing comments for callback functions? I want to explain the "why" behind the function when the function and parameter names are insufficient to explain what's going on. I have always wonder why comments like this can be so ordinary in documents of libraries in dynamic languages:               /**      * cb: callback    // where's the arguments & effects?      */      func foo( cb )      Maybe the common attitude is "you can look into source code on your own after all" which pushes people into leaving minimalist comments like this. But it seems like there should be a better way to comment callback functions. * * * I've tried to comment callbacks in Haskell way:               /**      * cb: Int -> Char      */     func foo(cb)      And to be fair, it's usually neat enough. But it gets into trouble when I need to pass some complex structure. The problem being partly due to the lack of type system:               /**      * cb: Int -> { err: String -> (), success: () -> Char }  // too long...      */     func foo(cb)      Or I have tried this too:               /**      * cb: Int -> { err: String -> (),      *              success: () -> Char }  // better ?      */     func bar(cb)      The problem is that you may put the structure in somewhere else, but you must give it a name to reference it. But then when you name a structure you're about to use immediately looks so redundant:               // Somewhere else...     // ResultCallback: { err: String -> (), success: () -> Char }          /**      * cb: Int -> ResultCallback    // better ??      */     func foo(cb)      And it bothers me if I follow the Java-doc like commenting style since it still seems incomplete. The comments don't tell you anything that you couldn't immediately see from looking at the function.               /**      * @param cb {Function}  yeah, it's a function, but you told me nothing about it...      * @param err {Function} where should I put this callback's argument ??      *                       Not to mention the err's own arguments...      */     func foo(cb)      These examples are JavaScript like with generic functions and parameter names, but I've encountered similar problems in other dynamic languages which allow complex callbacks.


How to achieve N-Tier type in Codeigniter MVC

I know that N-Tier intended to separate layers on different network but I would like to have the same code separation in codeigniter I got this idea to have **Model** : for database CRUD - > Data layer **REST** API : for business logic—> Business layer that calls CRUD method from models **Controller** & **View** are going as before and flow will be **View** <—> **Controller** <—> **API** (with Business classes) <—> **Model** I wanna know what kind of drawbacks it can be such architecture


Is garbage collection needed for implementing safe closures?

I recently attended an online course on programming languages in which, among other concepts, closures were presented. I write down two examples inspired by this course to give some context before asking my question. The first example is an SML function that produces a list of the numbers from 1 to x, where x is the parameter of the function:               fun countup_from1 (x: int) =         let             fun count (from: int) =                 if from = x                 then from :: []                 else from :: count (from + 1)         in             count 1         end      In the SML REPL:               val countup_from1 = fn : int -> int list     - countup_from1 5;     val it = [1,2,3,4,5] : int list      The `countup_from1` function uses the helper closure `count` that captures and uses the variable `x` from its context. In the second example, when I invoke a function `create_multiplier t`, I get back a function (actually, a closure) that multiplies its argument by t:               fun create_multiplier t = fn x => x * t      In the SML REPL:               - fun create_multiplier t = fn x => x * t;     val create_multiplier = fn : int -> int -> int     - val m = create_multiplier 10;     val m = fn : int -> int     - m 4;     val it = 40 : int     - m 2;     val it = 20 : int      So variable `m` is bound to the closure returned by the function call and now I can use it at will. Now, for the closure to work properly throughout its lifetime, we need to extend the lifetime of the captured variable `t` (in the example it is an integer but it could be a value of any type). As far as I know, in SML this is made possible by garbage collection: the closure keeps a reference to the captured value which is later disposed of by the garbage collector when the closure is destroyed. My question: in general, is garbage collection the only possible mechanism to ensure that closures are safe (callable during their whole lifetime)? Or what are other mechanisms that could ensure the validity of closures without garbage collection: Copy the captured values and store it inside the closure? Restrict the lifetime of the closure itself so that it cannot be invoked after its captured variables have expired? What are the most popular approaches? **EDIT** I do not think the example above can be explained / implemented by copying the captured variable(s) into the closure. In general, the captured variables can be of any type, e.g. they can be bound to a very large (immutable) list. So, in the implementation it would be very inefficient to copy these values. For the sake of completeness, here is another example using references (and side effects):               (* Returns a closure containing a counter that is initialized        to 0 and is incremented by 1 each time the closure is invoked. *)     fun create_counter () =         let             (* Create a reference to an integer: allocate the integer                and let the variable c point to it. *)             val c = ref 0         in             fn () => (c := !c + 1; !c)         end          (* Create a closure that contains c and increments the value        referenced by it it each time it is called. *)     val m = create_counter ();      In the SML REPL:               val create_counter = fn : unit -> unit -> int     val m = fn : unit -> int     - m ();     val it = 1 : int     - m ();     val it = 2 : int     - m ();     val it = 3 : int      So, variables can also be captured by reference and are still alive after the function call that created them (`create_counter ()`) has completed.


How can I present some printed Visual Basic source code in an aesthetically pleasing manner?

Right now I'm interning at a major engineering company. I'll be leaving in a few months though, so my project manager has requested a print out of my source code for a VBA project I've been working on. He would like to have it reviewed to make sure I didn't do anything ridiculous, and to make sure it's organized well enough for someone to maintain easily enough once I'm gone. I'm not really sure why he would want a print out instead of files, but since the VBA editor is ugly as sin this is probably a good thing. I would like to make an impression with this - however minor - so my question is how can I make this look professional? I.e., maybe there are certain fonts that make sense here, perhaps I could apply a color scheme to the words, etc?


MVCS - Model View Controller Store

I recently decided to start learning iOS Development, and to this end I’ve been reading iOS Programming: The Big Nerd Ranch Guide. In the book the authors describe a design pattern _MVCS - Model-View-Controller-Store_ , the basic idea being that since many applications make use of multiple external sources of data keeping the request logic in the controller can get very messy, instead the authors propose that moving all the request logic out of the controller and into a separate object. In short to quote the book > Model-View-Controller-Store puts request logic into a separate object, and > we call this object a store (Figure 28.4). Using a store object minimizes > redundant code and simplifies the code that fetches and saves data. Most > importantly, it moves the logic for dealing with an external source into a > tidy class with a clear and focused goal. This makes code easier to > understand, which makes it easier to maintain and debug, as well as share > with other programmers on your team. And > The cool thing about asynchronous stores is that even though a lot of > objects are doing a lot of work to process a request, the flow of the > request and its response are in one place in the controller. This gives us > the benefit of code that’s easy to read and also easy to modify. I wanted to find out more about this pattern and to see what others might have to say about it, but while searching online the only references I could find were to that same book (is the pattern perhaps known by some other name?). To me the author’s logic seems to make sense, and it seems like a logical extension of the regular MVC pattern, but perhaps that's because I don’t really have much experience with the MVC pattern in practice (aside from foray into iOS development I have sort of used MVV with backbone.js (that is, if you consider it MVC)). I was hoping that perhaps someone with more experience can shed some light on whether there are any obvious flaws/problems with the _MVCS_ pattern that I’m missing.


For a front-end application broken down in a MV* manner, should I have models dedicated to UI logic?

I am not talking about simple UI logic like clicking a button directs you to another page, but where one action may result in several different of behavior depending on current application state, and may also trigger response in other parts of the application. Currently my view publishes all UI event so the response can be delegated to other parts. The problem is which other part? In order to avoid writing 'fat' controllers that hold arbitrary amount of domain logic, I thought it might be nice to have a non-persistent object that models UI behavior, but am not sure if this makes sense or if I am just pushing the problem around and being object-happy?


What tools or techniques are useful for describing an unfamiliar codebase?

When manually inspecting unfamiliar code (to review or modify), I seem to have three options.   * A **top-down read** of the code, choosing each next source file by how fundamental the filename seems. _I usually end up reading nearly everything. Some files twice._   * A **breadth-first read** , where I find and read all of the invoking method with minimal understanding. Then read all the functions that function called, and so on. _My mental stack tends to overflow if I make it a few calls deep._   * A **depth-first read** , where I step through all the code in a debugger, unsure of whether this will take 8 minutes or 8 hours. Once I've read enough of the code to have a fairly solid understanding of what it's doing, I often reflect that **I've read 80% or more of the codebase, while the fundamental code is 20% or less**. I've wasted a lot of time. What tools are useful for getting a quick grasp of unfamilar code? Are there any tools that can give a "big picture" of the critical code path and allow me to drill down to the details of any one part?


WCF service as a proxy for publishing real-time data to a WPF/MVVM clients

I've been tasked with creating a dashboard application to show real time updates for our servers. The raw data comes in from an XML file on our intranet which I need to parse and present to the user. It is not an option to have every user of the dashboard pull this XML file at the same time for their updates. From what I have been reading, I need to use a WCF service to consume the XML file server side and then have it push updates to all clients who are looking at the service. I need it to be scalable, there will be around 20 concurrent users at the start but I will need to scale to hundreds in the future. I will need to update from the XML file every 30 seconds to 1 minute. Am I on the right track with WCF? Are there other options that I should consider?


Design for a tree using a visitor pattern, how to implement different kinds of traversal?

I've been asked a theoretical design question with an eye upon the GoF patterns.: "Given a design for a tree using a standard visitor pattern, how would your design look to allow a user to choose between om pre-order, in-order or post- order traversals?" I'm thinkin of just letting the visitor be, but give the traversal over to an Iterator object following the Iterator Pattern. The idea would be to implement 3 iterators that enable the desired traversal. They have an interface and the Visitor only needs to interact with this interface, giving itself as an argument to the iterator which provides traversal. The user can choose which iterator to use when giving one to the visitor. Does this sound like an elegant solution? Any better ideas?


Should I fix small issues or let them go?

I ran into the following issue where a keyboard shortcut I was used to was no longer working in Ubuntu. That's just an example. For programming, this kinds of thing happens a lot, but it also happens in any aspect of work and life. I'm always tempted to fix it right away because I have an idea of what might fix it in a few minutes. Of course, a lot of times the idea is wrong, and much more effort is required. I basically go through an optimization process where I continuously ask myself "Did I spend too much time looking for a fix already?" in trying to decide whether to abandon the effort. I think any one issue can be abandoned, but I think that if I do it for all of them, my life will be a mess of inefficiencies. **Question:** How do you effectively approach this temptation of small problems? As I wrote up in the above rambling blog post the pros and cons for the decision to pursue any one individual issue are: **Pros:**   * I fix the small problem the "right" way, so I don’t have to settle for a half-ass sweep-under-the-rug solution.   * I get to spend an hour being open to the possibility of learning new things relevant to my work and exchanging information with the community of fellow Linux users. The computer world evolves on a daily basis, with new technologies, approaches, ideas constantly emerging. So, it’s important to stay connected to the latest developments.   * I get to practice persevering in dealing with frustrating issues. **Cons** :   * It is not guaranteed that I find a solution.   * It always takes longer than you thin. At first, it seems like the fix would not take more than 5 minutes, and when it does (50+% of the time), I become progressively more invested in it as time goes on. It’s the same principle that keeps you gambling in a Casino until all your money is gone.   * Perfectionism is an addiction. We live in a world of inefficiencies that could be easily optimized if you just give it a few minutes. Sometimes it does take minutes, but sometimes it may take days. The more you feed this addiction, the harder it becomes to exist peacefully in an inefficient world.


Can thesaurus items have more than one USE relation?

I want to model a Thesaurus using the ANSI/NISO standard relation description like "broader term", "narrow term", etc. (see this Wikipedia article for details). Is it valid for a Thesaurus item in this description standard to have more than one "use" relationship?


Are programming skills and computer knowledge taught at university sufficient for industry?

I am student currently attending my fourth year at a Swedish university and will, if all goes well, take my Master's degree in Computer Science in winter of 2011. It is a respectable university, at least here, and am overall satisfied with my choice - both of university and major. While I've learned much in the courses I've attended, I am a bit concerned if what being taught is sufficient when moving from the safe practice grounds of the university to the volatile battlefields of industry. In truth, I would say more than half of my programming skills and soft- and hardware knowledge have been self-taught on my own spare time - either through projects initiated on my own accord or studying non-mandatory topics of material in conjunction with courses. Indeed, sometimes these "off-topics" have proven more interesting and valuable than the course material itself. In terms of programming skills, even less have been learned directly through university courses. To my knowledge, I don't know of a single course at my university which covers how to program efficiently. Sure, there are many courses in how to program in a particular language, several in how to write algorithms for solving a particular problem, as well as one in how to program under pressure, but none in how to _think_ about programming and how to approach problems in an efficient manner. Also, I encounter many students who have never concerned themselves with C or C++: languages heavily used in industry. Even after having written code in one form or another for 15 years, I still feel I have so much left to learn. In truth, the more I learn, the more ignorant I feel. All this leave me with a concern that, had I relied solely on what I've been taught at university, I would not be adequately equipped for facing the working market; and even with my spare time learning I am not sure my skills are adequate. Is this a common problem? Are programming skills and knowledge taught at university sufficient for industry? What experience have you employers had with new workers fresh from univeristy in terms of their knowledge and skills? Do you feel that they are adequate, or should the universities improve or revise their teachings? **NOTE:** I originally asked this question on SO (http://stackoverflow.com/questions/3720486/are-programming-skills-and- computer-knowledge-taught-at-university-sufficient-for), but it was closed as it wasn't suitable for a Q&A website such as that. But I was recommended to post it here instead so I've simply copy-pasted the question.


What's the best way to manage reusable classes/libraries separately?

When coding, I naturally often come up with classes or a set of classes with a high reusability. I'm looking for an easy, straight-forward way to work on them separately. I'd like to be able to easily integrate them into any project; it also should be possible to switch to a different version with as few commands as possible. Am I right with the assumption that git (or another VCS) is best suited for this? I thought of setting up local repositories for each class/project/library/plugin and then just cloning/pulling them. It would be great if I could reference those projects by name, not by the full path. Like `git clone someproject`. edit: To clarify, I know what VCS are about and I do use them. I'm just looking for a comfortable way to store and edit some reusable pieces of code (including unit tests) separately and to be able to include them (without the unit tests) in other projects, without having to manually copy files. Apache Maven is a good example, but I'm looking for a language-independent solution, optimally command-line-based.


Multi-platform Map Application

I'm working on a web project (PHP, jQuery) which currently using Google Maps powering up the map functionality of the application, however we need to make it multi-platform like you can go to the dashboard and choose one from 5-10 map providers (which Goolge Maps is just one of them) to underlying your map functionality. So, as the application is supposed to show the data on map, almost in every single place we have to deal with the API provided by that specific map provider. Currently we are thinking about revising our modular structure and/or making something like an adapter for each provider to deal with their native syntax but via our standard methods. I wish to have your ideas and your experiences, specially if you ever made an interface for dealing via 2-3 different map providers. That would helps much and I really appreciate that. If you need any further information, just ask me to update the question. **Update:** As `Vicky Chijwani` suggested **Mapstraction** , now I'm also wondering which one is more better (pros & cons), having an adapter implemented on Javascript or PHP?


Is there a symbol or shorthand for "and is increasing/decreasing"?

This usually happens when I'm writing to developers or other IT professionals. The context would be something along the lines of ". . . measured at 100 MB/s (and is increasing)." On paper or a whiteboard, I've always drawn a bold up/down arrow. This situation mostly shows up when I type comments in email, code or revisions. I didn't not know if there was a symbol or shorthand in Unicode that could help out.


Smallest and Largest contiguous repeating sub-sequence in a sequence

I am trying to solve a outdated quiz problem.   I am tasked to find the smallest and largest contiguous sequence of repeating numbers in a larger sequence.   e.g.               {1,3,6,17,19,3,6,5,4,2,5,6,17,19,3,6,7,5,78,100,101}      For the sequence above, the smallest (non-zero element sequence) and largest non extensible sub sequence would be `smallest - 3,6` and `largest - 6,17,19,3,6`   Could not get started with an algorithm. Any help to get me started would be much appreciated.


Design for running active x components from local server

I have a requirement where some of the training scripts (active x components) needs to be rendered on the client application (IE 8). Till now the server was hosting these scripts using IIS and IE was used render these using HTTP protocol. However in some new customer scenarios I am required to look at the possibility of not having a server hosting this content due to bad network connectivity. The different options I am looking at are   1. Inside the LAN have a local server and use IIS within that to host these training scripts   2. Host the training scripts on each users local drive Option (1) may not be suitable to all customers since it requires an additional server and since my customers are banks they may not be OK with it. Option (2), playing the content from local file system will be considered as security threat and elevating the security privileges on browser in banking environment is a strict no-no. Also pushing updates on the training materials is cumbersome where I might need to push updates to say 30000 teller machines instead of 1 server machine. If i choose to go with option (2) is there any possibility of using any temporary local webserver? Are there any other alternatives to achieve this?


To use or not to use a backing app for website?

By suggestion in comments, I'll try to rephrase my question to better reflect my problem: I have to present users (few at first, as many as possible later) with a website. There they will be able to browse various data. The data will be served from a local "cache" db. Users should be always presented with data as fresh as possible. The source for most of the data will be external services with possible limits, long response times etc. The process of processing data from those sources to the schema of local db is also not straightforward (conversion, calculations, decoupling, recreating relations etc.) Is putting all that data mining and processing code ok (and doing all that work in the time between users click a link and receive data), or is my second idea - another, constantly running data-miner application - better? Or is there another option? Old text: I'm currently developing a website that will present both its own data (user profiles, their submited content) as well as data obtained from various external sources (e.g. via webservice calls). Varied sources will have varied limits of allowed calls, will respond with varied speed etc. No, the data user is presented with should be, by default, as fresh as possible with an option to request refresh (unless refreshed very recently). I started development in ASP.NET (for better or for worse), with some templates and some customization, and quite a lot of coding I ended up with a workable proof of concept. But then I started to think about large-scale operations. Displaying cached data is quick and easy, I didn't mess that up. Refreshing though is a problem. a) Requesting data for one user is fast, but it will eat through allowed api calls quickly. b) Requesting data for multiple users (for apis that allow that) saves potentialy great amount of api calls, but takes linearly longer (not 1:1, but still, it takes time to request, receive and parse tens of times more data than single request). There also comes the problem of exceeding the limits. Usually that would force the app to either cancel refresh, or wait few seconds for new allowance. But I don't really see the user happily waiting for several seconds for the page to load. I am currently concidering gutting the data-gathering part of the website and moving it into a single managing application, sharing a db with the website. The website would provide info which users need their data to be refreshed, the app would load-balance the external services to use them efficiently (not limited to "when a user opens a website"), and keep the data as fresh as possible - also possibly keeping part of the allowance for forced refreshes. Now, the main problem I see with this is cost of hosting not just website, but also a background running .NET application. But let's assume that the cost is not that relevant. What I actually fear is that I overcomplicate the solution. I might just put more of the website in Ajax and just wait for the request to complete in the background (when calls become available). So, does anyone has any simillar experience? I'm especially interested in the scenario where it is all scaled up, that is we can assume that there will always be deficit of available calls. PS I also worry about keeping website (which can be triggered independently by many users) from trying to refresh the same records twice etc. - I guess I should put some additional safeguards, lock or at least mark the records undergoing refresh etc. - a lot of code just to solve the problem that wouldn't exist with a single-backend....


myeclipse: can I customize templates like sysout in jsp

Myeclipse's java code templates like _sysout_ make coding easier, and they can also be customized. But seems it's jsp editor has no such capability. Is it possible to create and customize some templates like _sysout_ in myeclipse jsp editor, and if yes, how?


How to schedule large numbers of user-defined tasks?

Say you're running a website which generates a large number of tasks that should be run at particular times (e.g. reminder emails). You could run a cron which SELECTs a database table for unprocessed events before the current time (or even a long running process that polls the table), but this seems messy. On the other hand, as far as I know most producer/consumer messaging systems don't support arbitrary priorities. How to approach this?


Is using partial classes for supporting multiple versions of data entities for continuous delivery scenarios a bad idea?

When you want to have continuous delivery any data schemas that you have must support multiple versions of your application at the same time (as you may have multiple version deployed when new versions are rolling out) In my specific case I have entities stored in Azure table storage. When I am making changes to my entities I am usually having to add properties (as removing or renaming them is a bad idea as old versions of the application will potentially break), but once a new version is completely rolled out I don't need the old versions properties anymore as all the servers out there are using the new version, which means in the next rollout I can remove some of the old properties. I'm wondering if this problem can be solved more easily by having partial classes for each version of the entity. This ensures that one version will always be accumulative for a previous version (ie will never take anything away or change anything) but will allow delegation to an existing property if something just needs to be renamed. Once a version has been completely rolled out and the old version will never be needed then the partial classes could be consolidated into a single class again (and any unneeded properties removed). If you know that you are only going to have a couple of versions 'live' at anyone time then you could perhaps use a 'current' version and a 'vNext' version explicitly. I've not tried this as a solution yet but wondered if anyone else has tried an approach like this and has any feedback, or if anyone has thoughts on whether this is a good or bad idea?


Is Debug.Assert obsolete if you write unit tests?

Just like the question asks, is there a need to add Debug.Assert into your code if you are writing unit tests (which has its own assertions)? I could see that this might make the code more obvious without having to go into the tests, however it just seems that you might end up with duplicated asserts. It seems to me that `Debug.Assert` was helpful before unit-testing became more prevalent, but is now unnecessary. Or, am I not thinking of some use case?


IntelliJ with Maven compilation

I have a project that needs Hibernate jars. I added them as dependencies in the pom.xml and Maven compiles my project well. However, in the IDE, all annotations and calls to Hibernate API are marked as unresolved (red). How could I get IntelliJ being able to resolve them ? Is there a way to use Maven when I click on Build Project ? (ctrl+F9) Also, I am confused with the concept of facets within IntelliJ. Do I need them, let's say JPA facets to enable Persistence assistant etc... or there's an option to let Maven take care about ?


Why does the backing store of an array bind to the smallest type?

In C# it is legal to write               Animal[] a = new Giraffe[4]; //with obvious relationships      Because arrays are covariant. However, this is a breaking relationship. It's a runtime exception to then apply a different type of Animal to this array because the backing store is a `Giraffe`.               a[0] = new Cat(); //KABOOM      Why doesn't the language create a covariant backing store? This doesn't appear to be a limitation of the language because I can create this type of data structure myself:               class Program     {         static void Main(string[] args)         {             A[] a = new B[2];             a[0] = new B();             a[1] = new C();//runtime exception                  var containerLegal = new Container<B, A>();             containerLegal.Add(new B());             containerLegal.Add(new C());//works fine         }     }          class A { }          class B : A { }          class C : A { }          class Container<T,S> where T: class, S     {         S[] s = new S[4];         int currentIndex = 0;              public void Add(S t)         {             s[currentIndex] = t;             currentIndex++;         }     }      I'm cheating a little bit cause I'm not using `T` in `Container<>`...but I think its a fair relationship anyhow.


Temporary variables vs line length requirements

I've been reading Martin Fowler's _Refactoring_. It is generally excellent but one of Fowler's recommendations seems to be causing a little trouble. Fowler recommends that you replace temporary variables with a query, so instead of this:               double getPrice() {         final int basePrice = _quantity * _itemPrice;         final double discountFactor;         if (basePrice > 1000) discountFactor = 0.95;         else discountFactor = 0.98;         return basePrice * discountFactor;     }      you pull out into a helper method:               double basePrice() {         return _quantity * _itemPrice;     }          double getPrice() {         final double discountFactor;         if (basePrice() > 1000) discountFactor = 0.95;         else discountFactor = 0.98;         return basePrice() * discountFactor;     }      In general I agree except that one reason I use temporary variables is when a line is too long. For example:               $host = 'https://api.twilio.com';     $uri = "$host/2010-04-01/Accounts/$accountSid/Usage/Records/AllTime";     $response = Api::makeRequest($uri);      If I tried inlining that, the line would go longer than 80 characters. Alternately I end up with chains of code, which are themselves not that much easier to read:               $params = MustacheOptions::build(self::flattenParams($bagcheck->getParams()));      What are some strategies for reconciling the two?


Are using <<include>> and <<extend>> relationship in this use-case diagram actually same?

I am trying to draw a UML use-case diagram to model requirements for a software project. The two requirements I have issue to model are:   1. `TravelAgent` creates a booking for a [old] client who is requesting a home.   2. When a new client wishes to make a booking, the `TravelAgent` register him/her to the system before doing the booking. I have two approaches to model these requirements:   1. Modeling the first use-case as a sub-procedure of the second use-case (Figure 1).    2. Extending the first use-case (Figure 2). Both approach imply that the first use-case could be perform independently, but when the second use-case is executed, the first one MUST be executed too. Are they actually same and both correct? P.S. As another question, since the `NewClient` converts to a `Client` after the registration, should I show the `NewClient` as subclass of `Client` or something? Figure 1 ![Figure 1](http://i.stack.imgur.com/hGSC4.png) Figure 2 ![Figure 2](http://i.stack.imgur.com/Lg39Q.png)


naming convention for different types of functions (use prefixes or suffixes?)

Does anyone have suggestions for naming conventions for different types of functions, particularly wrapper functions that need to connect to and disconnect from the database vs. wrapper functions that are passed a db link and don't need to connect and disconnect? The project on which I am working has these types of functions (among other types):   * wrapper functions that need to connect to the database, then call other functions, then disconnect   * wrapper functions that are passed a db link and call other functions (these functions don't need to connect to the db, that has already been done) Has anyone worked in a similar environment? Did you follow any naming conventions to distinguish between these wrapper functions that need to connect vs. being passed a db link, such as using a particular prefix or suffix?


Pattern for select case on object type (of interface)

I have read that doing a select case is often a code smell. There are cases however where an interface cannot solve my problem. For instance, I have a set of date filter objects (last 7 days, last year, ect.) that implement a IDateFilter interface. In another part of the code, I need to determine the type of date filter so that the chart properties can be set. I may want to use a different chart tick interval for instance depending on the date filter. The problem is I do not want to store this information in the date filter object as it is interface related and I do not want to couple the two. How could a select case be avoided in this instance? Other than using select case on gettype or creating some enumeration for all the types and then exposing the type and doing a select case on that, I do not see a clean way to do this? The decorator pattern comes to mind but even then I would still need a select case. Any ideas?               if (type = last 7 days)      set this property      else if (type = last year)      set this property to something different      I'm using asp net c# in case that makes a difference.


In voice recognition programs, what methods are generally used to separate voice from noise?

I think voice recognition is cool, and I might start studying it soon, but one big question that I've always wondered about is "How do the programmers separate the noise from the voice?" I mean, if you've watched "Her", you'll notice the main character uses voice commands commonly in quiet places, but today, voice recognition is mostly used in the car, amid a LOT of background noise, and even possibly background voices. I've used Siri in these loud situations, and I'm always impressed that the program still understands me over the noise. So, without going into detailed specifics, **I'd like to know what methods or concepts are generally used by programmers to do this.**


How to use Dependency Injection in conjunction with the Factory pattern

Consider a module that is responsible for parsing files of any given type. I am thinking of using the strategy pattern to tackle this problem as I have already explained over here. Please refer to the linked post before proceeding with this question. Consider class B that needs the contents of the product.xml file. This class will need to instantiate the appropriate concrete implementer of the Parser interface to parse the XML file. I can delegate the instantiation of the appropriate concrete implementer to a Factory such that class B "has-a" Factory. However, class B will then "depend" on a Factory for instantiating the concrete implementer. This means that the constructor or a setter method in class B will need to be passed the Factory. Therefore, the Factory and class B that needs to parse a file will be tightly coupled with each other. I understand that I may be completely wrong about whatever I have explained so far. I would like to know whether I can use dependency injection in a scenario where the dependency to be injected is a Factory and what would be the right way to implement this so I can take advantage of areas such as mocking the Factory in my unit tests.


Using testing branches in Git

We have someone (let's call him Ted) that is responsible for testing new features and bug fixes. We're using Git and GitHub. `master` should be/is always deployable and `development` is where we commit/merge new features or bug fixes, but only after they have been tested by Ted. The project is in PHP. I'd like the testing process to go like this:   1. A developer wants to work on a new feature (let's say the feature/bug #123 as Ted documented in the issue tracker), so he pulls `origin/development` to `development` on his local repository and creates a new branch (let's say `issue-123`) from there.   2. Once he's happy with his work, he commits and pushes his new branch to `origin`.   3. Ted connects to `test.ourproject.com/choose-branch` and sees a list of the branches on `origin` and chooses to switch on `issue-123` (it should be doable through the webpage). He then goes on `test.ourproject.com`, tests the hell out of the web application (he's really pitiless) and after some back and forth with the developer, he's happy with the feature.   4. Ted tells the developer that he can merge `issue-123` onto `development` on `origin`.   5. Rinse and repeat. For the third step, I could hack something that does the job (showing and switching branches from a specific page), but I feel that what I've described is a very common pattern. So my question is: **Is this a good / sustainable / maintainable workflow for branching?** Can you back up your answer by citing some examples of other projects following this workflow?


How should my AngularJS "wizard" be structured?

For brevity's sake, consider the following scenario: Part of my application is a wizard for bringing on new clients and it's a dynamic page. One step contains billing information, another step is setup information, etc. Because it's one page, in my mind I have one controller for the entire wizard, but that also means I have models and functions for each step in one **controllername.js** file in addition to using a bunch of ng-show directives to "show" steps. This doesn't feel quite right..have I overlooked something in the docs? Edit: To exapnd a bit, I feel like I'm violating the SRP and I feel dirty.


Rails - to use STI or not...that is the question

Six months ago, I asked a question about modeling data for my app, and received some advice pointing me towards STI (see Rails data model - best practices question for the details). I played around with it, got it working somewhat, and then got distracted and put the project on hiatus. I just started developing it again from scratch, with the benefit of 6 more months of programming/ROR experience, and I have once again hit this wall when it comes to modeling ingredients for my beer recipes. To give a quick summary, assume I have three ingredient types (malt, hops, and yeast) - each one shares a few attributes (name, price, vendor) but each also has attributes specific to that ingredient type. They are all related (they are all ingredients) but they do have different "behavior" (for example, grains are mashed and there would be logic to deal with that which wouldn't apply to hops/yeast, etc...) The ingredients are just different enough that I am contemplating just having three separate tables in the db...but what about controllers? Could I use a single Ingredients controller to manage the separate models? I've read about alternatives to STI (class table inheritance, and multi table inheritance) but all the solutions seem kludgy. Are there any alternatives that give me the convenience of STI (such as getting all ingredients, regardless of type, with a single table query) without the drawbacks (null fields, unwieldy tables when you keep adding subclasses and fields, etc) Sorry, I know this question is a bit fuzzy, but I feel like I can't find a clean solution and I'm now trying to figure out which method out there is the lesser evil. I'm sure others have dealt with this, and I'd love to hear the pros/cons of different solutions. Thanks!


Is writing dead code useful?

Do you find writing dead code useful? Some says "If you have 2 logic to do some operation then instead of making other logic code commented or removing code make it dead code as it will not affect the operation." Example:-               if(true){         // logic - 1     } else {         // logic - 2  // dead code     }      Is it true? * * * I usually do not write dead codes instead I just remove the second logic.


I need a true random number generator web service

I need a way to get non-deterministic random numbers on demand for my application. However i do not wish/have the capabilities to build the hardware myself, thus I'm looking for a web service which does just that. Basically I'm looking for a non-deterministic random number generator for my application. Apparently my requirements is that it definitely have to take the analog world as input. I've found one at http://random.org. It is good enough for me, However it has a cap of 200k bits (only 6250 32-bit integers!) on each IP per day. 6250 integers per day is definitely not enough for my app. So I'm searching for one that gives a better quota. I don't mind paying to use the service (but obviously a free one would be better). I'm not asking a useless question. In fact, applications like online Casinos will need many non-deterministic random numbers on demand. In my situation, my economics/investment game requires a true random number for good simulation. A pseudo-random number is just "not good" enough for a "good" simulation you see. Btw please do not tell me that a pseudo-random number generator would "be good enough" for my application. It apparently isn't good enough for my situation here, which is the first, last, and only reason why I'll need a non- deterministic random number generator. Anyway, I'm aware that any data sent through HTTP/HTTPS has risks of being eavesdropped. I'm perfectly fine with that. I need a true random number. After I've gotten the number, I'm happy. A spy can eavesdrop all he wants and I won't mind a bit.


Copyright and porting an application

I was wondering who owns the copyright of the sourcecode if you port an opensource project from one language to another. Is there a clear answer, or does it 'depend'? edit: I'm aware that a license choice is bound to the license the original sourcecode is released under, but I'm strictly wondering about the IP/copyright. As in, could I change copyright (c) 2011 original author to copyright (c) 2011 my name in all source files.


Difficulty implementing algorithms from abstract understanding

I've got decent programming experience for an undergraduate. I just started the study of algorithms. I read the description and saw visual examples that make perfect sense in my head. But when it comes time to write them down in code, I'm unable to implement them. I'm talking about basic algorithms like insertion sort. I'm starting to feel that I'm just stupid. I love programming and the study of algorithms actually really fascinates me even though I haven't really gone into too much depth. But not being able to implement simple algorithms has really stopped me from getting past the beginner stage. I'm starting with Intro to Algorithm books/tutorials so I don't see how I go down a level. Is there anything else one can do while in this situation?


Alternate approaches to creating custom forms in a web application

We are putting together some distribution software, selling about 150K SKU's. Some of our items have additional requirements in order to be sold that are dictated by our vendors. For instance one type of product that we sell are prosthetic feet. Some vendors require that we capture the users weight, activity level, and some other information. This is just one example there are many different kinds of products that might have this kind of requirement (a custom set of information collected from the customer to complete the sale). The direct approach is to just create custom forms for each requirement and create new forms when new requirements are needed. This works. It's straightforward, but its also a PIA. I would like to be able to kick this back to our product team that handles entering in new items rather than having to have them always come back to us. The project is a web application based on python (Turbogears). Not sure if this was relevant as the question is more general than this but put it here just in case. How would you approach this situation to minimize or remove your involvement with creating/adding these forms after site moves to production?


Is it bad practice to use short-circuit evaluation instead of an if clause?

I'm working on an installation script, and especially there I have many things that need to be checked and actions that only need to be performed in case of related outcomes. For example, a folder only needs to be created if it doesn't exist:               MyDesktopFolderPath := AddBackslash(ExpandConstant('{commondesktop}')) +                              'My Folder';     if not DirExists(MyDesktopFolderPath) then     begin       ForceDirectories(MyDesktopFolderPath); //Create full path     end;     if DirExists(MyDesktopFolderPath) then     begin       //Perform other actions      Instead of this, I could use (exploit?) short-circuit evaluation to make it more compact:               MyDesktopFolderPath := AddBackslash(ExpandConstant('{commondesktop}')) +                             'My Folder';     IsMyDesktopFolderExisting := DirExists(MyDesktopFolderPath) or                                    ForceDirectories(MyDesktopFolderPath);     if IsMyDesktopFolderExisting then     begin       //Perform other actions      This would work too, but I wonder if it is bad practice, mostly because it is less obvious that actions might be performed. Any opinions on that? **Edit:** As pointed out by Secure, the code is not completely equivalent, but the discussion topic still stands for other cases.


How many skills should I list on my resume, CV?

I'm a maintenance programmer, and I work with a rather large list of technologies on a monthly if not daily basis. For example I'm competent (obviously not expert) in the following languages:   * Java (including J2EE)   * C#   * VB6   * ASP Classic When I go to work on my resume, how many of the technologies should I list? It seems pointless, or even a problem, to list them all. I don't like reading vast lists of technologies when I read resumes. How many should I list, and how should I choose?


What is the advantage to using a factor of 1024 instead of 1000 for disk size units?

When considering the disk space of a storage medium, normally the computer or operating system will represent it in terms of powers of 1024 - a kilobyte is 1,024 bytes, a megabyte is 1,048,576 bytes, a gigabyte is 1,073,741,824 bytes, and so on. But I don't see any practical reason why this convention was adopted. Usually when disk size is represented in kilo-, mega-, or giga-bytes, it has to be converted into decimal first. In places where a power-of-two byte count actually matters (like the block size on a file system), the size is given in bytes anyway (e.g. 4096 bytes). Was it just a little aesthetic novelty that computer makers decided to adopt, but storage medium vendors decided to disregard? Whenever you buy a hard drive, there's always a disclaimer nowadays that says "One gigabyte means one billion bytes". It would feel like using the binary definition of "gigabyte" would artificially inflate the byte count of a device, making drive-makers have to pack 1.1 terabytes into a drive in order to have it show up as "1 TB", or to simply pack 1 terabyte in and have it show up as "931 GB" (and most of them do the latter). Some people have decided to use units like "KiB" or "MiB" in favour of "KB" and "MB" in order to distinguish the two. But is there any merit to the binary prefixes in the first place? There's probably a bit of old history I'm not aware of on this topic, and if there is, I'm looking for somebody to explain it. (Apologies if this is in the wrong place. I felt that a question on best practice might belong here, but I have faith that it will be migrated to the right place if it's incorrect.)


What strategy to follow while matching sql server datatypes in C# Code First approach while using Entity Framework

While matching SQL Server datatypes with C# Code First Approach in Entity Framework, what are specific points that we should keep in mind so that our C# datatype should match exactly our SQL Server datatype? Specifically, while we have to match SQL Server datatype to C# datatype, let's say for particular datatype hierarchyid, which exists in SQL Server but not in C#, how can we make it possible?


Inc/dec vs +=/-=

I'm looking at a programming language design decision that's difficult to make precisely because there seems to be no objective basis for choosing one option over the other. The question is, given that a language doesn't have a `++` operator, would the better choice for an increment operator be as in C:               a += 1     a += b      or as in some versions of Pascal:               inc a     inc a b      (And similarly with `-=` vs `dec` of course.) Considerations I can see for `inc`:   * Slightly shorter for the typical case where the delta is 1.   * Less familiar to most programmers.   * Eliminates the corresponding `*=` etc operators, which are much less commonly used. Is there anything I'm missing?


Why does Ubuntu have a 6-month release cycle?

Why has Ubuntu committed to a 6-month release cycle? Why should it have a fixed cycle at all? Doesn't that go against the "if it ain't broken don't fix it" saying?


What code smell best describes this code?

Suppose you have this code in a class:               private DataContext _context;          public Customer[] GetCustomers()      {         GetContext();              return _context.Customers.ToArray();     }          public Order[] GetOrders()      {         GetContext();              return _context.Customers.ToArray();     }          // For the sake of this example, a new DataContext is *required*      // for every public method call     private void GetContext()     {         if (_context != null)          {             _context.Dispose();         }              _context = new DataContext();     }      This code isn't thread-safe - if two calls to `GetOrders`/`GetCustomers` are made at the same time from different threads, they may end up using the same context, or the context could be disposed while being used. Even if this bug didn't exist, however, it still "smells" like bad code. A much better design would be for `GetContext` to always return a new instance of `DataContext` and to get rid of the private field, and to dispose of the instance when done. Changing from an inappropriate private field to a local variable feels like a better solution. I've looked over the code smell lists and can't find one that describes this. In the past I've thought of it as temporal coupling, but the Wikipedia description suggests that's not the term: > _Temporal coupling_   >  When two actions are bundled together into one module just because they > happen to occur at the same time. This page discusses temporal coupling, but the example is the public API of a class, while my question is about the internal design. Does this smell have a name? Or is it simply "buggy code"?


Protect freelance work

I have developed some PHP and HTML code for a freelance project, I want to make my contractor able to use my code commercially, since they will sell my project to their own client (an enterprise), but I want to disallow them from recycling my code for further projects, could this be achieved by some GNU license? Also I want to be able to use my code for another clients I could have (since I'm freelance), and sell them projects with some snippets of my today's created code, 'cause I could use some of this libraries.


Query language for JSON

I have a server which is returning very big JSON message and my client application is only dependent on part of this response. Client application needs to check if "xyz" property exist in JSON message and depending on the result run a specific usecase. For this requirement converting the whole JSON message to object sounds bit expensive to me and hence this question. Is there a standard JSON query language like one we have for XML? If yes what are best know implementation of this query language in java. FYI : Changing or adding new service on server side is not an option.


What is the integration architecture used by Github for its web interface?

I am amazed by the way Github integrates with different systems like Travis. They are separate companies, but yet Travis builds blend seamlessly everywhere in the Github interface. Yes, i am asking _mainly_ about integration on the user interface level, there is enough electronic ink around about service integration. Usually web interfaces get blended via embeds, like for Disqus. On Github however, seems like the interface parts related to Travis are rendered on the server side. Do they enforce a markup structure, or specific style sheets, or do they require to describe the interfaces with a domain specific language?


Custom Video Player

I have a custom file type **.mft** which is basically a zip that has video inside (mpg,mp4,etc) that is encrypted/protected. My ideia is to create a custom video player which will read those **.mft** files, for a private group of users (users provide user and password), and the custom player will not allow to save the video, so that no one can re-share it, and can only view it. I saw that VLC has this library http://vlcdotnet.codeplex.com/releases/view/121099, so my player would use it. My question is : Is it really possible to block users from not saving the video? I don't think so, because there are several software to record desktop activity. What do you think?


What is an effective way to familiarize yourself with a new application in a new language (and still look productive at a new job)?

I started a new job working on an application I'm vaguely familar with, and it's in Perl! I come from a PHP and Java background, so while I understand the basics, there are lot of nuances in Perl that make it troublesome. _updated_ < Im supposed to be a UI developer, but the smallness of the office requires me to learn and do a lot more than just javascript. So that was slightly unexpected in some aspects and I'm just thinking about what approach to take with this > / _updated_ So far I've been sifting through the code to understand what each part does, printed out copies of code and try to lookup APIs I'm not familiar with, and so I dunno how effective this process is -- I feel like it's gonna take some time -- and I dont want my new employers to feel like I'm not being productive. Anyone have some ideas or approaches for this kind of situation? I read some of the questions about learning new languages, but I'm curious to see if anyone's had experience with this with Perl. **Thanks you guys for all the awesome feedback!**


Is it a Single Responsibility Principle violation?

I'm designing an OO graph library and at the moment I'm trying to figure out the design for a `GraphEdge` class. I've added setters and getters for it's nodes, direction and weight. This seemes perfectly reasonable. Then I've started working on the `Graph` class and I've come to the need of knowing if the particular edge is adjacent to the particular node. And now I doubt if I should add a `isAdjacentTo(Node)` method to the `GraphEdge` class or I should create a `GraphUtil` class(*) and add static `edgeIsAdjacentToNode(Edge,Node)` method to it. On the one hand, I can not see any additional reasons for changing `GraphEdge` if I stick to the first option. On the other hand, this seems to me like kind of second responsibility added to the class. Also if I stick to the first option this will probably violate the `Open-Close Principle`. The `GraphEdge` is not closed for changes, since later I will need to add `linksNodes(Node,Node)` method to it and maybe some others later. The questions are:   * Does adding `isAdjacentTo(Node)` method to the `GraphEdge` class violates the SRP?   * Why? (*) I stick to pure OO style with no free functions


How can NodeJS be "non-blocking"?

I'm learning NodeJS and just wanted to clarify something. In several introductory tutorials and books so far, very early on they've described Node's "non-blocking" architecture - or rather that it's possible (and recommended, the entire point) to code in a non-blocking manner. So for example, this example was given in a book I'm reading of an asynchronous way to get data from a database.               http.createServer(function (req, res) {       database.getInformation(function (data) {           res.writeHead(200);           res.end(data);       });     });      What happens (as I understand it) is Node makes the call to the database, then continues processing whatever may be next on the call stack. When the database request is complete, the data variable in the anonymous callback function will be populated and that function added to the call stack (and subsequently executed when Node gets to it). My question is, _what exactly is **processing** the database request?_ Surely Node has to block whilst it does that? What is taking care of the database request? Or if Node is waiting on an asynchronous HTTP GET request to an external resource, what is taking care of that request that allows Node to continue processing the call stack and be "non-blocking"?


How can/should a microsoft dev approach an android project?

I am a dev who mostly uses the Microsoft stack (C#/Silverlight/WPF/ASP MVC/.net framework) Although I am adding HTML5/CSS3/shivs/jQuery when using ASP.net MVC. I have the opportunity to do some Android mobile phone work but am unsure if/how my current skillset would apply. Anyone out there made this crossover transition? What new skillset is involved? What IDE development software would I need? # UPDATE: Thanks everyone for pointing me in a good directions! As a result, I took a couple of hours to check out Eclipse & the Android sdk plugin. So far, I find many comforting similarities between android and the MS stack that I’m used to. ## These are my discoveries (maybe help some noobs like me!): \--The Eclipse+AndroidSDK development environment is complete, understandable and is very much like visual studio. \--Java is very “c#-like”. \--Android separates the code (.java) from the layout markup (.xml). \--Android’s layout markup is very much like silverlight. \--Android has built-in basic controls with basic styling. \--Android has some really useful built-in widgets! (I’m guessing it accepts custom add-in widgets also?) \--Android Activities are like c# classes: methods/local properties + class- wide properties. Create instance & use them. \--Activity lifecycles are understandable: Overrides -- onCreate(), onStart(), onResume(), onStop(), onRestart(), onDestroy(). \--Android connects user events with event-handlers through the use of Listeners. \--Android uses a lot of “magic string” references in both .xml and .java (Oh- noooooo!) \--Found a great YouTube series “android tutorial & lessons” by CornBoyzAndroid (more than 30 informative episodes!) \--Android does try/catch/finally for error catching similarly to c# ## I’m still exploring, and I’m sure I’ll find answers to my further questions, like: \--How does android deal with remote and local data? (database access, local storage, Linq). \--How does android do asynchronous or long-lasting work? (callbacks, polling, sockets). \--I see android exposes threading…possibly useful, but I need more info. \--Does android have frameworks like MVVM or MVC and what about unit testing? Again, thanks everyone for your help!!! -- Mark


How to keep user's guide in lockstep with branches for a non-developer?

Our current user's guide is built using `asciidoc`. The documentation is managed by a non-technical person, but we keep the source text files as well as generated HTML in source control. Issues arise when they are making doc updates for version `x.z` in the `x.y` branch. Typically, one of the developers will update their environment, but they can be very forgetful. I know there has to be a better way to do this. How do you manage users' guides in a versioned manner without actually depending on non-technical users to learn VCS?


How do I choose a package format for Linux software distribution?

We have a Java-based application that, to date, we've been distributing as a tarball with instructions for deploying. It's mostly self-contained so deployment is fairly straight-forward:   1. Untar on the disk you'd like it to live on;   2. Make sure Java is in your path and a suitable distro and version;   3. Verify ownership and group on all the files   4. Start up the server processes with our start script If the user wants to get in to start-on-boot stuff with SysV we have some written instructions and a template init file for it in our tarball. We'd like to make this installation process a little more seamless; take care of the permissions and the init script deployment. We're also going to start bundling our own JRE with the application so that we're mostly free of external dependencies. The question we're faced with now is: how do we pick a package format for distribution? Is RPM the standard? Can all package management tools deal with it now? Our clients primarily run RHEL and CentOS, but we do have some using SuSE and even Debian. If we can pick a distro-agnostic format we'd prefer that. What about a self-extracting shell script? Something akin to how Java is distributed. If we're dependency-free would the self-extracting script be sufficient? What features or conveniences would we lose out on going with the script versus a proper package format meant for use by a package manager?


Just one class - Java

I've written a program in Java, it's only fairly small and I started programming and ended up just building one big class with everything inside it. The program works fine and exactly how I wanted it to, however, when writing up the documentation I've realized that it doesn't follow any sort of architecture pattern like MVC or 3-tier and seems most like a monolithic system. Is this likely to be detrimental? Maintainability is fairly important but the code is well commented and could be extended fairly easily if somebody wanted to add an extra algorithm for example. I'm just wondering if this is bad practice and whether it will be looked down upon? It is for part of a project so it will get assessed, I do have time to split it up into classes but it could be unnecessary work I feel and I wouldn't really know how to split it up. When I say a big class, its all relative but its about 1750 lines of code. I guess the main question is; it works as it is so is there any need to split it up into classes? Are monolithic systems particularly bad (not sure if it even is a monolithic system!)?


Efficient coding in Visual Studio (or another IDE), with touch typing

Moving the cursor to another position in code is one of the most frequent actions when coding. I don't write my programs from the beginning to the end, like a letter. However, moving the cursor requires me to move my right hand to the key arrows or to the mouse, which feels like an interruption to my writing rhythm, since I'm using touch typing. I want my hands to rest on the keyboard. It's difficult to explain what I mean, but I think every coder using touch typing knows what I mean. I tried many things, like defining some shortcuts as surrogate arrow keys (Shift+Alt+J, K, L, I), or buying a keyboard with a Trackpoint, Trackpad, or Trackball on it, but I have not yet found a satisfying solution to the problem. What is the best solution you know of, regardless of which IDE you use? **Edit** : Thank you for your answers. I am using a lot of shortkeys, but I think using a Vim plugin in Visual Studio would interfere too much with the shortkeys I am used to. Also, I have a keyboard with a built-in mouse, but I'm still looking for a better solution.


Creating a shared library that might be used with desktop applications and web projects

I have been involved in a number of MVC.NET and c# desktop projects in our company over the last year or so while also managing to kept my nose poked into other projects (in a read-only learning capacity of course). From this I've noticed that across the various projects and teams there is a-lot of functionality that has been well designed against good interfaces and abstractions. Because we tend to like our own work at times, I noticed a couple of projects had the exact same class, method copied into it as it had obviously worked on one and so was easily moved to a new project (probably by the same developer who originally wrote it) I mentioned this fact in one of our programmer meetings we have occasionally and suggested we pull some of this functionality into a core company library that we can build up over time and use across multiple projects. Everyone agreed and I started looking into this possibility. However, I've come across a stumbling block pretty early on. Our team primarily focuses on MVC at the moment and we have projects mainly in 2.0 but are starting to branch to 3.0. We also have a number of desktop applications that might benefit from some shared classes and basic helper methods. Initially when creating this DLL I included some shared classes that could be used across any project type (Web, Client etc) but then I started looking at adding some shared modules that would be useful in our MVC applications only. However this meant I had to include a reference to some Microsoft Web DLL's in order to leverage some of the classes I was creating (at this stage MVC 2.0). Now my issue is that we have a shared DLL that has references to web specific libraries that could also possibly be used in a client application. Not only that, our DLL referenced initially MVC 2.0 and we will eventually move onto MVC 3.0 for all projects. But alot of the classes in this library I expect to still be relevant to MVC 3 etc Our code within this DLL is separated into it's own namespaces such as:   * CompanyDLL.Primitives   * CompanyDLL.Web.Mvc   * CompanyDLL.Helpers etc etc So, my questions are:   1. Is it OK to do a shared library like this, or if we have web specific features in it should we create a separate web DLL only targeted at a specific framework or MVC version?   2. If it's OK, what kind of issues might we face when using the library that references MVC 2 in a MVC 3 project for example. I would be thinking that we might run into some sort of compatibility issue, or even issues where the developers using the library doesn't realize they need MVC 2.0 libraries. They might only want to use some of the generic classes etc The concept seemed like a good idea at the time, but I'm starting to think maybe it's not really a practical solution. But the number of times I've seen copied classes and methods across projects because they are **proven** tested code is a bit unnerving to be perfectly honest! **UPDATED** : Further to Bernards answer which I have taken on board and seems good advice. However I want to create some shared classes that will probably be useful in both MVC 2 and MVC 3 projects. However my shared assembly will have to reference one of the MVC frameworks in order for me to create my shared classes in the first place. So further to expand on my Q2 above.   1. If I wanted a MVC 3 web solution would I have to have a shared CompanyDLL.Web.Mvc3 project that would then specifically be referencing MVC 3? Would that mean copying over all the code from my CompanyDLL.Web.Mvc2 solution to this new Mvc3 shared project? It seems I'm missing some **fundamental** designing skills in the creation of shared assemblies and building and referencing against different framework versions. Or it might just be as simple as we suck it up and create a _CompanyDLL.Web.Mvc2_ , _CompanyDLL.Web.Mvc3_ , _CompanyDLL.Web.Mvc4_ etc etc libraries...


Is this common amongst many languages?

In C++, the integer variable `bar` evaluates to 1 in this code               int foo = 0;     int bar = ++foo;      and 0 in this code               int foo = 0;     int bar = foo++;      Is this behavior prevalent in most popular languages?


A new mission statement for my school's algorithms class

The teacher at Eastern Washington University that is now teaching the algorithms course is new to eastern and as a result the course has changed drastically mostly in the right direction. That being said I feel that the class could use a more specific, and industry oriented (since that is where most students will go, though suggestions for an academia oriented class are also welcome) direction, having only worked in industry for 2 years I would like the community's (a wider and much more collectively experienced and in the end plausibly more credible) opinion on the quality of this as a statement for the purpose an algorithms class, and if I am completely off target your suggestion for the purpose of a required Jr. level Algorithms class that is standalone (so no other classes focusing specifically on algorithms are required). The statement is as follows: > The purpose of the algorithms class is to do three things: > >   * Primarily, to teach how to learn, do basic analysis, and implement a > given algorithm found outside of the class. >   * Secondly, to teach the student how to model a problem in their mind so > that they can find a an existing algorithm or have a direction to start the > development of a new algorithm. >   * Third, to overview a variety of algorithms that exist and to deeply > understand and analyze one algorithm in each of the basic algorithmic design > strategies: Divide and Conquer, Reduce and Conquer, Transform and Conquer, > Greedy, Brute Force, Iterative Improvement and Dynamic Programming. > The Question in short is: do you agree with this statement of the purpose of an algorithms course, so that it would be useful in the real world, if not what would you suggest?


Programmer / Developer Personal Organization

What tools / methodologies / strategies do you use to keep organized in doing your work as a developer? Can you provide details?


Benefits/Pitfalls of include

Do web pages load faster or load slower when all headers, footers and basic functions are placed in external files and called using the statements below? Are there any other benefits to separating such content?               <?php include("includes/functions.php"); ?>     <?php include("includes/header.php"); ?>                     <?php require_once("includes/functions.php"); ?>


Are there any "enterprise ready" functional programming languages?

By "enterprise ready" I am referring to availability of tools: dependency management, build management, message servers, databases, application platforms and servers, and are secure and scale well? For example, is there a lisp (or ML) alternative to j2ee? Please exclude FP's ported to JVM or .NET CLR. EDIT: I know that one could use an FP jvm port i.e. clojure or F# on .NET CLR however I am curious to know if it is possible to develop a purely functional application for the enterprise without the JVM or CLR?


Bachelor degree in Software engineering in distance (online) in Europe

Currently I wish to expand my professional skills with Bachelor degree. However, I am not able to study full time abroad, but looking for University where I could study in distance (online from home), coming just several times in a semester to the University to pass exams, complete papers and so on. I am **looking for Software Engineering or Computer Science programs**. **Fully in distance** (online) **in English in Europe** , because I am living in Central Europe. Any suggestions?


How are Rust Traits different from Go Interfaces?

I am relatively familiar with Go, having written a number of small programs in it. Rust, of course, I am less familiar with but keeping an eye on. Having recently read http://yager.io/programming/go.html, I thought I'd personally examine the two ways Generics are handled because the article seemed to unfairly criticize Go when, in practice, there wasn't much that Interfaces couldn't accomplish elegantly. I kept hearing the hype about how powerful Rust's Traits were and nothing but criticism from people about Go. Having some experience in Go, I wondered how true it was and what the differences ultimately were. What I found was that Traits and Interfaces are pretty similar! Ultimately, I'm not sure if I'm missing something, so here is a quick educational rundown of their similarities so you can tell me what I missed! Now, let's take a look at Go Interfaces from their documentation: > Interfaces in Go provide a way to specify the behavior of an object: if > something can do this, then it can be used here. By far the most common interface is `Stringer` which returns a string representing the object.               type Stringer interface {         String() string     }      So, any object that has `String()` defined on it is a `Stringer` object. This can be used in type signatures such that `func (s Stringer) print()` takes almost all objects and prints them. We also have `interface{}` which takes any object. We must then determine the type at runtime through reflection. * * * Now, let's take a look at Rust Traits from their documentation: > At its simplest, a trait is a set of zero or more method signatures. For > example, we could declare the trait Printable for things that can be printed > to the console, with a single method signature:               trait Printable {         fn print(&self);     }      This immediately looks quite similar to our Go Interfaces. The only difference I see is that we define 'Implementations' of Traits rather than just defining the methods. So, we do               impl Printable for int {         fn print(&self) { println!("{}", *self) }     }      instead of               fn print(a: int) { ... }      **Bonus Question:** What happens in Rust if you define a function that implements a trait but you don't use `impl`? It just doesn't work? Unlike Go's Interfaces, Rust's type system has type parameters which let you do proper generics and things like `interface{}` while the compiler and the runtime actually know the type. For example,               trait Seq<T> {         fn length(&self) -> uint;     }      works on any type and the compiler _knows_ that the type of the Sequence elements at compile time rather than using reflection. * * * Now, the actual question: am I missing any differences here? Are they really _that_ similar? Is there not some more fundamental difference that I'm missing here? (In usage. Implementation details are interesting, but ultimately not important if they function the same.) Besides syntactic differences, the actual differences I see are:   1. Go has automatic method dispatch vs. Rust requires(?) `impl`s to implement a Trait      * Elegant vs. Explicit   2. Rust has type parameters which allow for proper generics without reflection.      * Go really has no response here. This is the only thing that is significantly more powerful and it's ultimately just a replacement for copying and pasting methods with different type signatures. Are these the only non-trivial differences? If so, it would appear Go's Interface/Type system is, in practice, not as weak as perceived.


Do serialization functions belong in a model or a controller?

I'm developing an application where:   * Models keep data as a multi-dimensional array, which are saved as-is to a MongoDB database. The model is used to provide methods to manipulate the data, and outside of those methods, the data properties are read-only.    * The model factory instantiates each object in a standardized way and allows shorthand "queries" to look up a database entry and instantiate an object with it at once.   * The "view" is Javascript, and all it does it ask the controller for certain things, and the controller responds over HTTP with JSON.    * The controller uses the model factory to instantiate model objects and do whatever the view is requesting, if possible. It always returns JSON. Generating that JSON is currently in a "helper" class, which I'm trying to eliminate. The serialization of MongoDB data involves converting MongoDates, MongoIDs, and other Mongo objects to strings. It's needed in the controller to output these to the browser as strings - for the most part, the controller knows how to output data to the view. But in some cases, it's needed in the model to tabulate multi-dimensional array data into a list before the controller gives it to the browser. The controller doesn't know enough about the model to do that tabulation. Is a helper class unavoidable here? Or should 100% of serialization take place inside of the model? Should I leave the serialization function in the abstract model and use it from the controller with a static call?


Highly available web service design?

I was wondering if any design gurus out there could help me understand how large web companies design their services to be highly available. The scenario I'm thinking of is:   1. Client A connects to Service A   2. Client A sends N requests   3. On the N+1 request, Service A blows up   4. Client A reconnects to Service B   5. Service B services requests N+1 onwards The only design I could think of was using a "metadata"/"discovery" service that the Client could be statically aware of. This service would give information on the best available Service, which the Client would then connect to and begin his requests, and re-query the "metadata" service when he realizes Service A went down. The application service is now highly available, but... ...the glaring problem is that the "metadata"/"discovery" service is static, will come under high load, and is not highly available, which kind of defeats the whole purpose. I suppose I could throw a lot of hardware under this service, but that's not a very good solution. How should I go to design a real highly available web service?


Would adding an @beta doc-comment tag be useful?

When a function has reached the end of its life, we add a `@deprecated` tag into its doc-comment to notify other developers that they should stop using this function, and then a couple years later it's removed. I was just thinking about an `@beta` tag to signify this method is brand new and hasn't been tested in a variety of use-cases yet. You might be thinking "you can write use-cases to ensure its correctness!" Of course you can, but its the API that concerns me, and how it behaves in edge- cases. Sometimes these decisions are not obvious until you have tried out the function in a variety of situations. Sometimes new parameters need to be added to cover more use-cases. Sometimes re-ordering them makes sense if you find that an argument is actually optional and needs to be moved to the end (or vice versa). By adding the `@beta` tag, you are warning other developers that the API of this method might change yet, and they should use it with extreme caution. This gives you more granular control over your API instead of making the entire project 'beta'. To get the most use out of this, however, IDEs and documentation-generators would need to pick up on this tag. What do you guys think? Could you see this as being useful, is it a waste of time, or do you have other ways of dealing with this? In the past, I have made such methods 'private' where possible, or prefixed them with an underscore.


Code repetition vs multi responsible method

I try to follow the Single Responsibility Principle (SRP) and also to omit Code Repetitions. However there are often places where there are code repetitions that are nothing more than code blocks of invocations that are resistant to extracting them into at least meaningfull named method:               DoAction1();     DoAction2();          if (value)         DoAction3();          DoAction4();      What is the best way to extract such code into a method and how to name it?


Guidance on android type app to connect to sql-server

Excuse my ignorance but we've got an application that we'd like to sample out on a mobile app The app is a C#/asp.net application connected to our sql server database. If we are going to write an android application for this app how exactly does one connect to the sql server instance? I've tried to find many articles, some say via a web service others say jdbc drivers, etc. I don't know too much about this because we've never done mobile development. If we were to write up a web service, is the web service simply responsible for connecting to the database layer and fetching records? Any examples would be greatly appreciated.


How do we make unit tests run fast?

We have reached the point in our project where we have almost a thousand tests and people have stopped bothering with running them before doing a check in because it takes so long. At best they run the tests that are relevant to the piece of code that they changed and at worst they simply check it in without testing. I believe this problem is due to the fact that the solution has grown to 120 projects (we usually do much smaller projects and this is only the second time we do TDD properly) and the build + test time has grown to about two-three minutes on the lesser machines. How do we lower the run time of the tests? Are there techniques? Faking more? Faking less? Maybe the bigger integration tests shouldn't run automatically when running all the tests? **Edit:** as a response to several of the answers, we already use CI and a build server, this is how i know the tests fail. The problem (actually a symptom) is we keep getting messages about failed builds. Running partial tests is something that most people do but not all. and regarding the tests, they are actually pretty well made, they use fakes for everything and there is no IO at all.


Why can't I implement an interface which has a bounded generic type in this code in java?

I have the following interfaces:               public interface Successorable<E> extends Comparable<E>          E suc();     }      and               interface IInterval <E extends Successorable<E>> {         E min();         E max();     }      I'm trying to implement IInterval by doing:               public class Interval<E> implements IInterval<E> {      ....      However eclipse complains that the type E is not a valid substitute for the bounded parameter `<E extends Successorable<E>>` of the type `IInterval<E>`. What am I doing wrong? Thanks!