instruction
stringlengths
34
36.1k
I am currently designing a programming language and I'm at the stage of making all the design choices that will guide the developement. My language has a slightly different syntax and concept to many other languages out here, and I wonder if it's more important that the language blindly follows its concept, or if it's ...
I'm doing some cleanup operations that could throw an exception, and I want to implement the logic of a finally block, but only if no exceptions are thrown: The initial implementation is this: acquireResource(); try { // stuff } catch (Exception e) { cleanupFromException(e); throw e; } finally { cleanup...
At the moment my specification files are along the lines of: Scenario Outline: Do stuff Given I am on the "<website>" And I have entered "red" into the search field When I do something Then something happens Examples: | Description | website | | Domain1 | www.domain1.com | | Domain2 |...
I have a data structure, a large dictionary, that is mutated by several functions. Each function does a database call, some calculations and then changes the value of a key in the data structure. Each function never changes more than 2 keys in the dictionary with the vast majority of functions changing only one. I've e...
I have a website that was originally created as a one page application that is now morphing into a full (multi-page) site. I am trying to refactor the various design elements for reuse on the other pages. Not all pages have the same elements. What would be the best way to do this: put the code for each element in a ...
I got this problem in an interview and want to confirm multi threading adds no value here. Case: You are writing an agent to buy stocks. The agent is initialized with a set of stocks to buy when they hit a certain price. A separate (out of scope) service monitors the market and invokes a callback on your agent when ...
Programming books usually preach to only test a single method in a unit test. This is supposed to keep the tests independent of each other and reduce the amount of work needed to rewrite the tests if a particular part of the system changes. But what about calls to set up the object under test? @Test public void testMet...
I've come across the following State Design Pattern which seems extremely logical and simple to implement: class CeilingFanPullChain { private State m_current_state; public CeilingFanPullChain() { m_current_state = new Off(); } public void set_state(State s) { m_current_state = ...
I'm developing a Xamarin.Forms app with a .Net Web API backend. I definitely don't want to do long polls on my app to the server, but I need the app to remain updated with the server information. I thought push notifications were the solution (I even started developing that way), until I saw several examples using it o...
def quicksort(N): if len(N) < 2: return N else: less = quicksort([number for number in N[1:] if number < N[0]]) more = quicksort([number for number in N[1:] if number >= N[0]]) return sum([less, [N[0]], more], []) print(quicksort([1, 9, 6, 10, 8, 7, 2, 4, 3, 5])) It seems to work,...
I am writing an application in Angular JS (1.5), and I need to be able to track a model for changes (updates/deletes/additions). For example, I have an ng-model that holds an array of user pets. This array has 5 pets, but the user (from the front end) can delete pets from that model or add more pets. I want to be able ...
No opinions, please. Is there any technical reason to typedef void? My current company and my last both have typedef void XYZ_void; where XYZ is the project name. I can understand a typedef for XYZ_INT, but void? Is someone afraid that the size of void might be different on another architecture?!
I have a method that updates employees data in the database. The Employee class is immutable, so "updating" the object means actually to instantiate a new object. I want the Update method to return a new instance of Employee with the updated data, but since now I can say the responsibility of the method is to update th...
Is it correct to say that threads were invented to enable programmers to expose process internals to the OS scheduler?
On the topic of Git; are there other types of version control systems? other than Local VCS, Centralized VCS and Distributed VCS stated in here?
I found an interesting quote in SICP that I think is highly relevant in object oriented design: We see that, in general, a type may have more than one subtype. Triangles and quadrilaterals, for instance, are both subtypes of polygons. In addition, a type may have more than one supertype. For example, an isoscele...
First off all: sorry for the title, but I didn't now how to better formulate the meaning of my following question in a single phrase. While I was writing the following Swift code: if errorData.isMemberOfClass(UIAlertController) { self.presentViewController(errorData, animated: true, completion: nil) } else { /*...
I've been tasked with overhauling a fairly large web-system that requires much user input. In an attempt to instruct the users when making input, the original creators has made extensive use of feedback structures like help texts and tool-tips. The problem for me is that all the text material used for user feedback is ...
Sometimes we meet a situation where we should iterate (or map) over a collection, applying the same procedure (function) for all elements except the first one. The simplest example is finding the max element of collection, but is not a good one: the operation here is idempotent. More realistic example is table dumping ...
I am trying to formulate a definition of a monad without needing mathematical terms or Haskell to understand. Can a monad be thought of as a function that accepts a value and wraps it such that it meets specific interface and behavioral constraints that have been found to be useful when working in a functional style? T...
When using tools such as TFS or JIRA to plan an application made of 10+ microservices, I am concerned should I consider microservice as an epic or as an new project? In TFS when splitting microservices as different projects, the benefit is a separated git repository, but on the other hand it is difficult to plan a sing...
I want to make a small command-line-run program that looks for a word or phrase in a target .txt. or .docx file, prints out a corresponding blurb about that phrase, and then replaces it with a different word/phrase. There are about 200 of these tuples. What is the best way to structure this? I'm thinking of putting th...
Most higher level (or scripting) languages out there have data structures that can hold different types of data (like numbers, strings and even functions) in the same structure, and you can also add elements without caring about their size, which you don't have to specify. They are sometimes called lists. In contrast, ...
I have a set of about 300 unit tests that have been through a difficult few months. The poor tests were subject to being upgraded from a V110 compiler (Visual Studio 2008) alongside Visual Studio 2012 to a V120 (Visual Studio 2013) compiler alongside an upgrade to Visual Studio 2015. These tests were passing in VS2012....
We have a web application that is accessed via kiosk workstations. We are looking for a way to track usage of each individual kiosk. Using the IP address was our first thought, but we quickly realized this wouldn't work since these particular machines are behind networks with dynamically allocated IP addresses. To acco...
I don't know very well Python. I'm trying to understand more precisely what exact features of dynamic languages (à la Python, Lua, Scheme, Perl, Ruby, ....) are forcing their implementations to be slow. As a case in point, Lua 5.3 metatable machinery would intuitively make Lua quite slow, but in practice Lua is rumored...
I have a requirement to (re)design an existing REST API which is written in Django REST. One of the main requirements is allowing third parties, approved by us, extending of our API. The API is a gateway to couple systems like central ldap, application databases, mail configuration etc. and provides couple means of aut...
So, I have a bunch of calls that are all being generated with a UUID1 throughout the day. At the end of the call the call is processed and some metrics around that call are generated and stored in Rethinkdb/Cassandra. Each call will generate something that looks like this [{ "company": "foo company", "campaign":...
I'm creating a .NET MVC solution that will have two web projects, one for API and for Web. Some models, such as customer, will be the same between the two projects. Is it best to have them kept in a common web library and referenced from the two web projects, or keep them unique to each project?
In a library with many code, some of them being the API which user would use to interact with the library, what should I call the rest of the code which is not part of the API directly? In other words, what's the opposite of API called? Internal code? Private code? Seems really simple but can't find the correct termin...
I am programmer with 1 year experience, recently I realized I seldom start a project correctly (most of my side project), normally the project cycle goes like Start with a few use-cases Start coding Realize a few things I did not handle well, and does not fit well in current codebase. Rewrite most part of code and th...
I am working with an effectively third-party library. This library has a base class that's used as the interface (C++ style), ComponentBase. ComponentBase has a number of methods and setters that are implemented by its derived classes. In particular, right now I am interested in one specific item there: the Value prope...
Let's say, I have created a business logic layer service (or a handler in Command/Query pattern) with a method DoSomething which processes a bunch of entities and stores them in database. Later on, another developer sees - "oh, this DoSomething method does almost everything I need, I can call it from my DoThisSomething...
For example, I have an UI with a button "Get Items" and a text field "Order". Then my button will retrieve all items from the order written in the text field. How should my controller know the order? Should it be public void GetItems(string order){ } or public void GetItems(){ string order = View.Order } or may...
After trying to write small programs with out reading much of the concepts in Java, the following syntax bugs me a little: Car volvo = new Car("Sweden"); class Car { String country; // constructor which has no return value and is to construct an object (fill with data) while creating it with the arguments supplied...
Apllication structure: Business layer public interface IOrderDataService { void Save(Order order); } public interface IOrderLineDataService { void Save(OrderLine orderLine); } public class OrderManager { private IOrderDataService _OrderDataService; private IOrderLineDataService _OrderLineDataService...
I was told to avoid "new" statements in classes or functions but rather create the objects from classes in the root of the program (maybe with the use of a DI-container) and then inject the objects into the classes. Anyway, I think there are many (the majority of) cases where this "rule" can not be true. Let's see this...
I referred this page for understanding about constructors in Java: http://www.javatpoint.com/constructor So, I pretty much got it as in my own words: constructor has no return value and is used to construct an object (fill with data) while creating it with the arguments supplied What is the purpose of using construct...
A Google Search on this topic just returns results explaining how to hack Google Analytics site search for POST-based search engine measurement. So, I thought I would turn to you fine men and women for help. I know the main differences between GET and POST involve security and caching (POST requests are secure and are ...
Let's consider an example wherein I have to model the following: Class to schedule exams for a Student, lets call it StudentExamScheduler Class to schedule exam for a Class. Let's call it ClassExamScheduler and currently it depends on the logic provided by StudentExamScheduler. So since both the classes schedule exam...
What is the term to describe all the instructions that executed as a result of a particular instruction? main(){ if(a) call_a(); else call_b(); } func call_a(){ //do_something //sleep... call_b(); } I would like to describe all the statements that are executed as a result of calling call_a() until it...
I recently encountered a class which provides pretty much every single-character as a constant; everything from COMMA to BRACKET_OPEN. Wondering whether this was necessary; I read an "article" which suggests that it may be helpful to pull single-character literals into constants. So, I'm skeptical. The main appeal of u...
Is the following an acceptable way of doing program licensing? A license file containing following informations: Magic identifier (to verifiy that it is a license file for the program) License id Customer id License create date License expire date (to check if it is expired) Last use date (to verify that the system t...
Our lecture provides us students a quiz to revise the material learnt of the last study session. The answer to the following questions was stated as "Yes": "The receiver of a message does not have to be known, when the message was sent." This really confused me, cause thus far I expected a sequence diagram to visuali...
Why doesn't System.String include a constructor capable of taking a IEnumerable<char>? The expected behavior would be: var foo = "hello"; var bar = new string(foo.Select(x => x)); Actual behavior: Cannot convert from 'System.Collections.Generic.IEnumerable<char>' to 'char*' If there is no obvious reason, I think it c...
I have a list of numbers (let's call it L) and I need to split this list into three groups (A, B, and C) such that the sum of the numbers in each group (sum(A), sum(B), sum(C)) is as close as possible to the sum(L) / 3. I'm sure it is an old problem, but I couldn't find a solution. The closest I got is to sort L, then ...
If I want to allocate a struct in C, #include<stdio.h> typedef struct container { int i; } Container; int main() { Container *ptr_to_container; ptr_to_container = (Container *) malloc(sizeof(Container)); ptr_to_container->i = 10; printf("Container value: %d\n", ptr_to_container->i); free(p...
I was solving a seating problem whose solution seems trivial but I am not able to get it. The problem states in short that we have to seat n (even) students in n/2 rows where students are labelled from 1 to n and no two adjacent students should have consecutive labels like "1 2" or "5 4". Also every student is either i...
I'm learning about paradigms of functional languages. So I've read that while Subtype polymorphism is typical for OO languages, Parametric polymorphism is typical for functional languages. But I wonder if there is Subtype polymorphism in functional languages. The functional language I know best is Haskell, and I know t...
I'm thinking about a way of finding similar parts in Strings. I have a set of strings of varying length i.e: The quick brown fox jumps fox force five the bunny is much quicker than the fox is First, i thought of just tokenizing the strings and count the tokens but in the case of "quick" here I also need to match "qui...
In an open source framework deprecated APIs were removed during the beta phase on the road to a new major version. Now users request to restore some deprecated APIs because it breaks compatibility. For me, beta stands for "Use at your own risk". Isn't it expected that due to a major version bump the API may change? I...
Given that Explicit is better than implicit. But also Simple is better than complex. I was wondering how accepted it is to transform code like this: import argparse def func(a, b): return a + b parser = argparse.ArgumentParser() parser.add_argument('a') parser.add_argument('b') parser.add_argument('c') args...
I am wondering why every git workflow merge develop into the production branch. Is there any reason why we cannot just leave the old production branches and create new ones from develop (in case we have only those two "special" branches). What is in there what need to be merged. Anyway every hotfix should be put into d...
The scenario is to have a Mobile App and Web App too. So currently I can think of two scenarios Which one do you guys think is better? PS : If needed I can also implement DAL Layer in both the cases in between DB and Business Layer. Edit 1 : I must mention here that, the functionality of the Mobile App is identical to...
I have a script that compares in some way each line from file1 and file2, and outputs the lines if there is a difference. I want to make it faster - right now it's in Python. I could use threads, but I would like to know is there some easier way to improve it? Since each test is independent, it could run in parallel -...
How to store a straight line (infinite length, not a line segment) efficiently? This is not a duplication of How to represent a geometric line programmatically?, because the linked question is about 3D, and it does not answer the main problem reflected in this question. Definition of a straight line: This question is a...
I noticed Wine has a policy: Why has my bug been marked as ABANDONED? A bug report is marked as abandoned after a long period of inactivity. You will have been asked to update the current status of the bug, to test a workaround or to test in a new version of Wine but have not responded to the request. This inact...
Earlier today I was asked to diagnose an issue in some development code. It turned out that the issue was caused by a new stub implementation returning random data which did not match the service specification. This led to a conversation with other with regards to the correct approach to dealing with this scenario and ...
Consider the following simplified example: abstract public class Controller { protected final boolean isUserAdmin() { return getServiceContainer().getUserService().isUserAdmin(); } /* ... other methods ... */ } public class UserController extends Controller { public Page showUserPage() { ...
I have a small project written primarily in C++ which is documented with Doxygen and tested with a unit testing framework (Google Test in my case, but that doesn't matter). I wrote several test cases for each method of each class to test the method's behavior under various conditions, and I want to leave some comments ...
I am currently writing a GUI for a C# application that adheres to the following software requirements (and am struggling with the conceptual design): Have a GUI with some choices of different operations to run. Each possible selection choice on the GUI should have a few sub-selections that the user can pick from. Each...
I am creating ASP.Net REST API application and stuck on the part where I should consume the REST service. I am not sure how to find the way let me accomplish the following: 1. I don't want it to be Pure REST in another meaning I don't want to lose the ability to use Sessions and authentication. 2. I want to have Simple...
I'm programming a game and am considering using some code released under the GPL license. I realize this means I will have to make the source code available and that won't necessarily be a problem even though I'll be selling the game, as long as I'm correct about the following few points (which I'm hoping someone can c...
I'm trying to better understand how to use a database in a personal website. I have a set of lists, like my shopping list, to-do list etc. Currently, they are all stored in text files with hard-coded links. I want to start learning database stuff with this simple problem: I want to be able to store my lists somehow,...
I am working on a simple project developing a telephone directory application. As such, it requires the implementation of the CRUD actions. Right now I have them as individual classes (e.g. "AddEntry"), which are nested under an "Actions" directory. I was considering creating an "Entry" class and having each action as ...
This is a common design pattern, but what is its name, and are its pros/cons discussed in any open literature? What do you think the pros/cons are? // get a token object that identifies this registration var registration = Registry.register("Foo", ...); // unregistration accomplished via the token object registration....
I need some assistance with designing a system which implements row-level security that could have multiple conditions that need to be satisfied. Context Suppose I have a user. A user can belong to 1...n organizations, 1...n departments, and 1...n positions. Maybe related/useful: These tables follow a hierarchical flow...
I saw an ad on StackOverflow today for a project called WinFsp. The site mentions the following features: Allows for easy development of file systems in user mode. There are no restrictions on what a process can do in order to implement a file system (other than respond in a timely manner to file system requests). Sup...
So I am writing a datamodel in python that interacts with an python module that queries the api. class QueryAPI(): def __init__(self, clientid, clientsecret): self.clientid = clientid self.clientsecret = clientsecret def create_user_info(self, name, address): ...... class MyModel(object): ...
I am writing a telephone directory program and need to store the entries in a CSV formatted file. However, I am having difficulty keeping the entries in order when adding. I was considering reading in the entire file to an array of entries and then write it back out when the program exists, but this seems inefficient. ...
With any method not requiring special permissions. I want to find out if a website can tell if my screen is off. Can a browser access that information in any way?
I am working on a library that allows the creation and manipulation of Vectors (lists with a known length), Matrices (lists of lists with known dimensions), and three-, four- etc. order Tensors (lists of lists of lists... with known dimensions). Now, printing a one-dimensional or two-dimensional data structure to the s...
It is quite easy to cover your code by writing tests first using TDD and you know that when to stop once you implemented a feature. For me it is trickier to decide how many functional tests to write for say a REST service. Currently I am in a situation where a service returns few fields in JSON and I can create/updade/...
The isocpp.org exception FAQ states Do not use throw to indicate a coding error in usage of a function. Use assert or other mechanism to either send the process into a debugger or to crash the process and collect the crash dump for the developer to debug. On the other hand the standard library defines std::logic_erro...
Edit: I'd like to point out that this question describes a theoretical problem, and I am aware that I can use constructor arguments for mandatory parameters, or throw a runtime exception if the API is used incorrectly. However, I am looking for a solution that does not require constructor arguments or runtime checking....
We have a REST api under design, to fetch an entity, eg persons, as follows GET /endpoint/version/persons/ Now we can get persons who live in a particular city, as follows: GET /endpoint/version/persons/?city=input_city We can also get all cities where persons are as follows, this provides person id and the city, per...
I am working on an existing database design. There is one table in which each row is created with only half the columns populated (the remainder are initially all NULL, except for an is_populated column), and later a single UPDATE to populate the remaining columns (usually weeks to a month later). None of the data in a...
I have three tables with a chain of two one-to-many relationships. There are two ways I can think of of fetching the data based on the primary key of the first table. JOIN each table (or LEFT JOIN if there are nonexistent rows) in a single query (SELECT * FROM t1, t2, t3 WHERE t1.id = 123 AND t2.t1_id = t1.id AND t3.t...
I'm a little confuse how to create domain objects right. In all/most web application we have simple objects created from POST request. We need to create domain objects that we will use in deeper layers. How we should do this? What kind of pattern should be used? It is very general question but I've considered many patt...
I have to replace SQLAlchemy "table" (declarative) class with mostly functionally equivalent wrapper, which will use API of another microservice. All the usages can be edited, so there is no need to do complete mimicry of the SQLAlchemy features, but with reimplementing I am loosing some useful things like smart cachin...
Imagine we have a administrative system that is designed to be as fast and lean as possible, without too much fancy CSS or JS. The UE is not that great, but still it is pleasing on the eyes and gets the job done. But my question is, is in such situation AJAX and the added overhead in form of JS worth it to save few HTT...
I have a method named IsDone. This method does some checks and returns true or false. Is there any benefit in using a Property without a setter instead?
I am working with Ruby on Rails at work and have been reading the Pragmatic Programmer on the side. I was given the task to create some small registration application with ~10 form fields. From my previous experience, when dealing with forms it becomes a painful process and Rails doesn't seem to make my life much easie...
There are six primitive data types in JavaScript: Boolean, Number, String, Symbol, undefined, null A WeakMap can't have primitive data types as keys. And a WeakSet can't have primitive values. Why is this? Is it a language design decision (in which case, what drove this?) or is there a fundamental reason why primitive...
I am not sure how to phrase this. I believe this should have been asked somewhere, but I am unable to find it because I don't know the keywords. Basically, I have some types like this: interface Foo class Bar0 extends Foo class Bar1 extends Foo class Bar2 extends Foo And Foo is an interface like this: inte...
I have an ArrayList of objects that may be added/deleted/updated via REST calls. In order to prevent issues that may result from concurrent accesses, will a ReadWriteLock be appropriate, and efficient?
I am writing a program that looks for a solution of a diophantine equation. The program is cycling for (int d = 0; d <= max; d++) { for (int c = 0; c < d; c++) { boolean possibleSolution = true; possibleSolution =test1(c,d); if(possibleSolution) {possibleSolution =test2(c,d);} ......
I am trying to understand the ideas of pointers and references in C++. I am stuck with the following, what would be the specific behaviour in this case? I have a class like this: class MyClass{ public: MyClass(const QByteArray & raw){ this->m_rawData =raw; } private: QByteArray m_rawData; } Let's ...
With the recent publishing of Pokemon Go, we're reminded yet again at how often online-dependent software (especially games) fails to run appropriately on launch-day due to server errors. I've been playing video games for a little over a decade now and I've noticed that this is a very common trend. Typically, according...
I'm writing an API, in which one of the function calls of which is meant to be a call to a factory for a series of tree nodes that take a number of parameters, some of which are the same and some of which are different. The kicker is that it's on the user to specify the exact structure of the tree - doing it algorithmi...
A monad is an object that has: A transformation that takes a type and produces a new type. In C# we call such a transformation a "generic type". We have a generic type M<T>, we have a type int, and we produce a new type M<int>. A generic function unit which accepts a value of type T and produces a value of type M<T...
I'm working on a web application that has users with multiple roles and each user can perform multiple operations, based on user's role, and the permission level the role has on the operation. I came up with the following schema. Users +--------+-------------------+ | UserID | UserName | +--------+------------...
There is an internal API, REST client over DB, all of which methods require User ID as parameter. User ID is an integer value - numeric PK in User table. Also there is an public API, that is like a Auth+Proxy Gateway: it checks the JWT token, extract User ID and then redirect to internal API. So right now User ID is...
I have been using GCC in a nix environment for as long as I remember. Given the wide range of processors, such as those from Atmel, ARM, Intel, and possibly a custom-made soft-core on an FPGA, and types like CISC and RISC, how a compiler like GCC turn my C++ code into machine code has been something I have not looked i...
When writing API clients, what is considered the proper way of concatenating a URL together with multiple endpoints? For example with the Blizzard API: WowEndpoints := [...]string{"achievements", "realm"} Bliz := &Blizzard{ Url: "https://us.api.battle.net/wow", Params: ReqParams, Client: BClient...
I am building a provisioning system, where other software/app/device/user would connect to it. I want a create a recognition mechanism so that I can identify the thing that is connecting to the system is a valid identity. Some kind of key, specific to the connecting software. The requirement is that the key should be ...
I'm asking as a web developer who hasn't yet used Ci. If a bug is discovered and confirmed but judged to be low priority or difficult to fix, how do teams set up Ci servers to to allow them to continue to work on other issues? I imagine I would want to write a test to confirm the existence of the bug, and have the CI ...
What would be a good system to use domain names as C++ namespaces in order to avoid name clashes between developers? The idea appears to be popular in the Java world. We cannot use namespace example.com { ... }, since dots are not allowed. A practical, but as I find not very elegant, workaround would be to replace each...
I am developing a 2D tile-based RPG game for desktop and (hopefully) Android. To represent a tile location in the game, I am using a class called Location, which has a value for x, y, and room. room refers to the Room that the Location is in. I use the Location class for calculations like whether a tile is passable or ...
I am working on a Spring/JSF app in which i have 1 scheduler to load user's sleep activity from fitbit. Right now what i do is that whenever the scheduler kicks in, I load ALL users from mongoDB and for each user i send a request to fitbit api to fetch sleep activity and save it in mongoDB one by one. As of now, its w...