instruction
stringlengths
34
36.1k
The deadline for a release is tomorrow, your collegue finally finished his task that's crucial for this release, project manager is standing over your shoulder and presses you to finally make a build and you notice a flaw in your collegue's code during review. Not a critical one, but something you wouldn't let go if it...
I have a class hierarchy for which I would like to separate the interface from the implementation. My solution is to have two hierarchies: a handle class hierarchy for the interface and a non-public class hierarchy for the implementation. The base handle class has a pointer-to-implementation which the derived handle cl...
So I working on a project and want to profile my code. I have been using KCachegrind to get general idea of what functions cost the most. But now I want to get the exact time spent on those particular functions. So I decided to measure them manually using clock_gettime using object oriented approach. ie. wrap clock_get...
I had an interesting discussion with a coworker that revolved around how people interpret the use of properties and methods on an interface. For example, let's say we have a blog with posts in various statuses: Working and Published. When in "Working" the author is still making changes and shouldn't be visible to reade...
I just want to check that my current understanding of Java interfaces is correct. If an interface says it must include public void increase(int amount), then does that just mean the class that implements that interface must have a matching method?
Similarities and differences between the two: Template Method Relies on inheritance. Defines the steps of an algorithm, and leaves the task of implementing them to subclasses. Factory Method Relies on inheritance. A superclass defines an interface to create an object. Subclasses decide which concrete class to instan...
So I had this idea to map my framework's folder structure to namespaces with a dynamic build process. To give you an idea how this would work here an example structure: src/ FS/ File/ open.php (function) Math/ add.php (function) test.php (function) MAGIC.php (consta...
So I know this diagram is really wrong. But I honestly don't know how to express my ideas using UML notation and it is hard to find resources to this very specific case. basically I have these questions After the customer entered his or her details, the Arrangement class will calculate the cost and the distance based...
I have a set of ORM models that are shared between the main business application and a couple minor side applications (such as an administrative web interface). I don't want to put the object's business logic for the main application inside the ORM model classes because the web interface doesn't use any of it (and it w...
A number N and a range a to b will be input by the user, with a < b < N. The program purpose is to generate random sets of positive integers that sum up to N, with each positive integers within the range a and b. For example, N = 26 a = 1 b = 10 And here are some possible output of the program: 1,1,10,1,1,1,1,10 3,2,1...
Some background: I develop web services for internal departments of a large organisation that are used in public facing websites. There is a geographic differences between myself and my colleagues in these departments so most communication is by email, phone, skype etc. My process for development is develop in test env...
I'm currently trying to refactor some rather complicated object graph to use dependency injection. I'm using C# and StructureMap, but the problem isn't really technology specific. I understand the basic principle, but drawing blanks on how would I resolve a dependency like this: public class Food { public Food(...
I've been brainstorming on a specific problem for a while and today I've thought of a solution. But am not too sure about it. Hence this question for feedback and suggestions. I'll use the simple example of a product T-Shirt. The T-Shirt has multiple options: Color: White, Black Size: Small, Medium, Large Now in the ca...
Below is an example image, if I have a point of the white dot in the middle and I want to find the nearest possible location for the blue circle (which is obviously at the location where I placed it) if all the red circles already exist. How can I find that location? Performance for me is not a major concern for this a...
Let's say I am using a RSA keypair to encrypt and decrypt a large amount of traffic over a public network. Assume all traffic is padded and the key is 2048 bits, how often would you recommend renewing the private key? Is there a mathematical solution to how much encrypted data is needed in bytes that would allow a hack...
We currently have a store/shopping cart system that uses a single database. We have products with a field for the number we have in inventory (say 100 widgets). We have a customer table. When someone adds a widget to their cart, we insert a record in a join table between the customer and the product which represents...
Suppose that there are multiple classes (let's call them Container-s) that have somewhat similar structure. They are smart containers for some other Foo-s classes. These Container-s have: [1] A single private STL container (vector, set, map) for objects of some other class Foo [2] Standard public operations to work wit...
This is probably a naive question but I'm trying to figure out the industry best practice for working with magic numbers and their corresponding display texts. For example, whether a transaction is debit or credit might be stored as a bit field in the database, but the true/false/0/1 need to be displayed as "Debit" or ...
I would like to create a multiplayer mobile game where players play together over an ad-hoc network, with no internet connection required. Players should be able to join and leave mid-game, and the game should not rely on a "host" device being online. How can I coordinate game state across multiple devices in an ad-hoc...
This is a specific question here, but I'm interested in the general "best practice" for similar situations as I'm new to Java. Suppose I have Java code that needs to open a file (see below for code). I first have a function that checks for the files existence. If the file exists, we call functions to open it and proces...
When I'm trying to create an interface for a specific program I'm generally trying to avoid throwing exceptions that depend on non-validated input. So what often happens is that I've thought of a piece of code like this (this is just an example for the sake of an example, don't mind the function it performs, example in...
Title says it all. Should I increment my API version if I add, say, an image property to each instance of my JSON-represented 'Restaurant' resource? or should API versioning change only when implementation changes?
I am currently in middle of designing a backup application in JavaFX written in pure Java (meaning without Fxml) . I am having trouble implementing the MVC pattern for the following reason. The way I understand it is that the view has to be separate from the controller which processes events and updates the model to re...
Many times I find myself null checking when fetching a value from some data hierarchy to avoid NullPointerExceptions, which I find to be prone to errors and a needs a lot of boilerplate. I've written a very simple routine which allows me to skip null checking when fetching an object... public final class NoNPE { p...
There are cases where I don't know how to use exception handling. To make it clear, let me divide exceptions into two types: exceptional cases that may happen occasionally, such as when you try to open a non-existent file. exceptions that you wouldn't expect to happen if you have written your program correctly, such a...
I've seen a few answers on this already but nothing that really applies to my particular situation. I'm going to be building a mobile application, so primarily phones, tablets etc. Probably using Amazon Web Services, and I plan on having large amount of user data among other things, like statistics, images and so on. S...
I am currently in a dilemma. I am thinking about downloading a JSON file from a GitHub repo to replace local files. The local files are stored in a folder named lang, which is stored in the project folder. The repo is stored on GitHub and can be accessed using a URL. The GitHub solution, in my opinion, would be good s...
I'm developing a Java software according to the object-oriented Layers architectural pattern. Every layer should be clearly separated from the rest, and provide a well-defined interface to use it's services (maybe more than one). A common example for these layers could be an architecture consisting of a request process...
When you are working with an external library in git, should you add it to Git or should it be in gitignore? If you put it in gitignore, you run into the problem that if someone (or you yourself on another PC) wants to work on your code, they will first have to download and link the library. If you do include it, the g...
I come from a background where using a configuration file for every, if not every, constant is the best solution for maintainability and flexibility of the program. By this I mean, every hard coded string, integer, table/array, boolean, color, formatting expression, etc. are all put in one file or class (often called t...
I have an OpenGL application that plots data in real time. I would like to have a background TCP server that will accept data from a client without blocking on a call. The data is originally an array of 2048 doubles. Once this array of data arrives, I need to place it in a circular array buffer that is read from the...
With almost every software there are errors and those must be given levels. Grave errors may simply stop your program while simple notices can be resolved with a click. I've always proceeded by giving them a certain numeric degree of importance. But is there a "general rule" between programmers on how to chose these de...
I'm building a web site and I want to use a big background image. Because of speed considerations, I thought that it would make sense to send a low-res version of the image the user first (for fast page loading and smooth user interface experience), and when the page finish loading, use JavaScript to load the higher-re...
I am currently implementing WYSIWYG editor that will be available on the web, what are the main security issues I should tackle? The editor currently works that when user is done typing, the text gets saved to folder with editor text on same domain, and the iframe gets refreshed with the contents of it. I know that wh...
Consider an alphabet of k symbols and a requirement to optimally encode a series of values of known frequency. The obvious choice for this is to use Huffman coding, which is known to be optimal for this problem. Consider now the extra requirement that when the coded values are received it will be unknown whether or n...
The moment of working on a system that gives you statistics based on some data gathered from the database has arrived in my company. How do you efficiently gather statistics from a database in such a way that does not add too much overhead in loading a page, or too much complexity in cache management? Currently, statis...
I need to implement a site with a real-time graph. I'm currently using WebSockets and chartjs.org for displaying the values. Now I'm not sure whether I should send all data points in every message or just only the new data points and save the remaining data points on a client-side ring buffer. In the current setup I ne...
Is it the number of iterations or recursive calls made? Or is it the number of times the conditional check has been applied? Ex: if there are 10 elements in an array in descending order. The time complexity will be 10 log 10(base 2). The answer is 33.2192. Here is the java implementation of the code. I have added a cou...
I have a class that models LogicalExpressions. The leaves are classes that implement an interface IEvaluable, that has a method called Evaluate which returns a boolean as the result. public class MyEvaluable : IEvaluable { public bool Evaluate(Environment env) { } } Some of these evaluable objects need t...
A classical problem: read the words from a text file and list the occurence of each unique word in the file. I solved the problem using a hash map, but how could the performance be improved? I tried reading multiple lines of that file using threads, but even that would be like a bottle neck and there are chances of r...
I have this two types open FSharpx open FSharpx.Reader type First = { Name: string Items: string list } type Second = { Name: string Numbers: int list } Using a Reader monad from the FSharpx library I can do this let map f = fun n xs -> { Name = n; Items = xs } // : Second ...
Recently I had to implement a Semaphore using a Mutex and a Conditional Variable (this combination is also known as a Monitor) for an exercise at the university: the Semaphore's decrement operation blocks until its counter is more than zero before decrementing, and the increment operation increments the counter and th...
I would consider myself an intermediate Python programmer. One of my recent challenges was creating a list of all possible solutions to a given Countdown problem. Without getting into too much detail, I have approached the problem through: first generating a list of all possible Number-Operator arrangements using RPN...
Should you format numbers in the view or in the services layer? If you are going to round a number to 2 decimal places. Does it make sense if that number is rounded in the view or in the services layer? What about if that number is a nullable type like in C#? I don't want to write if(number.HasValue) { number.ToString(...
doing an lscpu cmd this is what i get $ lscpu Architecture: x86_64 CPU op-mode(s): 32-bit, 64-bit Byte Order: Little Endian CPU(s): 2 On-line CPU(s) list: 0,1 Thread(s) per core: 1 Core(s) per socket: 1 Socket(s): 2 NUMA node(s): 1 Vendor ID: ...
I wrote a parser for a certain type of binary file with recursive structure. I made its API to be similar to SAX, that is: the parser accepts an object of a specific interface, this interface has several methods called as the parsing happens: startFoo(type, name), endFoo(), datum(type, name, value), badEntry(errorMsg)...
In any software development project that involves distributed systems with multiple developers, having Logical and Physical Architecture diagrams is best practice but in my experience these diagrams always start off being well maintained at the start of a project but do not get updated as the project get released and t...
In cloud computing these two terms really confuses me, block-level virtualization and file-level virtualization . As of my knowledge, in file-level virtualization compute systems are not allocated partitions and just deals with the storage systems APIs to retrieve or upload a file. Block-level virtualization is allocat...
Let's say that we have the following interface - interface IDatabase { string ConnectionString{get;set;} void ExecuteNoQuery(string sql); void ExecuteNoQuery(string[] sql); //Various other methods all requiring ConnectionString to be set } The precondition is that ConnectionString must be set/intializ...
I'm trying to wrap a RESTful API around an existing implementation of a game. Here is a possible state diagram of a simple API design that comes to mind: I'm having troubles here because the existing domain implementation does not expose a list of moves. Instead it exposes the state of the whole board. A list of moves...
In my current project I'm refactoring the code to get a DBAL. I have a class Entity that is the base class for all classes that model a database table. So there are several classes that inherit from Entity like Document, Article and so on. abstract class Entity { /** @var DatabaseRequest $dbReuest */ protected ...
I am inheriting an api decision in an SDK I am writing where I am required to fetch domain objects (entries) from the server like this: blogEntries = client.content_type('blog').entries As you can see, the setter for the content_type property here is parameterised. To implement this design my Client class has a method...
I have to write unit tests and integration tests for a project. Should all tests be put into a single tests folder? Or should unit tests and integration tests each be in a separate tests folder? Or should I even put them into separate projects? If I keep them together, are there any advantages or drawbacks with this ...
I've a domain class named Campaign. Class Campaign { public long CampaignID { get; set; } public string CampaignName { get; set; } public DateTime StartTime { get; set; } public DateTime EndTime { get; set; } } In addition to that, i'm using Asp.net MVC, and I defined a model class. [DataContract] publ...
We have an application that allows users to enter conditionals in the form bound op x op bound2, we store this as a string, and then parse it at runtime to evaluate it. It is a decent amount of work, for a very limited conditional statement. We are looking for a way to serialize and then evaluate complex conditions, wi...
An example would be if you had multiple inputs, each of which effect a completely different process, (perhaps one changes a div's width, while another sends ajax request for predictive search), would you bind a single event use a switch statement to call the process functions, or set multiple eventListeners bound to ea...
I work in a Data Warehouse that sources multiple systems via many streams and layers with maze-like dependencies linking various artifacts. Pretty much every day I run into situations like this: I run something, it doesn't work, I go through loads of code but hours later I realise I've managed to conceptualise the proc...
At my work, we use Git as our version control system. We have a master branch, which I have direct commit access to. Sometimes I have to make a trivial fix, such as fixing a typo in documentation, and the unwritten standard in our office is that getting reviewers for that is a waste of time (please don't argue this poi...
We are retrofitting an architecture on a fragmented landscape of about 9 software products. These products are all related to a social/community platform. These software products, consisting of webapps, webservices and smartphone apps, were developed by students with no adherence to any architecture. The apps themselve...
From the interview with Kent Beck in a recent Java Magazine issue: Binstock: Let’s discuss microservices. It seems to me that test-first on microservices would become complicated in the sense that some services, in order to function, will need the presence of a whole bunch of other services. Do you agree? Beck: It see...
I was thinking it should hold pointers: struct Expr { string sym; Expr*[] sub; this(self, string sym) { this.sym = sym; } @property auto dup() const { auto e = new Expr(sym); foreach (s; sub) { e.sub ~= s.dup; } return e; } } But then that...
I work with a team of developers who are given choices as to what hardware and software they run. Our feeling is that this scenario lets us see a wide variety of target systems before ever hitting test. Our experience is that we find a number of strange problems in different browsers and operating systems soon after th...
If I need to have a function do some processing in order to initialize multiple of the object's variable (I'm having a hard time coming up with a simple example that doesn't seem weird). Which of the following patterns is preferable? class foo( object ): def __init__(self, bar, bar2): self.bar = bar ...
First, I am not a programmer (yet) and I can only understand basic algorithms written in pseudocode (+Dijkstra, which is a little harder than others, for me). I have been trough logic, set theory, relations, combinatorics. Currently, I am studying graph theory. Can you give me a simple explanation on how Lyndon words...
I am wondering how the apps that allow a user to choose an item and, once the user has selected an item and checked out, give the retailer information about order that has been placed. For example, say a takeaway has an iOS app and customer has chosen fish and chips and placed an order. How does the takeaway kno...
Imagine we have an integer amount (e.g. integer cents) to be allocated across a weighted set of items where the total allocated amount must sum to the original amount. For example: Amount: $1.00 Item Weight Allocated Amount a 1 $0.33 b 1 $0.33 c 1 $0.33 Whi...
Von neumann architecture allows sequential processing of instructions. So, a single core within a CPU executes instructions sequentially. Consider, OS providing 1-1 threading model(here) in a multi-core processor system, Properties of concurrent system Multiple actors(say, each thread assigned to a different core) Sh...
Let's say I want to model a phonebook. I would like a phonebook to be maintained in sorted order by name of the person that the phonebook entry is created for. However, since it is quite possible that there are two people with the same name, I cannot use any of the sorted collections, because they require the use of k...
In a multi-threaded environment, we must consider concurrent access to writable resources. A common approach is to use Monitor or its shorthand form lock. Task is at a different abstraction level than Thread. A task may run on a thread of its own (and according to the logs, they do so in our application), but that is n...
I'm currently working on a native mobile solution where I need to design a modular application. Imagine a scenario where you have your core application and 3 supporting modules. You can either sell your entire application or your client can negotiate and select what modules are more important. Your client might also w...
I have added this method to a C# class: public bool CanAddLeave(Leave newLeave, out AddLeaveResult result) { result = _repository.CreateSqlQuery("CanSendLeaveRequest ") .SetParameter("employeePositionId", newLeave.EmployeePosition.EmployeePositionId) .UniqueResult<AddLeaveResult> (); re...
I have a few operations to make over many similar elements. I would like to collect data from each element firstly and next bind all the data to an object (binding is expensive operation so I need to do it once). Is it consistent with the Visitor pattern? Example of my problem: class Element { public $name; p...
I am working on problem where a call to reduce a counter will come to a service and if counter is greater zero then call should be able to reduce it else fail. Pretty straightforward? huh! For a request get the counter value, reduce and put it back Well it becomes interesting with below Constraints: Request is sandbox...
When you browse for the phrase "constructors must not do work", then in various blog posts you will find the advice to not let the constructor do work. Despite this, I am having some trouble understanding why this is the case. Additionally, this popular post suggests to take such advice with a grain of salt. I have an ...
I'm building libraries with various small utility functions in C#, and trying to decide on a namespace and class naming convention. My current organization is like this: Company Company.TextUtils public class TextUtils {...} Company.MathsUtils public class MathsUtils {...} public class ArbitraryPrecisionNum...
I was cleaning unused variables warnings one day, and I started to ponder, what exactly is the problem about them? In fact, some of them even help in debugging (e.g. inspect exception details, or check the return-value before returned). I couldn't find real actual risk in having them.. Examples I do not mean lines that...
Visual studio projects, as opposed to makefiles or other projects I know, have some quirks: The directory structure of the project has no real connection to actual directory structure - all directories are purely virtual - this makes it harder to re-add mass of files while keeping directory structure The project consi...
We are designing a RESTful API that is mainly intended to meet the needs of a single client. Because of its very particular circumstances, this client has to make as few requests as possible. The API handles i18n through an Accept-Language header in the requests. This works for all things that the client needs to do e...
I'm developing a Cordova app and I've got the UI ready but I need data to my app from a database. For example I want my cordova app to include user authentication when the user opens the app which means, I have to access my database in some way to check the user input. I would also like to get data from the database an...
I am working on a project that is using Thrift and as a result has auto generated code. Firstly, what are the pros and cons of placing this generated code in SCM vs not and insisting developers generate themselves if the wish the build the dependent software package. I feel like auto generated code shouldn't be placed ...
Should every single class in my system have an interface? I understand that interfaces provide an abstraction from the implementation of a class and so changes to the implementation do not affect classes that are using the interface, i.e. cross platform implementations may differ but the interface can stay the same. B...
I recently did a phone interview with a company. The interviewer told me that he didn't like like to get people to write code on the spot without access to stack overflow or documentation because that's not how programming works in real life. He emailed me a small programming task to complete in the next couple of days...
We are currently building a framework (closed source static library) that will communicate with some Smart home devices via Wi-Fi. This framework will be used by 3rd party developer to build their own applications (mainly mobile application) in order to communicate with those devices. Currently, we have split opinions ...
We have here a large legacy code base with bad code you can't imagine. We defined now some quality standards and want to get those fulfilled in either completely new codebase, but also if you touch the legacy code. And we enforce those with Sonar (code analysing tool), which has some thousands violations already. Now t...
I'm building a multi-tenant cloud application and actually I need a bit of help to solve a situation about the login. My app is a webscheduler, this allow to each customer to have a certain location where store the appointment, the location is the database of my customer (buyer). Each buyer can have multiples location...
I was wondering if there were a set of standards or best practices for displaying information in lists for mobile applications (specifically Android applications that utilize RecyclerViews and custom RecyclerAdapters). I would be especially interested in hearing about this from Android developers who currently work or ...
I worked on a project and found a working solution, but now I got some questions on how I solved some problems in the code. First of all, I am no expert in design patterns, but I know the (anti-)pattern of singletons and normally I avoid them. But what I use quite often, are static helper / utility methods. So the proj...
I was wondering what is the best way to represent a function that is passed as a parameter in UML. Because I want to create a sequence diagram of my current networking code in my Swift project and some functions pass a function as parameter to other functions. So I was wondering is their a standard way to describe it i...
Is a multi-tenant database: A DB server that has a different (identical) database/schema for each customer/tenant?; or A DB server that has a database/schema where customers/tenants share records inside of the same tables? For instance, under Option #1 above, I might have a MySQL server at, say, mydb01.example.com, a...
Here I am in the process of scoping and estimating a relatively small new software development project. I have been through the user stories suggested by the customer and placed tasks against each, with an estimate and some brief notes on how the task will be accomplished. There are acceptance criteria. All ought to be...
I went for an interview, and got a workload problem: Problem: write a function to tell whether a series of workloads will exceed the maximum workload or not Input: MaxWorkLoad: example 10 Timeslot and workload: example [(2, 6, 3), (3, 8, 2), ... ] The (2, 6, 3) is begin time, end time, and work...
I am doing database programming using Java with SQLite. I have found that only one connection at a time to the database has write capabilities, while many connections at once have read capability. Why was the architecture of SQLite designed like this? As long as the two things that are being written are not being writt...
I am creating object oriented design for a simple app through which users can order food from restaurants. User can browse nearby restaurants, explore menu, add items to cart, and finally checkout. For now I am concentrating on two main classes User and Restaurant and the interaction that a user can browse nearby resta...
So I'm writing a game and using the Google Play Services framework to send and receive data. I have to implement the IRealTimeEventListener interface and override the functions below to receive incoming network data. class EventHandler : public gpg::IRealTimeEventListener private: //IRealTimeEventListener void On...
I'm writing a trading framework in MQL and I'm confused how I should organise my class hierarchy. |-- Terminal (Log) | |-- Market | | |-- Chart | | | |-- Draw | |-- Account | | | |-- Trade (Orders?) | | | | |-- Orders? | | | | | |-- Order In the brackets are the class variables wi...
We have customers that often have varying requests. Currently, we do things such as if customer_code = ? then ... and do something different just for that customer. I want to employ something similar to how Wordpress/Magento works where you can subscribe to events, receive the data, process it how you want and then ret...
We have an Android app written as a Cordova AngularJS SPA which has now grown so that we need to add some work to it meaning we have to improve the synchronization part of the app. The app is mainly used offline. I can't give details of the business use but data structure and constraints can be illustrated with an ov...
I have read the guide and they say Query Router Sharding is transparent to applications; whether there is one or one hundred shards, the application code for querying MongoDB is the same. Applications issue queries to a query router that dispatches the query to the appropriate shards.link to guide Does it mea...
In Chen notation multi-valued attributes are denoted by double eclipse(oval) and derived attributes are denoted by dotted eclipse(oval), but how they are denoted in crow foot notation? Also how associative entities are denoted in crow foot?
All articles (example) I read till now about regular expressions and NFAs explain three operations: sequence alternation (union) repetition (Kleene star) No one talks about negation. Is the negation not regular? Update: @RemcoGerlich What does it mean "swap the states". Can you explain it with the Kleene closure? H...