Balance between "right tool for the job" and familiarity

So when choosing what language to use for a project, in an ideal world the language is chosen because it's the right tool for the job. However, I often prefer to use a language that I am _fluent_ in rather than one I would have to learn or that I am only conversational in. Of course language fluency also entails knowledge of the applicable libraries in the language. Just because I really like a fairly general-purpose language like Java doesn't mean I should always use it, but at the same time it doesn't mean I should break out something like Perl every time there's some text processing to be done. How does one find the balance here?


What is the best way to approach visualization projects?

I work on several areas related to information visualization, linked data, computer vision and other stuff, so mainly front-end. I am not really happy with the fact that visualizations take lots of iterations and lots of time from first prototype to production ready code. So here is the question: what can I do to improve that? Sometimes we do a prototype in few hours, add something, do another prototype, rewrite it to use jQuery instead of Prototype because it's a better fit and so on and so forth, but almost all visualizations go trough 15-20 iterations (sometimes taking up to few months of development time - the code will also go from the 300 lines of the initial prototype to 2000 or 3000 lines due to evolving requirements and iterations). Since I am working at multiple projects, from my point of view the fact that sometimes it can take months is not a problem, just that I am not really happy, as I could do 40 visualizations per year instead of 15 for example, if I would only be able to improve this process by reducing the number of iterations or by any other means. If somebody with a higher score wants to add information visualization to tags and edit my question after, I would not mind. Best regards!


Software development life cycle in the industry

I am taking a module called "Requirements Analysis & Design" in a local university. Common module, I'd say (on software development life cycle (SDLC) and UML). But there is a lot of things I wonder if they are actually (strictly) practiced in the industry. For example, will a domain class diagram, an not anything extra (from design class), be strictly the output from Analysis or Discovery phase? I'm sure many times you will think a bit about the technical implementation too? Else you might end up with a design class diagram later that is very different from the original domain class diagram? I also find it hard to remember what diagrams are from Initiation, Discovery, Design etc etc. Plus these phases vary from SDLC to SDLC, I believe? So I usually will create a diagram when I think will be useful. Is it the wrong way?


What are the benefits of using geospatial datatypes?

We currently store points as three floats (lat,lon,alt) and support only one type of query (points within a given radius) but look forward to support more queries. We are using PHP and MySQL. What are the benefits of using geospatial types?


Is it reasonable to concentrate on one topic of CS for one semester at university?

As usual, I need to do courses from several different areas of Computer Science for my Master's degree. I'll focus on Algorithms, Theoretical Computer Science (Computability and Complexity, the foundations,...) and Parallel/High Performance computing plus maybe a bit of Programming Languages at the side. To finish in time, I have to do 5-8 courses per semester. Is it reasonable to focus on one topic per semester? E.g., I'll do about 5 courses on Algorithms. My assumption is that if I do all of these in one semester, I'll get a deeper understanding of the topic. Or would it be more beneficial for me to do 1-2 courses form each area per semester?


Breaking 1NF to model subset constraints. Does this sound sane?

My first question here. Appologize if it is in the wrong forum but this seems pretty conceptual. I am looking at doing something that goes against conventional wisdom and want to get some feedback as to whether this is totally insane or will result in problems, so critique away! I am on PostgreSQL 9.1 but may be moving to 9.2 for this part of this project. To re-iterate: Does it seem sane to break 1NF in this way? I am not looking for debugging code so much as where people see problems that this might lead. # The Problem In double entry accounting, financial transactions are journal entries with an arbitrary number of lines. Each line has either a left value (debit) or a right value (credit) which can be modelled as a single value with negatives as debits and positives as credits or vice versa. The sum of all debits and credits must equal zero (so if we go with a single amount field, sum(amount) must equal zero for each financial journal entry). SQL-based databases, pretty much required for this sort of work, have no way to express this sort of constraint natively and so any approach to enforcing it in the database seems rather complex. # The Write Model The journal entries are append only. There is a possibility we will add a delete model but it will be subject to a different set of restrictions and so is not applicable here. If and when we allow deletes, we will probably do them using a simple ON DELETE CASCADE designation on the foreign key, and require that deletes go through a dedicated stored procedure which can enforce the other constraints. So inserts and selects have to be accommodated but updates and deletes do not for this task. # My Proposed Solution My proposed solution is to break first normal form and model constraints on arrays of tuples, with a trigger that breaks the rows out into another table.               CREATE TABLE journal_line (         entry_id bigserial primary key,         account_id int not null references account(id),         journal_entry_id bigint not null, -- adding references later         amount numeric not null     );      I would then add "table methods" to extract debits and credits for reporting purposes:               CREATE OR REPLACE FUNCTION debits(journal_line) RETURNS numeric     LANGUAGE sql IMMUTABLE AS $$     SELECT CASE WHEN $1.amount < 0 THEN $1.amount * -1 ELSE NULL END; $$;          CREATE OR REPLACE FUNCTION credits(journal_line) RETURNS numeric     LANGUAGE sql IMMUTABLE AS $$     SELECT CASE WHEN $1.amount > 0 THEN $1.amount ELSE NULL END; $$;      Then the journal entry table (simplified for this example):               CREATE TABLE journal_entry (         entry_id bigserial primary key, -- no natural keys :-(         journal_id int not null references journal(id),         date_posted date not null,         reference text not null,         description text not null,         journal_lines journal_line[] not null     );      Then a table method and and check constraints:               CREATE OR REPLACE FUNCTION running_total(journal_entry) returns numeric     language sql immutable as $$     SELECT sum(amount) FROM unnest($1.journal_lines); $$;          ALTER TABLE journal_entry      ADD CONSTRAINT CHECK (((journal_entry.running_total) = 0));          ALTER TABLE journal_line     ADD FOREIGN KEY journal_entry_id REFERENCES journal_entry(entry_id);      And finally we'd have a breakout trigger:               CREATE OR REPLACE FUNCTION je_breakout() RETURNS TRIGGER     LANGUAGE PLPGSQL AS $$      BEGIN        IF TG_OP = 'INSERT' THEN           INSERT INTO journal_line (journal_entry_id, account_id, amount)           SELECT NEW.id, account_id, amount             FROM unnest(NEW.journal_lines);           RETURN NEW;        ELSE           RAISE EXCEPTION 'Operation Not Allowed';        END IF;      END;     $$;       And finally               CREATE TRIGGER AFTER INSERT OR UPDATE OR DELETE ON journal_entry      FOR EACH ROW EXECUTE_PROCEDURE je_breaout();      Of course the example above is simplified. There will be a status table that will track approval status allowing for separation of duties, etc. However the goal here is to prevent unbalanced transactions. Any feedback? Does this sound entirely insane? # Standard Solutions? In getting to this point I have to say I have looked at four different current ERP solutions to this problems:   1. Represent every line item as a debit and a credit against different accounts.   2. Use of foreign keys against the line item table to enforce an eventual running total of 0   3. Use of constraint triggers in PostgreSQL   4. Forcing all validation here solely through the app logic. My concerns are that #1 is pretty limiting and very hard to audit internally. It's not programmer transparent and so it strikes me as being difficult to work with in the future. The second strikes me as being very complex and required a series of contraints and foreign keys against self to make work, and therefore it strikes me as complex, hard to sort out at least in my mind, and thus hard to work with. The fourth could be done as we force all access through stored procedures anyway and this is the most common solution (have the app total things up and throw an error otherwise). However, I think proof that a constraint is followed is superior to test cases, and so the question becomes whether this in fact generates insert anomilies rather than solving them. If this is a solved problem it isn't the case that everyone agrees on the solution....


Looking for tips on managing complexity with SCM repositories

I am a solo developer in my department and I have a lot of individual projects, all created and managed by me. I started using SVN at ProjectLocker via Versions on the Mac a couple years ago when the variety of projects started getting unwieldy. _Scenario 1_ : Now I have a process that is of reasonable complexity it can be broken up into multiple smaller applications and they all share files. In one phase, there is a single shared file—a constants file—that is shared between a Cocoa app and an iPhone app framework. In the second phase, the iPhone app framework will be used to create individual apps of the same ilk—controller classes and what not will all be the same—but with different content in each. The problem that I am running across is that the file in the first phase is in one repository with the application that started it, and the app framework is in a second, separate repository. _Scenario 2_ : I have another application framework that partially relies on code from an open source project. This is all internal, non-commerical work, but again, the application framework is going to be used to create a variety of unique products and processes. So, now I have an internally managed repository and an externally managed one out of my control. I make little changes to the open source code to meet the needs of my framework when there is an update I download, but I never commit back into the external repository (though, now that I think about it, I don't think I'm committing it to mine either. Oops). **The Problem** I have all of this set up on my production Mac quite nicely, but duplicating and subsequently maintaining that environment on my laptop has been challenging. For Scenario 1, I've thought of merging these two projects together into the same repository because they are, for all intents and purposes inextricably linked. But, Scenario 2, I think I'm stuck just managing files as best I can. **The Question** I'm wondering if anyone has any tips on how to manage either of these situations, as well as other complex SCM scenarios when it comes to linking various files from various repositories together. My familiarity with SVN only comes from my work with Versions. It's been great, but I'm a little out of my depth here.


Number of lines of code in a piece of software

Our manager has asked for a report on on the number of lines of code in our software. What should we do?


What are some good Object Oriented Design (OOD) interview questions?

I'm looking to prepare for a job interview and I wanted to go over some good Object Oriented Design (OOD) questions. Here are some of the OOD concepts that should give a good starting point:   1. inheritance    2. multiple inheritance    3. encapsulation    4. abstraction   5. composition    6. polymorphism    7. overriding polymorphism Would you please suggest any other OOD question(s)/topics that should be reviewed?


Benefits of porting C library to C++

Say we take any C library such as libpng or libvorbis and convert it so that it compiles as C++ (only the minimum changes to make it compile as C++ code). Can the compiler do extra optimizations when its C++ code? Is there **any sort** of benefit to be gained by porting the code to C++? What are the downsides that might cancel out these benefits?


Confused about implementing Single Responsibility Principle

Please bear with me if the question looks not well structured. To put you in the context of my issue: I am building an application that invoices vehicles stay duration in a parking. In addition to the stay service there are some other services. Each service has its own calculation logic. Here is an illustration (please correct me if the design is wrong):               public abstract class Service     {        public int Id { get; set; }        public bool IsActivated { get; set; }        public string Name { get; set }        public decimal Price { get; set; }     }          public class VehicleService : Service     {           //MTM : many to many        public virtual ICollection<MTMVehicleService> Vehicles { get; set; }     }          public class StayService : VehicleService     {          }          public class Vehicle     {        public int Id { get; set; }        public string ChassisNumber { get; set; }        public DateTime? EntryDate { get; set; }        public DateTime? DeliveryDate { get; set; }        //...        public virtual ICollection<MTMVehicleService> Services{ get; set; }     }      Now, I am focusing on the stay service as an example:   I would like to know at invoicing time which class(es) would be responsible for generating the invoice item for the service and for each vehicle? This should calculate the duration cost knowing that the duration could be invoiced partially so the rule is as follows: not yet invoiced stay days * stay price per day. At this moment I have InvoiceItemsGenerator do everything but I am aware that there is a better design.


Search Substring in String collection

I have a big collection of strings _a[1], …, a[N]_ where _N_ is about several millions. I am provided a string _m_ and I need to iterate over all the strings _a[i]_ that contain _m_. In other words, I need to find all the strings _a[i]_ having _m_ as substring. What would be the most efficient data structure for that problem? I need to be very careful with memory as I am working with a big number of strings.


What do these cocoonJS terms of use mean

I was looking at the terms of use for CocoonJS and noticed this section > License Grant. By uploading User Content via the Services, you expressly > grant, and you represent and warrant that you have a right to grant, and do > so grant, to Ludei, a royalty-free, non-exclusive, worldwide license to use, > reproduce, modify, publish, list information regarding, edit, translate, and > make derivative works of all such User Content and your name, voice, and/or > likeness as contained in your User Content, if applicable, in whole or in > part, and in any form, media or technology, whether now known or hereafter > developed, solely for use in connection with the Services. I am not too clear on the legal jargon, but to me this sounds like I'm basically giving someone unrestricted access to any intellectual property that I have submitted to their servers, and the ability to use my identity in any form as they wish. Can someone clarify what the excerpt means?


long lines in git or svn

I am coding a program which has persistent data (the MELT monitor, related to GCC MELT). The data is persistent because it is expected to be read and overwritten by most executions. (That data is in particular made of abstract syntax trees) Currently, this persistent data is an Sqlite database. Of course, I am backing up it in textual format, obtained by sqlite dump, and I want to manage this textual dump with a version control system (probably git, but perhaps also subversion ....). Unless I take special precautions, these SQL dumps will probably have quite long lines (e.g. several dozens of kilobytes). Wide SQL columns would probably contain JSON text of many kilobytes. Would `git` (and `svn`) be more happy with shorter lines (in particular would they perform slower with long lines, or have repositories using much more disk space)? I'm probably not mostly interested in the `diff` commands (e.g. `git diff` or `svn diff`), because I expect that using them for such textual dump is not very interesting for the human developers. I am coding the persistency routines, so I am able to change slightly the format (e.g. to add newlines in some JSON text, which `sqlite3 dump` is dumping verbatim). If you are curious, my current code snapshot is on http://starynkevitch.net/Basile/monimelt-bgc-21apr2014.tar.bz2 and contains a `state-monimelt.sql` dump file (which will of course become much larger, perhaps near or above a megabyte)


Extreme Programming for a single developer

I've been working with some basic extreme programming concepts for the last two weeks, for a small scale, for-profit, multiplayer, arcade game. I've spent a week developing user stories and determining requirements to create a release plan. I've also spent a week coding and applying the first iteration plan I came up with. I've identified a few of the obviously useful concepts for a single developer.   * Continuous Integration   * Never Add Functionality Early   * Test Driven Development   * Choose a System Metaphor   * Use a single Integration Point   * Test out all bugs   * Constantly refactor   * Set a sustainable pace   * Simplicity   * Frequent Releases I'm curious if I'm missing anything in particular that might be suited to working with a single developer project? Also, in this light given the idea of simplicity and test driven development, is it better to use established, feature-rich, ready made platforms? Or should I work from the ground up, when feasible, to avoid running into the issues presented with rules such as constantly refactoring and never adding functionality early?


What are the Characteristics of a Software "Center of Excellence" (CoE)?

Recently a new director of my department came in and expressed his wish that we become a "center of excellence". I expected that since he is my first boss who actually has a programming background that there would be some description of this. However, it was left at that. As I reflected on this over the last few days, I am coming up empty on what a CoE actually means beyond just "being effective" at delivering the product. Here are the main items I am struggling with:   1. Is this just a term that is thrown around by management types?   2. What qualities make a group of software developers and testers excellent?   3. How do you measure excellence in this context?


What is an algorithm?

What exactly is an algorithm, as in what does Algorithm mean? The little I understand the word, is that it's not specific to a particular language, or design pattern, rather it's one the most basic principles (so I guess this question makes me look stupid). One of the "options" I have of understanding it, is that it means the method of getting something done, that could be written as a list in pseudocode. When I write more complicated code, I think what needs to be done, with what, and how I would get there (not in a programming language), then write that in code. Is that good way to go about it, and is that anything to do with algorithms? (I wanted to ask here rather on Stackoverflow, because it's not about a specific problem/language plus I get the feeling that the majority of people here know the 'why', or at least the answers here are more detailed, rather than on Stackoverflow where it's different, I'm sorry if I should have asked over there)


How do you work out timings for larger projects?

I work for a small company that hasn't done much work in bespoke development. It's something we're growing into. With all our projects, whether a bespoke development piece of work, or a simple brochure website, we plan out how long we expect the job to take us and then multiply that by our daily fee to give us a quote for the customer. That has always worked well for us with the smaller projects, the CMS sites, the eCommerce sites, where we know the systems well and don't come across many issues. We have timings down well and can predict costs accurately. However with these larger bespoke projects we're starting to find that no matter how much we plan ahead, no matter how much we nail the specifications of the system, our timings are always out. We've started adding in a considerable buffer for bespoke pieces of software, but even then a couple of nasty bugs can really set things back and push us beyond what we expect by quite a long way. How do you quote for these larger projects? Is it simply a case of keep going and eventually we'll get it right? Or are we missing something here as it seems almost impossible to nail pricing down for bespoke websites that fall outside our standard CMS or eCommerce site. * * * **Update** As @Zeroth pointed out there's probably a few things missing out about the team. We don't run sprints. We have one large project on the go and have milestones and just set goals based on our estimates of how long things should take. As for the team, currently it's made up of 4 people, although 2 new people are being trained up at the moment. The 4 people make up a salesman and designer (he's also the office manager), a designer and website builder, a website builder who also deals with content for the sites and day to day customer facing issues, and me, the developer. I deal with development of custom projects and improving / fixing our CMS and eCommerce platforms. The two people being trained up are another designer and website builder, and a junior developer. Once a project reaches certain milestones, everyone pitches in to test it as thoroughly as we can. I always put in as much logging and debugging information as I can think of to help track down the inevitable bugs as quickly as possible, but no matter how much we do, we can't test every situation. I understand this is a complex and widely varying answer, I guess I'm mostly after some advice and also some pointers to resources (thank you @MichaelT for the link to the book) that can help us improve. We need to be able to pull a profit from custom work as we're currently fully booked until June for development work and we need to make this work for us. Over the last year, it just seems no matter how much we learn from each project we work on, we still get it wrong with our estimates.


Inheritance using non-abstract base class

This post is based on the question http://stackoverflow.com/questions/49002/prefer-composition-over- inheritance/11758048#comment15634305_11758048. Some people said - check whether there is “is-a” relationship. If it is there use inheritance. What I think is there should be a second check for using inheritance. Use inheritance only if the base class is abstract. If the base class need to be instantiated then use composition; not inheritance. E.g 1. Accountant is an Employee. But I will not use inheritance because a Employee object can be instantiated. (When you talk to business people, they will tell you - Accountant is an Employee. But in OO world Accountant is not (should not be) an employee) E.g 2. Book is a SellingItem. A SellingItem cannot be instantiated - it is abstract concept. Hence I will use inheritance. The SellingItem is an abstract base class (or interface in C#) What I am looking for here is an example that will challenge my argument –that is a scenario in which inheritance is better than composition even though the base class is non-abstract (base class can be instantiated). Can you please provide such an example? Note: It would be more helpful if you can provide a scenario based on Bank domain, HR domain, Retail domain or any other popular domain. Note: In the design, please assume that we have full control of the code. That is we are not using any external API. Also we are starting from beginning. I will mark as answered if there is an example that explains a scenario that proves my argument is wrong. It is not a mere discussion on whether to use Composition or Inheritance. I support @anon answer in http://stackoverflow.com/questions/3351666/why-use- inheritance-at-all?lq=1 > The main reason for using inheritance is not as a form of composition - it > is so you can get polymorphic behaviour. If you don't need polymorphism, you > probably should not be using inheritance. @MatthieuM. says in Code Smell: Inheritance Abuse > The issue with inheritance is that it can be used for two orthogonal > purposes: > > interface (for polymorphism) > > implementation (for code reuse) **REFERENCE**   1. Employee- Accountant Example http://stackoverflow.com/questions/11759120/issue-in-using-composition-for-is-a-relationship   2. Selling Item Example - http://codereview.stackexchange.com/questions/14077/is-it-proper-tpt-inheritance   3. Programming SOLID Principles   4. Code Smell: Inheritance Abuse


Is it bad to have an "Obsessive Refactoring Disorder"?

I was reading this question and realized that could almost be me. I am fairly OCD about refactoring someone else's code when I see that I can improve it. For example, if the code contains duplicate methods to do the same thing with nothing more than a single parameter changing, I feel I have to remove all the copy/paste methods and replace it with one generic one. Is this bad? Should I try and stop? I try not to refactor unless I can actually make improvements to the code performance or readability, or if the person who did the code isn't following our standard naming conventions (I hate expecting a variable to be local because of the naming standard, only to discover it is a global variable which has been incorrectly named)


In C and C++, what methods can prevent accidental use of the assignment(=) where equivalence(==) is needed?

In C and C++, it is very easy to write the following code with a serious error.               char responseChar = getchar();     int confirmExit = 'y' == tolower(responseChar);     if (confirmExit = 1)     {         exit(0);     }      The error is that the if statement should have been:               if (confirmExit == 1)      As coded, it will exit every time, because the assignment of the `confirmExit` variable occurs, then `confirmExit` is used as the result of the expression. Are there good ways to prevent this kind of error?


How to create an Intelligent Agent

I am currently doing my Honours in Computer Science and taking Artificial Intelligence as a subject. As part of completing the subject I have to develop my own basic intelligent agent. I have yet to wrap my head around what I actually have to do for this project. I am not the most technically gifted programmer and I have no idea of what to do or where to start Could someone please point me in the right direction as to where to start learning how to develop an Intelligent Agent as well as any possible idea's of what to actually do for a project? The requirement for the project are very vague as we were not told how technical or big the project should be. (Hopefully not too big as I have another 8 subjects who require projects as well). Any VB.net references would be appreciated as well. (I know it's not the best language to develop an IA with, but due to my time constraints this is the programming language I 'feel' most comfortable with).


Is a "build" assembly?

In an old book I have, they say that "build" is either a process of converting source code into executable or the actual result - assembly. Is that correct? Is a build actually the assembly, I mean from terminological point of view.


How to have quicker launch and lesser memory footprint using IntelliJ Idea?

I am trying to move from Eclipse to IntelliJ Idea. I am trying out various dev plugins cases for IntelliJ Idea - android, clojure, scala, python, javascript, java, gwt, dart, jboss, spring etc. The start time increases as more plugins are installed (as mentioned by IntelliJ Idea wiki). _I am keen to learn different aspects of programming_. I am trying to find out how developers use IntelliJ Idea when working with multiple language environment. 1) Do they have different IntelliJ Idea installations to work with different language environments i.e the above scenario have 5-6 different IntelliJ installations with only appropriate plugins installed only. 2) Does IntelliJ Idea provide a mechanism to turn off different plugins within a single installation?


Sorting and averaging the highest values of pixel data

Currently, I am using Android/Java. I am looking for the most efficient means to determine the average of the highest 100 pixel values taken from a greyscale preview. The preview part I am more or less okay with; however, it determining which sorting methodology is the most efficient. The other option is to apply a threshold, which will eliminate most of the data. Which sorting algorithm would be most efficient for an unsorted data set of over 3 million values?


Anything beneficial from ORM for a NodeJS project already plain-SQL-implemented?

Well, actually it's a assignment project and I've already implemented a simple yet functional forum with NodeJS. But now we've been required to **use ORM frameworks to refactor part of your code worth refactoring**. As I use Node.JS, there's no such _type-safe_ benefits from ORM I could get. Besides, the code is already functional and I just don't see what good ORM could bring to it... (Requests are handled pretty swiftly and independently... I don't think I would like to cache tons of `Object`s from database to `request.session`...) My question is, what possible benefits will an ORM bring to a stable NodeJS project?


I need a public cryptography system that works on small keys

I just need it to support signing and signature verification. I need it to have public and private keys that fit _each_ in 16 bytes. The signature itself must fit 16 bytes. I don't really care about cryptographic strength, as this is part of something bigger. Is there such a thing?


Giving a double type for sqrt library function in C

_The C Programming Language_ by Ritchie says that: > The library routine `sqrt` expects a double type and will produce nonsense > if inadvertently handled something else. So if `n` is an integer, we can use > `sqrt((double) n)` to convert the value of `n` to double. But the following code works fine on my system:               printf("%f",sqrt(9));      Then also it is giving the same result as `sqrt((double)9)`. Why is my compiler not following the book?


How often should I be compiling?

For the longest time I've just done small app development. Building and debugging took a matter of seconds (or should I say - second?). I got fairly used to just debugging to test literally everything (and it's nice to see my stuff working - like a programming high almost). The problem is that as of late I've been working on a much larger project. The single solution contains 4 (and probably more soon) projects each very large. As it expands, compile times naturally increase making debugging a real pain. I'm stuck in my "compile every update" mode and it has wasted quite a bit of my time. Every visible update I want to see it. **So...** How can I get out of this irrational compile/debug habit and how often should I actually be compiling and debugging my application? **EDIT:** I'm utilizing Visual Studio. My compile times I realize are minuscule to what most of you are used to I realize, but it is still wasting my time :)


When using Hibernate can we forget about Database Design?

We started (just me and my friend) working on a website. As a part design phase we have finished the drawing a Site Map, decided on the content in each of the web page and the navigation. As we want to use the Spring MVC and Hibernate we want to start on Classes design (domain classes) first so that the database part is taken care by Hibernate (Except for some tables for static data). Does our approach correct? Is my understanding correct that when we use Hibernate the 80% of the database design can be forgotten?


SQL DB design to support user feeds (in application like facebook)

I have a social network server with a MySql DB. I want to show the users feeds like done in Facebook. Example - UserX now Friend with userY, userX did like on postX etc. Currently I have table: C1 : UserId C2 : LogType (now friend, did like etc) C3 : ObjectId (Can be userId or postId) - set depending on the LogType. Currently to get all related logs to show to the user I do the following queries: 1. Get All user Friends userIds 2. Query all rows which C1 is in userIds (I query completed) 3. Scan the DB and see - if LogType equals DidLike, check if post's OwnerId is the userId - if yes add it to logs. And so on. Obvious this is not efficient at all. I am looking for a better way. I thought I had in mind: Create a new table (in addition to the Log table) C1 : UserId C2 : LogId (from Log table) C3 : UserID of the one who did the action When querying logs - look in the table and get related Logs (by LogId) from LogTable. Updating the table: Whenever user doing action that should be in the log: 1. Add the Log entry to LogTable. 2. Scan the DB and see which users are interested with the Log (Who my friends are, Who is the owner of the post) and add related entries to the new table. (must be done in BG). 3. If user UNFRIEND another user - then look in the logs for all rows where C3 == UNFRIENDED user id and delete them. Any opinions? Other suggestions?


How do you handle multiple projects that form the same product(s)?

I have limited experience when it comes to build and version control systems. I feel like I've run into a common problem but I'm having trouble uncovering how it is typically handled. Say you have four source code projects:   * fooLib - Shared library   * fizzLib - Shared library   * buzzApp - Application that depends on fooLib   * barApp - Application that depends on fizzLib and fooLib Now, say you have two products:   * ProductA - only needs buzzApp   * ProductB - only needs barApp If my task were to make bug fixes to ProductB, how would I go about checking out the projects? Am I supposed to figure out the dependencies (or look them up) or is there some automated way of doing this? Also, how could this be automated for nightly builds for each product?


Dealing with under performing co-worker

I'm going to try to keep this topic as generic as I can so the question isn't closed as too specific or whatever. Anyway, let's get to it. I currently work on a somewhat small project with 15-20 developers. We recently hired a few new people because we had the hours and it synched up well with the schedule. It was refreshing to see hiring done this way and not just throwing hours & employees at a problem. Alas, I could argue the hiring process still isn't perfect but that's another story for another day. Anyway, one of these developers is really under performing. The developer is green and has a lot of bad habits. Comes in later than I do and leaving earlier than I am. This in and of itself isn't an issue, but the lack of quality work makes it become a bit frustrating. When giving out tasking the question is no longer, what can realistically be given but now becomes - How much of the work will we have to redo? So as the project goes on, I'm afraid this might cause issues with the schedule. The schedule could have been defined as a bit aggressive; however, given that this person is under performing it now in my mind goes from aggressive to potentially chaotic. Yes, one person shouldn't make or break a schedule and that in and of itself is an issue too but please let's ignore that for right now. What's the best way to deal with this? I'm not the boss, I'm not the project lead but I've been around for a while now and am not sure how to proceed. Complaining to management comes across as childish and doing nothing seems wrong. I'll ask the community for insight/advice/suggestions.


Improving the running time of Breadth First Search and Adjacency List creation

We are given an array of integers where all elements are between 0-9. have to start from the 1st position and reach end in minimum no of moves such that we can from an index i move 1 position back and forward i.e i-1 and i+1 and jump to any index having the same value as index i.   Time Limit : 1 second   Max input size : 100000 I have tried to solve this problem use a single source shortest path approach using Breadth First Search and though BFS itself is O(V+E) and runs in time the adjacency list creation takes O(n2) time and therefore overall complexity becomes O(n2). is there any way i can decrease the time complexity of adjacency list creation? or is there a better and more efficient way of solving the problem?               int main(){              vector<int> v;         string str;         vector<int> sets[10];              cin>>str;         int in;         for(int i=0;i<str.length();i++){             in=str[i]-'0';             v.push_back(in);             sets[in].push_back(i);         }              int n=v.size();         if(n==1){             cout<<"0\n";             return 0;         }         if(v[0]==v[n-1]){             cout<<"1\n";             return 0;         }                   vector<int> adj[100001];         for(int i=0;i<10;i++){             for(int j=0;j<sets[i].size();j++){                 if(sets[i][j]>0)                     adj[sets[i][j]].push_back(sets[i][j]-1);                 if(sets[i][j]<n-1)                       adj[sets[i][j]].push_back(sets[i][j]+1);                 for(int k=j+1;k<sets[i].size();k++){                     if(abs(sets[i][j]-sets[i][k])!=1){                         adj[sets[i][j]].push_back(sets[i][k]);                         adj[sets[i][k]].push_back(sets[i][j]);                     }                 }             }         }              queue<int> q;         q.push(0);              int dist[100001];         bool visited[100001]={false};         dist[0]=0;         visited[0]=true;              int c=0;         while(!q.empty()){             int dq=q.front();             q.pop();             c++;                  for(int i=0;i<adj[dq].size();i++){                 if(visited[adj[dq][i]]==false){                     dist[adj[dq][i]]=dist[dq]+1;                     visited[adj[dq][i]]=true;                     q.push(adj[dq][i]);                 }             }              }              cout<<dist[n-1]<<"\n";              return 0;     }


Writing a job requirement for a web application developer

I'm currently writing a job requirement for a software engineer position for my company, in which we are looking for a developer to work on client-side web application work. How should I title the job title / position? I don't necessarily want to call it a "Web Developer", for fear that it might attract more designer-y types. On the other hand, "Software Engineer" doesn't really give the indication that the work, while application based, will be web-based. Is "Web Application Software Engineer" a valid position title? Also, I'm somewhat torn on what the required skills set should be. I don't necessarily think that the ideal candidate should have x years of experience in say, JavaScript or ActionScript, but rather am just looking for someone who has experience in developing client-side applications, and is willing to learn and develop web applications. My current attempt at this, is that I have a section in which I state: > Experience in the following frameworks and technologies are a plus, but not > necessarily required for the position:


Must I think about compiled machine code when I write my code?

For example I've got following code:               auto z = [](int x) -> int {         if (x > 0) {             switch (x) {                 case 2: return 5;                 case 3: return 6;                 default: return 1;                 }             }         return 0;         };      And later I call this several times. In asm code I see external calls with lambda....something... It's becoming not easy to read and I think it also can cause performance. So maybe I win in meta-programming but do I lose in asm debugging and performance? Should I avoid modern language features, macros and other meta programming aspects to be sure in performance and debugging simplicity?


Map multiple functions over a single data item

I'm in the process of learning Scala and I came across a scenario today where I need to map multiple functions over a single piece of data and wondered if there was a formal name for this. It sort of feels like the inverse of map. I'm not sure this is the correct way of expressing it, but this is what I did:               dmap(x: Object, fns: List[Function]) = fns.map(_(x))      Is there a built in way to do something similar? Is there a formal name for this function?


Ranking players depending on decision making during a game

How would I go about a ranking system for players that play a game? Basically, looking at video games, players throughout the game make critical decisions that ultimately impact the end game result. Is there a way or how would I go about a way to translate some of those factors (leveling up certain skills, purchasing certain items, etc.) into something like a curve that can be plotted on a graph? This game that I would like to implement this is League of Legends. Example: Player is Level 1 in the beginning. Gets a kill very early in the game (he gets gold because of the kill and it increases his "power curve"), and purchases attack damage (gives him more damage which also increases his "power curve". However, the player that he killed (Player 2), buys armor (counters attack damage). This slightly increases Player 2's own power curve, and reduces Player 1's power curve. There's many factors I would like to take into account. These relative factors (example: BECAUSE Player 2 built armor, and I am mainly attack damage, it lowers my OWN power curve) seem the hardest to implement. My question is this: Is there a certain way to approach this task? Are there similar theoretical concepts behind ranking systems that I should read up on (Maybe in game theory or data mining)? I've seen the ELO system, but it doesn't seem what I want since it simply takes into account wins and losses.


Expected time for lazy evaluation with nested functions?

A colleague and I are doing a free R course, although I believe this is a more general lazy evaluation issue, and have found a scenario that we have discussed briefly and I'd like to find out the answer from a wider community. The scenario is as follows (pseudo code):               wrapper => function(thing)     {         print => function()         {             write(thing)         }     }          v = createThing(1, 2, 3)     w = wrapper(v)     v = createThing(4, 5, 6)     w.print()     // Will print 4, 5, 6 thing.     v = create(7, 8, 9)     w.print()      // Will print 4, 5, 6 because "thing" has now been evaluated. Another similar situation is as follows:               // Using the same function as above     v = createThing(1, 2, 3)     v = wrapper(v)     w.print()     // The wrapper function incestuously includes itself.      Now I understand why this happens but where my colleague and I differ is on what should happen. My colleague's view is that this is a bug and the evaluation of the passed in argument should be forced at the point it is passed in so that the returned "w" function is fixed. My view is that I would prefer his option myself, but that I realise that the situation we are encountering is down to lazy evaluation and this is just how it works and is more a quirk than a bug. I am not actually sure of what would be expected, hence the reason I am asking this question. I think that function comments could express what will happen, or leave it to be very lazy, and if the coder using the function wants the argument evaluated then they can force it before passing it in. So, when working with lazy evaulation, what is the practice for the time to evaluate an argument passed, and stored, inside a function?


How to report a bug to developers? A programmers quest to educated on bug reporting

I'm hoping to get some tips and advice on how to educate the rest of the company on how to submit proper bug reports. Currently we get tickets like:   * When I click this link I get a 404. (They include the page that 404s and not the page that caused it)   * Sometimes the right column flows into the button column. (no screenshot or additional information)   * Changes to xxx does seem to be working right. (EOM) Does anyone have a bug submission process/form that guides users into submitting as much information as possible?


Interview question: how much would you test before you stop?

This was a question I got in an interview. After asking the coding question, the interviewer asked how I would test the function. I answered with writing unit tests and test cases to try to cover every edge case. The follow-up was how much would I test before I stop? What's the interviewer looking for in these questions? and what are some good answers?


What's a schrödinbug?

This wiki page tells : > A schrödinbug is a bug that manifests only after someone reading source code > or using the program in an unusual way notices that it never should have > worked in the first place, at which point the program promptly stops working > for everybody until fixed. The Jargon File adds: "Though... this sounds > impossible, it happens; some programs have harbored latent schrödinbugs for > years." What is being talked about is very vague.. Can someone provide an example of how a schrödinbug is like (like with a fictional / real-life situation)?


Where Should I Put Configuration Files?

I'm creating a project that I want to be able to distribute across platforms. I'm writing in Java and AWT which already gives me a pretty large range of devices, but I'm mostly interested in Windows and Linux (Debian/Ubuntu). I'm trying to determine where I should put config files. I have application- wide configuration files and user-specific files. Where are common directories to put these files? Here's my current setup: ## Windows: App Config: `%PROGRAMDATA%\MyApp\config\` User Config: `%USERPROFILE%\AppData\Local\MyApp\` ## Other: App Config: `/opt/MyApp/config` User Config: `$HOME/.MyApp/`


What obligations do highly public developers have to their users? (Or,  _why the lucky stiff's tale)

Why the Lucky Stiff removed most of his online profile on Aug. 19th, 2009. The author of Why's (poignant) guide to Ruby, Hpricot, and many other projects left behind many confused and upset users. Zed Shaw called it a "dickhead thing to do". John Resig called his work a "Sand Mandala". Do developers have an unwritten obligation to their users? Does their obligation increase with their prestige?


Calling MSSQL stored procedure from Zend Controller ? Any other approaches?

_MSSQL and DB, Zend as PHP Framework_ , I am using this way to call SP with I/P Parameters and to get O/p Parameters. It seems I am writing SQL code in PHP. Any other good approaches?                $str1 = "DECLARE @Msgvar   varchar(100); DECLARE @last_id int;          exec DispatchProduct_m_Ins $DispatchChallanId,'$FRUNo',$QTY,$Rate,$Amount,     ".$this->cmpId.",".$this->aspId.",".$this->usrId.",@Msg = @Msgvar OUTPUT,@LAST_ID = @last_id OUTPUT;          SELECT  @Msgvar AS N'@Msg',@last_id AS '@LAST_ID'; ";//Calling SP               $stmt = $db->prepare($str1);          $stmt->execute();     $rsDispProd = $stmt->fetchAll();               $DispatchProductId   = $rsDispProd[0]["@LAST_ID"];//get last ins ID as O/p Parameter


In reference to .NET development and startups

Not posting a question of my own per se, but I am a ".NET developer". I read the following article about one startup CEO's opinion of hiring .NET experienced developers. He has some comments on the blog but not much of a discussion format as what's possible here. I also know nothing about this man, or am promoting his blog in any way, but the article did throw me off some, and I would like to hear some feedback from developers. Personally, I see his point as it's very easy for some people to create a basic ASP.NET website or some other automated solutions without much knowledge of anything beyond that, and thus would not make them good programmers. But I also think he largely ignores the reality that while many pieces of the framework have been automated and work just fine, you can come up with some very advanced solutions if you really have the know-how and the drive to explore the full capabilities of the framework. Much of their automated tools are "black box", but I've never had a problem where if I needed to get more "low-level" or extend some base class to give me what I really needed in a way that wasn't already available. What's your opinions for or against? CEO Friday: Why we don’t hire .NET programmers


HTML5 and gaming practices

I am trying to build an app with HTML5. Is there a certain syntax to follow when making objects for games? Anyone tried that and what are good practices to follow?


As an interviewer, asking a candidate to find errors in small sample code. Is this fair?

We've been interviewing on and off for about two years, and I've run this by about 30 candidates. I wrote some 20 lines of code which perform a relatively basic operation, but has a bunch of errors in it. None of them are syntax errors. Errors range from bad memory management, incorrect data types, multithreading problems, misuse of keywords, and a couple functional errors that would give undesired output. People get _really nervous_ during this question. Is it a fair question to be asking? The goal is to get an idea of their comfort level with the language (Objective C has some very strange behaviors, and most applicants we get are relatively inexperienced in ObjC specifically as compared to other languages), as well as see their ability to recognize logical problems in otherwise foreign code. Once a candidate has made a first pass, I often will point to specific lines that have remaining errors on them and see how much hand-holding it takes to get a correct identification and/or fix from them. At our company, this is a real world scenario, as programmers would be thrust straight into a 100k line app and given bugs to fix, and we need people that are comfortable with working with the code of 6 other programmers. However, today, another of our interviewers told me he hated this problem (I didn't quite understand what his reason was, admittedly). Is this something I should continue asking, or should I look for alternate avenues?


How to enforce implementation of interface to behave a certain way

Suppose you had the following interface               public interface IUserRepository     {         User GetByID(int userID);     }      How would you enforce implementers of this interface to throw an exception if a user is not found? I suspect it's not possible to do with code alone, so how would you enforce implementers to implement the intended behavior? Be it through code, documentation, etc.? In this example, the concrete implementation is expected to throw a `UserNotFoundException`               public class SomeClass     {         private readonly IUserRepository _userRepository;              public SomeClass(IUserRepository userRepository)         {             _userRepository = userRepository;         }              public void DisplayUser()         {             try              {                 var user = _userRepository.GetByID(5);                 MessageBox.Show("Hello " + user.Name);             }             catch (UserNotFoundException)             {                 MessageBox.Show("User not found");             }         }     }


Agile (scrum) and UML round-trip tools

How effective are automated round-trip tools for UML modeling? Do they help in coding quick, clean, efficient code? In what ways do these tools fit into the Agile methodology?


When is it appropriate to develop a gui application, as opposed to a web application?

I've been thinking about an application that I want to develop for a while now. In short, I want this application to perform some crud operations. The application will be for a law firm so overall security is going to be very important. My primary programming language is php but I wouldn't mind learning some Java or possibly Objective C to make my application os-x and iOS native. Back to my question, what are the pros and cons to developing a gui application as opposed to just developing an app for the browser? The reason I ask is because if there are some benefits to developing an gui app in, say, objective c, then I guess I need to start focussing on learning the language. Important considerations about the application I want to develop:   * Database connectivity   * Security(Very important)


What elements of my JUnits should I mock?

My classes are following this structure Service Tier (creates and maps InputDTO to DB Data) -> DAO Tier (actually executes DB calls) When I write the service tier JUnits, and when it calls DAO Tier, it expects an actual DB connection and getting data from the DB. Should I be mocking the DAO tier completely from the service tier, or should I be mocking the DB connection and data received from the DB? Secondly, the app expects certain data from a Cache. For JUnit run time, there is no Cache, so how should this be handled - since the service tier method includes looking up the cache to get the details.


Worth of Algorithm Challenges and event?

I'm interested in knowing whether it is advisable for computer science students to spend their major chunk of time on the online judges practising programming(like Topcoder and codeforces) or it's more worth to develop a software or contribute to open-source ?


Saying "I don't know" in a technical interview

If asked a series of technical questions in a programming interview, does it look bad to admit when you don't know the answer to a question? In other words, does admission make you look incompetent or ill prepared? Or, is it assumed that no one will know the answer to every question? Does admitting it instead of taking a shot in the dark make you look honest or like you're a know-it-all?


MVC Validation with ModelState.isValid through a wizard

I'm working on a small educational project on MVC 3, and I'm facing a small problem, when attempting to handle validation in my application through a wizard. I tried to get benefit from the ability of MVC3 to deliver content of a different view using the same URL, when handling an `[HttpPost]` method on a page. I my case,my main model's class contains about ten `[Required]` properties, that I would like to expose through a small wizard in 3 steps , So I want that the user may be able to enter his personal informations in the first step, then respond to some questions in the second stepp and finally receive a confirmation mail from the web application whit his credentials in the last step. I can't access the last step, because of the ModelState.isValid method that I use to handle validations, and which can't perform properly if I define some properties as `[Required]`, but don't put them on the first view. As the replies to those questions remain in a couple of choices, I've thinked that I may use some nullable `bool?` for in order to avoid validation issues, but know that it's not the proper way. Are there someone who would like to help me find a way to extend my validation to those three steps ? Thanks in advance and sorry for my english, I'm not a native speaker.


Help finding the tilde of the following algorithm

Suppose I have an algorithm that takes N^100/2^N to complete. Would the tilde of this be 0? But then that does not make sense. However, since the alogrithm tends to 0 as N increases, what should the tilde approximation be? Thanks in advance.


Estimating the time it takes for this quick find algorithm to complete

I am trying to run an estimate on how long this quick find algorithm takes on Union Find type problems. Here is the code:               public int find(int p) {       return id[p];     }          public void union(int p, int q) {       int pID = find(p);       int qID = find(q);       if (pID == qID) return;            for(int i = 0; i < id.length; i++) {         if (id[i] == pID) id[i] == qID;       count--;     }      Note: count variable is based on the id length. So basically, what is the minimum time this algorithm would take (in days) that be able to solve a problem with `10^9` sites, `10^6` input pairs, on a computer capable of executing `10^9` instructions per second? Assume that each iteration of the inner for loop takes 10 instructions. My Work: Since there are `10^6` input pairs and `10^9` sites, I just multiplied them together and got `10^15` instructions that needs to be completed. After dividing by 10 and the number of seconds in a day, I got roughly around 11 days to complete. Is there any variables that I am missing? I have noticed that it said "minimum". I guess in minimum case, the array would be accessed `(N + N-1 + N-2 ... 1)` (Input Length).


Benefits of Masters of Engineering Professional Practice for the lowly (yet aspiring) programmer

I've been looking into in state online degree programs 'to fit my busy lifestyle' (i.e. three children, wife and hour and a half commute). One interesting one I've found is that Master of Engineering in Professional Practice. It looks more useful and practical than a MBA in project management. I'll contact the admission dept there about the specifics. But here I'm just asking in general. Do the courses in this degree apply to software engineering/development in even an abstract sense. The university I'm looking at does not have a Software Engineering major in the school of engineering. I'm not interested in architecture astronomy, but I am interested in helping my company succeed and being able to communicate technical information at a high and effective level as well as being able to lead my co-programmers toward a more robust end product. So my multipart question is:   1. What might be the real benefit to me and my brain and    2. How do I convince my boss (the owner of the company, who does do some tuition reimbursement) that just because it doesn't say anything about software that it might still do us some good?   3. Oh, and how do I get past the fact that a masters degree would make me more qualified to be the project manager than... the project manager? (who is my supervisor)


String send to web not support utf 8

I try to send some text to web and this is my codes , but it's not support utf8 For example `آرین Show ????` how can I delete this problem?!               FragmentForm                     package com.kamalan.phpandroidapi;          import java.io.BufferedReader;     import java.io.IOException;     import java.io.InputStreamReader;     import java.net.HttpURLConnection;     import java.net.MalformedURLException;     import java.net.URL;          import android.app.Activity;     import android.app.ProgressDialog;     import android.content.Context;     import android.content.Intent;     import android.net.Uri;     import android.os.AsyncTask;     import android.os.Bundle;     import android.provider.Settings.Secure;     import android.support.v4.app.Fragment;     import android.util.Log;     import android.view.LayoutInflater;     import android.view.View;     import android.view.ViewGroup;     import android.widget.EditText;     import android.widget.ImageButton;     import android.widget.RatingBar;     import android.widget.TextView;     import android.widget.Toast;          public class FragmentForm extends Fragment {              // An interface to display or dismiss of ProgressBar          public interface OnSendingRequestToServer {             public void DisplayLoding(boolean setVisibility);         }              private final String TAG = "FragmentForm";              private OnSendingRequestToServer onRequestToServer;         private Context context;         private EditText etName;         private EditText etComment;         private RatingBar ratingBar;         private ImageButton ibSubmit;                   @Override         public void onAttach(Activity activity) {             super.onAttach(activity);                  try {                 onRequestToServer = (OnSendingRequestToServer) activity;             } catch (ClassCastException e) {                   throw new ClassCastException(activity.toString() + " must implement OnConnectingToServer interface.");             }                  context = activity.getApplicationContext();                  Log.d(TAG, "Fragment attached to activity.");         }              @Override         public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {             super.onCreateView(inflater, container, savedInstanceState);                  View view = inflater.inflate(R.layout.fragment_form, container, false);                  etName    = (EditText) view.findViewById(R.id.etName);             etComment = (EditText) view.findViewById(R.id.etComment);             ratingBar = (RatingBar) view.findViewById(R.id.ratingBar);             ibSubmit  = (ImageButton) view.findViewById(R.id.ibSubmit);             //TextView tvcm  = (TextView) view.findViewById(R.id.tvComment);                  Log.d(TAG, "Fragment created.");             return view;         }              @Override         public void onActivityCreated(Bundle savedInstanceState) {             super.onActivityCreated(savedInstanceState);                  ibSubmit.setOnClickListener(new View.OnClickListener() {                      @Override                 public void onClick(View v) {                               String strName = etName.getText().toString().trim();                          if(strName.length() <= 0) {                         Toast.makeText(context, "نام خود را وارد کنید", Toast.LENGTH_LONG).show();                         return;                     }                          String strComment = etComment.getText().toString().trim();                     if(strComment.length() <= 0) {                         Toast.makeText(context, "متن جک را وارد کنید", Toast.LENGTH_LONG).show();                         return;                     }                          int rate = (int) ratingBar.getRating();                     if(rate <= 0) {                         Toast.makeText(context, "امتیاز جکتان را وارد کنید", Toast.LENGTH_LONG).show();                         return;                     }                          String deviceId = getDeviceId();                          new SendFormTask(deviceId, strName, rate, strComment).execute();                                          }                      private TextView findViewById(int tvcomment) {                     // TODO Auto-generated method stub                     return null;                 }             });         }              private String getDeviceId() {             return Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);         }              /*----------------------------------------------------------------------------          * This method is responsible for creating another thread in parallel with          * main UI thread in order to send a request to server and get data (if any).          * ---------------------------------------------------------------------------*/         public class SendFormTask extends AsyncTask<Void, Void, Boolean> {                   String deviceId, name, comment;             int rate;                  SendFormTask(String deviceId, String strName, int rate, String strComment) {                 this.deviceId = deviceId;                 this.name = strName;                 this.rate = rate;                 this.comment = strComment;             }                  @Override             protected void onPreExecute() {                 Log.d(TAG, "SendFormTask is about to start...");                      onRequestToServer.DisplayLoding(true);             }                  @Override             protected Boolean doInBackground(Void... params) {                 boolean status = false;                  HttpURLConnection urlConnection = null;                      try {                     URL url = new URL(LinkManager.getFormAPI(deviceId, name, rate, comment));                     Log.d(TAG, "Try to open: " + url.toString());                     urlConnection = (HttpURLConnection) url.openConnection();                     int responseCode = urlConnection.getResponseCode();                     Log.d(TAG, "Response code is: " + responseCode);                          if (responseCode == HttpURLConnection.HTTP_OK) {                         BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));                         if (in != null) {                             StringBuilder strBuilder = new StringBuilder();                             // Read character by character                                           int ch = 0;                             while ((ch = in.read()) != -1)                                 strBuilder.append((char) ch);                                  // get returned message and show it                             String response = strBuilder.toString();                             Log.d("Server response:", response);                                  if(response.equalsIgnoreCase("1"))                                 status = true;                         }                              in.close();                     }                 }                 catch(MalformedURLException e){                     e.printStackTrace();                 }                 catch (IOException e) {                     e.printStackTrace();                 }                 finally {                     urlConnection.disconnect();                 }                      return status;             }                  @Override             protected void onPostExecute(Boolean result) {                 Log.d(TAG, "SendFormTask finished its task.");                      onRequestToServer.DisplayLoding(false);                      if(result)                     Toast.makeText(context, "جک شما ارسال شد, منتظر تایید آن باشید", Toast.LENGTH_LONG).show();                 else                     Toast.makeText(context, "جک شما ارسال شد , منتظر تایید آن باشید", Toast.LENGTH_LONG).show();             }         }     }      and `LinkManager.java`               public class LinkManager {              private final static String API_FORM = "http://jimmy.ir/jimmy/sendjoke.php?p1=#@#&p2=#@@#&p3=#@@@#&p4=#@@@@#";         private final static String API_Comment = "http://jimmy.ir/jimmy/index.php?p1=#@#";              public static String getFormAPI(String deviceId, String name, int rate, String comment) {             String url = API_FORM;             url = url.replaceAll("#@#", deviceId);             url = url.replaceAll("#@@#", name);             url = url.replaceAll("#@@@#", Integer.toString(rate));             url = url.replaceAll("#@@@@#", comment);             url = url.replaceAll(" ", "%20");                  return url;         }              public static String getCommentAPI(String deviceId) {             String url = API_Comment;             url = url.replaceAll("#@#", deviceId);                  return url;         }     }      Sry My English is bad.


How to lock/unlock a button based on tweeting

I have a button that will be disabled until you send out a tweet that I have crafted. Only users with twitter accounts will have access to this, and I will require users to sign-in to be able to access this button. What kind of tools are available for me to check whether   1. The user has actually tweeted it   2. The user has not deleted the tweet afterwards Now, there is no way to actually stop the user from deleting the tweet, but I would like to disable the button if the user has actually chosen to delete it afterwards.


What is a good use case for scala?

In a current project we have setup the build so that we could mix Java and Scala. I would like to use more Scala in our code base to make the code more readable and concise. In the process also learn the language by handing over real features. So I plan to use Scala for some classes to showcase its benefits and convince other devs to look into using Scala too. For a rest based web server or a program in general what kind of code structures lend themselves to Scala's functional programming style.


What are the caveats of the event system built on Messenger rather than on classic .NET events?

MVVM Light and PRISM offer messenger to implement event system. the approximate interface looks like the following one:               interface Messanger     {         void Subscribe<TMessageParam>(Action<TMessageParam> action);         void Unsubscribe<TMessageParam>(Action<TMessageParam> action);         void Unsubscribe<TMessageParam>(objec actionOwner);         void Notify<TMessageParam>(TMessageParam param);     }      Now this model seems beneficial comparing to classic .net events. It works well with Dependency Injection. Actions are stored as weak references so memory leaks are avioded and unsubscribe is not a must. The only annoyance is the need to declare new TMessageParam for each specific message. But everything comes at a cost. And what I'm really worried about is that I see no shortcomings of this approach. Has anoyne the experience of some troubles with this design pattern? **Update**   We tried it and the most unpleasant thing with messages is their implicitness from the point of view of interface. Messages contrary to Events are not exposed explicitly in the interface so additional documentation must be provided.   As Laurent said below very loose coupling comes at a cost of vagueness.


Reconciling contradictory programming advice: get something working and iterate vs. really think it through before coding

I am an intermediate programmer with a few years of professional experience who is halfway through a masters degree. In learning to program I've often heard two pieces of seemingly contradictory advice. The first piece of advice was get something working quickly, see how it works (either through prototyping or informal testing), improve the version , see how it works again, improve it again...and then repeat the cycle until you're done. This is sometimes called "spiral development" or phrased as "release early, release often." The second piece of advice was: really think a project through before ever writing any code. I've had success with both methods and I would say that I agree with each philosophy. But now I'm starting to tackle much more complex projects that I have no idea how to complete (like distributed applications and performance-driven graphics programming). How do I go about these projects? Do I just start coding SOMETHING and learn (platforms/methods/languages/architectures) as I go -- or do I hold off from coding and do a ton of research/reading before I even open the IDE? How do I reconcile these contradictory pieces of programming advice?


Method chaining vs encapsulation

There is the classic OOP problem of method chaining vs "single-access-point" methods:               main.getA().getB().getC().transmogrify(x, y)      vs               main.getA().transmogrifyMyC(x, y)      The first seems to have the advantage that each class is only responsible for a smaller set of operations, and makes everything a lot more _modular_ \- adding a method to C doesn't require any effort in A, B or C to expose it. The downside, of course, is weaker _encapsulation_ , which the second code solves. Now A has control of every method that passes through it, and can delegate it to its fields if it wants to. I realize there's no single solution and it of course depends on context, but I would really like to hear some input about other important differences between the two styles, and under what circumstances should I prefer either of them - because right now, when I try to design some code, I feel like I'm just not using the arguments to decide one way or the other.


How can a collection class instantiate many objects with one database call?

I have a `baseClass` where I do not want public setters. I have a `load($id)` method that will retrieve the data for that object from the db. I have been using static class methods like `getBy($property,$values)` to return multiple class objects using a single database call. But some people say that static methods are not OOP. So now I'm trying to create a `baseClassCollection` that can do the same thing. But it can't, because it cannot access protected setters. I don't want everyone to be able to set the object's data. But it seems that it is an all- or-nothing proposition. I cannot give just the collection class access to the setters. I've seen a solution using `debug_backtrace()` but that seems inelegant. I'm moving toward just making the setters public. Are there any other solutions? Or should I even be looking for other solutions?


How can I unit test that a class uses a trait in the expected manner?

A `class` has a `trait`. The `class` is expected to call a function provided by the `trait` during a certain `method` invocation. How do I write a `unit test` to ensure that that happens? The difficulty, to me, comes from the fact that a `trait` is part of the `class definition`, so I cannot mock the trait in the test, as I could if the `trait` was instead an `object` that was passed in to the `class` constructor.


What are common patterns for handling possible pluralization in message properties?

Obviously users like to see text properly pluralized, and pluralization schemes vary in the various written languages one may encounter. When internationalizing an app, what pattern(s) are useful for handling messages with possible pluralization? What about messages with multiple possible pluralization? For example: "N review(s):" One pattern would be               reviews.title.singular="{0} review:"     reviews.title.plural="{0} reviews:"      And this may not support all languages. Or a more complicated case: "Found M question(s) with N comment(s)." This would be difficult to support even in English.


Why are there two different kinds of linking, i.e. static and dynamic?

I've been bitten for the n-th time now by a library mismatch between a build and deployment environment. The build environment had `libruby.so.2.0` and the deployment environment had `libruby.a`. One ruby was built with RVM, the other was built with `ruby-build`. The reason I ran into a problem was because zookeeper was compiled in a build environment that had the shared library but the deployment environment only had the static library. In all the years I've been writing application code I have never once wished that the binaries I was using where linked against shared objects. What is the reason the dichotomy persists to this day on modern operating systems?


How does office bureaucracy affect code quality

I'm interested in stories where **office bureaucracy** has had direct effect on the final **code quality** result. For example, a friend just told me that at his previous work place the version control system was so bulky that programmers were not allowed to create new "modules" (root directories in the source tree) without asking permissions from the VCS gods. The result was that programmers were unwilling to go through the extra bureaucratic step and instead of properly componentizing their services they ended up piling unrelated functionality on top of existing modules even when functionality was just remotely related to the current definition of the module or the module's name was way in the past. (not to mention renaming a module...) I'm interested in similar stories of office, operational or any other bureaucracy that eventually, perhaps unintentionally affected software quality


Penny auction concept and how the timer works

I am creating a penny auction site using PHP yii framework. The main consideration of the system is to update the database records of all active auctions (max 15 auctions) with the current ticker timer. I am seeking for advice on how I should design the system where every auction item will have its own countdown timer stored in the database. When someone bids the auction item, the counter should reset to 2 min. All users who are connected to the system should see the same countdown timer for that particular auction. I am little confused on how I should design the system. Will there be a performance issue if there are frequent updates to the database (Mysql)? If there are 15 active auctions, and they are updated every second, the countdown timer decreases by a second in the database table for the particular auction. My first idea for the underlying schema, for a table called `auction_lots`:               Auction_id,startdatetime,counter_timer,status      I am seeking for advice on how I should design this.


Selling your services when you use uncommon technologies

I took a look in Stack Overflow most popular profiles, and then I did the same in several other sites, and then I took a look in job postings in several boards, mostly out of curiosity, because I noticed this: If you work with Java, .NET or other managed languages, or you work with stuff that is popular for web development (Ruby, JavaScript, etc...) you can get lots of points on Stack Overflow, find lots of jobs and clients, find forums, friends, colleagues, etc... But how a programmer of uncommon languages (Lua, pure C, Lisp, D, ADA, Haskell, etc...) find information, sell his services, and so on? EDIT: This also applies to fields: You work with web, corporate software, database, etc... it is great... You dislike those previous 3, no one ever will hire your services...


Naming conventions for newtype deconstructors (destructors?)

Looking into Haskell's standard library we can see:               newtype StateT s m a = StateT { runStateT :: s -> m (a, s) }          newtype WrappedMonad m a = WrapMonad { unwrapMonad :: m a }          newtype Sum a = Sum { getSum :: a }      Apparently, there (at least) 3 different prefixes used to unwrap a value inside a `newtype`: _un-_ , _run-_ and _get-_. (Moreover _run-_ and _get-_ capitalizes the next letter while _un-_ doesn't.) This seems confusing.   * Are there any reasons for that, or is that just a historical thing?   * If I design my own `newtype`, what prefix should I use and why?


Best practices for versioning project after dependency upgrade

Say, my project have dependency N with version 1.0.0. Then something have changed, and I should depend on newer version - let it be 1.0.1. OK, I'm incrementing dependency version, nothing else changes in my code. It looks like I should increment my own projects' version, but how exactly I should increment? Should I increment only third number (so-called revision), or best practices here are more complicated. For example, may be, if we are changing projects' dependency minor value, we should do the same thing in the project itself?


Is Operator Overloading supported in C

Today when I read about the LCC (Windows) compiler, I found out it has the implementation for operator overloading. I'm puzzled because after a bit of Goggling, it has been confirmed that operator overloading ain't supported in standard C, but I read some people's comment mentioning LCC is ANSI-compliant. So my real question is, is LCC really standard C or it's just like objective-c, a C variant with object-oriented features?


What makes Erlang suitable for cloud applications?

We are starting a new project and implementing on our corporations's instantiation of an openstack cloud (see http://www.openstack.org/). The project is security tooling for our corporation. We currently run many hundreds of dedicated servers for security tools and are moving them to our corporations instantiation of openstack. Other projects in my company currently use erlang in several distributed server applications, and other Q/A point out erlang is used in several popular cloud services. I am trying to convince others to consider where it might be applicable on our project. What are erlang's strengths for cloud programming? Where are areas it is particularly appropriate to use erlang?


I think the title "Method flags as arguments or as member variables?" may be suboptimal, but as I'm missing any better terminology atm., here goes: I'm currently trying to get my head around the problem of whether flags for a given class ( _private_ ) method should be passed as function arguments or via member variable and/or whether there is some pattern or name that covers this aspect and/or whether this hints at some other design problems. By example (language could be C++, Java, C#, doesn't really matter IMHO):               class Thingamajig {       private ResultType DoInternalStuff(FlagType calcSelect) {         ResultType res;         for (... some loop condition ...) {           ...           if (calcSelect == typeA) {             ...           } else if (calcSelect == typeX) {             ...           } else if ...         }         ...         return res;       }            private void InteralStuffInvoker(FlagType calcSelect) {         ...         DoInternalStuff(calcSelect);         ...       }            public void DoThisStuff() {         ... some code ...         InternalStuffInvoker(typeA);         ... some more code ...       }            public ResultType DoThatStuff() {         ... some code ...         ResultType x = DoInternalStuff(typeX);         ... some more code ... further process x ...         return x;       }     }      What we see above is that the method `InternalStuffInvoker` takes an argument that is not used inside this function at all but is only forwarded to the other private method `DoInternalStuff`. (Where `DoInternalStuff`will be used privately at other places in this class, e.g. in the `DoThatStuff` (public) method.) An alternative solution would be to add a member variable that carries this information:               class Thingamajig {       private ResultType DoInternalStuff() {         ResultType res;         for (... some loop condition ...) {           ...           if (m_calcSelect == typeA) {             ...           } ...         }         ...         return res;       }            private void InteralStuffInvoker() {         ...         DoInternalStuff();         ...       }            public void DoThisStuff() {         ... some code ...         m_calcSelect = typeA;         InternalStuffInvoker();         ... some more code ...       }            public ResultType DoThatStuff() {         ... some code ...         m_calcSelect = typeX;         ResultType x = DoInternalStuff();         ... some more code ... further process x ...         return x;       }     }      Especially for deep call chains where the selector-flag for the inner method is selected outside, using a member variable can make the intermediate functions cleaner, as they don't need to carry a pass-through parameter. On the other hand, this member variable isn't really representing any object state (as it's neither set nor available outside), but is really a hidden additional argument for the "inner" private method. What are the pros and cons of each approach?


Keep a programming language backwards compatible vs. fixing its flaws

First, some context (stuff that most of you know anyway): Every popular programming language has a clear evolution, most of the time marked by its version: you have Java 5, 6, 7 etc., PHP 5.1, 5.2, 5.3 etc. Releasing a new version makes new APIs available, fixes bugs, adds new features, new frameworks etc. So all in all: it's good. But what about the language's (or platform's) problems? If and when there's something wrong in a language, developers either avoid it (if they can) or they learn to live with it. Now, the developers of those languages get a lot of feedback from the programmers that use them. So it kind of makes sense that, as time (and version numbers) goes by, the problems in those languages will slowly but surely go away. Well, not really. Why? Backwards compatibility, that's why. But why is this so? Read below for a more concrete situation. * * * The best way I can explain my question is to use PHP as an example: PHP is loved thousands of people and hated by just as many thousands. All languages have flaws, but apparently PHP is special. Check out **this blog post**. It has a very long list of so called flaws in PHP. Now, I'm not a PHP developer (not yet), but I read through all of it and I'm sure that a big chunk of that list are indeed real issues. (Not all of it, since it's potentially subjective). Now, if I was one of the guys who actively develops PHP, I would surely want to fix those problems, one by one. However, if I do that, then code that relies on a particular behaviour of the language will break if it runs on the new version. Summing it up in 2 words: backwards compatibility. What I don't understand is: why should I keep PHP backwards compatible? If I release PHP version 8 with all those problems fixed, can't I just put a big warning on it saying: "Don't run old code on this version !"? There is a thing called deprecation. We had it for years and it works. In the context of PHP: look at how these days people actively discourage the use of the `mysql_*` functions (and instead recommend `mysqli_*` and PDO). Deprecation works. We can use it. We should use it. If it works for functions, why shouldn't it work for entire languages? Let's say I (the developer of PHP) do this:   * Launch a new version of PHP (let's say 8) with all of those flaws fixed   * New projects will start using that version, since it's much better, clearer, more secure etc.   * However, in order not to abandon older versions of PHP, I keep releasing updates to it, fixing security issues, bugs etc. This makes sense for reasons that I'm not listing here. It's common practice: look for example at how Oracle kept updating version 5.1.x of MySQL, even though it mostly focused on version 5.5.x.   * After about 3 or 4 years, I stop updating old versions of PHP and leave them to die. This is fine, since in those 3 or 4 years, most projects will have switched to PHP 8 anyway. My question is: **Do all these steps make sense? Would it be so hard to do? If it can be done, then why isn't it done?** Yes, the downside is that you break backwards compatibility. But isn't that a price worth paying ? As an upside, in 3 or 4 years you'll have a language that has 90 % of its problems fixed.... a language much more pleasant to work with. Its name will ensure its popularity. **EDIT** : OK, so I didn't expressed myself correctly when I said that in 3 or 4 years people will move to the hypothetical PHP 8. What I meant was: in 3 or 4 years, people will use PHP 8 if they start a new project.


What are the advantages of next-iterator over this-iterator?

I don't work too often with Java/C# iterators directly but when I do I always wonder what was the reason to design iterators in "next" fashion. In order to start you have to move iterator, in order to check if there is some data you have to check if there is next element. More appealing concept for me is this-iterator -- it "starts" from the beginning, and you can check this state, let's say `isValid`. So the loop over entire collection would look like this:               while (iter.isValid())     {       println(iter.current());       iter.next();     }      As you here in order to check if there is next element, you go there, and then you check if the state is valid. YMMV but anyway -- is there any advantage of next-iterator (as in Java/C#) over this-iterator? **Note:** this is conceptual question, about the **design** of the language.


Are there any algorithms for resource scheduling of courses-teachers-classes?

I'm developing an application to help school principals in dedicating teachers to classes and courses over the hours of a week (scheduling). The scenario is roughly something like this:   1. User enters the list of teachers and their free times into the system   2. User enters the list of courses for this semester   3. User enters the list of available classes into the system Well, up to here, there is no big deal. Just simple CRUD operations and nothing extraordinary. However, now what makes this system useful is that the application should **automatically** and **based on an algorithm** create the semester scheduling. I think you've got the main idea here. For example application should suggest that teacher A should go to class 1 for mathematics, and at the same time teacher B should go to class 2 for physics. This way all of the classes would be dedicated to lessons and teacher times won't overlap each other. Piece a cake for school principal. However, I can't find a good algorithm for this resource dedication. I mean it seems hard to me. Searching Google resulted in articles from different websites, but they are of no help and use to me. For example: http://en.wikipedia.org/wiki/Resource_allocation or http://en.wikipedia.org/wiki/Scheduling_(production_processes) Is there any algorithm out there, or any application or engine which can help me here? Does this requirements have a known name, like for example _time scheduling engine_? Any help would be appreciated.


can we use C programming now a days to build a game?

Can we use C programming to build a game or it has certain limitations may be it is not graphically rich i guess. can we build games like temple run your candy crush using C programming.


What is a static method compared to instance/class/private/public methods?

I'm learning programming in Objective-C and I can't understand what a static method is. I know what class/instance/private/public methods are. Can someone explain what it is using an example and comparing it to the others I mentioned? And in what situation would someone use it? From what I read on Wikipedia, it sounds like a class method that can't access anything in `self`. This sounds to me like its a stand-alone function - that shouldn't be associated with any class in the first place, since it can't access `self`.


for vs. foreach vs. LINQ

When I write code in Visual Studio, ReSharper (God bless it!) often suggests me to change my old-school for loop in the more compact foreach form. And often, when I accept this change, ReSharper goes a step forward, and suggests me to change it again, in a shiny LINQ form. So, I wonder: are there some _real_ advantages, in these improvements? In pretty simple code execution, I cannot see any speed boost (obviously), but I can see the code becoming less and less readable... So I wonder: is it worth it?


Point me to info about constructing filters (of lists)

I would like some pointers to information which would help me understand how to go about providing the ability to filter a list of entities by their attributes as well as by attributes of related entities. As an example, imagine a web app which provides order management of some kind. Orders and related entities are stored in a relational database. And imagine that the app has an interface which lists the orders. The problem is: how does one allow the list to be filtered by, for example:-   * order number (an attribute)   * line item name (an attribute of a n-n related entity)   * some text in an administrative note related to the order (text found in an attribute of a 1-1 related entity) I'm trying to discover whether there is something like a standard, efficient way to construct the queries and the filtering form; or some possible strategies; or any theory on the topic; or some example code. My google foo fails me.


For an open source project, is it legal and acceptable to link to commercial libraries? For example, an open source application I'm involved in would benefit from using commercial 3rd party user interface library.


Design: Method that loads data from one of two file formats?

Say I have a class Person:               class Person     {       string FullName;       int Age;     }      And I need to load a list of Person's from a plain text file. The text file could be in one of two formats. I want a method such as LoadFromFile(string path) that will 1) detect the file format 2) parse appropriately for the file type and 3) return a list of Persons. The quick and dirty solution would be to have a single method LoadFromFile where I read the header of the file, I can determine which file type it is, and then, keeping the file open, switch on the type and read it appropriately. On the other hand, the fact that it's two different "types" of files makes me think it's a good candidate for polymorphism. This would be especially good if there was a third file type. However, having separate classes makes it seem like it would be harder to keep the file open from the "type detection" phase to the "parse phase". Though maybe wanting to keep the file open is just premature optimization. I want the client code to simply call LoadFromFile(path) and have it detect the file type and load appropriately. What is a good design for this (in terms of class names and method names)?


Is UTF-16 fixed-width or variable-width?  Why doesn't UTF-8 have byte-order problem?

1. Is UTF-16 fixed-width or variable-width? I got different results from different sources: From http://www.tbray.org/ongoing/When/200x/2003/04/26/UTF: > UTF-16 stores Unicode characters in sixteen-bit chunks. From http://en.wikipedia.org/wiki/UTF-16/UCS-2: > UTF-16 (16-bit Unicode Transformation Format) is a character encoding for > Unicode capable of encoding 1,112,064[1] numbers (called code points) in the > Unicode code space from 0 to 0x10FFFF. It produces a variable-length result > of either one or two 16-bit code units per code point.   2. From the first source > UTF-8 also has the advantage that the unit of encoding is the byte, so there > are no byte-ordering issues. Why doesn't UTF-8 have byte-order problem? It is variable-width, and one character may contain more than one byte, so I think byte-order can still be a problem? Thanks and regards!


Take screenshot of inactive workspace

I am trying to write a program that will take a screenshot of each workspace and then display them together to create an expo type effect. I am currently using gtk and I can only take a screenshot of the active workspace (using gdk_get_default_root_window and gdk_pixbuf_get_from_drawable). The only method I have currently found of taking a screenshot of an inactive workspace is to switch to it, take the screenshot and then switch back, but this will make the screen flash. So my question is, is there way of capturing the workspaces without flashing the screen?


How to do simple natural language categorization

How would you go about parsing a sentence like "Bought two kilos of steak from Acme supermarket" into a data structure like the following JSON representation:               {       item: {name: "steak", tags: "meat,beef" },       quantity: { value: 2, unit: "kg"},       source: "ACME Supermarket"     }      ? I'm looking for a high-level conceptual overview of where to start e.g. some papers or introductory material that don't require PhD level knowledge. For context, this is part of the preliminary investigation for a personal expense tracker I'm planning to build. To break it down a little further, I'm interested in basic named entity recognition, and categorization strategies. I don't have a CS education, so you may want to keep that in mind when answering :) Thanks in advance. Not interested in 3rd party web services, since this is a learning exercise, and is intended to work offline.


How to verify if 3rd party payment succeeded?

A more specific version of this question was kicked off of StackOverflow so I hope this is now the right place for this question. I'm working on a payment processing website that will function like PayPal does on many e-commerce websites. The idea is for the customer to fill their shopping cart and click checkout, then be directed to the payment page on a secure site. After the payment page processes the payment, it directs the customer back to the original website. So far, I think I'm ok up to the point of receiving the payment, but what mechanism do sites like PayPal use to allow the original website to verify whether the payment was successfully received? * * * My Current Process:   * Customer click's checkout   * Store cart items as a pending order in database   * Post merchant ID, payment amount, the return URL, etc. to secure payment page. This uses SSL and I have also posted a hash of the other posted values to ensure they are not tampered with in transit.   * Customer enters card info and clicks "Pay"   * Secure site redirects to the specified return URL with a query string of relevant transaction information including a flag indicating success or failure. For the last step, the original site needs to be sure the request came from the payment site so that a user can't just navigate to that URL, providing the query string themselves, to complete an order. I currently have the same hashing mechanism in place to make sure the query string variables are not tampered with. It is very crude. I append the variables into one long string and then append a shared secret key to the end, hash that whole string, send it. The receiving end does the same thing and compares the hashes.