instruction
stringlengths
34
19.9k
I often run into this problem, especially in Java, even if I think it's a general OOP issue. That is: raising an exception reveals a design problem. Suppose that I have a class that has a String name field and a String surname field. Then it uses those fields to compose the complete name of a person in order to display...
I work for a company that has several products, and several databases and tons of data. To sorta merge all this data what we've been doing moving some of our data over to Amazon Redshift (a data warehouse). We store as much as we can here (everything very de-normalized). We consider redshift our 'source' data, as we'...
I am trying to apply "SOLID" whenever I can and try to use common sense and avoid a pattern when I see that a pattern is creating more problems than it's trying to solve. I don't want to apply a pattern and make life difficult for somebody else using my code just for the sake "I write patterns" if you see what I mean. ...
An interesting characteristic of C compared with some other languages is that many of its data types are based upon the word size of the target architecture, rather than being specified in absolute terms. While this allows the language to be used to write code on machines that might have difficulty with certain types,...
I currently have a long running application on an embedded Linux environment and all debug messages are currently being outputted to stdout using printf. This isn't ideal for special users who actually need to use the terminal. Is there is a way to output to a pseudo-device file, a custom stderr or some type of unhooke...
In my application there are 2 views both have 70% common fields like name, icon etc. One view is about list( contains 2-3 fields). On clicking the list , the next view which is the details should be called. Other functionality in both views is same. e.g while loading , presenter will be called to load data from the ur...
In creating trig functions my_sind(d), my_cosd(d), my_tand(d), that used a degree argument rather than a radian one and provided exact answers at multiples of 90, I noticed that the result was sometimes -0.0 rather than 0.0. my_sind( 0.0) --> 0.0 my_sind(-0.0) --> -0.0 my_sind(180.0) --> -0.0 my_sind(360.0) --> 0.0 ...
I'm writing a library to allow users to generate 3D models programatically. User writes code (e.g. Square(4)) User views preview of 3D model (with built in visualizer) User can "print" the model to a .obj file that can be read by other 3D modeling programs and visualizers What is a good way to architect the data obje...
I am trying to write a couple of classes using SOLID principles and having some trouble. The problem is quite simple. I have an application that tracks leads. Leads are created when events are raised by the customer - eg file download, registration, page view, etc. A lead can have multiple opportunities - ie opportunit...
I am going through Relational Database Design by JLM. I have come across words like database, data model, DBMS etc. which I am able to understand. But, I get confused when the author tries to use Database and Database Environment with supposedly different meaning (as per my understanding). What does Database Environmen...
In the process of writing a special collection I utilized the already exisiting IndexOutOfRangeException as e.g. a list or array would throw if I were to access an illegal index. Code analysis tells me, however, that this exception should never be thrown by user code, and I fail to see why. If I were to hand out refere...
Given a system which provides: Optimistic concurrency control / versioning per object (using CAS - Check-and-Set) Transactions that never need to span more then a single object. Snapshot Isolation Is this system considered serializable? From Snapshot Isolation In a write skew anomaly, two transactions (T1 and T2) co...
So I have code producing k sorted intervals in an n-sized array. What I'm brainstorming is the possibility of in-place merge of these intervals into a single sorted interval/array. The problem is managing space-complexity. For simplicity consider the problem of in-place merging just two intervals into a single sorted i...
I've looked at encapsulation and cohesion, but they look like the same thing to me. Isn't an encapsulated object already highly-cohesive?
Currently, I do not have a fixed process for cross device testing other than randomly asking the people around my co-working space to test my site on whatever device they have on-hand. This is quite a hit-or-miss approach, so I was wondering if anybody had a proper approach to this, as a freelancer. I know some organis...
I apologise if this is a bit of a stupid or broad question, but I'd like some general feedback please! Say I have this DB structure for users (in Mongo/JS, but really it's all pseudocode- and the IDs would actually be DB references, not basic integers): users = [ { id: 1, name: 'John Smith' }, { id: 2...
Are there any other languages that use the new C++11 uniform initialization syntax thoroughly throughout the entire language, or is this entirely a C++ idiom at this point? I tried googling and thinking of any off the top of my head and couldn't really find any. For those not familiar with C++11: Basically, your typica...
Studying for my algorithms test by spamming Algorithm Design Manual exercises, but I'm stuck on this one. I know I have to keep score somehow. Let G = (V,E) be a tree with arbitrary weights associated with the vertices. Give an efficient algorithm to find a minimum-weight vertix cover of G. Some of my thoughts: The ...
Currently learning Java so this may be a question resulting from lack of understanding of Java (while also learning Streams API) In the declarations of function I often see two templated types for the return values. For instance below we have <T,U> and also Collector<T,?,U>. How should I read this? That it returns one ...
I'm designing a simple game where all players use one battlefield via browser. I'm using websockets. So I'm wondering should I always send all data about battlefield to every user when smth is being changed or there is a way just to send delta to users who already have a data about battlefield? Will message brokers (li...
I am trying to make use of SOLID principles for the first time. I am re-factoring a File class that stores file information and makes file operations available. This class is then inherited to specific file types to make available methods for that type. I have started with SRP and have tried to make a FileWriter and Fi...
On MySQL at least, the following two queries are functionally identical: select * from users limit 0, 1000; SELECT * FROM users LIMIT 0, 1000; However, most example sites and most developers I've worked with use the latter, while I prefer the former. Is there a reason to write SQL statements in all-caps? I find it to...
Suppose I have a type sequence through which I want to search: template <typename...> struct TypeSequence { using type = TypeSequence; }; I want to create a metafunction Search that returns true if a given type exists in my type sequence, or false otherwise, and I want it to have better than O(N^2) space-complexity! ...
I have a theoretical social network where two people, A & C, can become friends if and only if, they have a common friend B amongst them. The simplest solution is to iterate over the two lists and see if they have any friends in common. My question is, can I use bloom filters instead? I will have a bloom filter for ev...
In an n-ary tree... Given a reference to some child node And a reference to a distant parent of the referenced child node Is there a method that a parent node can use to figure out which of its children is closest to the referenced child node and has a big-oh that's less than O(number of edges between parent and child...
I originally posted this on stack overflow but was told that here is a better place to ask this kinda stuff. I couldn't find any other similar answered question but if there is one please give me a link. I am developing a software which uses a database that is hosted on a main server(MSSQL). Multiple clients can be con...
IN view of creating a MIS (Management Information System) one architectural/design issue that's confronting us is managing allocation for set of employees. Scenario: Employees get allocated to projects and hence get their time (in full or part) for a duration is allocated to a specific task. How can this be represented...
Houston, we have a problem. I can't think of a simple class name. I have abstract class, something like that: public abstract class DataDisplay { public abstract void dataDisplay(Data data); } This class only displays data in some way: paint it to canvas, send SMS, send bytes through socket, etc.
I have seen a reliability of the system expressed like this: Rel=No of tests executed / Sum of crashes or other critical events Does it make sense and what actually is the output?
I'm developing a wcf based solution for a webservice layer that "occasionally-connected" mobile devices will be using. The service will not be using queuing (at this stage) due to the additional complexities, and so it will instead be operating a simple Request / Response approach. Of course, being a mobile device, ...
We're building an app based on Flux/React - and we're trying to establish a scalable pattern for configuring routes and registering dependencies. The two approaches we have can be broadly categorised as 'distributed' vs 'centralised' DISTRIBUTED: This version allows us to distribute configuration around the application...
How to carry more or less than six significant figures (4 , 5 , 7.. ) in the computation while running a program ? i'm writing a program to solve a system of linear equations /using Gauss elimination method in the following example / . and i want to consider the relative errors happening , in this example , the result ...
We are developing two related systems. One of them (A) will be installed on our customers' machines. The remaining (B) will be used by my organization. Each system has its own database (relational) and their schemas differ. However, both systems have to be synchronized. In addition, some changes in B has to be exporte...
I just started a new job as a developer in an organizational unit which is responsible for development and maintenance of several small Java applications. Just like most other Java apps out there, they use numerous dependency libraries. In my previous job, we used Artifactory for dependency management and our Maven bu...
Let's forget scaling or cloud configuration for a second. Think of an application with a few platforms: Mobile (iOS, Android) Desktop (Windows, OS X) Web (HTML/CSS/JS) The question is regarding the back end. Obviously the backend has to include a web server to handle the web traffic. And if there wasn't a need for M...
Does it make sense to implement a message queue system such as RabbitMQ or Kafka for the purpose of storing data in a queue? For example, this could be done in order to handle things such as notifications and instant messaging between users, while still storing message information in an actual database such as Cassandr...
I have found the following implementation of a Flow algorithm in Python: class Edge(object): def __init__(self, u, v, w): self.source = u self.sink = v self.capacity = w def __repr__(self): return "%s->%s:%s" % (self.source, self.sink, self.capacity) lass FlowNetwork(object): ...
I m first time creating a custom action filter and following this link http://www.asp.net/mvc/overview/older-versions/hands-on-labs/aspnet-mvc-4-custom-action-filters They are saying to Extend ActionFilterAttribute class and also implement IActionFilter interface. ActionFilterAttribute already implement IActionFilter. ...
I was looking at some examples on how to call a Web Service from SQL Server. And all of them show very unreadable code, that I imagine would be a nightmare to maintain. So, the main question is why to choose that approach vs a standalone program that can do the same. Just for example one of the how to call a web servi...
Exercise from The Algorithm Design Manual 6-10. [4] Let G = (V,E) be an undirected graph. A set F ⊆ E of edges is called a feedback-edge set if every cycle of G has at least one edge in F. (b) Suppose that G is a weighted undirected graph with positive edge weights. Design an efficient algorithm to find a minimum-weig...
I'm trying Haskell's Gloss module, and I found a a pattern of things required to properly display an object: Its position, dimensions, scale and Picture representation. This seemed like a good use case of typeclasses, so I wrote this up: class Displayable d where toPicture :: d -> Picture getDims :: d -> ...
Shameless plug: this question is for StackMode – a StackExchange client for GNU Emacs 24+. The product I'm working on, version-controlled with git, is a desktop application with an innately exposed API. Naturally, we want to adopt Semantic Versioning to the best of our ability. (Hopefully, perfectly and without error.)...
I'm writing an implementation of Ex (hopefully Vi eventually) as a personal project. I need to somehow store an identifier for the file associated with each buffer. In terms of security/race conditions and performance (and convention, if there is one), should I store the name of the file as given by the user, the file ...
I have a very large Oracle database, with many many tables and millions of rows. I need to delete some of the rows end-to-end. By end-to-end, I mean, if I want to delete a row from a table then I must delete all the corresponding records in child tables first and ensure that deletion happens without any constraint viol...
The team in my new company does not have a code review process. I come from companies with code review as a must culture and thus I don't feel comfortable committing my code without having it reviewed by someone. I'm a firm believer that code review is a way to improve quality and save time because it catches potenti...
What is the difference between a Functional Requirement and a System Requirement? As I know, the term 'Functional requirement' refers to a requirement which describes a function that needs to be implemented to solve a problem. But what is meant by the term 'System requirement' and how does that relate to 'Functional r...
Basically the scenario is this: There is one main version of an application, but it is modified for each client. The development is usually through the version that is currently worked on. All the other versions should be updated after adding new features or bug fixes. Application is written in ASP.NET MVC C# Git is u...
I'm coding in Python, but the question seems independent of programming language. I have a class that represents some system check: class Check: @abstractmethod def run() """ You have to define your own run(). As a result, it must set self._ok. """ ... @property def is_ok(): return self._i...
Since 2009 we are developing a fork of a CMS that was started in 1999 as commercial project, but released 2009 additionally under GPL. The original programmer sold copyright, code, name and website in 2012 to a new owner (who is now using the name and website because they have a high google pagerank). Should our copyr...
I wanted to look into communication/decoupling patterns and how to improve them. My current approach is to have a centralized commander in the form of an Event Bus and make him be the one to respond to most external interactions, like UI or network. Whenever a new event pops up, the receiver callback sends a signal to ...
CURRENT FLOW: I am using a custom algorithm(presently in php) to rank the MYSQL records before INDEXING it to SOLR . WHAT I WANT : Is it possible implementing this ALGORITHM(may be in JAVA) inside LUCENE library.Is it a good way ? WHY I WANT TO DO THIS : Right now ranking algorithm is taking approximately 2 mins to ...
I have an architectural problem, and would be glad to receive some consultancy :). The application I am developing (let's call it system A) is responsible for management of work groups, where these groups have a leader, a set of members, roles, categories etc. The information about the people who will become the group ...
I have a need to do some processing from a format A to a format B and from B to A. The job in one direction is very similar to its counterpart. Both formats are represented with an interface Msg. In such a case, I can see four obvious solutions, which is the cleanest? I hope there are some concrete principles explainin...
I have the following problem: An user can withdraw money from 2 payment systems (but the number of payment systems can change anytime in the future). If user has a trusted account on either of these payment systems, money is transfered automatically If user enters a new account then he needs to wait until the end of...
I'm doing poor man's DI (manual injection) in my application. My (pseudo-) composition root looks something like this: var connectionSettings = new Settings(SqlParameters) var dataLoader = new SqlDataLoader(connectionSettings) var data = dataLoader.LoadData() //yuck var someOtherDependency = new SomeClass(...) ... //...
I'm creating a web site that deals with monetary transactions. Users can deposit funds into a wallet and use them on the site. I'd like to keep track of some stats for the web site, like revenue and balance. I already have a database table for tracking transactions, but I'd like to also store a summary of all transacti...
I recently ran into a race condition while accessing a configuration setting. After examining what I could of the code, I came to the conclusion that the Configuration class' laziness1 was the source of the race condition. Pondering that lead me to me wonder if laziness naturally yields a greater chance of race condi...
I'm building a charting component that displays data directly from the raw data records. It should be able to filter data (subset) and then perform some rudimentry maths on the data (sum, avg, etc). It will finally display the data in a month-wise manner with a scrollbar to navigate through months. I'm currently buildi...
My lead is enforcing TDD on our project. He says he's following Uncle Bob (Robert Martin) and SOLID principles. One of the rules he's reinforcing is what I call "the single cog rule"--there should be no more than one cog in the implemented chain in your unit test. We have a component that has a repository (IRepository)...
So I have a list of DefaultSearchModal items that have an enum called TypeSearch in every list item. I would like to order the list to have a different enum property each row. So if you have an unordered list by this: 1,1,2,2,3,3,4,4,5,5,5,5,5,5 I would like to order it to: 1,2,3,4,5,1,2,3,4,5,5,5,5,5 What would be a g...
I will explain my question by way of example, but I'd love a general solution. I am writing a JavaScript application that needs to function differently depending on its run-time context. To handle this, I have have done the following. (1) At the beginning of the program, I set two context variables—let's say is_foo and...
I'm in the process of getting to know (modern) filesystems. As part of it, I came across log structured filesystems that also handle allocations in a log structured way. I wonder how they handle allocation of space in the most efficient way and if they probably use a data structure, I'm not aware of. As far as I unders...
I am allocating memory on the stack, and distributing it manually to shared pointers. I end up doing something like this at startup (I've simplified it by ignoring alignment issues): char pool[100]; std::shared_ptr<Obj> p = new(reinterpret_cast<void*>(pool)) Obj; pool += sizeof(pool); Of course, it is possible that t...
I have a set of songs where I want to sort them by a particular quality. In order to do this (by crowdsourcing) I will present users with a comparison between two songs. The user will then choose which one ranks higher. What algorithm can I use to weight the different comparisons? Given that I'll have a data set of com...
Our company is currently halfway through a software project with a consulting firm. As someone who will be taking ownership of the project after the consultants finish, is it reasonable for our company to ask the consultants to write automated test scripts and pass them on to us?
Sometimes I have clients that from start gives you huge flow of words about "how task should be done in details", like "you must use SQL Server here", "should do this in do-while-loop", "should make two functions like that, and they should run in parallel", etc.. But they never-ever give you any word about "what is thi...
I am currently implementing a software that uses a GSM terminal to perform actions. Actions can be sending messages, checking balance, receiving status report messages, setting the pin, ... The communication between terminal and program runs over a serial port. I am sending AT commands (basically strings) to the device...
I'm in the process of building an application which needs extensive logging of points in time at which certain events happen. For example when it renders a sequence of different shapes to the screen then we need a logfile with info like 'shape A rendered to surface at time X, shape B rendered to surface at time Y, surf...
In case I would dynamically link to a LGPL-licensed library (in this case Qt) in a commercial application: Which way do I have to provide the library's source code? Is a link to the project homepage sufficient? Or would I need to host the source code on our servers? For which period of time after distribution of the s...
whats the best way to go about this in python? I have a number of like so def test1() .... code ..... def test2() .... code ..... def test3() .... code ..... how could I create one database connection and use it across all the functions? I'm connecting to my database in a test file like so: import MySQLdb ...
I think using codenames are quite widespread. Our company is using them too. But my main concern is these names are usually not documented anywhere. And the meaning is spread by the word of mouth. And the names have nothing to do with function of the tool or entity it's named. I see the pattern that the internal test m...
How are Creational patterns useful? Most of the material I came across explains the use case to "solve common problems associated with object creation, improve flexibility". I can think of just two similar cases where these might help: Encapsulating object creation code into a factory like class, so that all object c...
My friend and I were discussing a script for automating a certain task and the solution involved using Selenium to automate the pressing of certain buttons. However when we click the send button of a form, how do we know it always has the same function? Even if a script works the first 100 times, the page may totall...
Is it necessary to include the GPL / LGPL license text to every distributed copy of my program? Or can I just put a link in the About-dialog?
Since JSON shows a lot of benefits over HTML, why don't just abandon HTML? Qt frameworks with QML shows it is perfectly possible to use JSON to design rich content EDIT: Many of you think about this question in terms of performance vs html but i'm not about that. HTML is just less readable and it's not enough per-se t...
In a project, certain related classes can be grouped together in one package. But some other useful classes are not related to any other class and so cannot be put into a package with any other classes. A StackOverflow answer I read says that it isn't a bad practice to put such classes in their own packages (just one c...
I am looking to develop an application whereby field staff can complete forms in an offline capacity (when onsite I`m assuming no internet connection) on an Apple or Android device and post the results to a web service when they are online. I have been lead to understand that this is achievable using sharepoint or info...
At work we use a private pypi server. This pypi server is specified as a dependency link: ... from setuptools import setup config = ConfigParser.ConfigParser() rc = os.path.join(os.path.expanduser('~'), '.pypirc') config.read(rc) dependency_links = [ 'https://{}:{}@<private_url>'.format( config.get('dc', '...
While making a struct creates some overhead at run-time, packaging a bunch of frequently-used-together variables can dramatically increase code readability. How do you balance the two? I was just asked to "unroll" a struct that contained 12 variables, which now makes calls to the function header monolithic; it seems ...
I'm working in a large legacy project which was build with ASP.NET Web Forms and the idea to add in the MVC libraries to the same project has been tossed around. I know that this is possible (there are plenty of articles available), but I'm wondering if/why this is/is not recommended by anyone who has done something s...
So I stumbled across some frameworks for doing CSS post processing such as pleeease.io and I was wondering what are some main benefits or use cases for using CSS post processing? I feel you can achieve more or less the same thing with preprocessing mixins/functions. How are they used in conjunction with preprocessing l...
I had an exam today and I feel that I did pretty well, except I could not for the life of me figure out what appears to be an unbelievably simple question. We were asked to give theta notation run times for a few programs(with input size n), and this was one of them: int sum = 0; for int i = 0; i < n; i++ for int j ...
Both live coding, and revision control, are very valuable tools when programming. But they seem to have inherently conflicting characteristics. Is it possible to fully benefit from both at the same time, or are they fundamentally incompatible? EDIT: To those who don't bother reading the whole length of my question: ple...
type PromptSegment = IO (Maybe String) instance Monoid a => Monoid (IO a) where mempty = return mempty mappend = liftA2 (<>) This behaves exactly how I want for my purposes. For example: ghci> let a = return $ Just "hello" :: IO Maybe String ghci> let b = return $ Just " world" :: IO Maybe String ghci> let c = re...
I want to lock a remote file with the string "ip + filename" using java. public boolean execCmd(String ip,String filename, String command) { String file = ip + filename; String lock = file.intern(); try { synchronized (lock) { System.out.println(file + "get the lock"); ...
Creating an array of strings for configuration or verification purposes can get long and ugly in code. For example: arrayOfStrings = ['one','two','three','four'] Often to reduce the characters and improve readability I will use string operations to contruct these from a raw string: arrayOfStrings = 'one two three four...
I'm cleaning up the includes in a C++ project I'm working on, and I keep wondering whether or not I should explicitly include all headers used directly in a particular file, or whether I should only include the bare minimum. Here's an example, Entity.hpp: #include "RenderObject.hpp" #include "Texture.hpp" struct Entit...
This is the type of question that one would probably get in an exam, but now it happens to be in the real word. :-) I would appreciate some advice regarding the datastructure/algorithm that can be used to solve the following scenario. A bit of background: I have a controlling program that reads C# source code from a da...
I have used SignalR to achieve real-time messaging functionality in several of my projects. It seems to work reliably and is very easy to learn to use. The temptation, at least for me, is to abandon developing a Web API service and use SignalR for everything. I feel like this could be achieved by thoughtful design, and...
I have a private (i.e. no chance of sharing the source) and commercial application, now I would like to use a library which is under the Apache 2.0 license. I've read the Apache license and FAQ section, but I am not clear about this. Is it the same as GPL3 which forces the application to provide the source code?
From Wikipedia: There are four different types of association: bi-directional, uni-directional, Aggregation (includes Composition aggregation) and Reflexive. From what I know: Composition relationship is used for objects that have a has-a relationship to each other. E.g. A car has-an engine. Whereas, aggregation...
I would like to build a system that basically offers the option to make various APIs interchangeable for usage to the end user. For example, the person using the software would have the option of choosing a single existing supported Billing System at any one time. They could for example choose to use WHMCS, Host Bill o...
I'm starting to work on a project where it would be quite useful to have something like a project file that holds all the data being used in a form that can't be opened/modified/used in anything but this application. Kind of like excel has an xls format or something like that. Right now all I know how to do is creating...
I have a script which different people may use. I have print statements so people can follow along what the script is doing, and if it breaks where it went wrong, and if a certain step takes a long time which step it was. Which way for print statements is better in this case and why? This: def do_something(): ... ...
I have the following types: data Bomb = TimedBomb { bPos :: Point, bPower :: Float, detTime :: Float } data Enviro = Enviro { bombs :: [Bomb], stuff :: [Picture]} When the TimedBomb timer reaches 0, I need it to explode, damage any enemies within it's blast radius (controlled by bPower), and persist for a few secon...
I have had this argument for a while, because I have noticed some people prefer "readable" code over properly structured one. So in the example I am showing, basically I have this Mapper class in which different Mappable instances are injected and the Mapper uses the instances to know how to map some data. The question...
Our client sells several products in an online shop (our software) for a especially low price on the first purchase. Further purchases of each product will fallback to the regular price. E.g. product costs 10 EUR on the first purchase (quantity fixed to 1) and 20 EUR each on the next purchases (any quantity). To preven...
I currently have a linq to sql project that was used for one project and not much work was put into it, only the generated context and entities were used. Since then the project has started to become referenced in other projects and is growing rather quickly. My concern at first was duplicate code, for example: using (...
I'm working on a fairly new project where I'd like to share some config items used by a JavaScript plugin. Specifically, the project is using jQuery dataTables and I want to find a good way of sharing config items. At the moment, the code I've been given is fairly simple. It is roughly equivalent to: // It might not be...
My employer's legacy system started off (in 1997) as very structured procedural code (with a smidgeon of OO), and it was luckily one of the 10% of software projects that was successful. It may look a little antequated today, but at least it is structured and provided a framework to hang extensions upon. Fast forward to...