instruction
stringlengths
34
19.9k
I know these sorts of questions come up, but I couldn't find a simple answer, most of the answers are "don't do that" For play, I built myself a webapp, it uses sjcl to encrypt and decrypt notes on the client, whilst sending the encrypted form back to the server. I am storing the key in local storage. From my research,...
This problem has kept me from pursuing a project I'm working on because it influences the entire structure of the application. This question has been briefly touched on here, but I feel that it wasn't seen by many people and therefore wasn't very well answered. I'm working on an application in charge of navigating and ...
Using a REST API for front-end code is a desiderable and quite common practice. However, I was wondering if using it also for the back-end could be a good choice. What I mean is leaving the burden of retrieving data from the database all to the API, and then call it from other parts of my back-end (mainly views and con...
I am given a number n , which is always a power of 2. I want to check whether n is odd power of 2 or even power of 2. For example: n=4 , ans= even n=8, ans=odd (because 8 is 2^3) n=1024 , ans=even. Can I do it using bitwise operations/ or some faster method.
I am making a program on my spare time that I want to run as quickly as possible. The program is written in C. A large set of the procedures operate on pointers to 7 integers that are sorted by their numerical values from high to low. Up to this point I have used the library function "qsort" to sort my integers. Now wh...
What do you recommend as a default fallback for line endings if the operating system cannot be determined? Example Mac OS up to version 9 uses carriage returns (\r) for line endings. Unix-like systems do line endings with line feeds (\n) and Windows uses two characters (\r\n) to mark a line ending. What's the best fall...
I have developed a scrolling guide for a television company but attempting to use CSS animations, jquery animate, and velocity.js have all failed me. They work as intended but the animation is choppy and almost gives a pulse feel to it. I considered attemping to go down the route of creating this canvas base but wond...
I always wondered what are the effects of including not needed headers to the final executable once compiled. In my code some times I may included many different headers that I do not need (or I used to need but now I don't and forgot to remove them). Now before compiling the final executable I always clean up my heade...
Searching the specification for the btrfs file system i stumbled once more over the catchphrase: "The code is the documentation". This implies that changing the code changes the specification. Does this approach make sense while working on a file system that will be used from various drivers or applications? I can unde...
I'm doing a class diagram for a game project, but I'm stuck on a coupling problem. Context The projet is a turn-based game. Two users are playing. They've got units on a map. They play until 1 player has all his units dead or if a predefined number of turns are reached. At each round, each player will review his units ...
I'm working/playing on an app where individual users' data will be completely independent from each other. Of course, there will be common tables for other parts of the app (e.g. "users"), but for the rest of the tables, would it be wise to create a new set of tables for each user? e.g. List of tables: users user1_tran...
Here is the scenario: libA.so and libB.so both statically link to the same STL. libA.so has a public API that returns a std::string. libB.so calls this function and receives a copy of the string. When libB.so's copy of the string goes out of scope the string's destructor is called. The application seg faults attemptin...
I came across this one problem, There is a particular sequence only uses the numbers 1, 2, 3, 4 and no two adjacent numbers are the same. Write a program that given n1 1s, n2 2s, n3 3s, n4 4s will output the number of such sequences using all these numbers. Output your answer modulo 1000000007 (10^9 + 7). I can't...
The following code looks rather harmless on first sight. A user uses the function bar() to interact with some library functionality. (This may have even worked for a long time since bar() returned a reference to a non-temporary value or similar.) Now however it is simply returning a new instance of B. B again has a fun...
In order to decrease the number of false positives, I came up with a couple of possible solutions. Create two different types of Bloom filters; eg. filter1 using 3 different hash algorithms, filter2 using 3 other hash algorithms. Create two different lengths of one type Bloom filter; eg. the number of bits would be di...
I'm having a bit of a debate with my friend over whether these two practices are merely two sides of the same coin, or whether one is genuinely better. We have a function which takes a parameter, fills out a member of it, and then returns it: Item predictPrice(Item item) I believe that as it works on the same object t...
According to the Wikipedia article, UTF-8 has this format: First code Last code Bytes Byte 1 Byte 2 Byte 3 Byte 4 point point Used U+0000 U+007F 1 0xxxxxxx U+0080 U+07FF 2 110xxxxx 10xxxxxx U+0800 U+FFFF 3 1110xxxx 10xxxxxx 10xxxxxx U+10000 U+1FFFFF 4 11110...
When I build a RESTful API, I use an MVC pattern. And in order to make controllers skinny and code reusable outside of the API (e.g. in Cron tasks), I put much of my code into services (commonly known as libraries). My routers delegate to controllers which then delegate to services, which use models. I am wondering: Do...
I am trying to find common prefixes for a sorted set of strings. i.e. if the following strings are given: AB123456 AB123457 ABCDEFGH ABCDEFGX1 ABCDEFGY XXXX then my function should return three prefixes and their suffixes: AB12345 6,7 ABCDEFG H,X1,Y XXXX (no suffixes) Some background information: I'm trying to ...
So I'm an android programmer,have been programming for about 3 years,but it wasn't until 5 months ago that I started really taking it seriously. Recently I got my first internship,and I'm happy with it. The problem that I'm having is that I worry a lot about using too many libraries for certain tasks whether it be comp...
Usually, computer science papers describe algorithms in Algol-like pseudolanguage, similar to Pascal or even C/C++. But Donald Knuth uses his own assembly language (MMIX). Are there any good known algorithms inexpressible in Algol-like language but expressible in unstructured assembly code? Like coroutines, maybe?
I'm building a website with articles, and I'd like to count unique-per-day visits for each article. The idea to use cookies suggests itself, but I simply can't set a cookie for each and every article visited - ofc the user typically won't go through everything, but better to be safe. If I put all into one cookie, I'll ...
A friend of mine without programming knowledge asked me this question and I found it interesting. I think it is not possible because it would require a really advanced artificial intelligence capable of analyzing the text of a problem, think about a solution and program it. Just thinking about a machine being able to p...
I am new to programming (self teaching Javascript so I am missing some of the basics). I'm not sure if this falls under a style or best-practice question. When writing a function that will be used often, and that has many slightly varied output expectations, should an internal if-statement be run to determine the outpu...
I'm developing a small HRMS system for my company, and am currently thinking of how to integrate attendance and holidays. We currently have an in_time/out_time based daily attendance system, but the HR (naturally) also wants to be able to define holidays, special days off, etc. Broadly, I can think of the following two...
I was wondering whether every interpreted language can be compiled? And can every compiled language be interpreted?
I have a front end single page app deployed on S3. It is minified on production. It creates error only when it is minified via grunt on production. I cannot repro the issue in dev. How do I go about debugging such issue? Thank you.
I have written an Interpreter / Compiler simply as a programming algorithm using features such as recursive functions and concepts from finite-State machines. To me, these things are ideally suited to building a compiler (Although it does end up getting pretty complex). Doing a little bit of research on the subject, I ...
I am trying to convince people in my company that we should switch to event sourcing. Our software is a product that consist of many modules - like a module for wiki, blogs, documents, etc. I would like to use event sourcing also to allow easy collaboration on artifacts (like blogs), to have a history of changes, to mi...
I know this seems like a weird question, since the point of two or more objects sharing the same class is that their behavior is the same, i.e. their methods are identical. However, I'm curious if there are any OOP languages that allow you to redefine the methods of objects in the same way that you can assign different...
What is the main method for reclaiming the memory in LISP? Does LISP really need garbage collection? Would not reference counts suffice? I just wanted to know whether reference counts are enough or not for memory management in LISP, since I am not much familiar with LISP language and other functional languages eit...
Suppose I have a function that does things with a text file - for example reads from it and removes the word 'a'. I could either pass it a filename and handle the opening/closing in the function, or I could pass it the opened file and expect that whoever calls it would deal with closing it. The first way seems like a...
There are a big number of programming languages. Some of them grow up and become very popular. People use such languages more and more often. The founder of such language (or founding organisation/community) may try to implement changes to make the language better. But sometimes it's hard to make some changes because o...
Is naming a class according to its implementation an acceptable practice? e.g. SortedSet if the class is maintains a sorted list of unique items or TreeSet if it using a binary search tree structure instead.
I'm wanting to create an admin dashboard for my app, and to show new events there. In order to know which events are new, I'll need to store at least one extra datapoint to the server: the last date at which the admin user (me) looked at the events and marked them all as read. I'm trying to figure out where it makes s...
My logic goes like this: def A(val): return {'a':val} print(A(7)['a']) is the same as class A: def __init__(self, val): self.a = val print(A(7).a) Obviously, there are problems and some differences: This only applies to languages like python where you can create a dictionary with different types in...
I am writing a web application with Python and Flask. At a high-level, the web service takes an ID, downloads a file from a third-party API based on that ID, reads and analyzes the data inside the file, and finally returns that analysis to the client. Since this process takes a fair bit of time, I'd like to have notifi...
I'm designing an application using the MVP pattern, but a few of the edge cases for the system rely on communication between multiple presenters. View 1 calls Presenter 1 which does Operation A returning Result X. View 2, View 3, and View 4 are all interested in Result X. They each have their respective presenters, an...
I am just beginning to learn Haskell, after coming from the JavaScript/Ruby worlds. I have come across https://github.com/HoTT and the Homotopy Type Theory book, which I am very eager to read. However, I will be learning the math and type theory concepts as I go, so it seems like it will take a long time before I under...
Some background on my system: I have 1 query with multiple pages. There are filtering parameters on the left of the page which $_POSTs on submission. The posted parameters will change the query at the top of the page. My problem is that I am dealing with WordPress and the pagination is absolute links. Each time a user...
I allow my user to create profiles, meaning they potentially could create some with duplicate names. This can be problematic so I want to prevent them from doing so. I coded up this first pass recursive-ish algorithm for detecting what number copy I should assign to the Name, however I'm almost certain there is a bet...
I want to know if all the logic related to permissions and access control belongs to controllers (Application logic) or models (Business logic). Currently I have a controller that does something like that: function delete (resource) { if (resource.belongsTo (currentUser) { resource.delete (); } else { ...
I have been using sizeof.js to investigate the size of various objects in javascript. It appears from this that the size of a function is essentially zero bytes, regardless of how many instructions the function executes. Why is this so?
I am trying to understand automatic parallelization and a special case of that is auto vectorization. As I understand it auto-vectorization is more or less: The compiler takes parts of the code which are "serial" and transforms them to a vector. For example: X1=Y1+Z1 X2=Y2+Z2 Xn=Yn+Zn is transformed to for(int i=0;i<n...
I have a text file of ~600 CIDR notation IP blocks which, when expanded, amount to ~17.5M IP addresses. I need to socket connect to each one. If it connects, I add it to a "live" list, if it returns an error/refusal, to a "dead" list. Then the socket is closed. I don't need to read from it, I don't need to write to it....
I saw this explanation Where first step is: "start building a list of types, the first element is the type we’re linearizing right now," however the result of this is: // start with D1: B with C with <D1> I don't get it. We start with D1 why is it in <> at all? why is C with D1 and not D1 with B. I don't get wh...
Typically, I place authorization decisions in my server side controllers. These have been RESTful endpoints recently, but I think the same stands for MVC type architectures. For the sake of argument assume that it's role based authorisation. A protected method will be annotated or make checks and return 403s if nece...
I was thinking about thread synchronization issues in compiled languages like C++, versus synchronization issues in languages like Java. I'm wondering how a JVM language like Java doesn't (at least in practice) suffer from coredumps/segfaults/undefined behavior when race conditions occur. Consider a C++ program with 2 ...
Facebook announced that it's using the architecture they call Flux to develop their projects. It consists of a single direction dataflow, and concepts like a Dispatcher, Stores and Actions (well described here). This is their illustration of how the pieces glue together: Views ---> (actions) ----> Dispatcher ---> (re...
Is factory pattern a right pattern when we want to consolidate the related objects? Problem - In the Set-top box, I have a user-io, basically the interface to control the settop box - The user-io can be rcu i.e. remote control, front panel - the buttons on the Set-top box, and the rear-rcu - this is used for testing th...
I'm completely stuck on a problem to write a function that does NOT use recursion, locals, or lambda. Only abstract list functions can be used. The function must input a list of positive integers, and output a list of integers that are strictly greater than 1. any ideas on how to do this? I've never implemented abstr...
Whenever I feel like choosing from a list of implementations I always prefer to fill a map first and then call whatever I need based on a parameter, instead of using switch or else if statements. What is the pattern I'm looking for here? I've been told repeatedly that using maps is not the optimal solution for this, bu...
I am writing software for compiling programs. Therefore have a Compiler that compiles a given sourcecode. It then returns a CompileResult that is similiar to an Either type (it is actually internally delegating to an Either object). Now there can be 2 (non-exceptional) cases: The compile is successfull (CompileSuccess...
In a DDD approach, suppose I have an Order (this is my aggregate root) and a Line (a descendant of an Order). In both objects I have private setter for properties and a builder that handle creations of the cluster of object. As far as I know every action on the cluster goes through the aggregate root. Is this right? Fo...
We often use c++ structs to define data structure as opposed to class which can be a complete module with member methods. Now deep down, we know they both are the same (loosely speaking). The fact that we often use/treat structs as data only entities creates this urge that we not add default constructors as well. But c...
This isn't really related to anything I am working on currently, its more of a question I really couldn't find an answer for. Class modifiers like MustInherit or NotOverridable to me, seem like they only need to be used in larger programs that have multiple people working on and editing it. I can see in a situation lik...
I have an action on my controller called DeleteLine. This removes a line from the users basket. My controller action looks like this: [HttpGet] public ActionResult DeleteLine(int orderId, int lineId) { var orderResult = _salesOrderService.DeleteLine(_workerContext.CurrentCustomer, orderId, lineId); var errorMe...
As the SRP says, the way to achieve this principle is divide all into smaller. And what you have just made small, make more smaller. As consequence we got more files and my question is about it, how organize all this new classes that are generated to keep our dirs clean, as the code. For example. I'm developing an Andr...
I have some stream workers. They are listening to twitter stream and save into mongodb. I need to aggregate saved tweets for intermediate analyze result. I have analyzer workers. They are periodically aggregated with some (15 query) queries. At this time mongodb loads increase and use whole cpu and ram. This is reasona...
Consider the following case, image I making a simple chat program; I want it to be extensible such that it would be fair easy to add add different scripting and user interfaces. I want the core controller and model to be separate from the interface so I could something like the following, I am using python syntax for s...
I have a Figure represented through a matrix of bytes (bitmap-like matrix). Example Figure is shown on the Picture 1. The goal is to find the best rotation angle of some given Figure. When Figure is rotated by best angle, the rectangle that is parallel to X and Y axes and inscribes the Figure has the smallest area. R...
I want to develop a chat application that reminds a bit whatsapp, I am doing it as a learning project. I am currently doing it on Android just because I am doing an Android course. The requirements are: users register with some data (phone number, name) users can write messages to friends who also use the same applica...
I'm developing an application and I have a database with it using Entity Framework Code First concept. I like this approach very much. I'm using the latest version of EF which is 6.1.1. My main concerns are how to deal with database changes without losing data. I've done quite a few changes and a few of those changes g...
I developing an app with tree(folder-file) structure, on which I should perform full-text searches with MongoDB. I did a research on the best tree structure practices and found this great article, but I still can not decide which DB structure will fit my needs. I have the following requirements in my mind: I should be...
I'm adopting a git push to deploy method where I setup a bare repository on the live server which I push my local changes to. Using a post-update hook, executed after I've pushed I pull my changes to the directory housing the live site. This method works extremely well but as we are using virtual servers sometimes disk...
I want to use my programing skills to make my day-to-day life easier, to do this I want to be able to program in my appliances like alarm clock or microwave or refrigerator, air conditioner etc, wish they had firmware that I could flash with my program to control them and adjust their work to my liking. Right now I am ...
So this is a general question about the use of monitors in the Reader/Writers problem. I know the monitor procedures for the Readers/Writers problem are used for mutual exclusion to a critical section, but my professor claims the critical section is outside the monitor as opposed to being inside the monitor for the Re...
There are many good questions out there about choosing an open source license, reasons to go open source, etc. However I have not seen an answer to this question and I feel like more people could relate... Say I am working on a project, putting up code on GitHub for the world to see. At what point do I go about selecti...
In Big O notation, allocate an array of N element is defined by O(1) or O(n) ? For example in C#, if I allocate an array like this : int[] a = new int[10] When I display this array, I have : {0,0,0,0,0,0,0,0,0,0}
I need an algorithm that distributes same items across a list, so maximizing the distance between occurrences. E.g. I have a list of 15 items: {a,b,c,c,c,d,e,f,f,f,g,h,h,i,j} The algorithm should reorder these in such a way that all the duplicates are spread as uniformly as possible. The mentioned list should result ...
Supposing I have an interface Foo and a given implementation FooImpl. public class FooImpl implements Foo If I want to define a new operation on this class that depends on the particular implementation, is it correct to define it in the implementation class or as a static method on an Util class like FooUtils.operat...
We currently have the following SQL Schema: Projects Budgets BudgetTabs BudgetSections BudgetTasks BudgetTaskDetails BudgetUnits The data held in these tables is used to specify how much a project will cost to complete. The problem I foresee ...
I am not new to programming, but I am one that started a few years ago, and I do love templates. But in the before times, how did people deal with situations where they needed compile-time code generation like templates? I'm guessing horrible, horrible macros (at least that's how I'd do it), but googling the above ques...
Let's say I have a Book that has it's title and description localized in any number of languages. Localization only matters for e.g. administrators, because users chooses their localization and they need to see only their localization, not all of them. Administrators, however, needs to have full support for localizatio...
I have adopted a pattern in one of my projects that I really like and I suspect it's likely to be something standard. I'd like to describe it here and see if you guys can tell me how other JavaScript programmers solve this type of problem. A few rules I established for myself before I started the project. 1. Functio...
I'm currently learning about unit testing, specifically JUnit (with Java). Searching the web I see many threads talking about why you should use it, what type of methods you should use it with but I can't seem to find much information on when you should implement a unit test. Is it best to incorporate it from the ver...
I know that basically, CC can be computed as number of decision + 1. In addition, every logical operator in the condition causes CC to increase by 1. But why? Having the code if(A || B || C) else... the control flow graph would simply be a node with two outcomes - two branches. So I always thought branch coverage is ab...
I'm trying to understand what a regular language is. There are 3 compound regular expressions for regular language: concat {AB}, union {A+B} and iteration {A*}. When they are used in a simple ways it's clear for me how operate with them. But I'm frustrated with questions like this: Find regular language equivalent to: ...
possibly a newbie question here. I heard that if a real AI were to exist it would have to evolve, by that I think it means it should be able to write new code then run itself with the new code. Could this be possible in a compiled language like C/C++? Just wondering, thanks.
I want to create an action menu to trigger some actions on a single page application and I wonder what's the most appropriated html5 tag for this? I know the nav tag but it seems more suited for navigation than actions. Should I use a simple div tag or is it a more semantical tag?
I have an application with a custom high availability (HA) feature that provides automatic failover from an active primary server that experiences a failure to a passive backup server. To date, this feature has included manual replication of all data between the primary and backup server on independent disks but with m...
We have an application where there is an API to create a document with a POST and update it with a PUT. There is a separate API to share document with users. Now, How should we approach updating the list of users who the document is shared with ? Should it be a POST or PUT that actually deletes the whole association an...
We have a context of the application which is a static class named Holder containing several static properties initialized by objects that are used throughout the application. All over the unit tests we need to initialize the context by mocks. In the current implementation, the context defense itself from reinitializin...
I'm just starting to get to grips with TDD, and I have 2 quick questions; I'm assuming that if I were writing software for a software company, that TDD would work alongside the software design? i.e all the UML, ERD diagrams, flow diagrams etc... My second question is, the way I'm doing my tests at the minute, I think a...
I have found an open sourced server that is licensed under GNU GPL. We would like to use that server at our client's hardware as a part of our solution for him (we provide our own software but we need a server to run on). However our software is under no-disclosure agreement. Can we use the server? What do we have to ...
I'm building an application where there are different "Locations". There are Stores, Bars, Schools, and Churches (and so on) all of which are geocoded and defined by existing data sets. While not exactly alike, these entities can probably all fit into a "Locations" table. This will be helpful because users will const...
Suppose we have a process like the following: Super user receives an internal request to initiate a process. Super user approves the request. An external process belonging to a third-party is triggered. Once third-party process is complete, super user receives the result and either accepts or rejects it. It is easy t...
I'm about to learn to handle logging in my c# asp.net mvc app and are going to store my log in a noSQL-db. How to handle the logging is done. The thing is I'm having a hard time to figure out possible things to log. The app I'm building is a quite regular website, were a admin-user can login and edit content on the sit...
I'm in R&D working on a new software product. Management understandably focuses on the primary features that most obviously give a customer an advantage. But there are many requirements that can be seen as important as well (ex. performance, future extensibility, data traceability, security, smooth UI). These implicit ...
I am building a form in PHP. I would like to automatically verify that INSERT queries are successful, and populate data correctly, as opposed to running queries in Workbench or MySQL with every code change. The only ways I can think of are to count the number of rows before and after, and see if they are equal, or writ...
I understand that you're not actually supposed to hit the database or disk when doing unit tests... Why is that? Also, taking something like Moq, what is it actually supposed to mock and where? For example, let's say I want to create a method called "loadconfig" that loads an XML document. This would be a void method, ...
We've got a global system that we are attempting to solve a permissions issue around. Currently, our system serves a number of different applications out to our clients and each client has their own list of user types and users for our system. However, all of these things can be independent of each other. Such that ...
I am new at a company that has a saas web application, which uses iframes to load content from several different servers (all operated by us). Is there any known compelling reasons to use iFrames instead of DOM manipulation? I've tried searching google, stack overflow and programmers, but most questions and answers see...
I usually see this pattern at least once in every Python project I work on. For example, in a Django project, this is often added at the bottom of the base settings file: try: from .local_settings import * except ImportError: pass Also: try: import simplejson as json except ImportError: import json This has ...
Simple question: Should model/domain objects only include attributes that are meant to be persisted in a database or serialized to any other specific format? My understanding of a domain/model object is that it should reflect the data store (the model) as tightly as possible, rather than carrying "off-topic" attributes...
Amidst defining the hierarchy, firstly, one can think to embed the abstract method(behavior) in abstract class only because the derive concrete class possess that behavior as core behavior with it's specific implementation, secondly, one can think to embed the abstract method(behavior) in interface only because derive...
I've seen (and once used) this idiom a few times in Python: # At the end of a module: if __name__ == '__main__': main() # or whatever your entry point looks like, this line isn't important else: sys.modules[__name__] = SomeClass() Usually, SomeClass will implement one or more magic methods, to allow code like...
I am doing a research essay on the history of programming languages, and I was wondering, why did programmers ever write their programs on punch cards? Didn't computer screens and keyboards already exist by the time programmers used them? I know they were first invented for the use of the Jacquard loom and to control t...
Given an interface interface I { one(); two(); } An abstract base class partially implementing I abstract class A { @Override void one() { //something } } And lastly a subclass of A class B extends A (implements I) { @OVerride void two() { //something } } And now B...
TL;DR Storing ever-changing business rules so that an app can behave like it did at moment X in the past. Can it be done? If so, how? Long version At this very moment, this is more of a thought exercise than an actual need, though things could change in the not so distant future. The company I work for is in the payrol...