What are the drawbacks of sending XML to browsers and let them apply XSLT?

**Context** Working as a freelance developer, I often made websites completely based on XSLT. In other words, on _every_ request, an XML file is generated, containing everything we need to know about the page content: the name of the user currently logged in, the top menu entries, if this menu is dynamic/configurable, the text to display in a specific area of the page, etc. Then XSL process (caches, etc.) it to HTML/XHTML page to send to the browser. It has a good point to make it easier to create small-scale websites, especially with PHP. It is a sort of template engine, but which I prefer to other template engines because it's much more powerful than most of template engines, and because I know it better and like it. It is also possible, when need, to give an access to raw XML data on demand for an automated access, without the need to create separate APIs. Of course, it will fail completely on any medium-scale or large-scale website, since, even with good caching techniques, XSL still degrades overall website performance and requires more CPU serverside. **Question** Modern browsers have the ability to take an XML file and to transform it with an associated XSL file declared in XML like `<?xml-stylesheet href="demo.xslt" type="text/xsl"?>`. Firefox 3 can do it. Internet Explorer 8 can do it too. It means that it is possible to migrate XSL processing from the server to the client side for 50% of users (according on browser statistics on several websites where I may want to implement this). It means that those 50% of users will receive only the XML file at each request, thus reducing their and server's bandwidth (XML file being much shorter than its processed HTML analog), and reducing server's CPU usage. What are the drawbacks of this technique? I thought about several ones, but it doesn't apply in this situation:   * Difficult implementation and the need to choose, based on the browser request, when to send raw XML and when to transform it to HTML instead. Obviously, the system will not be much more difficult then the actual one. The only change to make is to add XSL file link to every XML, and to add a browser check.   * More IO and bandwidth usage, since the XSLT file will be downloaded by the browsers, instead of being cached by the server. I don't think it will be a problem, since XSLT file will be cached by the browsers (like images, or CSS, or JavaScript files are cached actually).   * Possibly some problems on client side, like maybe problems when saving a page in some browsers.   * Difficulty to debug code: it is impossible to obtain an HTML source the browser is actually using, since the only displayed source is the downloaded XML. On the other hand, I rarely go look at HTML code on client side, and in most cases, it is unusable directly (whitespace being removed).


"A", "an", and "the" in method and function names: What's your take?

I'm sure many of us have seen method names like this at one point or another:   * `UploadTheFileToTheServerPlease`   * `CreateATemporaryFile`   * `WriteTheRecordToTheDatabase`   * `ResetTheSystemClock` That is, method names that are also grammatically-correct English sentences, and include extra words purely to make them read like prose. Personally, I'm not a huge fan of such "literal" method names, and prefer to be succint, while still being as clear as possible. To me, words like "a", "an", and "the" just look plain awkward in method names, and it makes method names needlessly long without really adding anything useful. I would prefer the following method names for the previous examples:   * `UploadFileToServer`   * `CreateTemporaryFile`   * `WriteOutRecord`   * `ResetSystemClock` In my experience, this is far more common than the other approach of writing out the lengthier names, but I have seen both styles and was curious to see what other people's thoughts were on these two approaches. So, are you in the "method names that read like prose" camp or the "method names that say what I mean but read out loud like a bad foreign-language-to- English translation" camp?


What's so bad about the DOM?

I keep hearing people (Crockford in particular) saying the DOM is a terrible API, but not really justifying this statement. Apart from cross-browser inconsistencies, what are some reasons why the DOM is considered to be so bad?


distributed computing with remote hetrogenous machines

The way i am doing it now is using boost::asio TCP sockets handling everything manually with a main server that orchestrates the processes between the available machines, but the number of machines is increasing and when i need communication between specific machines i have to do it through the server and the number of machines is just to much to be handled by one server, so i am thinking about Open MPI. However i have 3 problems   1. the machines are Heterogeneous.   2. the number of machines available can be for example 50 at a time and also can be only 10 and sometimes it gets to 300 which is too much for my server to handle and there is always tons of data to process, and i can seem to utilize more than ~70 connections at the same time.   3. most of the machines are remote and some of them share the same network. if i want to scale things with my current design i would get ugly trees with multiple layers, i don't have the money to hire network experts/programmers for a non profit project, but i am fairly good at grasping new concepts, so how would you go around this? and with the above problems is OpenMPI for me? In other words, i am looking for a better design than mine, and i have no problem implementing it from scratch no matter how long it takes and i will be supporting linux only at the start because i figured that native code has a measurable advantage, i would like to hear your ideas.


Is it correct to require end-users to clear their cookies?

Is it any indications of poor programming if the support staff for a given product requires you to clear the cookies in order to troubleshoot issues with their web-site? As a point of example, if you're trying to activate a new SIM on a tablet, and the carrier's activation web-site is giving you an error message that their web-site is down, even though there is no problem with actually accessing their web-server, which responds with the our-website-is-down page just fine. Subsequently, the support staff instructs the user to try clearing the cookies (even though this activation web-site is not know to have been accessed prior to the error message taking place).


Where can I find Turbo Pascal dialect description/reference? Is it still availiable in some place? I'm looking for the famous Turbo Pascal dialect description/reference(yes, the one from 80s/90s time) but I'm not having luck with google.


Dangers when implementing features as plugins

_What kind of problems have you encountered when building plugin interfaces for your application? And how did you resolve them?_ **Background** I want to refactor an application so that various features can be moved into plugins, allowing them to be easily added and removed in future. I hope this will be a neater system than scattering `if (FeatureX_is_enabled)` branches throughout the code. (I may be wrong!) I believe I will need to define interfaces for each part of the system into which a features may plug in. I would like to benefit from your experience if you have already undertaken this kind of project. Perhaps you have endured mistaken designs, and can advise what _not_ to do. Perhaps you can recommend patterns or architectures that can make such a system more manageable. **Concerns** A few issues already spring to mind:   * I will need to provide some power to plugins so that they can get their job done. If I pass too little control, new plugins may be **too restricted** to do what they need (e.g. some Google Chrome extension authors complain about the inability to modify the core interface). However if I pass too much control, irresponsible plugins will have the power to break the whole application (e.g. Mozilla Firefox extensions).   * Some plugins may need to run in a **different order** on different events. I could register event handlers with a priority, e.g. 1-100, so that plugins can hook themselves into the appropriate order. Or I could just create `post_` and `pre_` events and hope nothing more finely grained is needed.   * If two plugins **depend** on another plugin to be available first then the plugin architecture will need some kind of dependency (and naming) system.   * Related, some plugins will need to know when other plugins are **present** , and perhaps even make calls into each other to handle edge cases.   * There may be difficulties **maintaining the state** of the application if plugins are enabled and disabled at **runtime**. (Chrome seems to handle this well, but many applications require a restart.)   * This kind of architecture will **obfusticate the flow** of execution (in exchange for keeping additional behaviour out of the core code). I will need to write neat interfaces so that unexpected behaviour is minimised.   * Sometimes the monolothic `if (FeatureX_is_enabled)` approach might be a better way to handle the situation than breaking out to a plugin, but I don't know how to recognise such situations. _It is likely there are other concerns I have not considered, so I would love to hear what you have had to deal with!_ **Related** Related question: How to turn on/off code modules? Related library: Bemson's curious Flow library for Javascript seems to provide various features to help adding and removing features to/from a program at runtime, but I have trouble getting my head around it!


When conducting a code review, should the focus be on the completeness of the requirement?

Given that the reviewer is not part of the project, but was assigned to review because he has done some coding for the application being updated/enhanced. Is it the reviewer's job to ensure that the requirement is complete and correct? Or is this the QA and business tester's responsibility? If the developer and the reviewer misses a requirement which is discovered in UAT, is the reviewer also at fault (probably to a lesser degree)?


Is input validation necessary?

This is a very naive question about input validation in general. I'm a MATLAB user (1.5 years old) and I learned about input validation techniques such as "parse" and "validatestring". In fact, MATLAB built-in functions are full of those validations and parsers. So, I naturally thought this is the professional way of code development. With these techniques, you can be sure of data format of input variables. Otherwise your codes will reject the inputs and return an error. However, some people argue that if there is a problem in input variable, codes will cause errors and stop. You'll notice the problem anyway, and then what's the point of those complicated validations? Given that codes for validation itself take some efforts and time, often with quite complicated flow controls, I had to admit this opinion has got a point. With massive input validations, readability of codes may be compromised.


How to manage a single branch

I read the _Continuous Delivery: Reliable Software Releases through Build, Test, and Deployment Automation_ book by **Jez Humble** and **David Farley**. The part that throw me off balance the most was their insistence on using a single branch. Thinking about it and what they are preaching, it does make sense. But the question is, how to achieve it?. At my company we are working on C# with TFS as our source control. And the following ideas came to my mind about how to achieve the idea of doing changes that you don't want to release yet, but you want to keep inside the vcs tool:   * Injections to be able to select the class that you want to use. So you can rewrite some functionality without affecting code that needs to be released.   * Related, an IoC container to make the above easy to achieve. So you can select at compilation (or even runtime) the ones that you want to use.   * Decorator pattern to add functionality in a very simple manner (which is just applying the other two above) At another similar question they talk about the **Release Line** from _Software Configuration Management Patterns_ (which I still have to ready). But the example that they are using deals with tags and creation of branches from them, which doesn't seem to be the same thing as what Humble and Farley talk about.   1. Do the techniques that I have described sound right for achieving a single branch strategy?   2. Is there anything else that could be done to manage having your code on a single branch?


What are the advantages of a client/server architecture in webapplications as opposed to a server generated frontend application

In our company, we need to build a web interface onto an embedded Linux platform. I kind of see 2 options: You use a technology where the HTML and JavaScript is generated on the server side (Think JSP, Grails, but is is something that is using C++ and generates HTML/JavaScript) or you create a HTML5 'client' application that talks to a JSON or XML generating backend. I have the feeling that web applications currently tend to go with the latter, but what are the advantages of doing so (The developers on the project choose the former, mainly based on the fact that they know C++ much better then HTML and Javascript)


How should I react to diminishing application performance?

Sometimes it comes to me that the biggest challenge for an engineer when he find his application getting worse in performance is lack of enough information. Imagine that you go through the weekly performance report from your application's access log, and find you get much lower response times from July. All you can do is to pray for it not to get worse the next time.


Junior developer support

I am a junior developer in my first work experience after university. I joined the company as PHP developer but I ended up developing using C# and ASP.NET. Right from the start I did not receive any training in C# and I was assigned with ASP projects with quite tight deadlines scoped by Senior developers. The few project hand overs I had from other developers were brief and it looked like I had to discover the system myself, in really short time. This is my first job as web developer and I wonder whether it is normal not to have a kind of mentor to show me how to do things, especially because I am completely new to the technology. Also, do you have idea how to tackle this? As you can imagine, it gets really frustrating.


How to refactor "nested" view classes to avoid deep method calls?

Lets say I'm displaying a bunch of data (`model`) using a `View` class for rendering. However, a lot of the data has sub-data (`model`s) complicated enough to require separate rendering classes. In my design, a `View` class has a `model` which it is rendering, and has many children `Views` which display the sub-data. In some cases, A `View`, while containing a model, may not have anything to render and serves more as a wrapper for it children. However, if you have very complex data and your sub-views have subviews,this design results in deeply nested method calls. Some methods are simply passing information to view classes who may do nothing with it except pass it to their children. This seems inefficient, so I figured there might to be a pattern or something that solves this more elegantly.


Level of detail in System Requirements

I've read in multiple places that the requirements must not be influenced by solution and must not contain solution. So in the below example , please can you help in letting me which is correct - Application A is interacting with Application B to install a new service / change the service type and disconnect a service. There 3 different service types 1,2 and 3. Application B does not support changing service from 1 to 2 or 1 to 3. Hence 1 must be disconnected and then 2 and 3 must be added. However service can be changed from 2 to 3 or 3 to 2 directly. In the above case , changing the service from 1 to 2 or 1 to 3 is a system level contraint. However from an end user's perspective this is a service change. In the above case , should I have a single system requirement stating system shall allow service to be changed for all the service types supported or should I have 2 different system requirement - 1 stating which all services can be upgraded directly and the 2nd stating in which cases service needs to be disconnected and installed?


Technical interview graphics-related concepts fundamentals

I'm having a technical interview with a graphics society in a few time and I'd like to expand my knowledge related to the following subjects:   * TLB (translation lookaside buffers and their role)   * low level optimizations   * cache and how the process of fetching data for an instruction execution works   * threads and synchronization   * interrupts, deadlocks and spinlocks, irqs and interrupt masking Can you suggest some exceptionally explained book/resource about these topics?


Doesn't "if (0 == value) ..." do more harm than good?

This is one of the things that I hate most when I see it in someone else's code. I know what it means and why some people do it this way ("what if I accidentally put '=' instead?"). For me it's very much like when a child goes down the stairs counting the steps out loud. Anyway, here are my arguments against it:   * It disrupts the natural flow of reading the program code. We, humans, say "if value is zero" and not "if zero is value".   * Modern compilers warn you when you have an assignment in your condition, or actually if your condition consists of just that assignment, which, yes, looks suspicious anyway   * You shouldn't forget to put double '=' when you are comparing values if you are a programmer. You may as well forget to put "!" when testing non-equality.


Most regrettable design or programming decision you made?

I would like to hear what kind of design decisions you took and how did they backfire. Because of a bad design decision, I ended up having to support that bad decision forever (I also had a part in it). This made me realize that one single design mistake can haunt you forever. I want to learn from the more experienced people what kind of blunders have they experienced and what did they learn from them. I'm sure this will be a lot of help to other programmers by helping them to not repeat those decisions. Thanks for sharing your experience.


Rules about the concreteness of method parameter types, return types and property types

Some time ago I read a kind of "rule of thumb" about the concreteness of method parameter types, return types and property types, but I just do not remember it. It said something about keep your return types as concrete as possible and your parameter types as abstract as possible... or vice versa. I don't know if it was actually a good or bad advice, so if you have your own thoughts about it, please let a comment. Cheers.


Why is the UI of nowadays application getting so "plain"?

Take a look at Google, Windows 8, etc. Why does everything look so plain now? Looks really ugly to me. Is it all because of smartphones and tablets? Do I have to follow that trend?


Would like to add features to Text Editor - which editor to choose?

I would like to add some new features to a text editor. The main requirements I have are:   * Should be a programmer's editor   * I would like to target C# editor features to start with (since I work in Visual Studio most of the time).   * I have considered Visual Studio addins/extensibility development, but I need to know some pros/cons of that. Mainly I am interested in the XAML editor features of VS 2010.   * Some other open-source editors I have considered are Scintilla and AvalonEdit. Again, I would like to know the learning curve for working with those. Since I have not yet started, all editors seem equivalent. I would like to know the pros/cons of developing for each of these.


will an assembly language book for intel x86 processor be compatible with amd processors?

I'm wanting to get an assembly book to learn assembly, and was wandering if i get a book for intel x86 processor will there be any problems assembling the code on an amd processor?


What are you telling yourself if you can't understand new concept, paradigm, feature ...?

Programming always required to learn new concepts, paradigms, features and technologies and I always have been failed at first attempt to understand new concept what i encounter. I start to blame and humiliate myself without remember before how i understood new concept which i hadn't understand it before. I can hardly stop to tell myself "why i cant understand ? Am i stupid or idiot ? Yes, i am stuppiiddddd!!!" What your inner voice tells if you can not understand new concept after spend long time till been tired or hopeless ? How do you handle your self-esteem in such situations ?


What are "User Process Components"?

This article about application architecture design mentions "User Process Components" as part of the presentation layer. > **User process components**. Your user process components help synchronize > and orchestrate user interactions. This way the process flow and state > management logic is not hard-coded in the user interface elements > themselves, and the same basic user interaction patterns can be reused by > multiple user interfaces. It looks like this is a standard term, but I have never heard of it so far. Can you provide a more precide definition or examples of UPCs which illustrate the definition above? **EDIT** : what's puzzling me particularly is the phrase _"help synchronize and orchestrate user interactions"_. Can you provide an explanation of what could be meant? Can you give an example of a problem that is solved using UPCs?


How to experiment with GPU programming on Linux+AMD/ATI card?

I've recently acquired a laptop with an Intel i3 CPU and an AMD/ATI 6300 card, running Ubuntu 10.10. How do I proceed in setting up a development environment that allows me to program the GPU? I assume I'll have to use OpenCL (CUDA is NVIDIA-only), but since I'm a novice with GPU programming, I'm asking the advice from more experienced programmers on the issue.


Do you run production boxes with logs completely turned off?

We are internally debating in our team if we should continue to run our production boxes with logs turned off completely and just log errors and exceptions with log rotations. I want to know how everyone else logs info in their production environment and any particular strategy/tool that has worked well for you. Thanks Isaq


Procedural--enough?

_I posted a similar question on the PHP section of stackoverflow and was told that this might be a better forum in which to submit my question._ Without any programming experience whatsoever, I started studying PHP beginning in the second quarter of this year with the goal of slowly building my dream website starting later this summer. Just as I was wrapping my head around PHP and beginning--I felt-- to truly understand the different concepts and how the code works (this is why I prefaced my post with my non-experience--I've really had to bang and cram it all in my head), I come across Object Oriented PHP. I've taken the approach of of mastering (trying, as much as possible, at least) as many of the concepts and ideas before diving in to try and create my own scripts; much like learning how to dribble, throw a baseball or football well, before playing a single game. (of course I've played around with and done some code -drills). My question to the experts is this: Should or must I learn and delve deep into Object-Oriented-PHP, thus delaying my "start-to-code" date? Or will procedural PHP Programming suffice if one would like to build good E-commerce, forum/comment-type (like PHP Help) or basic social networking websites? How far will procedural programming take me? A site with 1,000; tens-of- thousands; hundred thousand visitors? Thanks in advance for your expert insights.


Identify algorithm for my resource allocation needs

I'm trying to automate a task and I lack the right vocabulary to look up the correct algorithm. It really feels like a common problem that has likely been solved many times before. All I'm looking for is for someone to point me in the right direction or help me with the right search terms to look up a solution / algorithm. If you happen to know of an actuall library (javascript), then even better. # Made-up scenario Say I have 3 'buckets', `Bucket A`, `Bucket B` and `Bucket C`. Each of these can hold a certain number of 'Balls'.   * `Bucket A`: Capacity 10 balls.   * `Bucket B`: Capacity 15 balls.   * `Bucket C`: Capacity 5 balls. Now, I also have an inventory of balls and each one can only be put into certain 'buckets'. One ball can only go in `Bucket 2`, The next ball can go into `Bucket 1` OR `Bucket 3`, and so on. Now.. I need to determine the best way to place the balls in order to try to fill up each 'bucket' to it's capacity (or as close as possible). # Real scenario My real reason for this is to schedule `people` (balls) to visit `locations` (buckets) for a requested number of hours (capacity of the bucket). However, due to the following reasons all the libraries/algorithms I've found while searching for "scheduling" so far do not work in my scenario.   * I do not care about start/end times at all, only `person` -> `location`   * My people (balls) all have a strict list of locations they can visit. Each one is unique.   * Each person is available for an arbitrary number of whole (integer) hours that they can spend at _exactly one_ `location`. Using someone that's available for 8 hours for only 7 of those hours is OK.   * Each location (bucket) requests a certain number of hours that I try to fulfill to the best of my ability with any combination of people. I have ~50 locations and ~100 people. It's not a requirement that I get a **perfect** solution, but 'pretty close'. I found schedule.js which looks fantastic, but I've been unable to abuse it to fit my needs.


Dealing with co-workers who do not have a consistent coding style?

What do you when you're working with someone who tends to write stylistically bad code? The code I'm talking about is usually technically correct, reasonably structured, and may even be algorithmically elegant, but it just _looks ugly_. We've got:   * Mixture of different naming conventions and titles (`underscore_style` and `camelCase` and `UpperCamel` and `CAPS` all applied more or less at random to different variables in the same function)   * Bizarre and inconsistent spacing, e.g. `Functioncall (arg1 ,arg2,arg3 );`   * Lots of misspelled words in comments and variable names We have a good code review system where I work, so we do get to look over and fix the worst stuff. However, it feels really petty to send a code review that consists of 50 lines of "Add a space here. Spell 'itarator' correctly. Change this capitalization. etc." How would you encourage this person to be more careful and consistent with these kinds of details?


Where should heavy development assets like specification documents and multimedia editor source files be stored?

It's not uncommon where I'm working on a site that includes things like binary (or effectively undiffable due to factors outside my control) specification documents (e.g., PDFs, Word Documents, Excel Spreadsheets) and multimedia source files (e.g., FLA source files, Photoshop files, Illustrator files). How should these be stored? My instinct is to just throw them into git. Storage is cheap, but it does make the clone operation take much, much longer than it otherwise would. A potential alternative would be to use a wiki. I've tried it in some cases but never ran into a case where the wiki format's inherent strengths (layperson-accessible version history and easy access to latest copies) have or would have led to enough benefit to justify the additional work in maintaining the wiki. The third option is to just let them hang out locally and in email threads. So what approach should I take to this?


Which mathematical properties apply to XOR Swap algorithm (and similar bitwise operator algorithms)?

Assume you have two variables a and b, and you need to swap them, and for whatever reason, making a temporary variable for storage is not an option. This is the algorithm in pseudocode               a ← a XOR b     b ← a XOR b     a ← a XOR b      Based on examples I can see that this does work. But, _why_ does it work? More specifically, how was this derived? Was it a mere coincidence that `XOR` such and such values does this? This question applies to **all bitwise operators.** I understand perfectly what they do, and how they work, and various algorithms that take advantage of them. But, are there mathematical properties of these bitwise operators that these algorithms are derived from? What are those mathematical properties? And which of them apply to the specific example of an `XOR` swap?


Should a software developer carry business cards?

I was at Google Developer Day yesterday and I was approached by several companies looking for hire and for freelance work. As I am interested in doing some freelance work I chatted a little with the representatives of these companies and they all gave me their business cards. I was a little taken aback by this since I didn't have a business card for myself and the fact that I find business card to be quite simply outdated. So, lacking a business card, I gave them my website address where I have a portfolio, links to my GitHub and LinkedIn accounts and a blog. Should I order some business cards and carry them around in these events? I can't shake the feeling that business card are outdated, am I just plain wrong?


Outsourcing Quality Assurance and Testing

I was recently approached by a software firm that specializes in Quality Assurance and Testing. Up until this point, the developers at our (small) company have been responsible for their own QA for the most part and we've had mixed results. We're at the point where we are ready to hire a full time QA guy, but I was curious as to whether or not other's have used teams like this in the past and what the results were? I'm a bit skeptical but trying to be open-minded. **tl;dr What was your experience with an outsourced QA/testing team? Pros and cons?**


Are there any ways to track for the visitor of my site , which site visitor come from?

This is a problem because when I do email campaign, There is a link on the email, that link to my company homepage, I would like to differentiate between the visitor come from another way (e.g. search on google) or the visitor come from the email I have sent. Is it able to check such kind of information ? Thankyou


Should I just slog it out or discuss with my PM?

Having "completed" my task, I have recently been assigned by my PM to work on a maintenance project by another PM. In this other project, the client wants to add new features and I'm assigned to do a feature. I'm finding my job over my head for various reasons:   * code is difficult to understand/read as      * not well-documented     * standard naming convention is not followed (seems non-existent, and confusing at times because certain words are used in the wrong way)     * dead-code     * redundant code     * code such as (isTrue == true)     * temp variables that are not inlined and not prefixed with temp     * etc...   * visual sourcesafe is used   * visual studio 2005 is used, even though they have vs2008 and vs2010. I'm unable to use a plugin for quick navigation (more of an inconvenience)   * they just want to get things working, without caring about maintainability. I would love to refactor the code base, and suggest upgrading to svn and a newer version of VS. However, I don't feel that the PM or my new colleagues are amenable to such changes. On top of that, I don't have the confidence of delivering on time (if I'm even able to deliver), and if I do make these suggestions, he may assume that I think I feel that I am superior (not true) and I am competent enough for my assigned task, making it difficult for me to raise issues in the future. I just don't feel I have sufficient experience yet for a project of this complexity, and will likely end up writing copy-and-paste and googled code with lots of unpaid overtime. I will get surface learning without deep learning, and I feel the entire experience will mar my joy of programming, perhaps making me shun it completely. In the meanwhile, if I do nothing about it, I will probably just have to slog it out within the current constraints. To this end, I have borrowed books on brownfield application development and visual sourcesafe as references. What should I do? Should I make my suggestions? How early should I tell him if I don't feel I can deliver? Or should I just slog it out while risking not being able to get my task done?


Why do we need fork to create new process

In Unix whenever we want to create a new process, we fork the current process i.e. we create a new child process which is exactly the same as the parent process and then we do exec system call to replace the child process with a new process i.e. we replace all the data for the parent process eith that for the new process. Why do we create a copy of the parent process in the first place and why don't we create a new process directly? I am new to Unix please explain in lay-man terms.


How do people deal with Android fragmentation?

I've spent the past few years working on iOS apps, and I'm now giving some serious consideration to creating an Android port of one of my apps. I'm sure that complaints about fragmentation are a frustrating cliche to experienced Android programmers, but as an iOS programmer, I'm quite honestly overwhelmed by the number of configurations and devices that my app might end up running on. There are literally thousands of Android devices in the wild, but I know there are successful Android developers in the world and I know they're not testing or developing for thousands of different devices. So how can a relatively small company deal with fragmentation? Is it possible to pick the five or six most popular devices, focus on those and prevent the app from being installed on any other devices? Are there any other strategies for practically dealing with the number of different configurations an app will face?


Unit testing in node.js and mocking modules

I'm trying to test this wrapper to request that I made:               // lib/http-client.js     var app = require('app'),         request = require('request');          exports.search = function(searchTerm, next) {       var options = {         url: 'https://api.datamarket.azure.com/Bing/Search/Web',         qs: {           'Query': '\'' + searchTerm + '\'',           'Adult': '\'Off\'',           '$format': 'json',           '$top': 10         },         auth: {           user: app.get('bing identifier'),           pass: app.get('bing identifier')         }       };            request(options, function(err, res, body){              if (err) return next(err);         // TODO: parse JSON and return results       });     };      where `app` is an instance of express. The question is, how do I test the function of this "module" without having to touch the internet? If I was to do this in other languages I would have mocked the request module but I don't know if that's the best way to do it in node.js.               // NODE_PATH=lib          describe('Http Client', function(){       it('should return error if transport failed', function(){         var c = require('http-client'),             results = 'foo';         // request mock should return results when called         c.search('foo', function(err, results){           results.should.eql(res);         });         // TODO       });       it('should return an error if JSON parsing failed', function(){         // TODO       });       it('should return results', function(){         // TODO       });     });


Event and Objects

I have an array of objects. Instead of me when performing a task asking every object If they have anything to say about that, I would rather like the following:               Perform Task          Object #4 Hey, I have something to say about that!       And If object #4 says something about that, maybe Object #17 has anything to add up with, because Object #4 did say something. Do you understand? How do I structure this?


When required to convert code from a language you don't know, how do you go about it?

Scenario: Your boss tells you he needs a big chunk of code in language X converting into code Y. You know code Y but are only vaguely aware of X. You only have limited amount of time. Do you try and find a code converter? slowly hack through the code until it works? outsource? say you cant?


Looking for companies with strong R&D departments, specifically for A.I., but I can't seem to find many. Are there only a handful?

I plan to get a PhD in CS, concentrating in some subfield of artificial intelligence, not sure which one at the moment. I'm looking into R&D departments in industry, but there don't seem to be too many. For example, I have literally found hundreds of labs for the basic sciences and other engineering fields, but for CS I've found: Google, IBM Research, Microsoft Research, Yahoo Research, AT&T Research and GE Research. Are there not tons of companies like there are in other disciplines?


Three approaches for obtaining different sized versions of an image from the server

My android app needs different sized versions of images for different purpose and bandwidth preservation. Approach one:   * when the user uploads their avatar or another image, my php script creates 4 versions of that image: mini_200, medium_300, big_400 and original. those paths are then taken and stored in the database. Then, when I need the smallest image, I load it from `http://myserver.com/item_images/200_mini_27304lkewsjfimage.jpg` Approach two:   * same as approach one, but instead of adding prefixes to the names of the files, I store them in different folders - big, medium, mini. and in My app I just pass a parameter for which folder to look in Approach three:   * when the user uploads their avatar or another image, I only store the original. Then, when I need the smallest image, I load if this way: `http://myserver.com/image_resizer.php?image="93_iosdfj0sd9fj.jpg"&new_width=200&new_height=200` Which one is better and why? I feel like reinventing the wheel here, because this topic is too broad and I dont know where to read about it


What is best software design in creating methods?

I had created a extension method which extended the string type in C#.               // actually checks if the string is empty or null and then looks up the default     // promotion code which is set in the backend admin system.      promocode.HasPromode();       I thought that was fine and dandy, but another colleague thought I should inject the method through constructor injection, which should implement a interface. I think this is overkill to have a simple lookup function to do that. Another colleague thought that extending the string type makes it simpler to use it wrong and exposes it for the wrong purposes. Which one is right? All solutions work fine; but some of these solutions should be the best one, or does it matter actually? It should matter, because we are having those discussions and we're trying to make the code better.


JMS for synchronous calls vs leaving homebrewed messaging system?

I'm refactoring existing code. Right now the code has a main server with a CLI and restful interface as seperate applications which communicate with the server via a home-brewed message passing package that they share. The system is written by a few hardware engineers with no real programing experience. It looks a bit ugly at times, but it has been working in this code for a year+ with minimal hassle, beyond limiting passing of a single serialzed object per command. We now have to implement JMS communication to interface with a third system and I jumped all on it. I'm certain were use JMS queues to push some information that really should be pushed as well. My first inclination was to replace the whole home-brew message passing system with JMS. However, the home-brew system is written for synchronous calls, with an obvious "I make a request, wait and send me a response" sort of behavior. JMS is really used for async calls. I could make JMS work for synchrnous calls with a little hacking, but that hacking needs to exist in three applications... My question is, would it be better to remove an existin system that seems to mostly work with JMS to have the extra robustness of an enterprise level system, and a single communicaton protocol, or is it best to leave well-enough alone and not waste programing time trying to remove the homegrown system that seems to work? Incidentally, as far as I know there is no built-in tool to make JMS handle sycnrhnous calls without my maintaining a state machine is there? If there is a way I can tel JMS to send responses to my requests the way a restful interface would work and JMS will handle the blocking and keeping of tate to make it happen without my writing it I would definately switch entirely to JMS.


I am stuck on the following problem. I want to find an algorithm that finds all possible permutations of a certain numbers of distinct digits and then put them in a large matrix for instance. For instance for the digits 0, 1 and 2 I want to get the matrix: 2 1 2 0 1 0   1 2 0 2 0 1   0 0 1 1 2 2 Here they are in order but this is not required per se. Does anyone know a nice algorithm to achieve this? Thanks in advance.


Why most of large corporations websites are bad?

As a electronic customer, I sometimes have to go to manufacturer's websites to find information about products, drivers/firmware update, etc. More ore less, most of these websites, IMO, are bad. They're slow, not user-friendly (some time, really ugly), and take me lots of time to do what I need to. For example, in Sony's website, I must find "Vaio laptops" in a list of dozens (may be hundreds) products, then find my specific model in a list of hundreds model. Fail! I also see that on several websites, they may be slightly better, but still not good (HP, Dell, Lenovo (somewhat better), ...) Well, they may be have a large back-end system there, but that does not mean they can make the frond-end faster and more user-friendly. Is there an obvious reason that large corporation's website are that bad?


Where did the html/css 'float' concept come from?

Pretty straightforward, was wondering what the inspiration or precedent for the CSS 'float' concept. I'm not familiar with any other graphic APIs or other layout DSLs that use this concept, but it's such a huge part of HTML layouts. I'm curious if a previous language had a similar concept, or if 'floats' originated from the land of HTML/CSS. Thanks.


Many Blocking VS Single Non-Blocking Workers

Assume there is an HTTP server which accepts connections and then it has _somehow_ wait for headers to be fully sent in. I wonder what is the most common way of implementing it and what are the rest pros and cons. I can only think of these: **Many blocking workers are good because:**   * It is more responsive.   * Easier to introduce new connections (workers pick them up them selves rather than outsider waiting till it can add it to a synchronized list).   * CPU usage balances automatically (without any additional effort) as number of connections increases and decreases.   * Less CPU usage (blocked threads are taken out of the execution loop and do not require any logic for jumping between clients). **Single non-blocking worker is good because:**   * Uses less memory.   * Less vulnerable to lazy clients (which connect to the server and send headers slowly or don't send at all). As you probably can see, in my opinion multiple worker-threads seem a bit better solution overall. The only problem with it is that it is easier to attack such server. **Edit (more research):** Some resource I found on the web (Thousands of Threads and Blocking I/O \- The old way to write Java Servers is New again (and way better) by Paul Tyma) hints that blocking approach is generally better but I still don't really know how to deal with fake connections. P.S. Do not suggest using some library or applications for the task. I am more interested in knowing how it actually works or may work rather than have it working. P.S.S. I have split logic into multiple parts and this one only handles accepting HTTP headers. Does not process them.


(Dis)advantages of datetime vs. long in globally used applications

I am currently designing a web/mobile application the bulk of whose users will be distributed across the different U.S. time zones with a potential of scaling up to other countries and time zones as well I have worked with several other globally used apps and noticed they all used datetime to record timestamps with the default time zone being that in which the application is typically hosted. In displaying the times, they would typically do not care about the user preference (locale) and simply display the timestamp with the TZ and leave it up to the user to convert if (s)he wishes. I am entertaining the idea of shifting away from that paradigm and recording timestamps as one global time (GMT) in long milis regardless of the user location and collecting the user locale by their IP or letting them change their TZ as a preference in their profile, which would later be used for display formatting of all their GMT long milis. This seems like a simpler solution than confusing the app design with TZs. I am curious to hear feedback of pros and cons to this approach. I am also curious to hear some explanations why the, IMO overcomplicated time zoned datetime data type has ever been used across databases and not a uniform single time zone with conversions just for display.


How can I improve these online java programming puzzles I wrote for my (middle/high school) students?

I'm teaching some middle and high school students programming right now, and I found that some of them really liked online programming puzzles. So I created http://www.kapparate.com/coder/ , and right now there's 4 categories of puzzles. All the puzzles are set up right now so that variables are pre-initialized, and the user plugs in some code in the middle. For example, the problem might say these are pre-initialized:               int x = ????;     int y = ????;     int z;      and then the program might ask the student to write the final line of code: `z = x + y;`. Now I know I could go a long way in improving the usability of this site (like having an area that lists the pre-defined variables), but I was wondering if this concept seems sound. I know some sites have kids fill in functions, but not all of my students know what functions are yet, and I'm trying to introduce online programming puzzles before that.


When a garbage collector compacts objects in the heap, does it change the references on the stack?

This seems like a simple question, but after a lot of reading on the subject, I still haven't found a definitive answer (perhaps because it is so simple). My question is this: when a garbage collector compacts objects in the heap, how are the references to those objects in the stack updated? I can think of two possible solutions:   1. Go through the stack (and references in the heap) and update the reference to point to the new location of the object. In an analogy to moving, this would be like sending a letter to anyone who has your address and asking them to update their address book with your new address.   2. Provide some sort of look up table. This would be like leaving a forwarding address with the local post office. Do garbage collectors predominantly use one of these two methods? Some other method? Both?


Is mod_security a good thing?

I've recently been frequented by erroneous error messages from mod_security. Its filter sets cover outdated PHP exploits, and I have to rewrite my stuff because Wordpress&Co had bugs years ago. Does this happen to anyone else? > Apache mod_security blocks possibly dangerous HTTP requests before they > reach applications (PHP specifically). It uses various filter sets, mostly > regex based. So I have a nice shared hosting provider, technically apt and stuff. But this bugged me: Just last week I had to change a parameter name `&src=` in one of my apps because mod_security blocks ANY requests with that. I didn't look up its details, but this filter rule was preventing the exploitability of another app which I don't use and probably never had heard about. Still I had to rewrite _my code_ (renaming parameter often suffices to trick mod_security) which had nothing to do or in common with that! And today, a silly regex blocks form submissions, because I wanted to submit php sample code. Given, this is the simple stuff that mod_security is there to protect against. But I don't believe mod_security can detect seriously obfuscated code, and just goes off at obvious (and in this case totally trivial) php snippets. Basically I'm getting penalized by mod_security because other people released bug-prone apps. (Not saying my apps are ultra secure - I'm pretty security wary, but make no hyperbolic claims.)   I've already asked my provider to disable it anyway, the benefits are too minuscle IMO and for my apps. * * * What do you think? Does mod_security make much sense outside of WP hosting? Or is it really just a bunch of blacklists of long passed security bugs? Which of its rules are actually helpful? Is there an application level equivalent?


Moving from local storage to a remote database: how should I cache the data locally?

I have a .NET (C#) application that I am releasing soon, which also has some support files. Right now I am storing those files as .txt files, and I update them as necessary whenever the application version changes. I am wondering if a better solution might be to store the information in those files in a central database instead, and have all clients access that database when then launch. This would prevent the need to update the software each time those reference files change. My question for the gurus here is this: Is this a wise decision, and if so...what would be the best method of storing the downloaded data? A temp file? in memory? something else? Any help would be appreciated.


How does jQuery's mechanism of event handlers work

I'm in the need of widen my perspective on the framework libraries, to be able to make well aware choices of if/which/when to add a framework to a website. One thing that got my attention was event handlers, as they seems to be somewhat more complex structured. For me, in the early days, an event handler were added inline with its element `<a onclick="DoSomething();">...</a>` Later on they were removed from being inline and added globally `document/element.onlick = "DoSomethingOnClick` or `document/element.onlick = "function() {...}` As of today, the frameworks add their own mechanism on top and I am trying to grasp what/how that actually means/is done. By studying code parts it appears to me, and here describe in a VERY simple way, that they add the `onclick` event similar to above global and then pass the event when raised, into their own handler, which itself is an object structure containing stored/added functions and elements and their relationships. Is this a correct observation? If not, then how is it done? Can this be showed with a simple written sample in Javascript? Based on the following quote, > "You can use the jQuery _on_ method to attach an event handler to the > document, and pass it a filter string that will cause your handler only to > fire when the event happens on an element that match the filter, and with > the matched element as _this_ value." how is the element that triggered the event identified in the handler (by the event object or ?) and how are the elements to be fired stored/identified? Do the other frameworks, other than jQuery, have a very much different structure of their implementation of event handlers?


Using functions as statements on Python

A great feature of Javascript is function statements. You can do this:               (function myFunc(){         doSomething();         doSomethingElse();     })();       Which is a way to declare a function and call it without having to refer to it twice. Can that be mimified on Python?


After writing code, why do I feel that "I would have written better" after some time?

I have been working on my hobby project in C++ for more than 2 years. Whenever I write a module/function, I code it with lot of thinking. Now see the problem,               do {       --> write the code in module 'X' and test it       --> ... forget for sometime ...       --> revisit the same piece of code (due to some requirement)       --> feel that "This isn't written nicely; could have been better"     } while(true);      Here `'X'` is any module (be it small/large/medium). I am observing that, this happens no matter how much effort I put while coding. So mostly, I refrain myself from seeing a working code. :) Is this a common feeling for many people ? Is this language specific phenomena ? (Because in C++ one can write the same thing in different ways). What should I do, if I get this **re-factoring** feeling for a real world production code, where changing the working code will not earn me much accolades but rather it may invite troubles if it fails.


Retried Operation with generic Exception

I am looking for a way to get the logic of retrying an operation in a single method while keeping the exception types of the operation. I.e., the implementation to retry an operation could look like this:               public void retriedOperation(Operable operable, int maxAttempts) throws Exception {         for (int attempt = 0; attempt < maxAttempts; attempt++) {             try {                 operable.doOperation();                 break;             } catch (Exception e) {                 if (attempt + 1 > maxAttempts) {                     throw e;                 }             }         }     }      This implementation is however only capable of throwing an unspecified `Exception` and thereby looses lots of information. Unfortunately, generic Exceptions can ~~neither be caught nor thrown~~ not be caught in Java, thus something like               public void <ExceptionType extends Exception> retriedOperation(...) throws ExceptionType { ... }      would only allow to catch an unspecific Exception, check if it is of the right type and then cast it. But if it is of another type, it cannot be thrown with this method header. **Is there a way to implement a generic retry function that preserves specific exceptions?**


How often is appropriate to destroy objects?

I know this is hard to answer without examples, so I'm looking for general principles or guidelines here. I'm thinking within the realm of small- to medium-sized mobile games and apps. I've read a few times the object reuse is a touchstone of creating efficient programs. So, I generally strive to reuse everything possible. But, then I came to realize that every object I'm keeping around has to exist _somewhere_ in memory, so it's begun to seem **inefficient**. I've thought it would be fine, as long as I'm not trying to render the objects' visual or auditory aspects. And I've feared that construction and re-construction of these objects would be too expensive to perform every time I just want to toggle their presence. Let's say, for instance, I've got a GUI comprised of 30 different objects that each represent a screen state-- buttons, panes, text, a background, maybe some animated UI components. Does it seem more sensible to initialize and de- initialize these objects, keeping them around in memory, but disabling their rendering, animations, etc? Or should I just be destroying these things and re-creating them? Other examples of things I keep around might be game objects like non-playable characters, weapons, items, etc.


Unit Test OR Console Application

I am to write some one-off code in c#.net that will do some db manipulation of existing records and call a third party REST Api to update those records. I proposed writing a unit test that does it. And running it in vs2012. My team mates were not too happy with the approach and preferred writing a console application to do it. What does the community think? Which ones do you prefer and what are the pros and cons of each approach. Update #1 - Exact scenario (to keep everyone happy) is as follows An in-house API handles newsletter subscription for my website (well.. the website i work on). So these details are with this API (emails and their preference (subscribe or unsubscribe)). But to achieve certain things we keep a track of these preferences in our application db as well (SQL Server, as a table). Now there is some data in the applicaton's SQL db which is not in sync with the records that API manages. To do this, i want to be able to write a unit test/console app that will read some emails from a given list (maybe an excel), call the api to get preferences associated with those email ids and then update application's SQL db table. Update #2 - Why i want to use unit test to preform this functionality   1. I want to add this test/tests to my existing test project. This way i will have access to ALL Dtos and Contracts (and objects in general) which are used in my application. Saves me time repeating/duplicating any code that i may need into a separate console app.    2. Since it will be part of the existing source control repo, i dont have to maintain a seprate project/application which i will have to if i do a console (if i want to share it with people)


Need help understanding Constructor Chaining

I'm trying to understand constructor chaining better. I understand that this technique can be used to reduce code duplication for initialization of a class object and I also understand the order in which they're executed. I found the following example and I cannot see clearly what the benefits are in the code? And whether it's necessary? I don't understand why both constructors have '`this`' keyword in them, would calling either constructor (and passing in relevant parameters) have the same result?               //Constructors     public MyClass(double distance, double angle) : this(distance, angle, 0)      {     }          public MyClass(double distance, double angle, double altitude) : this()     {     Distance = distance;     Angle = angle;     Altitude = altitude;     }


GPLv3 Software vs. BSD (3-Clause) OpenSource Project .. i don't get it

**Preamble:**   * If I say "BSD" I mean the 3-Clause BSD license   * If I say "GPL" I mean the GPLv3 license   * I am NOT the author of the GPL project   * I am the author of the BSD project **Simple Task:** I wan't to use a 3rd party software (GPL) in (or better 'with') my open source project (BSD) **Situation:**   * I won't change any of the GPL project code (using it AS IS)   * I want to use it as kind of a library (i know about LGPL but it's not available)   * I will use the GPL software as bulk, NOT only parts of the code   * I will indicate the use of the GPL project with license, homepage and where and why it is used in my BSD project (in readme file)   * I will not take the credits for the functionality of the GPL project   * I will take the credits for my project and the "Adapter" connecting my BSD project to the GPL project   * I don't want to re-license the GPL project as BSD (!)   * I won't charge any fees or something like that to gain insight you can find the BSD project at GitHub: MOC-Framework (see /Extension/FlowPlayer and /Module/Office/Video) and the GPL project here: Flowplayer (free flash-version) **Simple Question:** Is this possible? **Closing Words** I found some discussions, stating: "it is possible", others say "no". Most of the "no" was for commercial projects. Most of the "yes" are referring to: "include BSD in GPLv3", but that's not what I mean. I want GPLv3 along with BSD.. I simply can't figure it out.


Data decoding initialization/Constructor error handling

I have a set of loadable data decoders for a specific type of data and a stream to read containing data. Now I want the program to select the correct decoder in a reliable way so I want to use a trial-and-error algorithm. It seems resonable to create a decoder and connect it to the stream using a constructor:               // C++ code     // codecs is an array of structs containing function pointers loaded from a dll     FileIn src("foo.wav");     for(size_t i=0; i<N_CODECS; ++i)         {         try             {             WaveIn wavein(codecs[i],src);             //Process data             return;             }         catch(...) //Swallow error. It's likly that another codec works. But if it were another error??             {             src.reset();             }         }     //no codec found (definitly an error)      Here, there is probably no true error before we have tried all codecs in the list. The reason to try-catch here is that it is not possible to get return code from the ctor. Would it be better to use zombie objects in this case? EDIT: What the constructor does, is the following               WaveIn::WaveIn(Vtable& vt, FileIn& src):m_vt(vt)         {         m_handle=m_vt.create(src);         if(m_handle==NULL) //Resources allocated in DLL were released in this case.              {throw "Bad file";}         }      The dtor:               WaveIn::~WaveIn()         {         m_vt.destroy(m_handle);         }


Creating Compelling Desktop Application in .NET

I'm about to create an open source desktop application. I'm primarily a .NET developer , with experience in ASP.NET and SharePoint. I've created basic Windows Forms applications before, but I have never developed using WPF or Silverlight before. I want a compelling, highly interactive UI for my desktop application. What are my technology choices for doing this, using .NET? In particular, is HTML5 something I should be considering?


Automatically observing changes in database tables

currently I'm working on a project with the following setting:   * There is a proprietary application which performs transactions on a Microsoft Access database (which is actually stored as an .mdb file)   * The API of the application doesn't have enough functionality for the requirements we're facing   * Our application has direct access to the database We're designing a C# application which has to react to events which are not triggered through the API, so the only way I can think of is to somehow observe the database directly and react accordingly to custom events. One approach would probably be to query the DB time triggered and react, but this possibly leads to performance issues when the DB is large. I would rather appreciate an approach, where the DB itself notifies our application if specified events occur. EDIT: The proprietary application is Enterprise Architect modeling tool, so the expected number of concurrent users will definitely not exceed 10 users and the database size will not be larger than 50 MB. Would it probably be an acceptable solution to outsource the polling activity in a separate thread and notify the rest of the application by events? Concerning the number of users and database size, which load can the MS Access database approximately handle? Is there any well-known pattern/approach for this kind of problem available and if you don't know any, how would you face this problem?


Can we say objects have attributes, states and behaviors?

I was reading through Oracle's introduction to OOP concepts and I came across this description: > Real-world objects share two characteristics: They all have state and > behavior. Dogs have state (name, color, breed, hungry) and behavior > (barking, fetching, wagging tail). Software objects are conceptually similar > to real-world objects: they too consist of state and related behavior. My problem with that passage is that when describing _state_ its mixes _attributes_ there too. For instance, the name and color of a dog are its attributes, while it being hungry or thursty are its states. So in my opinion it's more accurate to break the characteristics of objects into three parts: **attributes, states and behaviors**. Sure, when translating this into a programming language I can see that the three-fold partition becomes a two-fold one, because both attributes and states will be stored into fields/variables, while behaviors will be store into methods/functions. But conceptually speaking it makes more sense to have the 3 things separate. Here's another example: consider a lamp. Saying that both the lamp size and whether or not it's turned on are states is a stretch in my opinion. The lamp size is an attribute, not a state, while it being turned on or off is a state. Or did I miss something?


Is it more important to focus on a business domain or a programming stack/technology for career growth?

i just basically realized that it's almost impossible to truly learn and master each programming language/technology before a new version is released. so my initial thought was to focus on the .net platform, but then what about the business domain side of the thing? does it make more sense to pursue more knowledge about the platform including taking MCPD, etc or does it makes more sense in the long run to focus on the business domain, i.e. web commerce and only things that is related? i'm just a starting up as programmer and would like to know what's a good way to direct myself to growth so that i could master a certain area for career growth. any tips or article would be nice ;)


How to get better understanding of the users as a programmer

I work at a company that wants to be agile, but the business analysts often provide us "user stories" that are more solution than problem statement. This makes it difficult to make good design decisions, or in more extreme cases, leaves few design decisions to be made. It does not help the programmers understand the user's needs or make better design decisions in the future. Our product owner makes an effort to provide us with problem statements, but we still sometimes get solution statements, and that tends toward a "code monkey" situation. An additional challenge is that some (not all) of my teammates do not see a problem with this, and some of them honestly want to be told what to do. Thus, when we receive a solution statement on our backlog, they are eager to jump right in and work on it. I believe that as a software engineer part of my job is to understand the user's needs so that I can build the right thing for the user. However, within our organization structure, I have zero contact with the user. What kind of things can I do to better understand our users?


Testing the Consumers of Subclassed Data Structures

PHP's SplQueue does not include a clear() or reset() function to wipe data out of the data structure. My application requires that functionality. This leaves two options: A) Create a subclass of SplQueue. Example:               class UserQueue extends SplQueue     {       public function clear() {         //dequeue everything       }     }      The problem with this approach is that I can't see a way to test _consumers_ of this subclass without relying on clear() as defined in the subclass. In essence I can't think of a way to stub that functionality in PHPUnit short of just depending on UserQueue's own tests. B) Implement the clear() function in every consumer of SplQueue that requires it (most consumers in my application), which seems obviously terrible but would appear to be the only testable method. I am hoping someone out there can tell me there is an obvious way to test option A that I've missed. I also considered wrapping SplQueue but I don't see how this improves matters. Or I could monkey patch it with runkit, but a nearly-allergic aversion to runkit has been beaten into me.


serving static or dynamic web-content based on user group

I need help understanding a problem I have, and that others surely have had as well. I'm working on a web-application that allows users to interface with a database. The application in general has multiple pages with tabbed navigation, that displays and allows _most_ content to be editable. So far, it works well. I need to restrict access to certain pages and disable dynamic (editable) content of the application based on the group (in the database) that the User belongs to, sounds simple, maybe it is. The issue is though, the editable pages have `input` of type buttons and text which should disappear for a user in a restricted group. Also, certain tabbed-navigation selections should not be displayed for Users of a restricted group. At what point in my application should this logic be handled? Using javascript for this logic seems like the wrong approach (using a library like `underscore.js` with templates), but I do need to hide or disable multiple options. My other thought was having dynamic and static web-pages and serve those based on User group. It's clear that I'm lost on this subject, and could use some insight as how this problem should be approached in a way that is sane so the next guy behind me won't say...wtf. I'm not sure if this question is better suited for stackoverflow or here. So hopefully this is the right place!


How do desktop applications talk to remote database server?

I have often seen desktop applications in stores and banks. How do these desktop applications talk to a remote database central server? There will be a desktop application which is installed on multiple computers in multiple different locations. How do all these machines talk to one central remote database server?


Should one declare alternative response types (e.g. JSON) in Rails controller actions even if not utilising them?

Just wondering what the accepted convention is for Rails controller design. Currently, every controller in my app that I've written it set up to send a JSON response when necessary. Thing is, I only ever utilse HTML responses in my app. So is it a good idea to have them defined? For example:               def show       @dog = Dog.find(params[:id])            respond_to do |format|         format.html         format.json { render json: @dog } # needed?       end     end      It makes the controller code less readable (because more LOC) and it also means I have to think deeply about what a good JSON response should be when HTML is not being is used, so it decreases the speed of my controller development. This is especially true when you have conditional responses. For example:               def create       @dog = Dog.new(params[:dog])            respond_to do |format|         if @dog.save           format.html { redirect_to @dog }           format.json { render json: @dog, status: :created, location: @dog }         else           format.html { render action: "new" }           format.json { render json: @dog.errors, status: :unprocessable_entity }         end       end     end      The only positive I can see is that it "future-proofs" the controllers (i.e. if I need JSON responses later on then they are already written). But if I'm writing JSON responses just _because_ then by that same logic I might as well write XML responses (i.e. `format.xml`) too...


How long should I wait before re-contacting someone I've interviewed with for a web development/programming job?

After the interview has occurred, and after the thank you letter has been sent, how long should I wait to re-contact them? Should I wait two weeks? One week?


Best practice to keep the changes in the project well documented

What is the best practice and software you use to document change related document. lso, how you prefer to document the changes in the project. Let say, you got a requirement to make some changes in the project. How do you proceed?   * Do you take the complete backup before processing. Will this backup be documented. If yes, then how?   * How the change will be documented? Any template? How this will be shared between the peers?   * What will be the content of the change request procedure?    * Do you keep the affected code, queries etc in some folder/document?


Drop table if it already exists and then re-create it?

I was just learning about sqlite in android programming from the New Boston Travis videos and I have come across something strange: It is said that if the database does not already exists, onCreate() method is called to create it. so far, so good. But, if the database already exists, then onUpgrade() method is called which simply drops the database and then re- creates it. What is the sense behind such an update? why not just leave the database alone?


What's meant by, "TODO Auto-generated method stub"?

I am using eclipse for android programming, and every here and there i see the statement, "TODO Auto-generated method stub." I understand that these methods were generated automatically by eclipse upon creation of classes and other trigger activities but I do not understand the need to have it mentioned everywhere. What's the need to have it mentioned everywhere repeatedly?


Expanding knowledge of python / Next book and/or Topic to read/research

I have been programming python and web apps awhile now but never delved very deep into OOP. I use classes all the time but I am pretty sure i am not fully getting what I could get from OOP. So today I popped open Learn Python (mark lutz) which i had read awhile ago, flipped through the oop section in about 5 minutes and realized it contained nothing new. What would you suggest as a next step in becoming better at understand OOP?


hginit - #ifdefs ridiculous

I was reading Joel Spolsky's mercurial introduction when it struck me: > "And now what they do is this: each new feature is in a big #ifdef block. So > they can work in one single trunk, while customers never see the new code > until it’s debugged, and frankly, that’s ridiculous." Why is this so _ridiculous_ anyway, isn't this, if nothing else, simply simpler to handle? It's nothing fancy but does the trick - at least if you are already "married" with subversion. What is the downside? I kind of don't get the argument.


Blocking IP address for web-scraping service

# Background Consider the following scenario:   1. **Link.** User provides a link to some poorly formatted website (e.g., _creative commons content_ ).   2. **Scrape.** Server downloads the content (web scrape), always throttled.   3. **Format.** Server formats the content (e.g., performs natural language processing).   4. **Return.** Server posts formatted results back to user. # Problem The server hosting the poorly-formatted website ( **host** ) can block the server that pulls down the content ( **scraper** ). If this happens, the user can no longer use the service to automatically change the format. Assume that the terms of service do not forbid scraping, nor is there an API available to pull the data directly. ## Comments Regarding Copyright   * The content is not subject to copyright: it is either creative commons content or already in the public domain.   * The content would be from whitelisted domains that have been vetted (e.g., U.S. federal government works).    * For what it's worth, I don't even know if the sites will block the requests (especially given how infrequent the requests will be and I will likely do some pre-caching). It's mostly academic at this point # Question What strategies would you employ (such as using a virtual network, or cloud service) such that the IP address of the **scraper** can easily (potentially dynamically) change to avoid being blocked by the **host**?


Call constructor using an arguments object in javascript?

Is it possible to call the constructor using an arguments object?               var MyClass = function(a, b){       this.a = a;       this.b = b;     };     var myClassInstance = function(){       //This line would not work, but is what I'm asking. Is there a way besides eval?       return new MyClass.apply(?, arguments);     }('an A value', 'a B value');


Accepting a numerical range in a function call

I have encountered two ways of doing it:               void foo(int from, int to); /* 'from' inclusive, 'to' exclusive */          void foo(int startIndex, int rangelength);      Has one style historically been preferred over the other? If so, was it just a matter of convention or was it due to some deeper underlying reason? I'm currently programming in Java and noticed that the Arrays class uses the former style. The exclusivity of the `to` argument felt somewhat unintuitive to me, which led me to ask this question.


Why does git use hashes instead of revision numbers?

I always wondered why git prefers hashes over revision numbers. Revision numbers are much clearer and easier to refer to (in my opinion): There is a difference between telling someone to take a look at revision 1200 or commit 92ba93e! (Just to give one example). So, is there any reason for this design?


How to represent days and time graphically for a project I have done

How to represent the days and hours of different tasks(design, development, testing) of a software project in a graphical way. I tried using a Gantt chart for it, but it does not represent the hours but just days, of a particular task, in a project. Is there any way to do this in software management, I need this to show it to a client for a project I did. Here is some of the values I intend to use.               ●   Research time        ○    Days 10 - 8 hours * 10 = 80     ●   Design time         ○    Days 10 -8 hours * 10 = 80     ●   Development time        ○    Days 15 – 8 hours times 15 = 120          ●   Testing time        ○    Days 3 – 8 hours times 3 = 24


How to deal with the programmer's block?

> **Possible Duplicate:**   >  Dealing with frustration when things don't work Something I find myself coding something difficult and after hours of struggle my mind goes blank and I don't know what I am doing anymore. I'm not sure if this happen to a lot of programmers. Does this happen to you How do you deal with it?


Difference between Zend Framework & Zend Server?

The title tells everything about my question but still let me elaborate to clarify : I know very well about the ZEND Framework but what about the Zend server? Does it work like Apache server or anything else? What is the main difference between these two? I also know that Zend Server is a product of the Zend Company but where is it used?


What is the proper way of nesting resources in REST model?

I'm designing a REST API of service and got stuck on proper way to nest resources. Resources: partners, tickets, settings Connections between resources:   * partner has many tickets,   * partner has set of settings, Bussines logic:   * you can list all partners as anonymous user,   * you can add new ticket to specified partner as anonymous user,   * only partner can list his tickets,   * only partner can modify his tickets,   * only partner can list settings,   * only partner can modify settings, What I did till now: **Partner resources** GET /partners - list all partners   GET /partners/:id - show details of the partner specified by :id parameter   GET /partners/:partner_id/tickets - list of partner's tickets   GET /partners/:partner_id/tickets/:id - details of the specified partner's ticket   POST /partners/:partner_id/tickets - saves new ticket   PUT /partners/:partner_id/tickets/:id - updates the ticket specified by :id parameter   GET /partners/:partner_id/settings - list partner's settings   PUT /partners/:partner_id/settings - update partner's settings **Problem/Question** Would it be proper way to split nested resources (tickets, settings) to seperate resources or duplicate them as seperate resources? E.g. GET /tickets/:id   POST /tickets   PUT /tickets/:id GET /settings   PUT /settings


Are specific types still necessary?

One thing that occurred to me the other day, are specific types still necessary or a legacy that is holding us back. What I mean is: do we really need short, int, long, bigint etc etc. I understand the reasoning, variables/objects are kept in memory, memory needs to be allocated and therefore we need to know how big a variable can be. But really, shouldn't a modern programming language be able to handle "adaptive types", ie, if something is only ever allocated in the shortint range it uses fewer bytes, and if something is suddenly allocated a very big number the memory is allocated accordinly for that particular instance. Float, real and double's are a bit trickier since the type depends on what precision you need. Strings should however be able to take upp less memory in many instances (in .Net) where mostly ascii is used buth strings always take up double the memory because of unicode encoding. One argument for specific types might be that it's part of the specification, ie for example a variable should not be able to be bigger than a certain value so we set it to shortint. But why not have type constraints instead? It would be much more flexible and powerful to be able to set permissible ranges and values on variables (and properties). I realize the immense problem in revamping the type architecture since it's so tightly integrated with underlying hardware and things like serialization might become tricky indeed. But from a programming perspective it should be great no?


Need help deciding if Joomla! experience as a good metric for hiring a particular prospective employee

My company has been looking to hire a PHP developer. Some of the requirements for the job include:   1. an understanding of design patterns, particularly MVC.   2. some knowledge of PHP 5.3's new features.   3. experience working with a PHP framework (it doesn't matter which one). I interviewed a man today who's primary work experience involved working with Joomla!. As an employee, he will be required to work on existing and new web applications that use Zend Framework, CakePHP and/or CodeIgniter. It is my opinion that we shouldn't dismiss hiring a developer just because he has not used the same technologies that he'll be using on the job. So, I'd like to know about the kind of coding experience working with Joomla! can provide. I've never bothered to take more than a brief look (if that) at the Joomla! package, so I'm hoping to lean on the knowledge of my peers.   * Would you consider Joomla! to contain a professional code-base?   * Is the package well organized, and/or OO in general, or is it more like WordPress where logic and presentation are commingled?   * When working with Joomla!, is the developer encouraged to use best practices?   * In your opinion, would experience working with Joomla! garner the skills needed to get up to speed with Zend or CakePHP quickly, or will there be a steep learning curve ahead of the developer? I'm not saying that Joomla! is a bad technology, or even that it is lower on the totem pole when compared to the frameworks I've mentioned. Maybe it's awesome, I dunno. I simply have no idea!


Is there a certain number of lines of code to be followed /maintain?

I am developing a software system (Patient Administration System) and I have noticed it already had 451 lines of code(in one namespace). Is this bad? Or does the number of lines of code not matter as long as the methods and comments are useful and they doing what they are intended to do? Or there is a number of lines of code to maintain like a namespace should only have 500 lines of code something like that


Use camera to analyze homogeneity

We are working with some screens whose in the production process change their state from a transparent state to a colored state. This colored state is achieved to block light transmittance. In this process where the screen gets tinted, this tint must be applied homogeneously. This is a very important point of the process. To check this homogeneity, I've been asked to develop a mobile app (Android) in which using the camera I could check if the tint is applied homogeneously. I'm an android programmer so the knowledge about android is not a problem. But I've never worked with images this way so I ignore if such a thing like this could be done. My first idea is to develop an app which using the camera takes a photo, this is the easy part. After this, I should process the image some way that I could identify non homogeneous parts, maybe convert the image to grey scales and check for clearer or darker tones. I'm not asking about how should I programm that, as this is just a first idea on how could I achieve this, what I'm asking help for is to know how could I do that kind of image processing that could detect homogeneity.


should F12's request headers show session id as cookie?

I'm trying to educate myself on potential web attacks. I just found a site (which will rename anonymous) where it shows me what looks to be like the php session id inside the cookies section of the request header. My immediate reaction was "wow, that's bad"... but then i couldn't really come up with a scenario as to how someone could use this to mess up the site. But maybe its because I'm a newbie to this stuff. But assuming that I got someone else's session id... I'd have to hack the site with their session id before it expires right? So my question is, how real is this threat? And is this common, where web developers store session ids in cookies, thereby making it visible in F12? Sorry for the remedial questions. I read the article: Why popular websites store very complicated session related data in cookies -- and what does it all mean? And i get that sometimes, you want to use cookies to move data off server to client... but I think I need more clarification on how serious a security breach this is.


How do you debug without an IDE?

Every time I look for an IDE (currently i'm tinkering with Go), I find a thread full of people recommending Vi, Emacs, Notepad++ etc. I've never done any development outside of an IDE; I guess I've been spoiled. How do you debug without an IDE? Are you limited to just logging?


How to write a good app store description?

> **Possible Duplicate:**   >  How to improve the quality of app descriptions I've just finished writing an iPhone app, and I've completed everything on my app store submission checklist except the description. Has anyone got any advice on how to write a really catchy description that's likely to get users interested?   * What things are important to include in the description?   * What _not_ to include? I really have no experience with this, as this is the first app I'll ever release to the store.


Why don't software vendors use existing scheduling facilities for automatic upgrades?

It is common for software vendors to offer automatic updates. The research and installation of these updates can be done   * at application startup   * through a service or process in the background (which often can be seen in the icon tray)   * Sometimes at the opening of a session or boot The problem I encounter today is that Google, Sun Java, Adobe and others... updates system seem to squander resources of my computer to watch for updates continuously. One uses a service, the other a running process... Why do those suppliers not use the scheduling tools offered by the operating system, like the **Task Scheduler**?


How should I charge for programming things which take two minutes to fix?

I am really confused with this. I believe that the more I am getting experience, the more I am becoming an expert at finding mistakes and fixing them quickly. Now my boss got website from a programmer who does very very bad coding. Now he sends the list of problems to fix. Suppose it's the stylesheet problem, and the old guy does not know how to fix it, but due to my experience I know straightaway what the problem is, and I can fix it in two minutes and many similar problems like that. But after fixing all that I realise that I fixed all problems in 15 minutes which other guy was not able to solve. I get 25$ per hour, so I feel very bad charging 6$ for that list of things which took many years of experience to learn. Is it OK to charge 6$ or should there be some way to charge things?


When a task can be accomplished by either Javascript or CSS, is it better to use CSS?

I always veto JavaScript by using CSS as much as possible. i.e. I create tabs and rollover buttons using CSS rather than JavaScript. I have seen some solutions—specifically the Wt web-framework—which advocate JavaScript; but gracefully downgrade to CSS if the browser isn't capable/js- disabled. I know CSS and JavaScript have different purposes, however there is overlap; which is the _bourne_ of this question. **Should I continue using CSS as much as possible over JavaScript?**


How to make models do more than setting and getting data and validation

I am asking this question because after developing a few small custom cms solutions in a framework, I developed the idea that Models can be easily substituted with ORMs which ease up the task of validating, getting and setting data, as thats all they are needed for.   I recently got an order for a complex custom client management solution. After researching a bit on how to proceed on it, I found this:   http://blog.astrumfutura.com/2008/12/the-m-in-mvc-why-models-are- misunderstood-and-unappreciated/      Now the idea is not new as thats what i had read about the MVC approach, models handle the business logic. But I am finding it hard to plan out an approach in which Models handle the business logic and are classes which are complete in themselves because of the type of work i have gotten used to.   Please help me out here by explaining the idea and pointing me to some examples, articles etc


A Project's Initial Commit to Source Control

I'm probably over-thinking this and it might not matter in the scope of things, but I'm wondering how people build up initial versions of their projects in source control? I'm talking about when you start with nothing but an idea, so no forking an existing project or anything.   * When do you do your commits before having an official or even unofficial version?   * At what point do you start branching for features, or do you this right away? I'm so used to working with existing code bases that I'm not really sure I know if there's a "best" way to build up a project history.


I need advice for a subsystem design?

I'm doing it in C++, I can't post the entire thing, because it's gigantic, I'll just sum it up with a simple example.I have:               class B;          class A     {      //Members and methods...       void DoSomething(B* owningSystem);     };          class B     {      //Members and methods     A memberA;     }      So the problem is, A needs to know about B to use its DoSomething method and A is actually a member of B.I have an array of B's, who's number is determined at run-time.This might sound like overdoing it, but I need extreme optimization in this specific project and I was wondering - is it better to pass B* owningSystem or to just store a pointer of each B inside its A member?I don't think DoSomething will ever be inlined, since their count and pointer locations are determined at run-time, but I can chose storing a pointer vs. passing it in the function.I need to minimize the overhead at this point by as much as I can, it's critical.I'm open to any suggestions, please


portfolio building, working for closed-source vs open-source?

I've currently graduated from my first run at higher education, landed my first full-time gig as a web application developer, and absolutely love it. My question is that in looking for jobs I ran across many jobs that require a certain level of experience and code examples. Much of the work I am doing is both protected by a login, and closed source. How does someone, that is just starting out and needs to be building a resume, go about preparing for the next job. (no matter how much i love my current job, i feel like it's only responsible to always be preparing)


Building a DBAL from scratch

I am considering building a **DBAL** from scratch with PHP to use within my projects and also to learn through the process. I have noticed on _SO_ and other reputable forums that whenever this is mentioned most users advise to use an established DBAL like Doctrine and to not " _reinvent the wheel_ ". Why is it that with this specific piece people continuously recommend to use a pre-made one? Is it that hard/problematic to create and build as you go? If so what are the main problem points? I assume security is one. In regards to the established DBALs like Doctrine, I have downloaded and inspected the contents and noticed its rather big, for those who have experience with this, is all of this really necessary? Do you use all of this functionality provided(and know whats happening in the backend)? From what I inspected I am finding it hard to see how I would use more than 40% of the libary, along with this I have the feeling that I am not completely sure whats happening in the backend with such a big library. Perhaps this is a common feeling and you get over it?


Poker software architecture

I have some classes so far.   * **Hand** stores information like SB, BB, ante, collection of Players   * **HandState** inherits from class Hand. has members like phase {POSTING BLINDS, PREFLOP, FLOP, TURN, RIVER, SHOWDOWN }, pot. I consider every action in a poker hand as a handState. Players post ante (if any), Small blind and big blind posts blinds, the first player to act (UTG) calls the blind, the 2nd player (UTG+1) raises, etc...   * **Player** members: name, position, list of actions so far, stack, etc...   * **Action** members: type {FOLD,CALL, RAISE, RERAISE}, amount The program receives as input the blinds, players, which player to act. Since the input I get is string (its a console program) I have to build the root handState. After I have the root handState, I can build a gameTree where every node is a handState. eg.:               stacks = "1000,2000,2300,1400,230";     actions = "200";     playerToAct = 2;     BB = 400;     SB = 200;          function makeRoot()     {         stacks = makeArray(stacks)         for(i=0; i < stacks.size; i++)         {             player = new Player;             player.position =  "UTG"             if (i > 0)                 player.position += i;             if (i == stacks.size-2)             {                 player.position = "SB";                 player.bet(SB);             }             if (i == stacks.size-1)             {                 player.position = "BB";                 player.bet(BB);             }         }                   }      My problem that Player and HandState has no connection. What if player has not enough chips to pay the BigBlind (230<400)? SB has enough chips, but if he bets 200, HandState's pot wont know about it? Should I keep track in both class?               //HandState     player.bet(200);     this.pot += 200;          //Player     bet(amount)     {         this.stack -= amount;         this.actions.push(new Action(amount, "BET"));     }      I hope there is some seasoned programmer with some poker knowledge to tell some opinion, critique my approach.


Why is subclassing TraversableOnce not recommended

Reading http://www.scala- lang.org/api/2.11.1/index.html#scala.collection.TraversableOnce: > Directly subclassing TraversableOnce is not recommended - instead, consider > declaring an Iterator with a next and hasNext method, creating an Iterator > with one of the methods on the Iterator object, or declaring a subclass of > Traversable. Why is subclassing `TraversableOnce` not recommended?


Should I use check or checked?

I'm designing a library that binds to html elements on a page. In this particular case the input[type='checkbox'] will be checked if the likeItem property returns true and unchecked if the likeItem property returns false. What's the best practice for naming properties? input { check: likeItem } or input { checked: likeItem } This would also apply to other things like enable/enabled, disable/disabled, etc.


How do you prevent the piracy of your software?

Is it still worth it to protect our software against piracy? There are reasonably effective ways to prevent or at least make piracy difficult?


What is the best way to become a professional in PHP and Website Building?

I would like to become a professional in php, I have learned nearly all about the language syntax and concepts and I have a good knowledge in C and C++, which made it easier to become familiar with PHP. (Of course, I learned MySql too.) But I don't feel like being able to build even a little good website of my own! It looks like PHP is all about knowing lots of functions and using them, while in fact I don't think it's like that, is it? How can I become a professional in PHP and Website Building? I would do anything and spend whatever amount of time required for that. **EDIT** I've also a very good knowledge in HTML and a normal knowledge in CSS and JavaScript. Sorry for not mentioning that, I just thought it was implicitly included.


java.util.HashMap lock on actual HashMap object compare to lock on object that encapsulate the HashMap

The below Javadoc is an snippet of HashMap documentation. Why authors would emphasize on putting a lock on the object that encapsulate a HashMap? Lock on the actual HashMap Object makes for sense. > **Note that this implementation is not synchronized.** If multiple threads > access a hash map concurrently, and at least one of the threads modifies the > map structurally, it _must_ be synchronized externally. (A structural > modification is any operation that adds or deletes one or more mappings; > merely changing the value associated with a key that an instance already > contains is not a structural modification.) This is typically accomplished > by synchronizing on some object that naturally encapsulates the map. If no > such object exists, the map should be "wrapped" using the > Collections.synchronizedMap method...


Does data size in TCP/UDP make a difference on transmission time

While discussing the development of a network component for our game engine, a member of our team suggested that transmitting either 500 bytes or 1k of data using UDP makes no difference from performance perspective of the system (the time it takes to transmit the data). He actually said that as long as you don't cross the MTU size, the size of the transmitted data doesn't really matter as it's all the same. Is that true for UDP? what about TCP? That sounds just plain wrong to me, but i am not a network expert. *I've been reading about other companies' game networking architectures, and it seems they're all trying to keep transmitted data to a minimum, making my colleague's claims seem even more unreasonable.