instruction
stringlengths
34
36.1k
In an Android project, I am using dagger 2 for dependency injection, applying mvp design pattern, and I am writing interface for almost every class. Although it does achieved the separation of concerns, each individual logic is not coupled with others. But for just making a simple REST call, it involved 20 plus java cl...
Here is my scenario. I would like advice on which path to follow, along with good reasons as to why. It would even be better if you could give an example based on experience of a similar decision but not absolutely necessary. I am working at a company wherein we have a backbone.js frontend app which has been around fo...
I am writing an API (using Java) that takes locale as a parameter. We want the clients to be able to specify "en-US" or "en_US" as they both seem to be widely used across all languages. I did go through these links How to get locale from string representation in Java en_US or en-US, which one should you use Java Loc...
I usually prefer to follow "composition over inheritance" rule, until I start stepping in the world of Java GUI. In my experience, for adding custom requirements in a GUI components, for example, add custom function in a JButton, usually create a class extends from JButton like this: public class CustomButton extends J...
In some books the implementation of Data Mappers simply update the whole row of a table using the data inside an object, but in a system is possible that two different operations update different fields from a same row in a database, which can make an update simply overwrite another one if both of them retrieve the old...
A while ago I've made a simple script in Javascript that tested how much time it takes to add elements to arrays. I've used 3 different methods: array.push(), array[array.length] and array[x] where x is the counter in the for loop. These results were stored and drawn to a simple graph using canvas. The script could bas...
I have a function that retrieves raw data from the database and returns an object which represents this data. Should the conversion between the raw data and the object be written in that method or should I dedicate a separate method for the conversion, according to SRP?
I was looking at bitwise ways to multiply and add numbers without using * or + operators. But I want to know that it might be possible that java may already be using a better approach underneath. I tried to find the algorithm for *,+,_,and / operations. I read some paragraphs of JVM Specification but could not find sat...
Java here. I have always used Spring DI (for Spring projects) or Guice (for non-Spring projects) for dependency injection, and have always loved them. I recently took a job where they do 100% "DIY DI". That is, every project's main/driver class has an init() method that creates all of their objects/factories for them: ...
This might be a little unrealistic bu i will ask anyway. Would this be possible to create literally create a new class during the run time execution, i don't mean a new instance, i mean a new class created from the code itself. I'm actually using reflection in java, i can get the field's name of the class and the met...
Background:I'm a not very experienced software developer, currently working on a legacy project where all the business logic is in the database(sqlserver) using stored procedures. Now we are asked to rewrite the application from foxpro to .net but using the same database. Question: My team architect suggest a n-layer a...
I am working on a project based on the Java EE technology. First I'd like to tell you what I want to achieve, then what I already tried. Task: Imagine two types of configurations, which you want to choose and edit/define in the JEE application via GUI entries. Config A is for the communication with System A and Config...
I have been reading some similar questions here but they are not the same. The project we have inherited from our partner has fixed scope and a fixed deadline to deliver. We are now thinking about way how to manage and agile seems to be the way (providing the framework). If there is basically nothing left to juggle wit...
Edit: There is no "right" or "wrong" answer here, I was merely trying to get people to share their dos and don'ts. Behind this rather vague topic I would like to address a few problems I've been having in my last projects. As a general rule, I try to keep it simple, follow design patterns and the Single responsibility ...
Recently, while writing some Spring/JPA code, I stumbled on an issue I tend to face with from time to time: I passed an empty collection to a repository method that generates an IN expression for the WHERE clause causing an SQL query syntax exception (WHERE column IN ()). To work around this issue I just return an empt...
In ASP MVC we have the Authorize attribute to perform check at either a controller level or at a controller method level. But what if you need to do check permissions inside a controller method e.g let say your doing some update or create action to submit a blog post. Some users with revant permissions can attach files...
I'm creating a library. I want to use it in multiple projects which may use multi-byte or unicode (std::string or std::wstring). I've adopted the old MS method of conditional compiling: namespace my_namespace { #ifdef UNICODE typedef std::wstring String; typedef std::wstringstream StringStream; #define Str(...
I am currently working in a project that is to build a online judging system like codeforces. That is where someone can upload a file for a programming solution and our system will compile the code and generate the output and finally send the result that the solution is correct or not. The front end is going to build ...
There are several database version control solutions out there to assist with controlling not only the versioning of a database, but also deploying and synchronizing databases. These systems are typically based-off either a "source/target difference synchronization" model, or a "direct application of migration scripts"...
I have following hierarchy of topics I am working on DataStructure Linked List Array Stacks Tree Enterprise Apps EJB JMS Android App Games Productivity Apps My question is how can I best organize it into GIT (Gitlab or BitBucket). Should I create one repository for DataStructure or individual for LinkedList, etc...
I have a web app with JavaScript front-end which communicates with back-end via REST API (AJAX calls). Front-end have a Sign Up page. When user decides to register, front-end makes REST call to register that user (POST request sent to /users resource URL). Users can also login/register via Facebook. When someone choose...
I'm struggling to set up a database to use in my School Academic system that is supposed to record all student's scores and then be able to prepare a report that shows students ranks. The hardest part is, if I have many students and many courses/subjects, and students take 2 tests every semester, how do I set up db tab...
I've been playing the rerelease of The Logical Journey of the Zoombinis recently, and trying to implement some computer algorithms that can solve the various puzzles. I'm stuck on how to approach the Captain Cajun's ferryboat puzzle. For those unfamiliar, a Zoombini is a creature with 4 attributes: hair, eyes, nose, an...
I really need someone to confirm the following, and if necessary help me filter what I have read so far. AJAX, which stands for Asynchronous JavaScript and XML, is used to exchange data and is a form of communication between client and server. Practically, it is used to retrieve data and update a page without having t...
I see that in many projects and examples that local includes are listed before external libs and before header files for built in compiler functionality. Is there any advantage here that I am missing? I have always used the following model: 1) built in header files 2) External lib header file A) External lib depende...
I am currently building a small project that is supposed to keep track of recipes. Each recipe has a bunch of information, including a rating for said recipe. Since the rating has some additional logic i put it in it's own class. Now i am thinking about how to call a rating vote on my recipe object: public class Recipe...
I am building a management tool for recipes. Recipes have a bunch of data, including very generic stuff like an ID, tags, ratings and trivia. I currently only manage recipes, but i want to add support for ingredients, products, etc in the future aswell. These will share the same attributes mentioned above. Does it make...
I'm searching for a way to open a TCP connection, send a HTTP post request and keep the connection open. It would be great if I can achieve this without administrator/root rights, from a command-line interface (CLI), cross-platform and with passing parameters. Some background info. I managed to rebuild a direct HTTP re...
I am maintaining and Android app that now suffers from an unsafe X509 TrustManager implementation. Since the app doesn't make any HTTPS calls except through dependencies, one of the dependencies is causing the issue. The problem is that I don't know what any of these dependencies are for (there are ~20) except for one,...
What will be the result of the time complexity of this piece of code i.e. int sum(int A[], int n) { int sum = 0, i; for(i = 0; i < n; i++) { sum = sum + A[i]; } return sum; }
I want to learn AngularJS but on the website I see a button with the text Try the new Angular 2. Is Angular 2 ready for production use or should I learn and use AngularJS 1?
I need to find an optimal distribution of some matching tasks on multiple jobs; each job is limited by a maximum workload and the grouped tasks should maximize the workload within the same job. However, tasks with similar values within the same source should have a higher priority to be included in the same job. For ex...
MongoDB is a NoSQL database which I've found quite easy to use. Recently I had to develop a simple application which needed to collect some data using HTTP requests and store some results after processing the data, and I tried using MongoDB. From this experience I found it much nicer to use than traditional relational...
I've switched to PHP 7.0 very recently and I was wondering that if password_hash was better than making your own salt and using the crypt function. I have three examples of code and I don't know which make the passwords the most secure. Example #1 (BCRYPT): $options = [ 'cost' => 12, ]; $hashed_password = passwo...
I have noticed that I recently wrote the following commit message: Since HTML changed, getting the index would always result in zero, since the element is now enclosed in a parent block. For someone who starts by viewing the diff of the commit commit first (for instance after doing a blame on a file) and doesn't get ...
I'm writing a program in which I fscanf a file and write to the same memory address repeatedly. I tried the following: FILE *f = fopen(fname, "r"); int* num; while(fscanf(f, "%d,", num) != EOF) { printf("%d\n", *num); } which, when I run it, produces Bus Error 10, which means to the best of my understanding tha...
I wondered whether a while loop is intrinsically a recursion? I think it is because a while loop can be seen as a function that calls itself at the end. If it is not recursion, then what is the difference?
You're writing an app where the model (as in MVC) is an object graph. Occasionally, you want to save this object graph to disk. What are some best practices to ensure that the write is consistent? (That is, how do you prevent the object graph from mutating in the middle of a serialization/write?) In my app, whenever a ...
I have 2 objects that I'm not very certain what is the proper (or better) way I should use. I have a query builder object that constructs an SQL statement like $qb = new SelectQuery('users'); $qb->columns('id', 'email')->where('id', '=', 25); print_r($qb->build()); print_r($qb->data()); Output SELECT id,email FROM us...
I have created a class HidDevice to form objects which concatenates input from each HIDDevice separately until a special key (ENTER) is pressed. So each instance of HidDevice have fields like int deviceId, String concatedInput. public class HidDevice { private int deviceId = -1; private String concatedInput; ...
Lets assume that we have a Spring Boot application that uses microservices architecture. Each of the services has its own domain models, but each service must reference a User domain object. What would be the best approach on how to solve this issue? Would it be better for each service to just have a userId and then, w...
I realized I haven't seen this type in Objective C or Swift. But we have UInt. Is there some more Computer Science specific reason we do not have an Unsigned Float? Afaik it's not in c# too.
Just to be on the same terms: Aggregation is a has-a relationship, where the owned components can exist independently of the owning component.E.g. a pond and some ducks swimming in it. A duck leaving the pond doesn't mean the duck giving up its existence. In an OO language (or actually any language without referential ...
Should an interface method implemented by a class always use all parameters? By interface I do not necessarily mean actual interfaces, these could be other (abstract) classes which are extended, too. I sometimes find it hard to use all parameters in all implementations. However, that seems to me as bad design. It makes...
There are lots of good resources on μServices that focus on concepts like Single Purpose, REST, Implementation and Deployment, CI/CD, Encapsulation and Isolation, Separating UI from API, etc. However, having made all the promises about μServices (plural), they all immediately go deep into designing a μService (singular...
Suppose I have a function f that uses two helper functions h and g to get the job done. There are two possible ways of dealing with this situation. (1) take explicit arguments and returns new objects from each helper function: def f(x): def h(x): <do something> return y def g(y): <do som...
At the moment, my (pretty standard) REST interface looks like this: POST /foo # creates a new foo PUT /foo/{id} # updates a specific foo GET /foo/{id} # returns a specific foo GET /foo # returns a collection of foos Only authenticated clients are able to use these operations. When using GET or...
I'm interested for some time in CPython implementation of Python. I understand that .pyc files contain serialized bytecode, including opcodes. However do these files contain mnemonics? I think that interpreter could use just opcodes. Am I right?
I have film's storage (3 tables in database): films{id:int, film:string} genres{id:int, genre:string}, films_genres{film_id:int, genre_id:int, probability:int(%)} (film_id, genre_id) is UNIQUE KEY(compound key). For example: films = { 1 : 'Some film 1', 2 : 'Some film 2' } genres = { 1 : 'comedy', ...
I've worked on a large Rails app where the use of ActiveRecord callbacks was rampant and harrowing. Saving a record often had unexpected side-effects and it was a challenge to reason about the system. At the same time, I've seen hooks used to good effect as part of inheritance (e.g. a parent class using a template-meth...
I'm currently re-factoring a part of our application at work. I'm normalising a data structure from a flat list of fields to a parent/child relationship. This has an impact on all layers in the application: The database Models Business logic; and The UI Instead of creating a few massive commits - where each commit co...
I am about to start prototyping a 'quiz'-like web application that tests test-scoring methodologies, and I have an interesting architectural question. Each quiz given to a user needs to use a set methodology to score it (e.g. Formula Scoring, Number Right Scoring, Negative Marking, etc.). A quiz consists of a series of...
I'm working on a C++ codebase targeted at multiple platforms, and we've just moved over to CMake as our buildsystem. Previously our buildsystem was a pretty ad-hoc affair; getting our code under a single common buildsystem has been a real step forward. The next pain point I've encountered, though, is that I'd like to b...
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...