instruction
stringlengths
34
36.1k
I'm working on a class that should manipulate files. Its interface has a Open(string filename) method, and various other methods to retrieve and manipulate the contents. Is it ok to call the open method before calling the method I'm trying to test? On one side, this documents the fact that the open method should be ca...
I was wondering what a good solution would be for ensuring that queue-names are entered correctly and are only used by the correct applications in a large system which uses message queues to exchange messages. We have a large system written in Java and Apache Camel. It is split into several microservices where they use...
Consider this data struture: key1 : value1 key2 : value2 key3 : value3 I have an operation that put this data in array format: key1, value1, key2, value2, key3, value3 Which would the the name of this operation? As far as I know, "collate" would be the opposite process, and "vectorize" would be about putting the data...
I am currently working on a site that heavily uses AJAX. I have a page that when called renders the basic HTML and then uses AJAX to get the data that the pages needs and then renders the rest of the page. There is no user interactivity on the page. I was of the belief that AJAX should only be used it there was going t...
I'm working on Apache Storm (but anyone who knows MySQL well could help too). Topology is like this: Single spout ----emit---> Multiple instances of a Bolt Each instance of the Bolt inserts a batch of rows to table ABC. The database table is located on a single server. The Bolt instances could be distributed across...
As far as I have known in CORS, browser sends preflight with OPTIONS request to the server to gain approval for the real subsequent GET/POST request. Now, HTTP is sessionless. Is the custom header THE WAY to ensure that the subsequent request is from the same client? Please view the comment section of the accepted ans...
I've noticed that a lot of my work follows this pattern: Decide that I need to add a behavior (say, align table columns right) Recall that I did it few months ago on a different project, try to find it Google the question Check several tutorials, find relevant code This is time consuming and I want to fin...
I've worked as a Full Stack Java Web Developer for many years now and of all the projects I have worked on two things are true of all of them: They were all Multi-Tenant applications with one database/one schema architecture They never utilized a Rapid-Application-Development framework (J2EE and Spring only) I can't ...
Why in, C# ASP.NET MVC Code First project, POCO Classes must have getters and setters ( {get; set; } ) in order to work? public float data { get; set; } or in db context class public DbSet<SGD.Models.MyData> MyData{ get; set; } I just don't understand why a simple attribute (without getters and setters) doesn't work...
How multiples processes are stored in the main memory , i understand every process will be divided into the equal size pages and will be stored in the frames of main memory. if whole main memory is divided into the pages then how are stack area, heap area, code section given to the process? my understanding is there is...
Java doesn't have a predefined recursion depth limit. As a result the recursion below (a dummy method that returns the value) throws java.lang.StackOverflowError after 62844 (with static) and 14002 (without static) iterations. public static int testRecursion(int number) { if (number == 1) { return 1; } ...
Imagine I find a completely new algorithm to compute the square root of a binary number (simplification of real scenario) on an internet forum that was an original creation. Is it ethical for me to adopt that algorithm into any future projects of mine, or is that plagiarizing? Should I contact the programmer who develo...
If there is some code that needs to be implemented across multiple controllers (lets say, 10), e.g.: // Inside a controller function var myField = null; var response = service.callBackend(function(){ // Other logic // starts here if (response) { myField = { name: response.name, ...
A program, I am referring to any program written in any programming language. It could be a Java program which has only one method to do the multiplication, and a main method executes that multiplication method. Or it could be a program in Python does the same thing. Or it could be an application program such as an ema...
I'm writing a central logging library. In it is an AutoLogAttribute method attribute that automatically logs entry/exit of methods and their parameters (automatically serialized) like this: [AutoLog] public void GenerateInvoice(string customerId) { ... } // Outputs // af8291: Entering GenerateInvoice with paramete...
Let's say I have a class MyClass ... which has a data member x class MyClass1 : def __init__(self) : self.x = 1 Also a method which does something with x Should I pass self.x as a parameter? class MyClass2 : def __init__(self) : self.x = 1 def multiple_of_x(self, x) : return x ...
Imagine I have two classes like this... public class SingleplayerGameSetup { public int Seed { get; private set; } public int AiNations { get; private set; } } public class MultiplayerGameSetup { public int Seed { get; private set; } public int AiNations { get; private set; } public List<IpAdress> ...
I am trying to learn WHEN NOT to use: classes member variables HERE IS THE CODE access_point_detection_classes.py from scapy.all import * class Handler : def __init__(self) : self.wap_list = [] self.TempWAP = None def process_packet_capture(self, packet_capture) : for packet ...
In my application I have to consume data from an API, do some processing and then store the data retrieved from the API in my own database. Should I have multiple Data Mappers? One for the API and other for my database? Thanks.
Pertaining to the Stable Roommates Problem and the algorithm developed by Robert W. Irving. There are two (sometimes broken into three) phases in which we may come to a stable pairing of everyone in a set and their stated preferences. The first, and sometimes recognized second, simple rejection phase(s) are pretty sel...
I'm reversing an old DirectX 7 game and I noticed that it sometimes uses Blt and BltFast but at other times, it locks the directdraw surface and directly writes to GPU VRAM. Why did developers take the latter approach? Not only is it slower (since all rendering is done in the CPU) but it's also much more difficult. Acc...
I have large and complex immutable data structure (language is F#, but should be applicable to any language really) where I defined a lot of functions making changes and returning new instances of ds with signatures like: val action: ... -> ds:Ds<U> -> Ds<U> What I want is to somehow abstract the changes that happene...
I have JSON file which has some hundereds of rows stored like below.. [ { "Id": "1", "Name": "A" }, { "Id": "1", "Name": "A" } ] I am trying to load this into collection of a class. This data is static and wont change, so I need to load this only once. I have created a class and loading this i...
Why do some compilers violate the defined language standard? I don't understand, in ISO/IEC 10206:1990 Extended Pascal standard on 6.8.3.2 Arithmetic operators section, Page 86. It says that, A term of the form i mod j shall be an error if j is zero or negative ; otherwise, the value of i mod j shall be that value o...
I have a class "Parent". "Parent" class creates an object of class "Child" in my CPP module. The use-case is "Child" has to request for some information from "Parent". This can be done in several ways and I can think of the following designs. 1) Store object pointer/reference of "Parent" in "Child" and let "Child" call...
With WPF and MVVM, properties of the ViewModel are bound to UI elements. When a property changes, its set accessor calls OnPropertyChanged which in turn raises the PropertyChanged event of the INotifyPropertyChanged interface. But it is possible to call OnPropertyChanged (with the property name as argument) from anywhe...
I currently have a system where there is a user table, a role table, and a user-roles association table, where one user can be associated to multiple roles (like Admin, BasicUser, etc.). I am able to authorize action methods based on these roles. Now I want to add support for privileges so that action methods can be r...
I'm looking for a way to achieve something like this using VS online ... I have a lot of small solutions in the root of the repo that are structured a bit like ... Foo.sln "/Framework/xxx" "/Foo/*.csproj" Bar.sln "/Framework/xxx" "/Bar/*.csproj" ... There are generally some common pieces in each of the so...
I have a database that has two columns. The first column is an index, the second is the path to a data file. There are two types of data files, X and Y. These data files are then processed and graphs are created from them. So some examples of the rows look like this: ID___| FilePath 0001 | /X/datafile1wfre.dat 0023 | /...
I want to expose a resource on the web. I want to protect this resource: to make sure it is only accessible to certain individuals. I could set up some kind of password-based authentication. For example, I could only allow access to the resource through a web server that checks incoming requests for correct credentials...
I am writing a program in Python, which basically manipulates strings, and I was wondering whether I should do it using OOP principles or not. The client did tell me he doesn't care about the code, he just want the thing done. I know that object-oriented code is not by definition cleaner, and conversely non-OO code is ...
JavaScript string type is immutable, but does it mean identical strings will share memory? Say two strings are created in complete different places, will a modern JavaScript engine be smart enough to not double the amount of memory for each "copy" and just re-use the one already created (that exists somewhere in memory...
If You've seen Hitchiker's guide to the Galaxy, you know that Deep Thought (pictured below) is a machine that was built to compute the meaning of life: Let's imagine that we were tasked with building this machine using Agile Scrum, and to use User Stories. There really only appears to be one Story, which is: "As a use...
In a large code base, what is a good practice between: Updating class properties inside the method vs. returning a value from the method and updating the property in the place where the call to the method was. Example 1: Updating class properties inside the method def sendFileToS3OrFileServer(Request request) { if (...
Reason: In an LR35902 (the processor in the Game Boy) assembly program of mine, I'm trying to figure out what bits have changed to 1's when comparing A with B, which would need a bitwise operation that I'm about to ask for. Question: is there a name for the following bitwise operation? *-*-*-* |A|B|O| *-*-*-* |0|0|0| *...
I'm planning to use Flickity in my MIT-licensed open-source JavaScript project. The license for open-source usage is GPL. Can I link the file via a CDN into my project, or is this considered a "derivative work?"
I have a web application that allows users to upload files. My application does processing on these files (parsing, modifying metadata, etc). What approach should I follow? Should I save the files locally in the web server until they are processed and finally upload them to S3 and delete them from local webserver? Or ...
I have a simple Go library (~300 lines, mostly type declarations and nice methods and compatibility methods for gomobile etc., also pretty-printing scripts). The heart of the whole project are two regexes, placed in a separate file in my Go repository. Now I want to port that simple library to Python, Java (Android), m...
I have a question about what the best design pattern to use would be. I have 2 specific scenarios, the first one fits neatly into a Unit of Work(UoW) pattern. The second is a little bit more fiddly. Basically, in certain business scenarios, I have a need to save some data even if all others information fails to save du...
if i>0 : return sqrt(i) elif i==0: return 0 else : return 1j * sqrt(-i) VS if i>0: return sqrt(i) elif i==0: return 0 else: return 1j * sqrt(-i) Given the above examples, I don't understand why I virtually never see the first style in code bases. To me, you turn the code into a tabular ...
Over the past several months I have learned a lot in software design and practices across several languages and frameworks. To me, the most attractive and useful designs patterns are those that follow an object-oriented approach. Particularly I am drawn to an approach that promotes reusability, modulariy, understanding...
I'm currently at the design stage of a component-based architecture in C++. My current design includes the usage of features such as: std::vectors of std::shared_ptrs to hold the components std::dynamic_pointer_cast std::unordered_map<std::string,[yada]> Components will represent data and logic of various items that...
I'm studying malloc and free and writing my own malloc and free. But when I read about the different algorithms (best fit, first fit, worst fit) then it doesn't say which algorithm is used for searching and which is used for sorting. The best fit strategy is quite simple: first, search through the free list and fin...
I need several duplex channels between two hosts. There are a number of advantages to establish only one TCP connection. But I doubt multiplexing would cause some inevitable problems. Will it harm performance or increase latency significantly? And what about memory usage and CPU usage? Is there any suggestion or caveat...
I have a C program "translated" (dont know what word is appropiate) to Javascript, so I can use it in node.js. C program consists of main that accepts command line parameters. I understand that I need to somehow use module object to pass those command line arguments, but I'm at a loss. My js program consists of 2 files...
I have a CPP class whose constructor does some operations. Some of these operations may fail. I know that constructors do not return anything. My questions are, Is it allowed to do some operations other that initializing members in a constructor? Is it possible to tell the calling function that some operations in cons...
This summer I got my first position as a programmer (intern), but it has been a disaster. Before the internship they misled me; they didn't tell me they were developing Django apps and told me to just be comfortable with Python (and they expected me to be able to dive right in, and of course I couldn't), and thus I spe...
We are using Apache Camel with ActiveMQ in a microservice architecture in a growing system of integration solutions. I was wondering how each service should react when they are unable to connect to the message queue, or if this should be handled at all. As the system is right now each service logs an exception for each...
I am wondering how compiler (or preprocessor) include headers. I have three files. First is header.h, second first.cpp <- and there is #include <iostream>, third <- it contains #include <iostream> too. header.h: #ifndef HEADER_H_ #define HEADER_H_ struct Student { std::string imie; int ocena; }; void foo();...
I have seen several different diagrams in several different views. Is is possible to use the state machine diagram in the development view in 4+1 Architecture?
I'm looking for advice on how to handle constraints on the input of a method. I have a method that only works if the input argument(s) fulfill certain constraints. If the method is called on input that does not fulfill the constraint(s), the method does something harmful. The concrete problem is this. I have a class In...
The title may have been a little vague... I am working on a piece of software that is designed to perform one task. I would like this task to work in parallel, allowing for multiple asynchronous threads to perform the same task. I am not concerned about the order of which these tasks get completed but I am concerned a...
I've been working on some embedded code that handles a Bluetooth Low Energy (BLE) radio. BLE has 40 channels, numbered 0 through 39. One function for the radio driver takes in the channel and sets the appropriate register with the correct setting. The obvious function prototype was SetChannel(uint8_t channel);. Howe...
I have a few services that sign some data with an asymmetric cryptography algorithm (like RSA). I need to spread some secret (private) keys between all instances of the service. I've found a few ways to do that: Share keys as configuration (looks insecure when I need to spread private keys) Embed keys into apps/images...
Searching for simplest solution where a User can order an item. If someone purchases an item he will have one address. Which then is the invoice and shipping address. But he could add another address if the invoice address is different from the shipping address. I wrote some code with two Classes Purchase and Address. ...
Here's the problem I'm trying to solve: There's a rather large API I'm trying to write a wrapper class around. The simplest approach would be to make one class with a method representing each possible API call. This gets unwieldly though as the API is very large. My first thought is to break up each API section into a ...
My use case requires me to implement multiple validators which implement the interface: public interface Validator { boolean validate(Object o); } Based on the business group of the Object o, a different combination of validators need to be applied. For each business group, I plan to maintain a list of Validators. Th...
This is intended to be a general language-agnostic question. It is written around a weird example simply because I could not find a better way to ask. Also, the "pseudocodes" provided look like a mixture of Java and JavaScript only because those are the languages I'm most familiarized with, but hopefully they will be e...
I'm trying to implement the Service Locator pattern. In the below diagram is my references between projects (.net projects), each box represents a project. The arrows indicate the dependencies. I am asking if this is a correct implementation of this pattern or is there a better way?
Is code that runs fast but written with a bad and hard to understand syntax, good code? Is code that runs slowly but written with a good and easy to understand syntax, good code?
One of my customers has a licensed software for business management and uses a SQL Server as database server (The database is open and I can run queries). They have a need that the current software does not satisfies and I would like to create a separate program to fill that need, using the same database that the progr...
Let me start with the fact that I'm prepared for this question to be closed as opinion based, but I am going to attempt to phrase it in such a way to keep it less based on opinions. The Short Version Are there any practical or best practice resons why configuration settings should not be stored in a Resource (resx) fil...
(Not sure if there was a relevant stack exchange site for this, I saw a few ones related to open source in companies and figured this was similar, but different enough to warrant a new question). We have a client that we're about to pick up for some work. We've gone off and done the exploration for their product and co...
I don't know much about how computers work internally, so I also don't know much about multithreading, and when it takes place. I know it is important in databases or web applications and such, where a lot of different machines try to access or modify the same resources, but what about "classic" code, like calculations...
While working on a small class called FractionNumber I found asking myself if I should implement an interface that I am already implementing. Sounds stupid, I know, but bear with me. My class FractionNumber extends Number; Number implements Serializable. And I am unsure if FractionNumber should explicitly implement Ser...
I'm interested in which approach to prefer. Consider some code which retrieves a translation for some text. It has to respect these constraints: Return translation only if the text will be used on a UI. If it's used some where else (debug log), return the normalized version of the text. Text normalization is costly (c...
I have the following constructors: public Class1() { this.Variable = new Variable(); } public Class1(Variable vari) { this.Variable = vari; } Which can be rewritten as: public Class1() : this(new Variable()) { } public Class1(Variable vari) { this.Variable = vari; } Is there any benefit from writin...
Could you tell me your opinion that which layer is the right one to place domain event handlers in DDD? For example, I have application service to add a new contract and I'd like to send an email notification to the contact person, when the contract has added, so is that email sender (which handle ContractAdded event) ...
Imagine this simple application use case, say, for fetching data from outisde of the app. These steps represent the "depth" of the layers, from top to bottom. UI touch event ViewModel handles said event Some service / manager reacts accordingly The correct request is built and executed The object is fetched and return...
In FP vs. OO, from the trenches, Michael Fogus says: Whenever I write some code to deal with data about people then functional programming seems to work best. Whenever I write some code to simulate people then object-oriented programming seems to work best. My question is: In a pure FP language, how do you "simulat...
We're in a project that has quite a lot of code and while in general we have a good test coverage and things work out pretty well, I noticed that our tests grew more and more complex over time up to a point where the tests are more complex than the code they test. As a bit of background we're using Spock for testing an...
Current situation I have a situation that I find frustrating: the integration tests in my project (a RESTful API) contain both API HTTP calls and SQL queries. Whenever an API call is made that writes something to the DB (a POST, PUT or PATCH request), a hand-written SQL query is launched to compare the API response wit...
Let's say we have an app deployed to Azure. App has external files not bundled with it, files which are required for app to operate. They are seperate but are essentially part of the software. Normally without a cloud service, we put these files on a disk path and tell the path to app using an environment variable. Sin...
We're facing the issue that we often have classes with lots of properties. But we don't need them for most API calls. So we end up having multiple versions for basically the same business object. E.g. public class SmallCountry { string Code { get; set; } string Name { get; set; } } and public class Country {...
I recently had engaged in a security discussion with my companies cyber security risk lead, discussing security controls and standards they would be holding the project to. The expectation of the Risk Lead was that these controls would trace back to architecturally driven Non-Functional Requirements defined for the pr...
I'm developing a producer/consumer system with three deques (each for one priority level, from max to min); first deque has major priority, so it must be read before others: once empty, others deques will be served. My code is something like this: // this is the class associated to a deque class DequeEntity { publi...
In C, we like to use #define or const globals to avoid hard-coding values and strings. How can we avoid hard-coding strings that need to be formatted? Consider, for instance, building a filepath to an i2c bus in linux: snprintf (dev, size, "/dev/i2c-%u", bus_no) I don't like the idea of adding a #define I2C_BUS_FMT "/...
I'm trying to figure out how to do something, and I can't quite seem to get it to work. Let me describe the situation: Using a hosts file, we redirect the resources (CSS/JS/etc) of a website, let's say blah.website.com, to our local machine 127.0.0.1. We then can do some development on any JS/CSS/etc on our local machi...
I'm receiving flat files with the stock price and number of held shares for an account. One file contains the price and shares to 6 decimal places. The other file contains the price and shares to 12 decimal places. The system needs to persist and later display these values (preferably to the number of decimal places re...
I work on a large project (C++, C#) in areas that can have a lot of churn. I'm in the habit of getting latest sources multiple times a day. Every now and then this results in an awful back-merge. Usually it results in either having to fix little things, which doesn't take too long, or if I'm lucky they're no conflicts ...
I would like to ask a question about XML and S-expressions(-ish) notation. S-expressions are pretty old; they are also really simple. We could consider two forms that are equal in meaning, different in syntax: (xml code taken from Polish wikipedia) <?xml version="1.0" encoding="UTF-8"?> <ksiazka-telefoniczna kategoria=...
Since high Cyclomatic Complexity is harmful, and it would be beneficial to lower it down by creating sub functions. However, it might lead to a long calling queue and lead to some super nested function that would also let the other programmers feel hard to read. What would be the beneficial solution or where should we...
Here's a pretty problem. I recently had a memory leak in a java program where one huge object was not collected, even though it "should" have been collected when the whole complex graph of objects that contained it became garbage. (Concretely, the large object is an image, and the complex graph is a window and all ...
I already have experience working with MVC based web apps and started reading recently about REST. But went into confusion when re-thinking about how existing web app not using any kind of framework/pattern could be refactored to use these two. So the application (entirely written in PHP) already has a web UI but it's ...
I have a couple of questions regarding MVVM view models. I have 3 view models in my scenario, which I have put together a shorter sample below. I was looking for a nice solution for 3 views working in conjunction with one another in a small part of a large application. There are 3 classes in play here: ParentViewMod...
How to index a massive, randomly selected, uncontrollable, constantantly changing dataset? Imagine you want to index all of the snow particles in a giant snowglobe that is constantly being shaken. Each snow particle represents a piece of lengthy text (say a book) that needs to be indexed, however, the particles are con...
Here are some requirements for a queue: Every few days add ~100k tasks with various priorities Workers will pull tasks at typically less than 10 / second Tasks need to be completed by ~2 unique workers (for error checking), and then depending on outcome potentially by an additional worker Persistent storage of tasks ...
I find myself often in the situation where I want to mock a non-copyable object, for example a DbHandle handle. I was going back and forth looking at different design choices, and I settled on the following design: In my production code, there is no need for a client of the Repository to know the DbHandle object, but f...
I have been having a huge and heated argument with someone on a slack group - the debate is this : My argument Portable code is that which compiles with various compilers and runs exactly the same on various architectures without modification. If your code depends on the sizeof(T) of an integral type, in order to keep...
I find myself writing small test cases and applications to post bug cases, answer questions in some forums, make feature showcases for clients, etc. and for that I created a TestCases project inside my workspace. Now, I want to keep track of all these small and unrelated applications in case I need to go back to them, ...
I have an InputStream and an OutputStream to a server. I can send a bunch of JSON requests over the wire and get a stream of responses back from this server. From this, I'd like to build a wrapper that provides getters like getFoo() that create a request, send it, and get a response. I'm not sure how to handle this con...
In my program I need to create xls or xlsx files and the file type is chosen using an option in a property file. This is how we can switch xls and xlsx file type using java code For xls: Workbook workbook = new XSSFWorkbook(); For xlsx: Workbook workbook = new HSSFWorkbook(); And what I do is, for creating every fi...
I would like to define a shared pointer whose operator== compares the pointed to values instead of the pointers, something like this: template <typename T> struct deref_shared_ptr: std::shared_ptr<T> { bool operator==(const deref_shared_ptr rhs) const { return (**this == *rhs); } }; This type has two ...
We have an Android app. The Android App uses Volley (https://developer.android.com/training/volley/index.html) to transmit network data. The point though is not about Volley, is about the pattern Volley uses to execute a remote call. Example: final TextView mTextView = (TextView) findViewById(R.id.text); ... // Instan...
As an example, lets say I am working on creating an eCommerce solution. Part of the functionality of this solution will be to ensure that the final price of an order is correct. Lets say the final price will include the grand total of all products, the shipping costs and any tax. Lets say I have two public methods: /**...
Say hi to the method: public void hello(Data data); This method uses some data and performs… whatever. Now, written like this, the method is very specific – i.e. the argument is very specific. But now, in real life, this Data (for example) may come from e.g. class called DataProvider: public class DataProvider() { ...
There are a few languages, that developed shorthand notations, notably e.g. ECMAScript can be generated from coffeescript: CoffeeScript is a little language that compiles into JavaScript. Underneath that awkward Java-esque patina, JavaScript has always had a gorgeous heart. CoffeeScript is an attempt to expose the goo...
I'm an amateur java developer and I have been working on this web application in my current company. The application is made in the Spring MVC framework. Hibernate is used as the ORM tool while the database is the DB2. Maven is used as the build and deployment tool for this application. The presentation layer and the s...
Is it generally considered good practise for a class name to reflect the namespace name it exists under, or should the namespace name implicitly be considered part of the class name? For example, suppose I have a collection of classes which all act to filter a class Foo: class FooFilter { public virtual bool operat...
Background I created a mod for minecraft using Minecraft Forge which uses "other" mod. I have the permission from author of the "other" mod to use and distribute his code with my code. Right now, my LICENSE.md file looks something like that: # License This project uses portion of code from ["other" mod](https://githu...