instruction
stringlengths
34
19.9k
Given a set of images on a webpage, what's a good way to pick a compelling image that is also representative of the webpage? The use case is displaying an image along with a description of a URL to a page, after a user includes it in a status update. I've found some techniques to find the most interesting part of a sin...
We have a Django-based website for which we wanted to make some of the content (text, and business logic such as pricing plans) easily editable in-house, and so we decided to store it outside the codebase. Usually the reason is one of the following: It's something that non-technical people want to edit. One example is...
You are writing a videogame about trading beans. Red beans, black beans, pinto beans, you name it. As everybody knows all beans are the same. You write the "Inventory" class for a trader in that videogame as follows (skipping all the null checks): class BeansInventory{ HashMap<BeanType,Integer> amountsOwned; publi...
I have a situation where I have several text documents and I want to create a list that contains the words in those documents. But I also need to record several properties of each word. These properties are The index of the word within all the words in the documents (Integer) The word itself (String) The document th...
Given a two dimensional matrix of alphabets, search the given word in all directions. Below is an example to search for the word "TEAM": No of occurrences is 4 in matrix below. What is the best approach to solve this? Its not a dictionary word. Its simply sequence searching in all the directions.
Say I have 9 jobs with estimates of how long they will take to complete, and 3 queues that process these jobs - this constitutes one batch. Note that all the jobs are allocated to a queue beforehand and not at run-time. So with poor-scheduling, some queues may remain idle while others continue to process a job. All t...
I am working on an application that uses Google Cloud storage to serve my app images. The images are submitted from an android app to google app engine code that is supposed to upload the images to GCS then create a link and update in my db. This works fine. The challenge am facing is I need different devices to serve ...
It's my first time using sql server, I usually go with MySQL, so I'm unsure how to do this. The project I'm assigned will be deployed to multiple platforms particularly PC's with different SQL server ranging from 2008 to 2014, some of them are express edition, some are standard edition and in Windows ranging from XP, 7...
Following is a question that I had posted at the incubator-storm-user mailing list (verbatim). I had decided to open up the question here as well, because it also contains a conceptual side to it, which might be answered by non-storm users. I am no python expert and am also a newbie to storm. I have gone over the st...
I started coding a chart library on top of d3js: My chart library. I read Javascript API reusability and Towards reusable charts. However, I am NOT really following the suggestions because I am not really convinced about them. This is how my library can be used to create a bubble chart: var chart = new XYBubbleChar...
All products seem to be released with a license, I'm curious to know how one would go about finding out the license of technologies like HTML, CSS and JavaScript?
Say, I am using a simple recursive algo for fibonacci , which would be executed as: fib(5) -> fib(4)+fib(3) | | fib(3)+fib(2)| fib(2)+fib(1) and so on Now, the execution will still be sequential. Instead of that, how would I code this so that fib(4) and fib(3) are calculated by s...
Maybe I miss something, but do the so called markup languages have the equivalent concept of semantics that you can find in C or C++? Judging from how you parse the language, you don't really have too many options, there isn't too much context, you just parse your tokens and apply them to the source code. I'm tempted t...
Is there an organization similar to W3C that creates standards for programming languages? If so, are there any programming languages, like browsers would using W3C standards, that implement these standards? I have done my own research and I have been unsuccessful thus far hence the question. The answers and most of th...
If I write a library that is released under the terms of the GPL v2 (or higher, at option); may that library depend on another library released under the LGPL v3 (or higher), without implicitly enforcing GPL v3. That is, I am purely linking to that library. Reading this and this, I understand that the LGPL v3 and GPL v...
I've been recently assigned for a new high-performance C++ project (finance) together with 3 other guys who, like, me, refer to themselves as "primarily C/C++ programmers", meaning, all of us have also done Java & other stuff, we all have comparable experience (8 to 10 years) and have successfully collaborated for the ...
Say you have a project that is a tangled mess. No code structure and breaking one area breaks the entire thing. Fixing one area breaks another area. The closest you can fix things is writing the code that's almost like redoing the entire thing. But then, the release is in the next week. Here's some facts that actually ...
Usually event listeners shouldn't outlive object that registered them. Does it mean that event listeners should be held by weak references by default (stored in weak collections by the object listeners are registered on)? Are there valid cases when listener should outlive its creator? Or maybe situation like that is a...
Recently I started same projects to improve my programming skills, so I tried to develop a point of sale software. I started to bay the required hardware (ticket printer, Barcode Scanner….) to make my personal lab, but I’m unable to find how to implement the payment process using an ATM terminal. Is there any possibi...
I have been in the web development industry for around 5 years now, always working in an open source environment. Mostly apache, mysql, and php with a little bit of ruby, using git for version control. But recently took up a job where development is entirely C# ASP.NET MVC. While I was able to pick up the language etc ...
The title is very bad so let me explain what I need to know. I have a server with let's say different images. What I want to achieve is be able to embed a frame, into any HTML site, and be the server the one that determines what image to show on that remote frame. Imagine the situation where you want to add a piece of...
This question is about whether to make a nested class in Java to be a static nested class or an inner nested class. I searched around here and on Stack Overflow, but couldn't really find any questions regarding the design implications of this decision. The questions I found are asking about the difference between stati...
While reading about strict mode on MDN I really was surprised to read the following near the end of the page, quote: Browsers don't reliably implement strict mode yet, so don't blindly depend on it. Strict mode changes semantics. Relying on those changes will cause mistakes and errors in browsers which don't imple...
Will the code int a = ((1 + 2) + 3); // Easy to read run slower than int a = 1 + 2 + 3; // (Barely) Not quite so easy to read or are modern compilers clever enough to remove/optimize "useless" parentheses. It might seems like a very tiny optimization concern, but choosing C++ over C#/Java/... is all about optimizati...
I have a SQLite Database in my Android app with a "Question" table, among others. That table contains "default" or "pre-loaded" data (in this case the questions asked by the app). Some of its columns are "technical" or "internal" data to be used behind the scenes - like the number of points the question is worth, the t...
I am currently creating something that has been inspired by another library. It is a complete rewrite on another platform - yet, has the same purpose and functionality and is written in the same language. As far as I understand it, this is still considered a derivative work. The original piece is licensed under the Apa...
I understand the intent of the open-closed principle. It's meant to reduce the risk of breaking something that already works while modifying it, by telling you to try to extend without modifying. However, I had some trouble understanding how this principle is applied in practice. To my understanding, there are two ways...
How can I test (what tools do I use) if my reference graph is correct and if objects are released at appropriate times (and there are no memory leaks)? In my case I'm using Java, but answers related to another languages are welcome too...
I am Elvis, trying very hard to learn to be Einstein. I work for Mort. What the hell is this crazy idiot talking about!?!? (You only need to read the first few paragraphs) If you don't feel like reading that link, basically, I am a professional programmer, and my boss is (this is scarily accurate): the professional li...
I recently came across a Java construct I have never seen before and was wondering whether I should use it. It seems to be called initializer blocks. public class Test { public Test() { /* first constructor */ } public Test(String s) { /* second constructor */ } // Non-static initializer block - copied into ever...
I'm designing/building a web application that will be available in two languages: French/English. I placed i18n mechanisms to extract every text from the application. But what about the user's input? I have some "system settings" that currently ask for both lang for their labels... But I can't obviously ask a translati...
Note: this is mostly a technical question but I have to explain the business background first. THE BUSINESS PART I have a really interesting situation on my hands, at least interesting for me. For the last 3.5 years I've been building a business/application called Snip Salon Software. It's scheduling software for hair ...
I'm a strong advocate for Software Engineering, but even I must admit that we do not have many of the same tools, priniciples, and laws as other engineering disciplines. Why is this? And, what should we do to get there?
My understanding of Akka is that it allows you to define groups of mini-threads ("Actors") and then have them communicate with each other (and do work) using events. My understanding of ZeroMQ is that its a TCP socket library that allows threads to communicate with each other over TCP/ports. My question: these seem lik...
I have a lot of calls to NSLog(...). I need to change all of these calls to CLSNSLog(...). So I added this to my precompiled header (.pch): #import <CrashlyticsFramework/Crashlytics.h> #define NSLog(...) CLSNSLog(__VA_ARGS__); Everything works. I don't see any drawbacks to this -- the team can continue to use NSLog(.....
Some of the legacy code I've inherited uses the fact that C# supports multiple assignment to write code like: void DisableControls() { ddlStore.Enabled = ddlProgram.Enabled = ddlCat.Enabled = btnSaveProxy.Enabled = btnCancelProxy.Enabled ...
Consider the following situation: She uses Django (BSD) for a website. She uses Haystack (BSD) for textual search in the website. She uses the backend of haystack, xapian-haystack (GPL), to use Xapian (GPL) as the search engine of Haystack. Question: must she distribute the source code of her website under GPL (or eq...
Java allows this: class X{ int i,j[]; // j is an array, i is not } and even worse, it allows this: class X{ int foo(String bar)[][][] // foo actually returns int[][][] { return null; } } Okay, the reason for this might be that it was lent from C/C++. However, Java meant to be easier than C/C++. Why did t...
I have written a library that is quite extensive and has taken up a lot of my time, so I would like to license it properly. The LGPL seems to have many of the things I want, but does not work with Javascript or other interpreted languages. Here are the things I want my license to say: My library can be used in commerc...
Sometimes we have code like this: private static final List<Goat> INEDIBLE_GOATS = [GOAT_A, GOAT_B, GOAT_C] void eatGoat(Goat goat) { if(INEDIBLE_GOATS.contains(goat)) { throw new CantEatGoatException(); } ... } Should it best tested (along with whatever tests for the actual eating) as: for(Goat goat...
I read somewhere that the chain of inheritance breaks when you alter a behavior from derived class. What does "altering a behavior" mean here? Is overriding an already implemented method in base class considered as "altering behavior"? Or, does the author mean altering method signatures and the output? Also, I ready Du...
I am using the XNA Framework to make a learning project. It has a Point struct which exposes an X and Y value; for the purpose of optimization, it breaks the rules for proper struct design, since its a mutable struct. As Marc Gravell, John Skeet, and Eric Lippert point out in their respective posts about GetHashCode() ...
I've the following Interface. public interface ValueInterface { long getValue(); } And the class: public class ValueCreator implements ValueInterface { private static long value = 0; public void setValue(long valueInDollar) { value= valueInDollar; } @Override public long getValue() { return...
I was just googling around to find a good definition of front-end developer and the definitions that I found were pretty much "a guy that does HTML/CSS/JavaScript (jQuery)". But I think this is no longer the case. Today we have very complex interfaces, say a single page BackboneJS app that require a lot more than just ...
Should you throw an exception if a method's input values are out of range? eg //no imaginary numbers public int MySquareRoot(int x) { if (x<0) { throw new ArgumentOutOfBoundsException("Must be a non-negative integer"); } //our implementation here } Now this method should never be called with a ...
I considering making my application open source on github. I don't intend to sell it (neither in binary form nor source code form). It probably isn't even useful to a lot of people except maybe for learning purposes. The application is developed in .NET 4.5 (WPF). It doesn't use any external libraries. Only pure .NET l...
Let assume we have the following service whose responsibility is to generate Excel reports: class ExcelReportService{ public String generateReport(String fileFormatFilePath, ResultSet data){ ReportFormat reportFormat = new ReportFormat(fileFormatFilePath); ExcelDataFormatterService excelDataFormatterSer...
I am working on a project where there will be plenty of static options being stored in the database. I looked at using Enums for this, but do not see how they could be useful. They do not create any kind of look-up table, just reference a number in the table which can be used in code as an enum option. The number is me...
I'm currently checking a older piece of C# code used to maintain a login session. public static ZRWebserviceSession CurrentSession { get { return _currSession; } set { _currSession = value; } } private static ZRWebserviceSession _currSession; public static bool IsSessionActive() { if (_currentSession == null || !...
I'm facing the following situation: There are 2 different teams working on the same project using Scrum, and every now and then, bugs related to user stories developed by team "A" are being assigned to team "B". We're used to fixing bugs made by other people when they belong to the same team, but things get a bit mor...
I am using a tree view in c# and i am creating custom icons for the nodes. Let say this is my hierarchy with a node that satisfies a certain condition: Root1 |_Ax |_Bx1 |_Bx2 |_Cx1 |_Cx2(condition true) |_Bx3 |_Bx4 |_Ay |_By1 |_By2 |_Cy1 when the tree it's collapsed I don't know if some inner child satisfi...
I have a number of operations that need to be performed, in series, on the same set of data. As the operations progress, later operations require information from the prior operations. So the initial object passed in to the first method snowballs as it collects results and metadata. At first I was passing around both...
When running a site that has a CRM with a logging facility that logs users interactions (someone changing a name, address or user permission etc), is it better to log system interactions (automated tasks and alike) as a fake user set up as a constant either in a "users" object, or as part of the application settings so...
Eric Lippert has written about cargo cult programming, and Steve McConnell has tackled the subject from a Software Engineering point of view. Eric provides a fairly succinct description: They understood the form but not the content. There are lots of cargo cult programmers -- programmers who understand what the code ...
I've two C++ classes with a relation: a container class which has a list of items. For example a library has got many books. The classes are the library and the book. Now from the external world I have to create, update and delete books. In addition there other classes that are interested to know when an event on a bo...
Take the (unprecedented and groundbreaking) example of the calculator: public class Calculator { public double Add(double augend, double addend) { return augend + addend; } } When I write calculator.Add(val1, val2) which of the following am I doing? Telling the calculator to add the inputs Adding...
In some languages (C++, Java, Ruby, etc.) an assignment returns a value and can be used in an expression: x = (y = z); // ok, 'x' gets the value of 'z' In other languages (Ada, VHDL), an assignment is a proper statement and cannot be used in as expression: x := (y := z); -- error! However, in both cases, it is p...
With Java 8, I've seen more and more articles about the use of Option/Optional. I understand what they trying to represent, and I see many examples of them being used as returns. However what I don't see is them being used as method/function arguments in languages that don't have the syntax for default/optional paramet...
Say for example I've got a RESTful webservice, and I need to support creating a widget via a POSTed http request. I need to Deserialize the POSTed widget. Validate the deserialized widget. Persist the widget to a backing service. Send a success response back to the client. Now, the problem is that my SLA does not all...
I'm working on a Web app that uses node.js on the server and AngularJS on the client. I'm new to Angular, but enables writing client-side applications that can be more self-contained than some other approaches. Here is the scenario. On the server, I query a DB and then transform the results into a list of nodes and edg...
What is a good method of storing JSON data/objects for development and unit testing with angular and jasmine? I have seen some ways of accomplishing this. However, since I am new to unit testing with JavaScript, I fear going in a bad direction. Here are some examples of what I'd like to accomplish: Let's say I want t...
I was reading a question and one of the comments mentioned that "The binary flag is only relevant on Windows". Given the context of the question and answer, I interpret this statement as on non-windows machines, we don't need to specify text or binary mode when doing file IO The context of the question is to read all b...
Coupling mean "dependency". It is the case of "Class A" dependent on "Class B" to get the job done. Tight Coupling is when "Class A" Use the implementation of "Class B". Loose Coupling is when "Class A" Use the abstraction on "Class B". Is this the correct understanding or is it oversimplify ?
A brief background on this specific question: After meeting with a client and hearing all of their requests, requirements, and other comments about a specific software job, planning out the software functionality, design, and basic user experience, the client comes back with a comment regarding, "That is not wha...
How does Lexer/Parser work in a 2D programming language like Funciton in order to transform such an unusual source-code to the correct AST?
Suppose we have the following class hierarchy: class Object { public: virtual void update() { // Update position } }; class Rocket : public Object { public: virtual void update() { Object::update(); // Orientate towards target } }; class SparklingRocket : public Rocket { public...
In my company, we have had a policy of tagging every release. Someone new joined, and he suggested that instead of formally using a Tag, we could just leave a comment for the release build when it is checked in. I like using a Tag, but, obviously, we can also get to the source code for a build also by looking for the c...
Assume you have two classes, a Manager who holds a set of Clients and the Client holds a backreference to the Manager. class Manager { public: void addClient(Client* client) { m_clients.push_back(client); client->setManager(this); } private: std::list<Client*> m_clients; }; class Client { p...
Assume an interface that allows queries on a spatial tree public ISpatialTree { int FindChildIndex(Vector point); bool IsLeaf { get; } ICollection<ISpatialTree> Children { get; } } and another one that allows changing the tree: public ISpatialTreeWriter : ISpatialTree { void Add(Vector point); bool...
I was watching this video on the maximum and minimum values of signed integers. Take an example of a positive signed value - 0000 0001 The first bit denotes that the number is positive and the last 7 bits are the number itself. So it is easily interpreted as +1. Now take an example of a negative signed value - 1000 00...
I have been searching for a good online course in data structures but have found that Google also returns results for algorithms courses, which say stuff like: In this course you will learn several fundamental principles of algorithm design: divide-and-conquer methods, graph algorithms, practical data structures (...
What strategy would you use to manage the releasing of versioned software to Azure cloud services (web and worker roles)? We are not looking for continuous integration. We are using Visual Studio 2013 and Visual Studio Online (Cloud TFS). At one point, we were releasing straight from Visual Studio using the Azure Clo...
In domain model of my web application I've an entity Foo which can be created only by a pojo FooBean: Foo.newInstance(FooBean fooBean) (Might have been better a Builder-pattern.) In the factory methode newInstance() the pojo FooBean is validated and throws NullPointerExceptions and IllegalArgumentExceptions if needed. ...
I've read How Do You Pull Something from a Release?, but it doesn't solve our problems, as our case is more complex. Our situation is as follows. We're developing an application for an internal customer. We're doing Scrum with four more or less aligned teams (i.e. sprints end on the same day), one of which is off site....
The blogosphere has a number of articles on the topic of AngularJS app structuring guidelines such as these (and others): http://www.johnpapa.net/angular-app-structuring-guidelines/ http://codingsmackdown.tv/blog/2013/04/19/angularjs-modules-for-great-justice/ http://danorlando.com/angularjs-architecture-understanding...
I consider myself to be a 'mockist' on the 'mockist' vs 'classicist' debate, but I am trying to understand the other point of view. Imagine I have this class, where a concrete instance of IDependency is injected by an IoC container. IDependency does not access a remote resource like a database or web service (in which...
In a centralized web service we break down the components into various small Git repos by software modules, e.g. authentication module, authorization module, data access module etc. (around 15 repos at the moment) The good thing is it is easy to manage the smaller code base, however, our productivity has decreased a lo...
I'm using Codeigniter PHP Framework for developing a web application, and when developing an admin zone, I've ended building a generic parent class called AdminController which is extended by the child classes to develop my Admin zones. I've shortened my code to show what I really want to show, my code is something lik...
from semver.org: Software using Semantic Versioning MUST declare a public API. This API could be declared in the code itself or exist strictly in documentation. However it is done, it should be precise and comprehensive. Why are we forced to declare a public API? Why can't I use it for my own website that has no API?...
I am mapping Field1 to Field2. The map object instantiates the field object and vice versa, creating an infinite loop. This is in PHP. class field { protected $maps; // mapCollection object. all the mappings of this field to others } class map { protected $field1; // field object protected $field2; // field obj...
I have four thread instances and they are executing run() code given below: public void run (){ System.out.println("1st line :"+Thread.CurrentThread().getName()); System.out.println("2nd line :"+Thread.CurrentThread().getName()); System.out.println("3rd line :"+Thread.CurrentThread().getName()); System.out....
I started using TDD for the first time on a project I started recently. I have a few objects with dependencies and structures that look something like this: public class MyClass { private readonly IDependency1 _dependency1; private readonly IDependency2 _dependency2; public MyClass(IDependency1 d1, IDepend...
We are going to track user engagement (i.e. time spent on website, most viewed part/page of the system, etc). I don't see Google Analytics / MixPanel being able to do this, since we have to analyze based on factors only present in OUR backend (such as users who go to specific school, users who are a specific type, etc)...
EDIT: Updated flow diagram to better explain the (likely unnecessary) complexity of what I'm doing. We at the company I work for are attempting to create complex PDF files using Java iText (the free version 2.1 line). The documents are built piece-by-piece from individual "template" files, which are added to the fin...
Given a data structure, I want to provide an API method Size which returns the number of items. I am vacillating between 2 approaches: Maintain a count and increment/decrement it in response to Add/Delete calls respectively Perform a traversal to calculate the count when Size is called. Approach #2 will take O(n) vs...
I have a huge collection of different moduli and associated with each modulus a fairly large list of remainders. I want to store these values so that I can efficiently determine whether an integer is equivalent to any one of the remainders with respect to any of the moduli (it doesn't matter which, I just want a true/f...
Sometimes I see people writing variable names like this: int _variable; IMO That's really ugly. What's that about?
I have the concept of a SlowLoading thing: public interface SlowLoading { boolean hasLoaded(); } I also have a component MyComponent: public interface myComponent{ void doSomething(); } My implementation covers both: public class MyComponentImpl implements SlowLoading, MyComponent { // omitted for brevity } I...
I'm new to the programming world and also a little bit confused. My brother would like to work with me on some program. I'm a graphic designer so he asked me for UI and all it's elements. I would really help him as much as it's possible so I have found Expression Blend for Visual Studio. At first it looked great but af...
Given a (intersecting) polygon, I'd like find out which tiles are being covered by the polygon. Example: Details: Tiles are square, 1 unit wide/high The grid begins in (0,0) The corners of the polygon can have floating point coordinates (i.e. 3.433, 5.234) In general, an edge of the polygon might be as long as 1000 -...
I am using Spring for a web application. To validate a user's input in a form such as for creating a Person entity I use JSR 303 validation to check for not null/empty or valid patterns etc.. Some things however I check in the service layer such as making sure a field is unique in the database and if not throwing an ex...
How can I deal with situations when multiple clients might edit same object at the same time? For example, I have a web app with admin console, which lets you edit profile data. Several users want to open the same profile and edit it. If I just let the things go as they do, I`ll get "the last who saves wins" situation ...
I work for a company that uses XML for storing a bunch of serialized Java classes. The framework we use is Apache Betwixt (abandonded in 2008) and it's kind of pain to maintain and extend (it seemed like a good choice back in the day). Crash course in Betwixt along with the detailed problem: Only supports public gette...
My Android app contains some Apache-2.0 licensed code from Google (in-app billing example) and links to com.android.vending.billing library in the form of a InAppBillingFile.aidl file (same license?). I would like to know what I have to do for my app to be license compliant, i.e. what to show in the About section, what...
In Core Data, we can put transient properties in our entity objects (or categories on our entities). These transient properties can calculate transient data based on actual entity properties. Is putting code that does NSFetchRequests in transient properties over the top and to be avoided? I feel this use is beyond the ...
I was working with a HashSet the other day, which has this written in the spec: [add()] adds the specified element e to this set if this set contains no element e2 such that (e==null ? e2==null : e.equals(e2)) I was using char[] in the HashSet until I realized that, based on this contract, it was no better than an Ar...
From this answer about latencies, we have some numbers (yes, caveat caveat) for latencies when coding (slightly edited): L1 cache reference 0.5 ns Branch mispredict 5 ns L2 cache reference 7 ns Main memory reference 100 ns Send 2K bytes over 1 Gbps network 20,000 ns Read 1 MB sequentially from memory 250,000 ns Disk s...
My code is given below. In the for loop I am getting unexpected output i.e. before completing the execution of for loop by 1st thread the 2nd thread comes in for loop and shows incremented value. public class ThreadSafe { public static void main(String[] args) throws InterruptedException { System.out.printl...
So far as I know, there are two forms of the Adapter Pattern: the class adapter and the object adapter. Could someone please explain to me the following limitation of the class adapter and why it is not a limitation of the object adapter: a class adapter is not suitable when we want to adapt a class and all of its su...
I'm modeling an Online Classified System where, naturally, who sells also can buy and vice-versa. The question is: should I have two different Actors, Buyer and Seller or I could have, say, an actor Client capable either buy and sell? How do you approach this Model? Cheers,