id
stringlengths
5
27
question
stringlengths
19
69.9k
title
stringlengths
1
150
tags
stringlengths
1
118
accepted_answer
stringlengths
4
29.9k
_cs.12667
Well, i have a binary search tree $T$ that is equilibrated by height witch has $2^d+c$ nodes ($c<2^d$). What is the number of comparisons that will occur in the worst case scenario, if we ask whether $k\in V(T)$ and why does it arise?
Worst case scenario in binary search tree retrieval
graph theory;search trees;search problem
null
_softwareengineering.155064
We are planning to adopt user-stories to capture stakeholder 'intent' in a lightweight fashion rather than a heavy SRS (software requirements specifications). However, it seems that though they understand the value of stories, there is still a desire to 'convert' the stories into an SRS-like language with all the attributes, priorities, input, outputs, source, destination etc.User-stories 'eliminate' the need for a formal SRS like artifact to begin with so what's the point in having an SRS? How should I convince my team (who are all very qualified CS folks by the way - both by education and practice) that the SRS would be 'eliminated' if we adopted user-stories for capturing the functional requirements of the system? (NFRs etc can be captured too, but that's not the intent of the question).So here's my 'work-flow' argument: Capture initial requirements as user-stories and later elaborate them to use-cases (which are required to be documented at a low level i.e. describing interactions with the UI prototypes/mockups and are a deliverable post deployment). Thus going from user-stories to use-cases rather than user-stories to SRS to use-cases.How are you all currently capturing user-stories at your workplace (if at all) and how do you suggest I 'make a case' for absence of SRS in presence of user-stories?
How do I convince my team that a requirements specification is unnecessary if we adopt user-stories?
agile;requirements;user story;requirements management
Baby steps. Continue to write the SRS for a while. Then call a meeting and discuss whether they still serve a purpose. Does anyone still read them? Is the time spent on them justified? Is there another intermediate step that would be more lightweight?You never know, you might find that you're wrong. Remember the Agile manifesto, we find more value in Working software over comprehensive documentation, but there is still value in the latter.My guess though is that you'll quickly discover that the desire to continue to write heavy documents falls away when they see how closely use cases and user stories relate.
_softwareengineering.246282
Should a view call a helper function?Say I pass in data from the DB to the view. The data is a unix timestamp. Should I make a call in my view to convert it to a human readable TS or should I convert it in the controller before passing it in? OR should I make a method in the model that converts...Looking for a best practice or secure coding concerned answer.
Should a view call a function?
mvc
This seems like a fairly trivial calculation, indeed, you could implement it in a few lines of javascript. It is your view that is in charge of displaying data; let it do its work.
_scicomp.26192
Given the one dimensional equation:$\epsilon\frac{\partial^2u}{\partial x^2} +\frac{\partial u}{\partial x} = 0 $ with $0\le\epsilon \ll1$ with boundary conditions $u(0) = 0$ and $u(1) = 2$, we can't neglect the diffusive term because of the boundary conditions. In which situations (with very small $\epsilon$ could we? What's the mathematical theory behind that could explain it?Also, if we had a time-dependent equation:$\frac{\partial u}{\partial t} = \epsilon\frac{\partial^2u}{\partial x^2} +\frac{\partial u}{\partial x}$ how would the situation change? what if the convective term were nonlinear, such as in the Burgers equation? I haven't been able to find references on this topic, I would appreciate any.
When is it safe to ignore the diffusion term in an advection-diffusion equation?
pde;hyperbolic pde;advection diffusion;advection;singular perturbation
The stationary equation you show transports information from the right to the left via the advection term; it also diffuses slightly. If you switch off the diffusion term altogether, then you only have transport from the right to the left, and you need to also drop the boundary condition at the left: because information is from the right to the left, nothing that happens at the left end of the domain has any effect on the solution.A similar argument can be made for the time dependent equation.In general, these equations are examples of singularly perturbed problems. You will be able to find a lot of literature on the subject.
_codereview.88645
Project Euler, problem #50:The prime 41, can be written as the sum of six consecutive primes:41 = 2 + 3 + 5 + 7 + 11 + 13 This is the longest sum of consecutive primes that adds to a prime below one-hundred.The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equal to 953.Which prime, below one-million, can be written as the sum of the most consecutive primes?I came up with this code, but it only works decently for primes below ten thousand.Any ideas on how to optimize it?from pyprimes import *def sequence_exists(l,ls,limit = 100): for x in range(0,len(ls)-l): if x+l > len(ls): return False if any (ls[i] > limit/6 for i in range(x,x+l,1)) : return False test_sum = sum(ls[x:x+l:1]) if (test_sum <limit) and is_prime(test_sum) : return True return Falsedef main(): n = prime_count(10000) prime_list = list(nprimes(n)) l = 6 for x in range(6,len(prime_list)): if sequence_exists(x,prime_list,10000): l=x print lif __name__ == '__main__': main()
Project Euler 50 in Python
python;programming challenge;primes
null
_softwareengineering.234116
I have recently learned about the MVC design pattern. I'm learning from the Head First Design Pattern book.According to this book (if I understand correctly):The Model is most of the application logic and data.The View is basically the GUI that represents the Model visually to the user.The Controller is responsible to 'mediate', and act as a 'middleman' between the View and the Model. The View reports to the Controller that the user made an action, and the Controller translates it to method calls on the Model.However, a lot of places on the web contradict what I understand from that book. They claim that generally the user interacts with the Controller, not the View.Which one is true or more common? Does the user interact with the Controller directly, or with the View directly? Are both approaches acceptable? Which is more common?
Model-View-Controller: Does the user interact with the View or with the Controller?
design patterns;mvc
The user interacts with the View, but the View must communicate the actions to the Controller. The Controller may update the Model, but it isn't required with every/any change.The description I am providing is based on my personal experience with the .NET implementation of MVC. Your implementation can be different.The Controller is where actions are processed, basically a business layer. A simple controller will do nothing more than get the data from the Model to feed to the View. A complicated Controller will perform all sorts of actions, up to security management, authentication, authorization, registration, and possibly many other things.The View should only be responsible for displaying the information in a fashion that the user can understand. There can be some cross over here with both the Controller and the Model as things like Single Page Applications (SPAs) will have data validation feedback for the user. Any other cross overs are heavily frowned upon.The Model deals with data. This includes validation of data (where applicable). Data storage and retrieval is also handled in this layer.UPDATEThere seems to be some confusion surrounding who does what when. I included two different overviews of the MVC architectures because they are similar, but not the same. There is room for either interpretation. Possibly, many more. The descriptions above are my interpretation of MVC from multiple sources, including my own experience building applications using this methodology. Hopefully, this update will help to clear up some of this confusion. MVC is an attempt to build a Separation of Concerns design pattern for software development. It has primarily been implemented in web based applications (to my knowledge).The View handles all of the user interaction. If your user clicks on a button, the View determines if the click is a user interface interaction or something that is beyond its concern (a Controller interaction). If the button does something like copy values from one field to another, your implementation will determine if that is a View concern or a Controller concern. You will most likely only have this blurring of concerns when dealing with a Single Page Application (SPA).The Controller is where your actions are processed. The View has communicated the user decided to change values for some fields. The Controller may perform validation on that data or it may be handled by the Model. Again this is implementation dependent. If the Controller has security features, it may determine that the user doesn't have sufficient privileges to perform the action. It would reject the changes and update the View accordingly. The Controller also determines what data to retrieve from the Model, how to package it, and update the View with that data.The Model determines how and where to store data. It may also perform validation of that data before storing it (it should do this because people will bypass the View on occasion).Wikipedia has an article on MVC.A model notifies its associated view/views and controllers when there has been a change in its state. This notification allows views to update their presentation, and the controllers to change the available set of commands. In some cases an MVC implementation might instead be passive, so that other components must poll the model for updates rather than being notified.A view is told by the controller all the information it needs for generating an output representation to the user. It can also provide generic mechanisms to inform the controller of user input.A controller can send commands to the model to update the model's state (e.g., editing a document). It can also send commands to its associated view to change the view's presentation of the model (e.g., by scrolling through a document).From Microsoft's Overview of MVC.Models. Model objects are the parts of the application that implement the logic for the application's data domain. Often, model objects retrieve and store model state in a database. For example, a Product object might retrieve information from a database, operate on it, and then write updated information back to a Products table in a SQL Server database.In small applications, the model is often a conceptual separation instead of a physical one. For example, if the application only reads a dataset and sends it to the view, the application does not have a physical model layer and associated classes. In that case, the dataset takes on the role of a model object.Views. Views are the components that display the application's user interface (UI). Typically, this UI is created from the model data. An example would be an edit view of a Products table that displays text boxes, drop-down lists, and check boxes based on the current state of a Product object.Controllers. Controllers are the components that handle user interaction, work with the model, and ultimately select a view to render that displays UI. In an MVC application, the view only displays information; the controller handles and responds to user input and interaction. For example, the controller handles query-string values, and passes these values to the model, which in turn might use these values to query the database.
_webapps.90641
I am trying to create 2 events that have custom repeats but I can't quite figure out the coding. I need an event that happens every 30 days but if the 30th day is a weekend I'd like it to move to the following Monday. But I also need it to stay on the original 30 day cycle.I also need an event that happens x week days before x day of the month. For instance I'd like an event that happens 3 weekdays before the 15th of every month.Any help would be great.
iCalendar RRULE Recurring Events Custom Repeat
google calendar;ical
null
_softwareengineering.43725
I am in charge of a group of about 30 software development experts and architects. While these people are co-located in the companies organization chart, they do not really feel as a team. This is due to their work enviroment:1) The people are spread over eight locations, with a max. distance of about 1000km (this is Europe).2) The people don't work as team but instead get called as single people (and sometimes small groups) into projects for as long as the projects run. 3) Travelling is somewhat limited as this requires business reasons. Lot is done via phone.Do you have ideas or suggestions on how I could make these people feeling part of a joint organization where they support others and get supported by others. So that they get to know their peers, build a network, informally exchange information? So that they generally get the feeling of having common ground and derive motivation and job satisfaction?
How to build a team of people not working together?
team;motivation
null
_codereview.158142
I am trying to write a program to find the practical numbers, from an input from \$1\$ to \$n\$.Practical numbersMy code is running correctly but it is extremely slow when calculating numbers around 50 - it gets stuck at 44.import Foundationfunc getInteger() -> Int { var firstNum:Int = 0 while true { // get value from user. Using optional input since readLine returns an optional string. let input = readLine() // ensure string is not nil if let unwrappedInput = input { if let unwrappedInt = Int(unwrappedInput) { firstNum = unwrappedInt break } else { // the input doesn't convert into an int print(`\(unwrappedInput)` is not an integer. Please enter an integer) } } else { // did not enter anything print(Please enter an integer) } } return firstNum}func addOne(signArray: [Int]) -> [Int] { // finds the combinations var signArray2 = [Int]() for i in 0...signArray.count-1 { signArray2.append (signArray[i]) } for i in 0...signArray2.count-1 { if signArray2[i] == 1 { signArray2[i] = 0 } else { signArray2[i] = 1 break } } return signArray2}func signEval (signArray: [Int], divArray: [Int], inNum: Int) -> Bool {// changes 2nd var counts = 0 for i in 0...divArray.count-1 { if signArray[i] == 0 {counts = divArray[i] + counts } if counts == inNum { return true } } return false}print(Please enter a number to find the summable numbers up to that number:)var input2 = getInteger()// if num = 1 print 1 if num = 2 print 1 and 2 else print >2 1, 2var inNum = 0var numHalf = 0.0var numRound = 0.0var numCheck = falsevar numCheck2 = falsevar numQuarter = 0.0var numSixth = 0.0var divArray:[Int] = []var theirArray = [Int]()var signArray = [Int]()// array of 0s and 1svar summableArray:[Int] = [1,2] // need to check if num is bigger than 2!for input in 1...input2 { numHalf = Double (input) / 2.0 numRound = round(numHalf) if numRound == numHalf { numCheck = true } if input > 2 && numCheck == false { // odd numbers greater than one are not summable } else { // these are possible summable nums numQuarter = Double (input) / 4.0 numRound = round(numQuarter) if numRound == numQuarter { numCheck = true } else { numCheck = false } numSixth = Double(input) / 6.0 numRound = round(numSixth) if numRound == numSixth { numCheck2 = true } else { numCheck2 = false} if numCheck == true || numCheck2 == true { theirArray = [] divArray = [] signArray = [] summableArray = []for i in 1...input { theirArray.append (i) }for i in 1...input { // creates an array of all the diviors of inputted number if input%i == 0 { divArray.append (i) }} for j in 1...divArray.count {// signArray.append(0) }for i in 1...input{let x: Int = Int(pow(Double(2),Double(input-1)))// int 2 to the power of input -1 var Boolcheck = false for q in 1...x-1 { // i to 2^n -1 (sequence to check) Boolcheck = (signEval(signArray: signArray, divArray: divArray, inNum: i))// checks signArray = addOne(signArray: signArray)// adding the ones to the array if Boolcheck == true { summableArray.append(i)// creates array of mini summable numbers break } } if summableArray.count == input { print (\(input)) }} }}}
Practical number algorithm
time limit exceeded;swift;mathematics
Some points in addition to what Roland already said:You are correct that the readLine() returns an optional and you needto ensure that it is not nil. However, nil is only returned on anend-of-file condition, which means that it makes no sense to callreadLine() again. You can only terminate the program in thatsituation. That is a typical use-case for guard:func readInteger() -> Int { while true { guard let line = readLine() else { fatalError(Unexpected end-of-file) } if let n = Int(line) { return n } print(Please enter an integer) }}Now let's have a look atvar signArray2 = [Int]()for i in 0...signArray.count-1 { signArray2.append (signArray[i])}First, this will crash if signArray is empty. Better use a half-openrange instead:for i in 0..<signArray.count { ... }or iterate over the indicesfor i in signArray.indices { signArray2.append (signArray[i])}or just iterate over the elements:for e in signArray { signArray2.append(e)}But actually, you are just copying the array:var signArray2 = signArrayDetermination of the divisors should be done in a separate function.Your codedivArray = []for i in 1...input { if input % i == 0 { divArray.append (i) }}can be simplified todivArray = (1...input).filter { input % $0 == 0 }There are various ways to make this faster. For example the observationthat with each divisor \$ i \$ of a number \$ n \$, \$ n/i \$ is anotherdivisor (see for example Find all divisors of a natural number).That allows to reduce the number of loop iterations to the square-root of thegiven number, and could look like this:func divisors(n: Int) -> [Int] { var divs = [Int]() for i in 1...Int(sqrt(Double(n))) { if n % i == 0 { divs.append(i) if n/i != i { divs.append(n/i) } } } return divs // or divs.sorted(), if necessary}Your code signArray = []for j in 1...divArray.count {// signArray.append(0)}creates an array with the same size as divArray, but filled withzeros. That can be simplified tosignArray = Array(repeating: 0, count: divArray.count)There is no need to use string interpolation when printing an integer(or any single value), print (\(input))can be simplified to print(input)Why is your code slow?There is a logical error in let x: Int = Int(pow(Double(2),Double(input-1)))// int 2 to the power of input -1because the number of possible combinations of divisors isjust \$ 2 ^ {\text{number of divisors}} \$, which can be computed as let x = 1 << divArray.countWith that change, your program computes all practical numbersup to 200 in 0.2 seconds, and up to 1,000 in 25 seconds(on a MacBook, compiled in Release mode, with optimization).A faster algorithmIn order to determine if \$ n \$ is a practical number,you test all numbers \$ 1 \le i \le n \$ if they are a sumof distinct divisors of \$ n \$, and for each \$ i \$ that is done by building allpossible sums of divisors, until \$ i \$ is found. It is more efficient to work the other way around. From the list ofdivisors of \$ n \$, build a list of all sums of distinct divisors.This can be done iteratively: Starting with \$ 0 \$, the first, second, ...divisor is added to the numbers obtained previously.Then check if all numbers from \$ 1 ... n-1 \$ are in that list.The following implementation uses a boolean array to mark all numberswhich are confirmed as sums of divisors. In addition, it uses thatpowers of two are always practical numbers (using the method fromDetermining if an integer is a power of 2).func divisors(_ n: Int) -> [Int] { var divs = [Int]() for i in 1...Int(sqrt(Double(n))) { if n % i == 0 { divs.append(i) if n/i != i { divs.append(n/i) } } } return divs.sorted()}func isPractical(n: Int) -> Bool { // 1 and 2 are practical numbers: if n == 1 || n == 2 { return true } // Every other practical number must be divisible by 4 or 6: if n % 4 != 0 && n % 6 != 0 { return false } // Every power of 2 is a practical number: if n & (n-1) == 0 { return true } var isSumOfDivisors = Array(repeating: false, count: n) isSumOfDivisors[0] = true var last = 0 // Index of last `true` element. // For all divisors d of n (except n): for d in divisors(n).dropLast() { // For all i which are a sum of smaller divisors (in reverse order, so that // we can simply update the array): for i in stride(from: min(last, n-1-d), through: 0, by: -1) where isSumOfDivisors[i] { // Mark i + d: isSumOfDivisors[i + d] = true if i + d > last { last = i + d } } } // n is practical if isSumOfDivisors[i] == true for all i = 0...n-1: return !isSumOfDivisors.contains(false)}Test code:let startDate = Date()let practicalNumbers = (1...10_000).filter(isPractical)let endDate = Date()print(endDate.timeIntervalSince(startDate))print(practicalNumbers)On my MacBook, this computes the practical numbers up to 1,000 in 0.003 seconds, and up to 10,000 in 0.1 seconds.
_codereview.151142
I got the idea for this program from this site.functions.cpp:#include <iostream>#include <cstdlib>#include <iomanip>namespace my{ int getOneOrZero() { return (rand() >> 14); // >> the bitwise operator }// getArray leaves the numbers ( 0-99 ) that have in their bit position represented by bigFlag the num ( 0 or 1 )void printNums(int8_t bitFlag, int num) // num is from getOneOrZero() so it's 1 or 0;{ for (int counter = 0; counter < 100; ++counter) // there are quite a few implicit conversions to one byte integers { if ( (counter & bitFlag) != num*bitFlag ) std::cout << std::setw(8) << ; else std::cout << std::setw(8) << counter; if ( (counter % 9) == 0) std::cout << std::endl; }}char getAnswer(){ while (1) { std::cout << \n Is your number shown above ?\n\n 'y' for yes , 'n' for no , 'r' for reset : ; char answer; std::cin >> answer; std::cin.ignore(32767,'\n'); if (std::cin.fail()) std::cin.clear(); if (answer == 'y' || answer == 'n' || answer == 'r') // I could use switch but nevermind return answer; }}void turnsPassed(int turns){ std::cout << \n This is turn << turns << \n\n;}int swapZeroOrOne(int num){ switch (num) { case 0 : return 1; case 1 : return 0; default: std::cout << \nSwapZeroOrOne ERROR !\n; break; }}int getUpdateForGuessNum(int8_t flag, int num, char answer){ switch (answer) { case 'n' : { int newNum = swapZeroOrOne(num); return newNum*flag; } case 'y' : return num*flag; case 'r' : break; default : std::cout << \n ERROR ! In getUpdateForGuessNum\n; break; } }}main.cpp:#include <iostream>#include <iomanip>#include <cstdlib>#include <ctime>#include functions.hpp#include constants.hpp#include <stdlib.h> // for system() commands >.<int main(){srand( static_cast<unsigned int>(time(0)));Reset : // goto !system(cls);int guessNum = 0;// guessing loop !for (int counter = 0; counter < 7; ++counter){ if (counter == 0) std::cout << \n Think of a number between 0 to 99\n; my::turnsPassed(counter + 1); // +1 cause counter starts from 0 int num {my::getOneOrZero()}; // this gives a randomness to the numbers shown each time you run the programm my::printNums(myVar::bitFlag[counter],num); char answer { my::getAnswer() }; if (answer == 'r') goto Reset; guessNum |= my::getUpdateForGuessNum(myVar::bitFlag[counter],num,answer); system(cls);}std::cout << \n Your number is \n;std::cout << \n << std::setfill('-') << std::setw(81) << \n;std::cout << std::setfill(' ') << std::setw(41) << guessNum << \n;std::cout << \n << std::setfill('-') << std::setw(81) << \n;system(pause); // I should fix thisreturn 0;}functions.hpp:#pragma oncenamespace my{ int getOneOrZero(); void printNums(int8_t,int); char getAnswer(); void turnsPassed(int); int getUpdateForGuessNum(int8_t,int,char); int swapZeroOrOne(int);}constants.hpp:#pragma oncenamespace myVar{ const int8_t bitFlag[] {0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80};}Please suggest ways to improve this program. Explain the suggestions you make because I need to know why I should change something.
Program that guesses your number using bitwise operations
c++;beginner;c++11;bitwise;number guessing game
Here are some things that may help you improve your code.Understand type implicationsThe code includes a bitFlag array that is declared as const int8_t but then contains a value that is 0x80. The problem with that is that when the compiler encounters the constant 0x80, it converts it into an int by default, and so that would be the value 128. However, 128 is not representable in an int8_t. That bit pattern is actually -128 as an int8_t, so I'd recommend either using a different type (such as uint8_t) for the variable or writing -0x80 for the constant which is correct, but a little strange looking.Know the standard typesThis function is in the current code:int getOneOrZero(){ return (rand() >> 14); // >> the bitwise operator}There are two problems with this. The first is that it apparently assumes that an int is 16 bits. However, on my machine, an int is 64 bits. In general, you can't assume that the size of an int is a fixed size. The standard only says (implicitly from the required range) that it must be 16 bits, but it may be larger. The second problem is addressed in the next point.Consider using a better random number generatorBecause you are using a compiler that supports at least C++11, consider using a better random number generator. In particular, instead of rand, you might want to look at std::bernoulli_distribution and friends in the <random> header.Here's one way to rewrite it:int getOneOrZero(){ static std::mt19937 gen{std::random_device{}()}; static std::bernoulli_distribution bd; return bd(gen); }Ensure every control path returns a proper valueThe swapZeroOrOne routine returns 1 or 0 under some set of conditions but then doesn't return anything at all otherwise (although it prints an error essage). This is an error because all control paths should return a value. Since it's only used once, and because it can be trivially rewritten, I'd probably replace this:case 'n' : { int newNum = swapZeroOrOne(num); return newNum*flag; }with this: return (1-num)*flag;Avoid using gotoHaving a goto statement in modern C++ is usually a sign of bad design. Better would be to eliminate them entirely -- it makes the code easier to follow and less error-prone. In this code, it's probable that you could use a loop instead:for (bool playing=true; playing; ) // code to play the game // ask user if they want to play again playing = answer == 'r'; }Don't use system(cls)There are two reasons not to use system(cls) or system(pause). The first is that it is not portable to other operating systems which you may or may not care about now. The second is that it's a security hole, which you absolutely must care about. Specifically, if some program is defined and named cls or pause, your program will execute that program instead of what you intend, and that other program could be anything. First, isolate these into a seperate functions cls() and pause() and then modify your code to call those functions instead of system. Then rewrite the contents of those functions to do what you want using C++. For example, if your terminal supports ANSI Escape sequences, you could use this:void cls(){ std::cout << \x1b[2J;}Think of the userIf the user were to get an error message that said:ERROR ! In getUpdateForGuessNumWhat use is that unless they also happen to be the author of the code? Instead, for errors that are an indication of a program flaw, I'd use assert or for things that are unusual but still should be accomodated by the program, use an exception.Use objectsYou have a guessNum and counter to support the game and then separate functions printNums and getAnswer, etc. that operate on guessNum. With only a slight syntax change, you would have a real object instead of C-style code written in C++. You could declare a GuessNum object and then printNums, getAnswer, etc. could all be member functions.Don't use std::endl unless you really need to flush the streamThe difference between std::endl and '\n' is that std::endl actually flushes the stream. This can be a costly operation in terms of processing time, so it's best to get in the habit of only using it when flushing the stream is actually required. It's not for this code.Omit return 0When a C or C++ program reaches the end of main the compiler will automatically generate code to return 0, so there is no need to put return 0; explicitly at the end of main. Note: when I make this suggestion, it's almost invariably followed by one of two kinds of comments: I didn't know that. or That's bad advice! My rationale is that it's safe and useful to rely on compiler behavior explicitly supported by the standard. For C, since C99; see ISO/IEC 9899:1999 section 5.1.2.2.3:[...] a return from the initial call to the main function is equivalent to calling the exit function with the value returned by the main function as its argument; reaching the } that terminates the main function returns a value of 0.For C++, since the first standard in 1998; see ISO/IEC 14882:1998 section 3.6.1:If control reaches the end of main without encountering a return statement, the effect is that of executing return 0;All versions of both standards since then (C99 and C++98) have maintained the same idea. We rely on automatically generated member functions in C++, and few people write explicit return; statements at the end of a void function. Reasons against omitting seem to boil down to it looks weird. If, like me, you're curious about the rationale for the change to the C standard read this question. Also note that in the early 1990s this was considered sloppy practice because it was undefined behavior (although widely supported) at the time. So I advocate omitting it; others disagree (often vehemently!) In any case, if you encounter code that omits it, you'll know that it's explicitly supported by the standard and you'll know what it means.
_unix.371667
I installed CentOS7 on Virtualbox. I have installed port map using sudo yum install portmap and then tried to enable it with service rpcbind start however I can not enable the service. I tried rebooting and entering following codes but nothing happened:[hadi@localhost ~]$ systemctl enable rpcbind.socket[hadi@localhost ~]$ systemctl restart rpcbind.serviceJob for rpcbind.service failed because the control process exited with error code. See systemctl status rpcbind.service and journalctl -xe for details.I appreciate your suggestionsif you need the status of rpcbind: Redirecting to /bin/systemctl status -l rpcbind.service rpcbind.service - RPC bind service Loaded: loaded (/usr/lib/systemd/system/rpcbind.service; indirect; vendor preset: enabled) Active: failed (Result: exit-code) since Sat 2017-06-17 18:32:07 IRDT; 32s ago Process: 4382 ExecStart=/sbin/rpcbind -w $RPCBIND_ARGS (code=exited, status=127)Jun 17 18:32:07 localhost.localdomain systemd[1]: Starting RPC bind service...Jun 17 18:32:07 localhost.localdomain rpcbind[4382]: /sbin/rpcbind: symbol lookup error: /sbin/rpcbind: undefined symbol: libtirpc_set_debugJun 17 18:32:07 localhost.localdomain systemd[1]: rpcbind.service: control process exited, code=exited status=127Jun 17 18:32:07 localhost.localdomain systemd[1]: Failed to start RPC bind service.Jun 17 18:32:07 localhost.localdomain systemd[1]: Unit rpcbind.service entered failed state.Jun 17 18:32:07 localhost.localdomain systemd[1]: rpcbind.service failed.
How to activate rpcbind service in CentOS installed on virtual box?
centos;nfs
Please see this bug report:https://bugzilla.redhat.com/show_bug.cgi?id=1396291rpcbind can fail to start after updating to the 7.3 rpcbind package from an earlier version, if the libtirpc package is not updated as well. [...] Updating the libtirpc package fixes this issue.In other words: update the libtirpc package and then restart rpcbind.
_webmaster.3028
I'm starting to create a site, and want to run it on a VPS rather than shared for a variety of reasons. This means that, if I were to want email services, I'd need to tackle the non-trivial task of running an email server. Not a fun problem for a noob like me.The three uses I can think of break down as follows:The usual email the admin/support/whatever services. I suppose I could get away with using [email protected] but I'd prefer to keep everything uniform if possible.Account confirmation emails / password resets. This seems like the major hurdle.Digest emails, i.e. the following has happened to your stuff in the last week - replies, votes, etc. Not dissimilar from the stackoverflow emails. Opt-in, obviously.Do I really have the option of not supporting email on my site?
How Important Is Email?
email
Email is still very important. And don't use a [email protected] / @hotmail.com account, it just sends all the wrong kinds of signals. On the other hand, nobody says you need to run an SMTP server yourself.One simple and low-cost solution is free Google Apps Standard on your own domain name. This gives you a simple web interface to manage email accounts, a GMail webmail application, and POP3 / SMTP / IMAP4 access to your emails. You can use a regular POP3/SMTP client library to send emails from your webapp servers. I have seen anecdotal complaints about slow'ish delivery and hitting Google's limits too soon while using the free Google Apps edition; but personally I have never had problems with Google Apps.If you need to send many emails you can always upgrade to a for-pay Google App Engine account, or switch your outgoing mailserver to something like Sendgrid.You should set up a Sender Policy Framework record to proactively whitelist the email servers for your domain, and include the SPF records of your external mail providers.One last thing: Don't underestimate the power of emails as a sales & retention tool. A targeted personal email after signup, a reminder email if someone isn't using the site during their trial period, etc -- these do help to reduce abandonment rate.
_cs.67472
The R-Tree creates 'rectangles' to index 2D data. How is their size calculated exactly? What happens to the performance by changing this parameter i.e. the size of this rectangle/MBR? Number of overlaps, area covered change but can this speed up some kind of queries or build a smaller index?
How is the R-Tree's MBR size determined? Changes to MBR?
database theory;databases
null
_cs.19657
Two strings $S$ and $T$ are said to be conjugate if there are two non-empty strings $A$ and $B$ such that $S = A+B$ and $T = B+A$ ($+$ is concatenation). How can I find if two strings are conjugate or not?Example: if S=tokyo and T=kyoto, then the pair $(S,T)$ is conjugate, because we can find A=to and B=kyo.
Check if there exist A and B such that S=A+B and T=B+A
algorithms;strings
null
_unix.1267
If I run a program with an infinite loop with nohup, will the program run indefinitely (until the machine is reset or until I manually terminate it)?
Is nohup indefinite?
command line;process;signals
Nohup sets the default behavior of the HANGUP signal, which might get overriden by the application. Other signals from other processes with permission (root or same user) or bad behavior (seg faults, bus errors) can also cause program termination. Resource limitations (ulimit) can also end the program.Barring these, your infinite loop might well run a very long time.
_softwareengineering.206470
At one of the DevDays conferences a presenter said that Workflow Foundation isn't just for applications that require persistence, but they can make it easier to write and maintain Async WCF code and the corresponding error handling. (try.. catch)Assuming that is true, is Workflow Foundation able to use all the CPUs in a system? (Async IO)What WF-specific guidance is needed before writing a CPU-heavy Async WCF application within the WF framework? (only tips that are specific to Workflow Foundation)
Is Windows Workflow Foundation appropriate for a CPU-heavy async application?
workflows;wcf;async;asynchronous programming;workflow foundation
null
_codereview.19786
I've written a couple of functions to check if a consumer of the API should be authenticated to use it or not.Have I done anything blatantly wrong here?ConfigAPI_CONSUMERS = [{'name': 'localhost', 'host': '12.0.0.1:5000', 'api_key': 'Ahth2ea5Ohngoop5'}, {'name': 'localhost2', 'host': '127.0.0.1:5001', 'api_key': 'Ahth2ea5Ohngoop6'}]Exceptionsclass BaseException(Exception): def __init__(self, logger, *args, **kwargs): super(BaseException, self).__init__(*args, **kwargs) logger.info(self.message)class UnknownHostException(BaseException): passclass MissingHashException(BaseException): passclass HashMismatchException(BaseException): passAuthentication methodsimport hashlibfrom flask import requestfrom services.exceptions import (UnknownHostException, MissingHashException, HashMismatchException)def is_authenticated(app): Checks that the consumers host is valid, the request has a hash and the hash is the same when we excrypt the data with that hosts api key Arguments: app -- instance of the application consumers = app.config.get('API_CONSUMERS') host = request.host try: api_key = next(d['api_key'] for d in consumers if d['host'] == host) except StopIteration: raise UnknownHostException( app.logger, 'Authentication failed: Unknown Host (' + host + ')') if not request.headers.get('hash'): raise MissingHashException( app.logger, 'Authentication failed: Missing Hash (' + host + ')') hash = calculate_hash(request.method, api_key) if hash != request.headers.get('hash'): raise HashMismatchException( app.logger, 'Authentication failed: Hash Mismatch (' + host + ')') return Truedef calculate_hash(method, api_key): Calculates the hash using either the url or the request content, plus the hosts api key Arguments: method -- request method api_key -- api key for this host if request.method == 'GET': data_to_hash = request.base_url + '?' + request.query_string elif request.method == 'POST': data_to_hash = request.data data_to_hash += api_key return hashlib.sha1(data_to_hash).hexdigest()
Authentication for a Flask API
python;authentication;web services;flask
null
_codereview.95590
Could you please review my spinlock implementation?class spinlock {private: static const std::thread::id lock_is_free; std::atomic<std::thread::id> lock_owner; int lock_count;public: spinlock() : lock_owner(lock_is_free), lock_count(0) { } void lock() { static thread_local std::thread::id this_thread_local = std::this_thread::get_id(); auto this_thread = this_thread_local; for (auto id = lock_is_free; ; id = lock_is_free) { if (lock_owner.compare_exchange_strong(id, this_thread, std::memory_order_acquire, std::memory_order_relaxed)) { ++lock_count; break; } id = this_thread; if (lock_owner.compare_exchange_strong(id, this_thread, std::memory_order_acquire, std::memory_order_relaxed)) { ++lock_count; break; } } } void unlock() { assert(lock_owner.load(std::memory_order_relaxed) == std::this_thread::get_id()); if (lock_count > 0 && --lock_count == 0) { lock_owner.store(lock_is_free, std::memory_order_release); } }};const std::thread::id spinlock::lock_is_free;
C++11 recursive atomic spinlock
c++;c++11;multithreading
Use of TLSI'm not completely sold on your use of TLS. This looks like a premature optimization to me, that said if you have measured and it improves your performance then keep it. Static memberI think it would be better style to not have this static member but this is highly subjective.ReadabilityYour code here: for (auto id = lock_is_free; ; id = lock_is_free) { if (lock_owner.compare_exchange_strong(id, this_thread, std::memory_order_acquire, std::memory_order_relaxed)) { ++lock_count; break; } id = this_thread; if (lock_owner.compare_exchange_strong(id, this_thread, std::memory_order_acquire, std::memory_order_relaxed)) { ++lock_count; break; } }is very difficult to read for me. In fact I'm struggling to understand what the intended behaviour is. To me it looks like what you really wanted was:// If we're being locked recursively, this will always compare false// (insert your desired memory_order here) because no one can fiddle// with `lock_owner` while we have the lock. If we're not entering// recursively then this will always compare true because the thread// doing the checking can only be in one place at one time. if(lock_owner.load() != this_thread){ // Okay so it's not a recursive call. do{ auto id = lock_is_free; }while(!lock_owner.compare_exchange_weak(id, this_thread, std::memory_order_acquire, std::memory_order_relaxed));}// Okay in any event, recursive or not we have the lock now.lock_count++;return;Note: I change compare_exchange_strong to compare_exchange_weak this is recommended when you call compare_exchange in a loop as per std::atomic::compare_exchange (cppreference.com).I would much prefer this implementation of unlock()void unlock(){ assert(lock_owner.load() == std::this_thread::get_id()); assert(lock_count != 0); --lock_count; if(lock_count == 0){ lock_owner.store(lock_is_free, std::memory_order_release); }}Following the style of std::mutex::unlock() stating that calling unlock when the calling thread doesn't own the lock is undefined behaviour we can simply satisfy ourselves with the two asserts to aid during debug-time.
_unix.332926
I have installed many packages on my RHEL 6.6 server. I am trying to install the dependencies of createrepo and createrepo itself. I want to have a yum repository. When I use rpm -ivh *.rpm in a directory with over 50 .rpms, I get this message of failure:/usr/bin/bash is needed by glibc-common-2.17-157.el7_3.1x86_64/usr/bin/cpio is needed by kmod-20-9.el7.x86_64I installed packages for bash and cpio to try to get around this problem. What should I do about these errors? I thought I had all the dependencies.Using the yum localinstall command failed too. I tried creating a link (with ln -s) of the cpio and bash files to the locations that were referenced in the error messages. I tried copying the cpio and bash files to those locations too. But that did not work either. The error kept happening.
How do I troubleshoot unmet dependencies for bash and cpio on RHEL 6.6?
rhel;yum
null
_softwareengineering.92532
I want to improve usability of K9 Email client, Make a new UI and implement some additional functionality.This software is Licensed Under Apache 2.0.http://code.google.com/p/k9mail/https://github.com/obra/k-9Can I use the whole source code of this app with some modifications to some of classes and make this app a Commercial One?I want some legal Advice.If I succeed in this then I have wish to share revenue with original developer of this app.Please give me some pointers on this.I have read about Apache 2.0 license.I am not clear about this line..provide clear attribution to The Apache Software Foundation for any distributions that include Apache softwareFrom Apache FAQhttp://www.apache.org/foundation/licence-FAQ.htmlAnd Clause 4 D from this linkhttp://www.apache.org/licenses/LICENSE-2.0Please Provide your Inputs on this..
Use of Apache 2.0 Licensed K9 Email Android App in Commercial Email App
android;client relations;email;apache license
null
_unix.164236
I use ubuntu 14.4, and attempt to redirect the output of grep command to a file, but I keep getting this error:grep: input file 'X' is also the outputI've searched for this issue and just found out that it was a bug in ubuntu 12.4 and there is not any describe about, can anybody help me to figure out this problem?I run the following command:grep -E -r -o -n r%}(.*){% > myfile
grep: input file 'X' is also the output
shell;ubuntu;command line;grep;io redirection
It is not possible to use the same file as input and output for grep.You may consider the following alternatives:temporary filegrep pattern file > tmp_filemv tmp_file filesedsed -i -n '/pattern/p' fileput whole file in the variable (not bright idea for large files)x=$(cat file); echo $x | grep pattern > file
_webapps.85727
I get at least two emails from Google every time I sign in to my account and I want it to stop.I tried changing the notification settings in Gmail, but they're still coming and they're useless.How can I stop this?
Make Google stop sending 'new sign in from ...' emails
gmail;notifications
Researching this I've seen others have this issue but no solution was presented. One fix would be to simply put a filter on your Gmail account that deletes any email that has the title of the email that is bothering you. It's not the perfect solution but it might do until you find something that is more palatable.
_webmaster.11721
Can anyone think of ways to prevent users from registering to a .php page under certain proxies? What would a group of proxies have in similar that might not effect regular users? For example, if you use Your Freedom, and try to access a .php page, is there any common factor that could be used to keep them off that part of the website in particular?I'm not looking for an answer like 'ban by IP' though. All of the IPs used by Your Freedom are from entirely different countries, and there are infinite ways to change the IP range.
Ways To Block Your Freedom and Similar Proxies?
php;proxy
null
_softwareengineering.321506
I have a large image distributed over multiple machines for which I need to implement the flood fill algorithm used in MS Paint. I am able to do it with a single machine but what approach must be followed for multiple machines.
How to implement to flood fill algorithm on multiple machines?
algorithms;distributed system
null
_webapps.80755
On Picasa Web Album, I can search all public photos via the explore features, for instance a search by tag: https://picasaweb.google.com/lh/view?feat=tags&psc=G&filter=0&tags=wikimania(Note, Google is hiding such features more and more in an attempt to force people to use other services. If at some point in the URL gets redirected elsewhere, see how it looks currently.)How do I do the same on Google Photos? https://photos.google.com/search/wikimania only finds my own photos with the word.Google Plus doesn't provide a side access either: https://plus.google.com/s/wikimania/photos only finds (very few) posts with photos, while I only want the photos themselves and all of them.There are other questions about searching posts and searching own photos. I also asked elswewhere how to mark and search Creative Commons images.
Search public images in Google Photos
google plus;search;picasa web albums;google photos
null
_webapps.75052
How can I create a cell in Google Spreadsheet that automatically updates its value when its respective value in the web (i.e. exchange rates) changes?Is there any function that allows to retrieve the value for exchange rates from the web, so that I don't have to change that each day manually?
Auto-update of exchange rates in Google Spreadsheets
google spreadsheets
null
_unix.281211
Data: one LHC thesis' page 16, where the picture is vectorised (most probably .eps). I am reviewing the answer here of the thread Software needed to scrape data from graph.I cannot find any tool that is made to extract .eps image from a PDF file. My whole system's pseudocodeNeutralise PDF file by gs -dSAFER -dBATCH -dNOPAUSE -sDEVICE=pdfwrite -sOutputFile=newfile.pdf badfile.pdf (source)Find native resolution for the extraction of the vectorised image from a pdf file. (not sure about this one because no zooming may be necessary; 100% zoom level of Adobe view cannot be optimal with a screenshot)extract vectorised image from a pdf file (current goal)extract graph from .eps image where doing all in the same system would be great. Open tools with (3)Possible image formats png/xpm/jpeg/tiff/pnm/ras/bmp/gifg3data but no .eps formatEngaude-digitizer is active here, and more popular than R digitize.R digitize was removed from CRAN, because no maintainer power; but now in tpoisot's Github here and its review in Luke's blog Digitizing data from old plots using digitize but they are trying to get back to CRAN here a ticket. I have experienced a sequence of problems with the software here. One big weakness is that they sensor their github, and no feedback is welcome. Systems with (3) and (4)most probably R package which can do both things: Tools only with (3) or (4) or noneTask (4) can be done in Mathematica as described here about Is it possible to extract data from an eps plot not generated in Mathematica. However, Mathematica not suitable for Task (3) according to devtalk. Adobe Acrobat > Editing. I could not find any suitable method to do it. It seems that no Linux version in Ubuntu 16.04. From vectorized and Steps (1-2)Drag-and-drop of the figure does not work here. So must programmatically extract the figure from the pdf. There exists a terminal tool for that which extract all images/eps/... from the document, but I have no idea how well they do what they do. I would like to find here something which is just good in extracting the .eps image from a pdf file. From Rasterized to Vectorized and Steps (1-2)Example image for DavidLeBauer about the insersection of the graph with the x-axis for the discussion hereand second example about points intersecting two axes here for DavidCode% https://unix.stackexchange.com/q/281211/16920gs -dSAFER -dBATCH -dNOPAUSE -sDEVICE=pdfwrite -sOutputFile=data_clean.pdf badfile.pdf% drag and drop picture from data_clean.pdf to your folder in Ubuntu 16.04 by having the default zoom level; I think zoom should not affect here the result of drag-and-drop% Result: image.png% g3data image.png% bug in 16.04: http://askubuntu.com/q/767982/25388% open figure in ubuntu - Print to File > Ps.% Result: image.png.psps2eps image.png.ps% Result: image.png.eps% https://mathematica.stackexchange.com/q/85320/9815%% Mathematica starts here (* Wolfram Language Test file *)fig = Import[image.png.eps]Import[http://raw.github.com/AlexeyPopkov/shortInputForm/master/shortInputForm.m]fig // shortInputForm% Run but get error: http://askubuntu.com/q/767992/25388% NB this error comes too if I have no code in the editor. So something wrong in my way of doing this. I am amateur in Mathematica. How can you extract .eps image and its graph from a pdf file in Unix way?
Unix way to extract vectorised image and its graph from a PDF file?
pdf;images
No sufficient supported solution exists for the case because the problem is hard inverse-problem in reality. Mathematica solutions have also significant problems with real-world applications.
_softwareengineering.349187
I am on a fairly new team that is also new to TDD and Agile/Scrum. Currently we are developing a project that consists of web API and a native iOS and Android application, with a small team of devs working on each one. We were having a discussion about how to solve issues in developing concurrently and all had differing opinions and were looking for insight.Right now, when we start a story we all branch our respective projects in Git for the story where the work sits through the approval process. Frequently, the native mobile application devs are stuck waiting for code on the web API end to move further in the process so that they can consume it and start the work.Some argue that it is the web API dev's responsibility to mock that data and API endpoint from the start based on a defined contract then swap that code out for the code that will actually sit at that endpoint while the mobile developers work. The issues with this are that the mobile developers will still have a (shorter) waiting period while the data is being mocked and it will require more work on the web dev's end.Others argue that the mobile developers should be mocking that data in their tests and develop using that mocked data on their end for their unit tests, letting their integration tests fail while the web API devs work on their code since the approval of the story depends on the two party's code in unison either way. The downside of this is that it still allows for the mobile devs to get ahead of the web devs and makes their testing and implementation of their UI much harder.What are some best practices regarding this? Are either groups right, is a mix of the two groups right, or are neither of the groups right and there is another way to avoid this problem all together?
TDD and waiting on dependencies
testing;agile;scrum;tdd;mocking
null
_webapps.14410
Will it be moral to copy all city pages information for all cities in my country from Wikipedia?I need those for my website.How can I do it?
How to download all city page of my country from Wikipedia
download;wikipedia
null
_codereview.23745
I have a class, which stores an enum to track if my object is modified, newly created, or no change. If the object is modified, I have additional booleans for each field that is modified.For instance,public enum status{ NoChange, Created, Modified}private bool? name;private bool? address;...private bool? numberOfDonkeysPurchased;So the idea is that if the status is modified, then the nullable bools will be either true or false, depending on if these fields are changed. If the status is not modified, then the nullable bools will be null.The problem with this is that I have a couple of these fields that I want to check (say 10). Is it valid to create a nullable bool for each field that I am checking, knowing that I maybe be storing a lot of nulls? Or is that not a concern?Is there a better way to store this?Thanks!
Better Alternative For Storing Multiple Booleans?
c#
Alternatively, you could use a bitmask via a Flags enum:[Flags]public enum Changes{ None = 0x000, Name = 0x001, Address = 0x002, ... NumberOfDonkeysPurchased = 0x100, ...}Then, you merely update the appropriate flags as you call setters:public string Name{ get { return name; } set { name = value; changes |= Changes.Name; }}Checking for changes is just a matter of comparing changes with Change.None.Note: this will be preferable to a collections object if you are transmitting your data between a client and a server, since the bitmask will be stored as a single int or long.
_softwareengineering.341433
I have a method processDataAssumingLinkedHashMapInput() that processes a Map. The Map must be a LinkedHashMap ordered by values. Data comes from getStrIntMap(query). This method gets resultSet from SQL and puts it in a LinkedHashMap. Here is the code:public void processDataAssumingLinkedHashMapInput(){ String query = select MYID, MYVALUE from MYTABLE order by MYVALUE; Map<String, Integer> map = SQLTools.getStrIntMap(query); for (Map.Entry<String, Integer> entry : rawEntryToSortOrderMap.entrySet()) { //do something, assuming that values are ordered } //do more stuff}//SQLTools method, used by multiple other classespublic static Map<String, Integer> getStrIntMap(String query){ Map<String, Integer> map = new LinkedHashMap<>(); //ResultSet to map return map;}My concern is that if someone decides to change getStrIntMap(String query) to Map<String, Integer> map = new HashMap<>(); (for instance for performance reasons) it will break processDataAssumingLinkedHashMapInput(). I can change return type of getStrIntMap to concrete implementation, but than it wouldn't look good and someone will change it back to an abstract Map. I can create two essentially identical methods one of which returns Map and the other returns LinkedHashMap, but this would break DRY principle. I can reorder data in the beginning of processDataAssumingLinkedHashMapInput method, but this again violates DRY rule. What is the best practice for this case?
Method requires concrete implementation of collection. Should I change all upstream methods to return concrete implementations?
abstract class;implementations
Use a little IoC. Refactor to allow the caller to inject the map instance, which will allow other developers to use the more efficient map and allow you to use the map with the features you want.public static void fillStrIntMap(String query, Map<String, Integer> map){ //ResultSet to map }
_codereview.173868
I have a Date Table like this one:Exit_Date Date_ID2017-05-31 12017-04-26 22017-01-02 32016-12-24 42016-11-27 5I use a loop to insert each of those Dates into a CTE to generates the last 15 years of these dates like this:declare @DI int = 1declare @d datewhile @DI <=5begin select @d = Exit_Date from Date_Table where Date_ID = @DI declare @EDTable table (Exit_Date Date); with a as( select dateadd(yy,-1,@d) d,0 i union all select dateadd(yy,-1,d),i+1 from a where i<14 ), b as(select d,datediff(dd,0,d)%7 dd from a) insert into @EDTable select d from b; set @DI = @DI + 1 endThe results is correct, I get 75 rows with my dates. I would like to know if there is a way to get rid of the WHILE loop by replacing variable @d by each date record from Date_Table?
Replacing a variable in a loop by records from a Table
sql;sql server
Selecting from Date_Table in aOne option is to select Exit_Date direct from Date_Table in a. The ordering of the end results won't be the same so you may need to add an ORDER BY clause (e.g. with DATEPART()). with a as( select dateadd(yy,-1,Exit_date) d,0 i from Date_Table WHERE Date_ID <=5 union all select dateadd(yy,-1,d),i+1 from a where i<14 ), b as(select d,datediff(dd,0,d)%7 dd from a)SELECT d from b --order by DATEPART(MM,d) descSee a sample here in this SQLFidle. CursorLike I mentioned in my comment, another option is to use a Transact-SQL cursor. In the squery below, we keep the temp variables @d and @EDTable. The SELECT statement from Date_Table could have ORDER BY Date_ID ASC added if you wanted to ensure those go in order (in case the records were not added sequentially).declare @d date;declare @EDTable table (Exit_Date Date);declare dateCursor CURSOR FOR select Exit_Date from Date_Table WHERE Date_Id <=5;OPEN dateCursor FETCH NEXT FROM dateCursor INTO @dWHILE @@FETCH_STATUS = 0 BEGIN with a as( select dateadd(yy,-1,@d) d,0 i union all select dateadd(yy,-1,d),i+1 from a where i<14 ), b as(select d,datediff(dd,0,d)%7 dd from a) insert into @EDTable select d from b;--*/ FETCH NEXT FROM dateCursor INTO @d END CLOSE dateCursor; DEALLOCATE dateCursor; SELECT * FROM @EDTableI am trying to get a SQL Fiddle working but having issues with the line endings. I will update when I figure that out.
_softwareengineering.139620
I'm dealing with pretty stressful (in my opinion) situation in my current work place. We've started developing new project, get some requirements, implemented it and then show to someone you can call a 'business advisor' (person who knows business requirements but will not use the program). That person is supposed to evaluate application from customers point of view, test it etc.Here how the 'process' looks:business advisor talks in the evening with my boss for hour or two on windows messengerthe next day I receive email with copy of that conversation. I am supposed to choose tasks from that, check reported bugs (which often aren't bugs, just poor testing and forgetting about past establishments)I implement changes, implementation gets accepted and then in a week or two it turns out that isn't want they want (they talked with some potential client that have seen software for 5 minutes and he suggested changes) - I have to do new changesDon't get me wrong, I understand that sometimes requirements change. What upsets me is how often the change occur in my workplace and how easy for 'management' is two give new requirements or sometimes fundamental changes to existing features. At the same we working on tight deadlines and I have impression that instead of going forward with our software we're running circles.I seek advise from you how to deal with this situation? Is this normal situation and I'm just hypersensitive about it?
How to deal with frequent requirements changes?
project management;software
null
_unix.65169
I have installed a local web server for an web application for a customer. Their server is behind NAT and uses proxy for access internet. Is there a way to access the web application remotely from my computer?
How do I access a web server behind NAT and proxy?
networking
You will need to either create a port forwarding on the NAT router, but beware because then its open to the whole internet, or you need to have something connecting out to allow you in.For example one thing what i like to do is to submit the following command behind a NAT.ssh -R 10022:127.0.0.1:22 [email protected] command connects to myserver.com and opens port 10022 there. Then everything that connects to it's port 10022 will be tunneled to the source hosts 127.0.0.1:22. Later I connect to myserver.com from anywhere, and on myserver.com I submit this:ssh -p 10022 127.0.0.1Like this I can get behind the NAT.You could also do the same by directly forwarding to the webserver, like this:ssh -R 10080:<private webserver ip>:80 [email protected], on myserver.com, you could browse to 127.0.0.1:10080 and would get to the webserver which is behind the NAT. Both solutions, port forwarding or SSH are working, but SSH is much more safe because you don't need to expose your private webserver to the internet.
_cs.227
Consider an filesystem targeted at some embedded devices that does little more than store files in a hierarchical directory structure. This filesystem lacks many of the operations you may be used to in systems such as unix and Windows (for example, its access permissions are completely different and not tied to metadata stored in directories). This filesystem does not allow any kind of hard link or soft link, so every file has a unique name in a strict tree structure.Is there any benefit to storing a link to the directory itself and to its parent in the on-disk data structure that represents a directory?Most unix filesystems have . and .. entries on disk. I wonder why they don't handle those at the VFS (generic filesystem driver) layer. Is this a historical artifact? Is there a good reason, and if so, which precisely, so I can determine whether it's relevant to my embedded system?
Why store self and parent links (. and ..) in a directory entry?
operating systems;filesystems
null
_unix.127533
I have one HDD. 2 partitions with Kali and Windows 8. GRUB is installed. Both OS work fine.I want to remove my Kali partition, and get it as a VM in my Windows 8 partition (I'm using VMware workstation).Is there a way to virtualize this Kali partition ? without damaging my windows 8 one ? Windows does not see the linux partition at all (at least with the Disk Manager, maybe another software is able to see it as GParted or EasyPart).Another solution is to erase my Kali partition and re-extend my windows 8 one, but I'm afraid the windows 8 partition would not boot after it. And it's less fun doing this way.But the Kali partition does not have important stuff that I want to keep/save. So if it's the only way to do it, I can format the kali partition.Hope I'm understable enough and at the right place to ask this kind of question.Many thanks.
Dual boot win/kali - virtualize the linux partition
partition;windows;virtualization;kali linux
You can use VMware Converter to convert the partition to a VM. After that, you would still need to remove the Kali partition and extend your Windows partition. If Windows doesn't see the Windows partition, try QTParted from a Knoppix LiveCD. When the partition is removed, you should be able to extend your Windows partition. I have done this several times, and I don't think extending a Windows partition has big risks associated with it. If you want to be really sure, take a backup first.
_unix.140792
I know there are solution for not rebooting after kernel update: https://en.wikipedia.org/wiki/KspliceBut If Ksplice isn't installed, and the user doesn't reboots it's notebook after even several kernel updates (so notebook running for even months). Could there be a problem about it? (not counting that an update probably came because there was a bugfix or security fix)
Could it cause any problem if I not reboot after a kernel upgrade?
linux;kernel;upgrade
It won't affect the kernel itself (besides not taking advantage of the update).However, some newly installed programs might rely on newer kernel features.Also, if you run a program that relies on loading a kernel module then you may find that that module is no longer installed, and newly installed modules won't load in the old kernel.Basically, if there is a problem, you'll see it. Otherwise you're fine.
_unix.319408
If I were to add custom scripts in /etc/init.d/ to link them from the link farms, what happens when the distribution is updated. Is it guaranted to preserve the scripts in /etc/init.d and not to remove links from the link farms in /etc/rc*?
Adding custom Sys V init scripts
startup;shutdown;daemon
null
_codereview.18158
First, some background. I have a Payment model that has_many :subscriptions. When a user pays (creates a new payment), I have an after_create callback that adds the newly created @payment.id to @subscriptions.payment_id. Here's what it looks like:def update_subscription @unpaid_subs = Subscription.where(:user_id => self.user_id).unpaid @unpaid_subs.each do |sub| sub.payment_id = self.id sub.start # call to state_machine to change state from pending -> active sub.save endendI know that doing database queries inside a loop is generally not good for performance, but I don't know any way to update multiple records at the same time. Also, is there a way to pass the @unpaid_subs instance variable from my create action to the callback (it's the same query on both) so that I can remove the query here?
Update subscription
ruby;ruby on rails;callback
Considering you have a state machine, you're probably doing the right thing by looping through the records. Although you could change all the subscriptions (including their state) in the database, you'd be bypassing the state machine and whatever checks and callbacks it has in place.But, if you really want to bypass the state machine, you could probably do something like this:unpaid_subs = self.user.subscriptions.unpaid # I'm assuming Payment belongs_to Userunpaid_subs.update_attributes(:payment_id => self.id, :state => 'active')Of course, it would require you to allow mass-assignment of both payment_id and (what I assume is named) state, neither of which sound like good ideas at all.So you'd have to bypass the state machine and ActiveRecord to directly update the records in the database with some raw SQL... ugh, gross.So, as I said, you're probably doing the right thing already :)
_webapps.22311
How do I report directly to Facebook an external website that is offering a Free App Download for Facebook that is directly infringing upon Facebook's Privacy Policy?
External Website Directly Infringing Facebook's Privacy Policy
facebook
null
_softwareengineering.352830
Which of these two is the better way of doing the same thing - public void someMethod(String s, boolean bool02){ boolean bool01 = s!=null; if(bool01==bool02){ doSomething(); }}ORpublic void someMethod(String s, boolean bool02){ List<String> list=new ArrayList<String>(); if(s!=null && bool02){ doSomething(); }}The way I understand it is,Option 1 -Computes s!=nullSet it to bool01Compares bool01 to bool02and Option 2 -Computes s!=nullCompares it with trueCompares bool02 to true(depending if step 2 was true)This is not a big deal but its bugging me to know which one is better. Or does the compiler optimization(if any) converts both of them to the same thing?
Which is better in terms of performance (bool01==bool02) vs (bool01 && bool02)
java;programming practices;performance;coding standards
null
_codereview.149090
I replaced the thread by a task so there's no thread locked when there is no job to execute for hours.Now i'm not sure if the lock without an AutoResetEvent is lock safe when AllowParallelExcuteion is set to false. public class BezJobManager : IBezJobManager{ private CancellationTokenSource cts = new CancellationTokenSource(); private readonly IBezServiceResolver _serviceResolver; private List<BezExecuteJobDetail> jobs = new List<BezExecuteJobDetail>(); private Queue<RunningJobData> runningjobs = new Queue<RunningJobData>(); public event Action<BezExecuteJobDetail> JobStartedEvent; public event Action<BezExecuteJobDetail> JobFinishedEvent; public event Action<BezExecuteJobDetail> JobErrorEvent; private static readonly List<AutoResetEvent> autoResetEventHandlers = new List<AutoResetEvent>(); public bool IsDisposed { get; private set; } public bool AllowParallelExecution { get; set; } public BezJobManager(IBezServiceResolver serviceResolver) { _serviceResolver = serviceResolver; } public Guid Prepare(string name, Guid userId) { if (IsDisposed) return Guid.Empty; var job = Create(name, userId); return job.Id; } public Guid Execute(string name, Guid userId, Action action) { if (IsDisposed) return Guid.Empty; var job = Create(name, userId); Execute(job, action); return job.Id; } public Guid Execute(Guid jobId, Action action) { BezExecuteJobDetail job; lock (jobs) job = jobs.FirstOrDefault(item => item.Id == jobId); if (job == null) return Guid.Empty; Execute(job,action); return job.Id; } public Guid Execute(BezExecuteJobDetail job, Action action) { if (IsDisposed) return Guid.Empty; RunningJobData runningJob; lock (runningjobs) { runningJob = CreateRunningJob(job.Id); runningJob.Action = action; } if (AllowParallelExecution) { lock (runningjobs) runningjobs.Dequeue(); Task.Run(() => RunJob(runningJob), cts.Token); } else RunSingleThread(); return job.Id; } private bool isSingleTaskRunning; private object singleTaskLocker = new object(); private void RunSingleThread() { lock (singleTaskLocker) { if (isSingleTaskRunning) return; isSingleTaskRunning = true; } Task.Run(() => { while (!IsDisposed) { try { RunningJobData jobToRun; lock (runningjobs) { lock (singleTaskLocker) { if (runningjobs.Count == 0 || IsDisposed) { Task.Delay(100).Wait(cts.Token); if (runningjobs.Count == 0 || IsDisposed) { isSingleTaskRunning = false; return; } } } jobToRun = runningjobs.Dequeue(); // It can be that the finished method is already set but not yet the action. if (jobToRun.Action == null) { runningjobs.Enqueue(jobToRun); // If there's only one job,; wait a bit, otherwise start immediatly in while loop with new other job. if (runningjobs.Count == 1) Task.Delay(50).Wait(); continue; } } RunJob(jobToRun); } catch (Exception ex) { var logger = _serviceResolver.Resolve<ILogger>(); if (logger != null) logger.LogError(BezJobManager:Error while running jobs, ex); } } }, cts.Token); } private void RunJob(RunningJobData runningJob) { var job = runningJob.Job; try { job.Status = BezExecuteJobDetail.BezExecuteJobDetailStatus.Running; OnJobStartedEvent(job); if (IsDisposed) return; runningJob.Action(); if (cts.Token.IsCancellationRequested) return; if (IsDisposed) return; job.Status = BezExecuteJobDetail.BezExecuteJobDetailStatus.Finished; if (cts.Token.IsCancellationRequested) return; if (IsDisposed) return; runningJob.Finished(cts.Token); runningJob.ClearAll(); OnJobFinishedEvent(job); } catch (Exception ex) { job.Status = BezExecuteJobDetail.BezExecuteJobDetailStatus.Error; job.ErrorMessage = ex.Message; var logger = _serviceResolver.Resolve<ILogger>(); if (logger != null) logger.LogError(BezJobManager:Error while running job: + job.Name + : + job.Status, ex); try { OnJobErrorEvent(job); } catch { } } finally { lock (jobs) jobs.Remove(job); } } public void ExecuteWhenFinished(Guid jobId, Action action) { var localJob = CreateRunningJob(jobId); localJob.AddFinishedAction(action); } private RunningJobData CreateRunningJob(Guid jobId) { RunningJobData localJob; lock (runningjobs) { localJob = runningjobs.FirstOrDefault(item => item.Job.Id == jobId); if (localJob == null) { localJob = new RunningJobData(_serviceResolver) { Job = new BezExecuteJobDetail { Id = jobId } }; runningjobs.Enqueue(localJob); } } return localJob; } public Task WaitTillFinished(Guid jobId) { return Task.Run(() => { var waitHandle = new AutoResetEvent(false); lock (autoResetEventHandlers) autoResetEventHandlers.Add(waitHandle); ExecuteWhenFinished(jobId, () => waitHandle.Set()); waitHandle.WaitOne(); lock (autoResetEventHandlers) autoResetEventHandlers.Remove(waitHandle); }); } private BezExecuteJobDetail Create(string name, Guid userId) { var job = new BezExecuteJobDetail { Name = name, Id = Guid.NewGuid(), RequestByUserId = userId, Status = BezExecuteJobDetail.BezExecuteJobDetailStatus.Created }; lock (jobs) jobs.Add(job); return job; } private void OnJobFinishedEvent(BezExecuteJobDetail obj) { var handler = JobFinishedEvent; if (handler != null) handler(obj); } private void OnJobErrorEvent(BezExecuteJobDetail obj) { var handler = JobErrorEvent; if (handler != null) handler(obj); } private void OnJobStartedEvent(BezExecuteJobDetail obj) { var handler = JobStartedEvent; if (handler != null) handler(obj); } public void Dispose() { IsDisposed = true; cts.Cancel(); } private class RunningJobData { private readonly IBezServiceResolver _serviceResolver; public BezExecuteJobDetail Job { get; set; } public Action Action { get; set; } private readonly List<Action> _actionsWhenFinished = new List<Action>(); public RunningJobData(IBezServiceResolver serviceResolver) { _serviceResolver = serviceResolver; } public void AddFinishedAction(Action action) { lock (_actionsWhenFinished) _actionsWhenFinished.Add(action); } public void ClearAll() { lock (_actionsWhenFinished) _actionsWhenFinished.Clear(); } public void Finished(CancellationToken token) { lock (_actionsWhenFinished) foreach (var action in _actionsWhenFinished) { var action1 = action; Task.Run(() => { try { action1(); } catch (Exception ex) { _serviceResolver.Resolve<ILogger>().LogError(BezJobClientManager:Error executing + Job.Name, ex); } }, token); } } }}
Safe locking, replaced thread by task inside Job Manager
c#;thread safety;locking
null
_webmaster.21725
I have created a few plugins and themes that I want to have special pages for. Now I do not want to make a complete new website or page for all the different plugins.Instead I want to have normal blogposts for each of my plugins and themes. Now to make things more simple I want to create a special domain name for them, with CNAME records. like this:facyplugin.mydomain.com CNAME mydomain.com/2011/09/new-fancy-pluginNow instead of giving people the long version of the link, I can just give the small one, without having to use a url crusher.--Now is this a good idea, or will this lead to problems in terms of SEO.
Creating a subdomain (sub.domain.com) for special posts on a blog: Good idea?
seo;blog;links
It will have no effect on your SEO. Subdomains are no different then subdirectories as far as SEO goes. If you think this will make it easier to promote your plug-ins then definitely do it. But don't expect any special rankings because of it.
_webmaster.14048
Sorry if this has been covered, I can't find anything on this specifically.I have wildcard subdomains on (*.mysite.com) I need a mod_rewrite expression for this rewrite:bob.mysite.com => mysite.com/users/index.php?user=bobbob.mysite.com/profile/ => mysite.com/users/index.php?user=bob/profile/Obviously bob and profile are just examples, I need the general case. Thanks for your help!
mod_rewrite rule for wildcard subdomains?
mod rewrite
The $ operator will let you extract backreferences from matches in rewrite rules and the % operator will let you extract references from conditions.RewriteCond %{HTTP_HOST} !www.mysite.com$ [NC] # Presuming you don't want to do wwwRewriteCond %{HTTP_HOST} ^(.*)\.mysite\.com [NC] # Catch subdomainRewriteCond %{REQUEST_URI} !index\.php [NC] # Don't rewrite if we already haveRewriteRule ^(.*)$ /users/index.php?user=%1$1 [L]
_unix.115583
To keep my Input Method (Bogo or Unikey) of IBus working with Dvorak keyboard layout after reboot, I use sudo dpkg-reconfigure keyboard-configuration to set keyboard as Dvorak, and go to tab Advance in IBus Preferences to check Use system keyboard layout.The problem is, sometimes my friends want to borrow my laptop and I can not easily switch to Qwerty layout because any Input Method will use Dvorak. The English - English (US) is the same as English - English (Dvorak) one.Any idea? Info: I'm use IBus 1.5.3 and it says this is the newest version. So do Cinnamon.
Can't use QWERTY layout after make IBus work with Dvorak layout after reboot
keyboard layout;reboot;input method;ibus
null
_softwareengineering.196293
With advent of WPF and MVVM Microsoft introduced DependencyProperties and INotifyPropertyChange interface to provide a way to implement the reactive approach used with those technologies.Sadly both of these constructs are very verbose, require much boilerplate, are clumsy to use, also are not really that safe since they require much use of magic strings.So here come the question: why didn't they put these functionalities directly into the language - why didn't they create new kind of properties created with a simple keyword, providing useful stuff of DependencyProperties (like events on change and so on...).What were stopping them?
Why DependencyProperties and not native language support?
c#;wpf;mvvm
Dependecy properties are very WPF-specific. As far as I know, even WinRT (which is XAML-based, just like WPF) doesn't use them. So, you are proposing adding a feature that wouldn't be at all useful for people who develop ASP.NET applications, Windows services, web services, WinRT applications, etc. That's points against this feature.Also, it's not clear to me how exactly would this work. How would you set the default value of the property? Or PropertyChangedCallback? What about attached properties? If the feature you're proposing couldn't handle all this, it would make it much less useful. If it did, I have no idea how would the syntax look like, but I doubt it would fit well with the rest of C#.And this feature doesn't actually add much, it just makes some code slightly more convenient.This all says to me that such a feature wouldn't be worth it, considering that it would be relatively complicated change that would be useful only in a relatively small subset of programs and even in those wouldn't be actually useful that much.
_softwareengineering.150915
I was just wondering if a language could support something like a Retry/Fix block?The answer to this question is probably the reason it's a bad idea or equivalent to something else, but the idea keeps popping into my head.void F(){ try { G(); } fix(WrongNumber wn, out int x) { x = 1; }}void G(){ int x = 0; retry<int> { if(x != 1) throw new WrongNumber(x); }}After the fix block ran, the retry block would run again...
Can a language support something like Retry/Fix?
programming languages
Yes, a language could do that.There are examples in existing languages. Common Lisp provides a system which allows an exception (condition, in CL terminology) handler to return control to the point at which the exception was thrown, passing extra information about how the condition should be handled.A good description of this is available in the book Practical Common Lisp, 19. Beyond Exception Handling: Conditions and RestartsAs other commenters have mentioned, Scheme's general continuation system could be used to implement this, and Eiffel provides similar functionality.Thanks to @9000 and @delnan for bringing up Eiffel and call/cc in the comments on the question
_unix.119762
I know to dump memory images in Windows. (eg-dumpit) But I don't know how to dump memory images in Linux.I want to get memory images in Linux and from Linux to Linux with ssh connection or something.How can I get in Linux?
How to dump memory image from linux system?
memory;forensics;dump
null
_softwareengineering.19317
I keep running into the same problems. The problem is irrelevant, but the fact that I keep running into is completely frustrating.The problem only happens once every, 3-6 months or so as I stub out a new iteration of the project. I keep a journal every time, but I spend at least a day or two each iteration trying to get the issue resolved.How do you guys keep from making the same mistakes over and over?I've tried a journal but it apparently doesn't work for me.[Edit]A few more details about the issue: Each time I make a new project to hold the files, I import a particular library. The library is a C++ library which imports glew.h and glx.h GLX redefines BOOL and that's not kosher since BOOL is a keyword for ObjC.I had a fix the last time I went through this. I #ifndef the header in the library to exclude GLEW and GLX and everything worked hunky-dory.This time, however, I do the same thing, use the same #ifndef block but now it throws a bunch of errors. I go back to the old project, and it works. New project no-worky.It seems like it does this every time, and my solution to it is new each time for some reason. I know #defines and #includes are one of the trickiest areas of C++ (and cross-language with Objective-C), but I had this working and now it's not.
How do you keep from running into the same problems over and over?
self improvement;productivity
I'd suggest determining what triggers the issue, and restructuring your development process to avoid that scenario. What 'restructuring' entails is highly dependent on the problem. It ranges from abstracting some behavior into a seperate class to changing the composition of your team.A journal detailing the context of the incident and resolution approaches can certainly help you converge on the root cause and/or a general solution. Once you've determined that there are a few obvious options:If the cause is avoidable: Try to avoid triggering the root cause next time.If the solution proves to be simple: Implement the general solution whenever the problem occurs.Restructure your development process so that it naturally avoids the issue.The options available depend on the information about the issue you have, and the amount of control you have over the development process.
_unix.204733
There are a number of Unix commands which do not work on my OS X Yosemite 10.10.3, Terminal Version 2.5.3. For instance, I often use this cheatsheet of Unix commands: http://mally.stanford.edu/%7Esr/computing/basic-unix.htmlTake the command webster, which gives the definitions of words via the Webster Dictionary. Naturally, Mac's Terminal does not recognize this command-bash: webster: command not foundIs there any way to download/import all Unix commands into OS X? Or at least import certain commands like webster? EDIT: It looks like the best way forward is to build my own set of Unix commands. webster just isn't available, outside of my fantasy Unix system on Stanford computers twenty years ago. Fellow Unix nerds, rise up! Let us achieve Unix greatness in days of yore!
How can I import new Unix commands on my OS X Terminal?
terminal;osx;macintosh
null
_unix.77054
I cannot find where I can set keyboard shortcut for switching languages.Update:New problem: I cannot set Alt+Shift combination for that.
Gnome3/cinnamon set keyboard shortcut
keyboard shortcuts;gnome3;cinnamon
I don't use Cinnamon so this might not work for you, but in vanilla Gnome 3.6 you could do this either via terminal:gsettings set org.gnome.settings-daemon.peripherals.keyboard input-sources-switcher alt-shift-lor via dconf-editor, navigating to org > gnome > settings-daemon > peripherals > keyboard and entering alt-shift-l as a value for the input-sources-switcher key:In Gnome 3.8 they have re-added this feature to Settings > Keyboard > Shortcuts, via an additional section called Typing:
_webmaster.88214
I installed Google Analytic on my website. I pasted the code into the right place. It is showing real time & other data, but it is not counting sessions and page views. It actually appears that the page views is counting down. What can I do?
Google Analytics not counting page views when installed on my website?
google analytics;statistics;visitors
null
_unix.104800
I'd like to use find to list all files and directories recursively in a given root for a cpio operation. However, I don't want the root directory itself to appear in the paths. For example, I currently get:$ find diskimgdiskimgdiskimg/file1diskimg/dir1diskimg/dir1/file2But, I'd like to getfile1dir1dir1/file2(note the root is also not in my desired output, but that's easy to get rid of with tail).I'm on OS X, and I'd prefer not to install any extra tools (e.g. GNU find) if possible, since I'd like to share the script I'm writing with other OS X users.I'm aware this can be done with cut to cut the root listing off, but that seems like a suboptimal solution. Is there a better solution available?
find output relative to directory
find
If what you are trying to do is not too complex, you could accomplish this with sed:find diskimg | sed -n 's|^diskimg/||p'Or cut:find diskimg | cut -sd / -f 2-
_softwareengineering.161945
So a client comes to me and says it needs some work done. Basically 4 tasks, which I agreed to perform for a certain price. The customer creates the job offer (a fixed time and price job) on ODesk, I accept it, but it took some days and constant reminding for the customer to initiate a contract based on that job.The problem is that the original task has been completed, the contract is still active, I have not been paid yet, the customer says he will pay when the project is completed, and until then, new tasks occur constantly, or changes to older tasks that require full re-doing of elements. For all of this the client promises payment. No updates from this client on ODesk, no new tasks there. I keep reminding the client about sorting out the administrative issues, but with no results. At the same time, the client pushes on continuing work, since the project is soon to be launched.I don't know what to do.If I refuse to perform any work without the bureaucracy, the project will be late. But it's not my fault, is it? I am scared that I might receive a negative feedback in this case, or something even worse.If I drop out of this project I'm afraid I won't be getting even what I've earned.If I continue like this, I'll be wasting a lot of time doing stuff similar to the stuff described here, but as a programmer (yes, it has already come to similar requests, for lots of hardcoded content).How do I communicate with such clients in such situations? How do I avoid a conflict?P.S. The client is a small company. Different people handle different aspects of this project, and everybody introduces their own changes to the original specs.After 2 years: Wow! Very question! Much popular!I decided to let everyone in on the ending of this story. I've confronted the customer, explained that I will not work until I get paid for what I did, and until a hourly contract is open. They paid me the next day and opened a contract. A fruitful, but short collaboration started. Everyone was happy. Except I didn't get any feedback.
Should I continue to perform freelance work for customers who keep on demanding more without paying?
freelancing;customer relations
Oh man, I was in this position so many times back when I freelanced I'm feeling your pain right now.It all changed when I changed my way of thinking about clients: all clients are con artists.Let me say that again:ALL CLIENTS ARE CON ARTISTSWhen you change to this perspective it is when you realize you actually have the leverage most of the time, even when you don't have a contract that backs you up.Here is what you do:If you have delivered already, you are already screwed: At this point you must decide if you want to keep getting screwed and have the client continue making you his b****.If you have not delivered, there is hope: The launch is your leverage and you can still get paid. Negotiate payment for at least 50% or just drop the whole project and leave him to his luck, this is your leverage. I was in this position at least two times and didn't take the chance when I could, things went bad for me and I paid the price. It sounds cold-hearted, but this is often the point of no return.If you think this is just a communication problem, you can fix it (if and only if the client wants to): You can use the previous still as a leverage, but the solution is to ask the client to designate a single representative for the project, your best options for this are:The project ownerA stakeholder designated by the project ownerThe owners' right-handThis will effectively make them funnel all requests to a single point where things can be sorted out on their side, not on yours. You are experiencing a mixture of feature creep and lack of expectation management.In any case and if I were you, I would contact oDesk for assistance with this case. I'm sure there are a lot of clients who behave like this to extort more work out of contractors. If you have evidence that the project is complete according with the contract, use the contract as your weapon. I'm sure oDesk has contracts for something.Also, it can also look like being cold-hearted, but when it comes down to getting screwed or not screwed, their launch, their deadlines, and their mind-faps are their problem, not yours. I made the mistake of caring too much about the client in my days, but you don't have to.Edit: Last piece of advice, don't make the final delivery until you have the final payment. You can always give a demonstration in your own laptop/premises to assure everything works. Alternatively and if you have absolutely no choice, and the customer needs the application deployed to pay you (because it is in the contract, otherwise don't give in), deploy it in your own infrastructure and give no access to it to anyone other to those that you would trust with your life (I'm serious about this). This is your last possible leverage where you can say: you have X days to pay up or the service will be taken down. Pretend that he is renting a house you own, and he might just leave one day unannounced and you will never be able to track him back or give him a reason to pay you.
_webapps.33946
I have a facebook profile with a custom url name. For example Catdog - www.facebook.com/Catdog.So does that mean if someone enters: www.facebook.com/Catdog into their browser AND they are not my friend OR mutual friend, could still see my Timeline even though I've set ONLY FRIENDS in the Who could look up my Timeline by name options in the privacy settings?Thanks in advance.
Can knowing a custom Facebook URL of someone bypass who can look up my timeline by name privacy option?
facebook;privacy;facebook timeline
No. Your privacy settings apply even to customized URLs for your Facebook profile.There is always going to be some public information provided when people visit your profile page (Profile pic, basic info unless hidden). If you'd like to see what the public sees when visiting your profile, go to the Settings gear box on your Timeline and select View as...The default view will show you how you appear to the public, as well as provide a box for you to see how your various friends see your profile as well.
_softwareengineering.228927
Fixed-point object locations allow for worlds which are much more scale-able. Using a 64-bit integer (per dimension), and 0.1 millimeter precision, a world can be created which is 100% numerically stable, and 12,000 astronomical units across.I have been looking all over the internet, and I can't seem to find a physics engine which supports this.Is there a 3D physics engine in existence, which uses fixed-point (i.e. Integer, hopefully int-64) values for entities' positions?It's for a really ambitious sci-fi game I'm working on.
Physics Engine with Fixed-Point Positions
java;3d;physics
I've never heard of one.And there are reasons why nobody does it that way.First, numerically-intense computations moved to floating point decades ago because of the amount of headache involved in keeping track of the decimal point across multiplications, divisions, and exponentiations. The moment you hit transcendental functions (sin, cos, exp), you die horribly.Second, one light-year is about 63000 AU, so your universe is 1/5 of a light-year across. Given that Alpha Centauri is 4.3 light-years from Sol, your Universe is limited to one (1) solar system. AT THE MOMENT, it is summer on Pluto, meaning that it is just inside Neptune's orbit, and so the whole basic Solar system is 60 AU across (30 AU to Neptune's orbit, x 2).You're proposing using 64 bits. It only takes about 55 bits to represent the basic Solar system, to your desired precision. Use another bit, and go out to 120 AU across.Now, x86 extended precision (double) is 80 bits, with a sign bit, a 15-bit exponent, and a 64-bit mantissa. Your suggestion uses a 64-bit mantissa, with NO exponent. Bluntly, you aren't saving yourself any trouble by writing your own fixed-point math package.My suggestion to you is this: Develop a prototype of your game, using plain vanilla extended precision floating point, and see whether you encounter numerical instabilities.
_codereview.102719
I have 3 tables: Table couples consist of save_id, id_candidate_red, id_candidate_blue Table candidates_red consist of save_id, id_candidate, enter_match Table candidates_blue consist of save_id, id_candidate, enter_matchAnd I am running the query SELECT * FROM couples as c LEFT JOIN candidates_blue as cb ON cb.save_id = 3 AND cb.user_id = c.id_candidate_blue LEFT JOIN candidates_red as cr ON cr.save_id = 3 AND cr.user_id = c.id_candidate_red WHERE c.save_id = 3 AND cb.enter_match = 1 AND cr.enter_match = 1 which seems pretty simple to me, but as I have a big dataset behind my tables, it takes quite a while to execute.
Joining couples, red candidates, and blue candidates
performance;sql;mysql;join
I'm afraid there's not much we can do to help with this kind of question. There's not much obviously wrong. You likely need to run the query analyzer and add some missing indices and keys. Regardless, there's still an opportunity for improvement, albeit not much performance wise... SELECT *Do you really need every column? Even with proper keys/indices in place, this will typically force a table scan. Explicitly state only the fields you need to return. It will result in less I/O and could possibly turn a scan operation into a seek. If it doesn't, you'll need to find the missing index to be added. The next thing you can do is remove the duplication. LEFT JOIN candidates_blue as cb ON cb.save_id = 3 AND cb.user_id = c.id_candidate_blueLEFT JOIN candidates_red as cr ON cr.save_id = 3 AND cr.user_id = c.id_candidate_redWHERE c.save_id = 3 AND cb.enter_match = 1 AND cr.enter_match = 1I suppose you added all the save_id = 3s in an attempt to speed up the query? Don't bother. It won't help. Specifying it once for the couples table is sufficient. Which actually brings me to an optimization. Your query is equivalent to using INNER JOIN, but without any of the benefits. You're not currently getting the unmatched records anyway, so you might as well switch. You might see a significant performance increase. SELECT * /* don't forget to specify the fields you actually want */FROM couples as cINNER JOIN candidates_blue as cb ON cb.user_id = c.id_candidate_blueINNER JOIN candidates_red as cr ON cr.user_id = c.id_candidate_redWHERE c.save_id = 3 AND cb.enter_match = 1 AND cr.enter_match = 1 One last thing: Very nice formatting! It's extremely easy on the eyes.
_unix.159803
When I do:echo #TEST >> /etc/passwdI get the following in audit logging:node=kayak.office.local type=SYSCALL msg=audit(1412687666.054:62033): arch=c000003e syscall=2 success=yes exit=3 a0=2939480 a1=241 a2=1b6 a3=76 items=2 ppid=12744 pid=12748 auid=1030 uid=0 gid=0 euid=0 suid=0 fsuid=0 egid=0 sgid=0 fsgid=0 tty=pts0 ses=1769 comm=bash exe=/bin/bash subj=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 key=identitynode=kayak.office.local type=CWD msg=audit(1412687666.054:62033): cwd=/rootnode=kayak.office.local type=PATH msg=audit(1412687666.054:62033): item=0 name=/etc/ inode=13 dev=fd:00 mode=040755 ouid=0 ogid=0 rdev=00:00 obj=system_u:object_r:etc_t:s0 nametype=PARENTnode=kayak.office.local type=PATH msg=audit(1412687666.054:62033): item=1 name=(null) inode=15883 dev=fd:00 mode=0100644 ouid=0 ogid=0 rdev=00:00 obj=system_u:object_r:etc_t:s0 nametype=NORMAL(spaces added for readability)The inode of /etc/passwd is indeed 11908, but this is hard to parse with external tooling, which make rules based on file names. Can I get the file name/path?
File path in audit log instead of inode number
linux;files;logs;audit
null
_reverseengineering.12726
I have made a plugin (using IDA Python) that requires the Hex-Rays plugin. As per the instructions in the hexrays_sdk folder, I've named my plugin starting with hexrays_ to make sure it loads after Hex-Rays is done loading. However, IDA decides to load my plugin earlier, and hence, it never is able to get True for idaapi.init_hexrays_plugin(). I've tried renaming my plugin in multiple ways, but still cannot seem to get the plugin to load after Hex-Rays.BTW, I think the issue might be related to the fact that I am storing my plugin in %IDAUSR%/plugins rather than %IDADIR%/plugins since I do not want to modify %IDADIR%.Is there any kind of workaround to make the plugin load later? Or can I force IDA to load Hex-Rays earlier?
Hex-Rays and IDA Python plugin loading order
idapython;idapro plugins;hexrays
When loading plugins, IDA goes through them alphabetically, and tries to load all the plugins.When loading a plugin, the loader check the plugin flags (idaapi.PLUGIN_PROC, idaapi.PLUGIN_FIX, and so on) to determine if the plugin should be loaded at the current time.If it is to be loaded, the init method is called. A plugin can return PLUGIN_KEEP to remain loaded, or PLUGIN_SKIP to avoid loading.As long as a plugin is not in memory (not yet loaded, or already unloaded,) IDA will try and load it again and again. This is how my plugin loader works.So the first thing you need to be sure of, is that you flag your plugin idaapi.PLUGIN_PROC, as this is when Hex-Rays loads (only when a processor module is active.)Hopefully, this will solve it. If not - you can use idaapi.load_plugin('hexrays') to explicitly load the Hex-Rays plugin. Again, this can only be done when a processor module is active, so be sure to use PLUGIN_PROC.
_cs.24597
I'm trying to proof/refute the following equation:$$n^n = \Omega(n!)$$Generally I would try to use Convergence Criteria and or l'Hpital's rule to solve such a problem.$$\lim_{n\to \inf}{{f(n)}\over{g(n)}} = K$$However, in this case $n!$ is somewhat of a party-stopper. I found Stirling's approximation which states that:$$n! \approx \left(\frac{n}{e}\right)^n\sqrt{2n} $$My idea was therefore:$${n^n}\over{(\frac{n}{e})^n\sqrt{2n}}$$$${n^n}\over{\frac{n^n}{e^n}\sqrt{2n}}$$$${e^n}\over{\sqrt{2n}}$$$$\lim_{x\to \infty}{{e^2n}\over{2n}} = \infty$$$$ 0 < K \leq \infty $$therefore the original equation is true.Is that approach ok, did I understand Stirling's approximation correctly?
Proof or refute $n^n = \Omega(n!)$ with the help of Stirling's approximation
asymptotics;check my answer
Stirling's approximation states that$$ n! \sim \sqrt{2\pi n} (n/e)^n. $$This notation means that the ratio between the two sides tends to 1 as $n$ tends to infinity. For your purposes, we can simply write$$ n! = \Theta(\sqrt{n} (n/e)^n). $$Since $\sqrt{n} = o(e^n)$,$$ n! = o(n^n). $$If all you want to show $n! = O(n^n)$, then as Jukka mentions you can use the simple bound $n! \leq n^n$.
_unix.101132
Before updating ubuntu to it's current version, bluetooth used to work just fine. But, now I've been facing problem regarding this bluetooth setting. While adding devices,it keeps on searching but never finds. Moreover, I can't set bluetooth setting to visible. I tried the method using Launchpad using this method. But, I failed that way. I got error on this line :# sudo dpkg -i indicator-bluetooth_0.0.6daily13.02.19-0ubuntu1_amd64.debThe error says like this:dpkg: error processing indicator-bluetooth_0.0.6daily13.02.19-0ubuntu1_amd64.deb (--install): cannot access archive: No such file or directoryErrors were encountered while processing: indicator-bluetooth_0.0.6daily13.02.19-0ubuntu1_amd64.deb
How to enable bluetooth in Ubuntu 13.10?
ubuntu;bluetooth
null
_codereview.139181
Question copied from the book:(Game: eye-hand coordination) Write a program that displays a circle of radius 10 pixels filled with a random color at a random location on a panel, as shown in Figure 16.28c. When you click the circle, it disappears and a new randomcolor circle is displayed at another random location. After twenty circles are clicked, display the time spent in the panel, as shown in Figure 16.28d.My solution:import javax.swing.*;import java.awt.*;import java.awt.event.*;public class EyeHandCoordination extends JFrame { private final int CIRCLE_RADIUS = 10; private final int TOTAL_CIRCLES = 20; private RandomCirclePanel panel = new RandomCirclePanel(); public EyeHandCoordination() { add(panel); } public static void main(String[] args) { EyeHandCoordination frame = new EyeHandCoordination(); frame.setTitle(EyeHandCoordination); frame.setSize(300, 300); frame.setLocationRelativeTo(null); // Center the frame frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } private class RandomCirclePanel extends JPanel { private long startTime; private long endTime; private int circleX = 0; private int circleY = 0; private int currentCircle = 0; public RandomCirclePanel() { startTime = System.currentTimeMillis(); addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { // Check if in circle if (inCircle(e.getX(), e.getY()) && currentCircle < TOTAL_CIRCLES) { currentCircle++; repaint(); } } }); } /** Display circle at a random location **/ private void changeCircleLocation() { circleX = (int)(Math.random() * (getWidth() - CIRCLE_RADIUS * 2)); circleY = (int)(Math.random() * (getHeight() - CIRCLE_RADIUS * 2)); } /** Check if inCircle **/ public boolean inCircle(int mouseX, int mouseY) { if (distanceFromCenterOfCircle(mouseX, mouseY) <= CIRCLE_RADIUS) { return true; } return false; } private int distanceFromCenterOfCircle(int x, int y) { int centerX = circleX + CIRCLE_RADIUS; int centerY = circleY + CIRCLE_RADIUS; return (int)(Math.sqrt((centerX - x) * (centerX - x) + (centerY - y) * (centerY - y))); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); int width = getWidth(); int height = getHeight(); changeCircleLocation(); if (currentCircle >= TOTAL_CIRCLES) { g.setColor(Color.BLACK); endTime = System.currentTimeMillis(); FontMetrics fm = g.getFontMetrics(); String s = Time spent: + ((endTime - startTime) / 1000.0) + seconds; g.drawString(s, width / 2 - fm.stringWidth(s) / 2, height / 2 - fm.getAscent()); } else { g.setColor(new Color((int)(Math.random() * 256), (int)(Math.random() * 256), (int)(Math.random() * 256))); g.fillOval(circleX, circleY, CIRCLE_RADIUS * 2, CIRCLE_RADIUS * 2); } } }}
Swing Game EyeHandCoordination
java;swing;event handling;gui
null
_codereview.98694
I am writing a C++ library which will interact on files, memory buffers and remote files accessible with the HTTP protocol.To handle that, I've decided to create some classes that will use the following interface:DataStreamInterface.hclass DataStreamInterface { public: virtual bool open() = 0; virtual void close() = 0; virtual std::streamsize length() const = 0; virtual std::streamsize tell() const = 0; virtual std::streamsize seek(std::streamsize position) = 0; virtual std::streamsize read(char *buffer, std::streamsize length) = 0; virtual std::streamsize read(int8_t *buffer) = 0; virtual std::streamsize read(uint8_t *buffer) = 0; virtual std::streamsize read(int16_t *buffer) = 0; virtual std::streamsize read(uint16_t *buffer) = 0; virtual std::streamsize read(int32_t *buffer) = 0; virtual std::streamsize read(uint32_t *buffer) = 0; virtual std::streamsize read(float *buffer) = 0; virtual std::streamsize read(double *buffer) = 0; virtual std::streamsize read(std::string *buffer) = 0; virtual std::streamsize peek(uint8_t *buffer, std::streamsize length) = 0; virtual std::streamsize peek(int8_t *buffer) = 0; virtual std::streamsize peek(uint8_t *buffer) = 0; virtual std::streamsize peek(int16_t *buffer) = 0; virtual std::streamsize peek(uint16_t *buffer) = 0; virtual std::streamsize peek(int32_t *buffer) = 0; virtual std::streamsize peek(uint32_t *buffer) = 0; virtual std::streamsize peek(float *buffer) = 0; virtual std::streamsize peek(double *buffer) = 0; virtual std::streamsize peek(std::string *buffer) = 0; virtual std::streamsize write(const char *buffer, std::streamsize length) = 0; virtual std::streamsize write(int8_t value) = 0; virtual std::streamsize write(uint8_t value) = 0; virtual std::streamsize write(int16_t value) = 0; virtual std::streamsize write(uint16_t value) = 0; virtual std::streamsize write(int32_t value) = 0; virtual std::streamsize write(uint32_t value) = 0; virtual std::streamsize write(float value) = 0; virtual std::streamsize write(double value) = 0; virtual std::streamsize write(const std::string &value) = 0; virtual ~DataStreamInterface() { }};Then I create MemoryDataStream for reading and writing inside a malloc'd buffer, FileDataStream for reading and writing into files and HttpDataStream for reading remote files.MemoryDataStream.ccMemoryDataStream::MemoryDataStream(const DataStreamInit &dsInit) : _bigEndian(dsInit.bigEndian) {}MemoryDataStream::~MemoryDataStream() { this->_buffer.clear();}bool MemoryDataStream::open() { return true;}void MemoryDataStream::close() {}std::streamsize MemoryDataStream::length() const { return this->_buffer.size();}std::streamsize MemoryDataStream::seek(std::streamsize position) { if (position < 0 || static_cast<std::streamsize>(this->_cursor) + position > this->_buffer.size()) { return -1; } this->_cursor = position; return this->_cursor;}std::streamsize MemoryDataStream::tell() const { return this->_cursor;}std::streamsize MemoryDataStream::read(char *buffer, std::streamsize length) { std::streamsize result = 0; for (int i = 0; i < length; i++) { result += this->_read(buffer++); } return result;}std::streamsize MemoryDataStream::read(int8_t *buffer) { return this->_read(buffer);}std::streamsize MemoryDataStream::read(uint8_t *buffer) { return this->_read(buffer);}std::streamsize MemoryDataStream::read(int16_t *buffer) { return this->_read(buffer);}std::streamsize MemoryDataStream::read(uint16_t *buffer) { return this->_read(buffer);}std::streamsize MemoryDataStream::read(int32_t *buffer) { return this->_read(buffer);}std::streamsize MemoryDataStream::read(uint32_t *buffer) { return this->_read(buffer);}std::streamsize MemoryDataStream::read(float *buffer) { return this->_read(buffer);}std::streamsize MemoryDataStream::read(double *buffer) { return this->_read(buffer);}std::streamsize MemoryDataStream::read(std::string *buffer) { std::streamsize i; std::string result; i = this->peek(&result); if (i < 1) { return i; } *buffer = result; this->_cursor += i; return i;}template <typename T>std::streamsize MemoryDataStream::_read(T *buffer) { std::streamsize result = this->_peek(buffer); if (result > 0) { this->_cursor += result; } return result;}std::streamsize MemoryDataStream::peek(uint8_t *buffer, std::streamsize length) { std::streamsize result = 0; for (int i = 0; i < length; i++) { result += this->_peek(buffer++); } return result;}std::streamsize MemoryDataStream::peek(int8_t *buffer) { return this->_peek(buffer);}std::streamsize MemoryDataStream::peek(uint8_t *buffer) { return this->_peek(buffer);}std::streamsize MemoryDataStream::peek(int16_t *buffer) { return this->_peek(buffer);}std::streamsize MemoryDataStream::peek(uint16_t *buffer) { return this->_peek(buffer);}std::streamsize MemoryDataStream::peek(int32_t *buffer) { return this->_peek(buffer);}std::streamsize MemoryDataStream::peek(uint32_t *buffer) { return this->_peek(buffer);}std::streamsize MemoryDataStream::peek(float *buffer) { return this->_peek(buffer);}std::streamsize MemoryDataStream::peek(double *buffer) { return this->_peek(buffer);}std::streamsize MemoryDataStream::peek(std::string *value) { int8_t c; std::streamsize i; int size; std::stringstream strm; for (i = 0; i < 32768; ++i) { if (this->_peek(&c) < 1 || c == '\0') { break; } else { this->_cursor += 1; } size = i; strm << c; } *value = strm.str(); this->_cursor -= size; return i;}template <typename T>std::streamsize MemoryDataStream::_peek(T *buffer) { T value; T finalValue; uint8_t *originalData; uint8_t *finalData; std::streamsize size = static_cast<std::streamsize>(sizeof(T)); if (static_cast<std::streamsize>(this->_cursor) + size > this->_buffer.size()) { return -1; } value = *(reinterpret_cast<T*>(&this->_buffer[this->_cursor])); if (_bigEndian && sizeof(T) > 1) { originalData = reinterpret_cast<uint8_t*>(&value); finalData = reinterpret_cast<uint8_t*>(&finalValue); for (int i = 0; i < sizeof(T); ++i) { finalData[i] = originalData[(sizeof(T) - i) - 1]; } value = finalValue; } *buffer = value; return sizeof(T);}std::streamsize MemoryDataStream::write(const char *buffer, std::streamsize length) { return this->_write(buffer, length);}std::streamsize MemoryDataStream::write(int8_t value) { return this->_write(value);}std::streamsize MemoryDataStream::write(uint8_t value) { return this->_write(value);}std::streamsize MemoryDataStream::write(int16_t value) { return this->_write(value);}std::streamsize MemoryDataStream::write(uint16_t value) { return this->_write(value);}std::streamsize MemoryDataStream::write(int32_t value) { return this->_write(value);}std::streamsize MemoryDataStream::write(uint32_t value) { return this->_write(value);}std::streamsize MemoryDataStream::write(float value) { return this->_write(value);}std::streamsize MemoryDataStream::write(double value) { return this->_write(value);}std::streamsize MemoryDataStream::write(const std::string &value) { return this->_write(value.c_str(), strlen(value.c_str()) + 1);}template <typename T>std::streamsize MemoryDataStream::_write(T buffer, std::streamsize length) { size_t pos = static_cast<size_t>(this->_cursor); size_t size = static_cast<size_t>(length); if (pos + size > this->_buffer.size()) { this->_buffer.resize(pos + size); } memcpy(&this->_buffer[pos], static_cast<T>(buffer), size); this->_cursor += size; return size;}template <typename T>std::streamsize MemoryDataStream::_write(T value) { T finalValue = value; uint8_t *originalData = reinterpret_cast<uint8_t*>(&value); uint8_t *finalData = reinterpret_cast<uint8_t*>(&finalValue); if (_bigEndian && sizeof(T) > 1) { for (int i = 0; i < sizeof(T); ++i) { finalData[i] = originalData[(sizeof(T) - i) - 1]; } originalData = finalData; } return this->_write(originalData, sizeof(T));}I would like to ask the following question :Is it alright to make DataStreamInterface an abstract class instead of an interface so I can use the templates like this ? Will it affect performance or memory consumption ? std::streamsize read(T *buffer); std::streamsize peek(T *buffer); std::streamsize write(T value);I've recently realized that any Android and iOS application would freeze when they'll use the library with their own DataStream implementation.For instance, if the C++ side call the HttpDataStream class implemented in Java to download a file, it would freeze the whole process and maybe the whole application until the download ends.Here is an example, calling the remote DataStream class defined in Java:std::streamsize DataStreamJava::read(double value) { jmethodID m = jni->GetMethodID(j_dataStream_class_, read, (D)J); jni->CallLongMethod(j_dataStream_global_, m); return 0;}I've been thinking about creating a class named DataStreamObserver on the C++ side, the DataStream constructor would take an instance of the DataStreamObserver class then call it every time a read or write operation has finished.Should I create DataStreamObserver as an abstract class with templates in order to avoid implementing methods like that?virtual void onReadSuccess(int8_t value, std::steamsize length) = 0;virtual void onReadSuccess(uint8_t value, std::steamsize length) = 0;virtual void onReadSuccess(int16_t value, std::steamsize length) = 0;virtual void onReadSuccess(uint16_t value, std::steamsize length) = 0;
DataStream interface for reading and writing data
c++;object oriented;template;interface
InterfaceSeems like none of these methods should actually be virtual.class DataStreamInterface { public: virtual bool open() = 0; virtual void close() = 0; virtual std::streamsize length() const = 0; virtual std::streamsize tell() const = 0; virtual std::streamsize seek(std::streamsize position) = 0; virtual std::streamsize read(char *buffer, std::streamsize length) = 0; virtual std::streamsize read(int8_t *buffer) = 0; virtual std::streamsize read(uint8_t *buffer) = 0; virtual std::streamsize read(int16_t *buffer) = 0; virtual std::streamsize read(uint16_t *buffer) = 0; virtual std::streamsize read(int32_t *buffer) = 0; virtual std::streamsize read(uint32_t *buffer) = 0; virtual std::streamsize read(float *buffer) = 0; virtual std::streamsize read(double *buffer) = 0; virtual std::streamsize read(std::string *buffer) = 0; virtual std::streamsize peek(uint8_t *buffer, std::streamsize length) = 0; virtual std::streamsize peek(int8_t *buffer) = 0; virtual std::streamsize peek(uint8_t *buffer) = 0; virtual std::streamsize peek(int16_t *buffer) = 0; virtual std::streamsize peek(uint16_t *buffer) = 0; virtual std::streamsize peek(int32_t *buffer) = 0; virtual std::streamsize peek(uint32_t *buffer) = 0; virtual std::streamsize peek(float *buffer) = 0; virtual std::streamsize peek(double *buffer) = 0; virtual std::streamsize peek(std::string *buffer) = 0; virtual std::streamsize write(const char *buffer, std::streamsize length) = 0; virtual std::streamsize write(int8_t value) = 0; virtual std::streamsize write(uint8_t value) = 0; virtual std::streamsize write(int16_t value) = 0; virtual std::streamsize write(uint16_t value) = 0; virtual std::streamsize write(int32_t value) = 0; virtual std::streamsize write(uint32_t value) = 0; virtual std::streamsize write(float value) = 0; virtual std::streamsize write(double value) = 0; virtual std::streamsize write(const std::string &value) = 0; virtual ~DataStreamInterface() { }};In your implementation you add _write(), _read() and _peek() that does the actual work. Seems like these are really your virtual functions the others should just be implemented in the base class DataStreamInterface to use these virtual functions.I think I would implement like this:class DataStreamInterface { public: // Virtual Interface: virtual ~DataStreamInterface() { } virtual bool open() = 0; virtual void close() = 0; virtual std::streamsize length() const = 0; virtual std::streamsize tell() const = 0; virtual std::streamsize seek(std::streamsize position) = 0; private: // All the interesting stuff for each class is encapsulated in // these threee virtual methods. All the other read/peek/write // methods should delagate their work to these and not need to // be re-implemented in each class. virtual std::streamsize vread(char *buffer, std::size_t size) = 0; virtual std::streamsize vwrite(char *buffer, std::size_t size) = 0; virtual std::streamsize vpeek(char *buffer, std::size_t size) = 0; template<typename T> std::streamsize tread(T *buffer, std::size_t size = sizeof(T)) { return vread(reinterpret_cast<char*>(buffer), size); } template<typename T> std::streamsize twrite(T *buffer, std::size_t size = sizeof(T)) { return vwrite(reinterpret_cast<char*>(buffer), size); } template<typename T> std::streamsize tpeek(T *buffer, std::size_t size = sizeof(T)) { return vpeak(reinterpret_cast<char*>(buffer), size); } // standard interface. // I did these in a hurry there will be mistakes. public: std::streamsize read(char *buffer, std::streamsize length){return tread(buffer, length);} std::streamsize read(int8_t *buffer) {return tread(buffer);} std::streamsize read(uint8_t *buffer) {return tread(buffer);} std::streamsize read(int16_t *buffer) {return tread(buffer);} std::streamsize read(uint16_t *buffer) {return tread(buffer);} std::streamsize read(int32_t *buffer) {return tread(buffer);} std::streamsize read(uint32_t *buffer) {return tread(buffer);} std::streamsize read(float *buffer) {return tread(buffer);} std::streamsize read(double *buffer) {return tread(buffer);} std::streamsize read(std::string *buffer) {return tread(buffer);} std::streamsize peek(uint8_t *buffer, std::streamsize length) {return tpeek(buffer, length);} std::streamsize peek(int8_t *buffer) {return tpeek(buffer);} std::streamsize peek(uint8_t *buffer) {return tpeek(buffer);} std::streamsize peek(int16_t *buffer) {return tpeek(buffer);} std::streamsize peek(uint16_t *buffer) {return tpeek(buffer);} std::streamsize peek(int32_t *buffer) {return tpeek(buffer);} std::streamsize peek(uint32_t *buffer) {return tpeek(buffer);} std::streamsize peek(float *buffer) {return tpeek(buffer);} std::streamsize peek(double *buffer) {return tpeek(buffer);} std::streamsize peek(std::string *buffer) {return tpeek(buffer.c_str(), buffer->length());} std::streamsize write(const char *buffer,std::streamsize length) {return tpeek(buffer, length);} std::streamsize write(int8_t value) {return twrite(buffer);} std::streamsize write(uint8_t value) {return twrite(buffer);} std::streamsize write(int16_t value) {return twrite(buffer);} std::streamsize write(uint16_t value) {return twrite(buffer);} std::streamsize write(int32_t value) {return twrite(buffer);} std::streamsize write(uint32_t value) {return twrite(buffer);} std::streamsize write(float value) {return twrite(buffer);} std::streamsize write(double value) {return twrite(buffer);} std::streamsize write(const std::string &value) {return twrite(buffer.c_str(), value.size());}};CommentsIs it alright to make DataStreamInterface an abstract class instead of an interface so I can use the templates like this ? An abstract class is an interface. The difference is terminology.Will it affect performance or memory consumption ?Sure. But not in any meaningful way. But before I can give a more exact answer I need you to be much more specific.For instance, if the C++ side call the HttpDataStream class implemented in Java to download a file, it would freeze the whole process and maybe the whole application until the download ends.Not a surprise. But nothing to do with it being a C++ function. If you ask the processor do do something it can not do anything else until it finishes. So it will freeze.Unless you explicitly make your code threaded and do some work on different threads.I've been thinking about creating a class named DataStreamObserver on the C++ side, the DataStream constructor would take an instance of the DataStreamObserver class then call it every time a read or write operation has finished.Sure. But its not going to help your stall processes by itself.
_unix.123773
I want to replace any 3 or more digit string in a text file with equivalent number of *.For example: abc-1234-45 --> abc-****-45echo abc-1234-45 | sed 's/[0-9]\{3,\}/*/'I tried this but it only replaces it with one *.Kindly suggest a solution here.
Replacing 3 or more digits with equivalent number of *
regular expression
null
_unix.271848
When I add ipv4 policy rules using ip rule add the resultant rules get added to the end of the policy table with decrementing priority from 32767eg:# ip rule add lookup 8# ip rule add lookup 90: from all lookup local32764: from all lookup 932765: from all lookup 832766: from all lookup main32767: from all lookup defaultBut when I use the same command for ipv6 ip -6 rule I get priority duplication.eg:# ip -6 rule add lookup 8# ip -6 rule add lookup 90: from all lookup local16383: from all lookup 816383: from all lookup 932766: from all lookup main16383 is 32766/2. But I don't understand why the behaviour is different and why there is priority duplication. I am using Fedora 21. Version of iproute is: iproute-3.16.0-3.fc21.x86_64. Is this the intended behaviour for ipv6 policy routing using iproute2?Can anyone else confirm this behaviour on other systems?
ipv6 rule priority duplication
networking;routing;ipv6
null
_unix.204822
I wanted to print some text between two patterns which doesn't contain a particular wordinput text isHEADER asdf asd asd COW assdTAIL sdfsdfsHEADER asdf asdsdfsd DOG sdfsdfsdfTAIL sdfsdfsHEADER asdf asdsdfsd MONKEY sdfsdfsdfTAIL sdfsdfsoutput needed isHEADER asdf asdasd COW assdTAIL sdfsdfsHEADER asdf asdsdfsd MONKEY sdfsdfsdfTAIL sdfsdfsconceptually something like this is neededawk '/HEADER/,!/DOG/,TAIL' text Kindly help
Print text between two patterns not containing a particular word
text processing;sed;awk;text
null
_webmaster.92872
Is there a term for the moment when a lot of users visit/log onto your website at the same time?
Is there a term for the moment when a lot of users visit/log onto your website at the same time?
terminology
null
_softwareengineering.310377
Scenario: I'm working in an Agile environment. The dev environment has not been configured yet, and I'm told to code a piece of an application.I code the module and write appropriate unit tests for it as part of the coding task, and test the code offline in my own box. There is also a testing task that needs to be performed by a non-technical testing person.Questions: At this point can I claim that I'm done with coding, since I haven't really tested my code even in the dev environment? Can I move my development task to DONE, or do I need to move it to BLOCKED due to the lack of an environment?
I'm done with my coding from Agile perspective
testing;agile;coding
Only your team can decide whether you've reached your definition of DONE.If this were my team I would be tempted to declare the task as BLOCKED but, maybe I don't have all the information. Maybe your scenario is unique somehow and your task can be considered finished.My point is that we don't know enough about your team, project, infrastructure, office politics, etc, to give you a meaningful answer.That's why teams typically make their own Definition of Done that best meets their needs.
_unix.74423
gentoo, kernel 3.7.10samba 3.6.12SMB/CIFS server: Windows Server 2003 3790 Service Pack 2I've encountered the situation when mount.cifs behaves differently from smbclient program.The following command works fine. I can log in the server and navigate through the share's contents.smbclient -U domainname/username //server.name/sharenameAnd if I try to mount this very share folder with the following command,mount -t cifs //server.name/sharename /mount/point -o user=domainname/usernamethen the command itself works fine (return code is 0, no error message). But /mount/point looks empty.What's the problem? Why mound.cifs and smbclient behave differently? Maybe smbclient uses some hidden settings?BTW, I don't know whether it is relevant to the problem but anyway. If I run mount.cifs command several times, I don't get any folder already mounted kind of message. Though afterwards I can run umount the same number of times until I get error umount: /mount/point/: not mounted
Why could mount.cifs mount an empty folder?
linux;mount;samba;cifs
Finally I've solved the problem. Thanks to Wireshark.From the Wireshark's logs I saw that when smbclient did its job then the peers exchanged GET_DFS_REFERRAL subcommands. But these messages were absent when I tried to mount the share with mount.cifs.It seems the server uses Distributed File System facilities so I tried to add the support of DFS to the kernel and that made the trick. Now I can perfectly navigate, read and write in my mounted share.Actually I thought that smbclient and mount.cifs used the same low-level instruments to connect to the SMB/CIFS servers but it isn't so. It looks like Samba can handle DFS itself without support of the kernel.
_softwareengineering.328784
We plan to refactor our company system into a micro-service based system. This micro-services will be used by our own internal company applications and by 3rd party partners if needed. One for booking, one for products etc.We are unsure how to handle roles and scopes. The idea is to create 3 basic user roles such as Admins, Agents and End-Users and let the consumer apps to fine-tune scopes if needed.Admins can create, update, read and delete allresources by default (for their company). Agents can create, update and read data for their company. End-Users can create, update, delete and read data, but cannot access same endpoints as agents or admins. They will also be able to create or modify data, just not on a same level as agents or admins. For example, end users can update or read their account info, same as agent will be able to do it for them, but they can't see or update admin notes.Let's say that agents by default can create, read and update each resource for their company and that is their maximum scope which can be requested for their token/session, but developers of client (API consumer) application have decided that one of their agents can read and create only certain resources.Is it a better practice to handle this in our internal security, and let them write that data in our database, or let clients handle that internally by requesting a token with lesser scope, and let them write which agent will have which scope in their database? This way we would have to track only token scopes.The downside of this, is that our team would also need to create fine-tuned access mechanisms in our internal applications.With this way of thinking, micro-services and their authorization system should not be bothered with clients needs, because they are only consumers and not part of the system (even though some of those consumers are our own internal apps)?Is this delegation a good approach?
Authorization and authentication system for microservices and consumers
security;authentication;microservices;authorization
Authentication and authorization are always good topicsI will try to explain you how we deal with authorizations in the current multi-tenant service that I am working. The authentication and authorization is token based, using the JSON Web Token open standar. The service exposes a REST API that any kind of client (web, mobile and desktop applications) can access. When a user is sucessfully authenticated the service provides an access token that must be send on each request to the server.So let me introduce some concepts we use based on how we perceive and treat data on the server aplication.Resource: It is any unit or group of data that a client can access through the service. To all the resources that we want to be controlled we assign a single name. For instance, having the next endpoint rules we can name then as follow:product/products/products/:idpayment/payments//payments/:idorder/orders/orders/:id/orders/:id/products/orders/:id/products/:idSo let's say that so far we have three resources in our service; product, payment and order.Action: Any kind of action that can be performed on a resource, like, read, create, update, delete, etc. It is not neccesary to be just the classic CRUD actions, you can have an action named follow, for instance, if you want to expose a service that propagates some kind of information using websokets.Ability: The ability to perform an action on a resource. For instance; read products, create products, etc. It is basically just an resource/action pair. But you can add a name and description to it too.Role: A set of abilities that a user can own. For example, a role Cashier could have the abilities read payment, create payment or a role Seller can have the abilities read product, read order, update order, delete order.Finally, an user can have various roles assigned to him.ExplanationAs I say above, we use JSON Web Token and with a custom property in the payload data, the roles that a user can own is declared. So, let suppose that we have a user can can have the roles of a cashier and seller at the same time, for a small retail store for instance. The payload will look like this:{ scopes: { payment: [read, create], order: [read, create, update, delete] }}As you can see, in the scope property, we don't specify the name of the roles (cashier, seller), just the resources and the actions that are implicated. When a client sends a request to an endpoint, the service should check if the access token contains the resource and action required. For example, a GET request to the endpoint /payments/88 will be successful, but a DELETE request to the same endpoint must fail.How to group and name the resources and how to define and name the actions and abilities will be a decision made by the developers.What are the roles and what abilities will have those roles, will be a decision of the customers.Of course, you must add extra properties to de payload in order to identify the user and the customer (tenant) that issued the token.{ scopes: { ... }, tenant: acme, user:coyote}With this method, you can fine tune the access of any user account to your service. And the most important, you don't have to create various predefined and static roles, like Admin, Agents and End-Users as you point out in your question. A Super User will be an user that owns a role with all the resources and actions of the service assigned to it.Now, What if we had 100 resources?, and we want a role that gives access to all or almost all of them?. Our token payload would be huge. That is solved by nesting the resources and just adding the parent resource in the access token scope.I have to say that english is not my native language, so I hope you understand my answer. Authorization is a complicated topic that must be addressed depending on the needs of each application.
_webmaster.104480
What affect does it make at page ranking if i link other websites to my website as my clients, like people i have worked for and i will place a link with their logo. Does it harm the ranking because every link will not be doing the same work that i do.Example.com (Doing web development work)example1.com (Food Business)example2.com (Travel Agent)example3.com (Real Estate Company)what if i link the above 3 links to example.comQ1. Will example.com get boost in ranking.?Q2. Will example.com get bad impresssion on google.?
Linking other websites to my website for seo boost but they did not do the same business
seo;google search;links;link building
Unrelated or off-topic niche backlinks can damage your sites reputation unless they can be associated with one another through a brand or trading name.For example:Stack ExchangeStack OverflowPro WebmastersDixons RetailPC WorldCurrysKnowhowDixons travelDSGi Business One or two off topic links isn't going to do a great deal in terms of being punished by Google or Bing but they are unlikely going to help either. You should only want to link in and from such websites if they are directly associated with one another because it helps promote the brand.If ever in doubt... always use rel=nofollow on your links.
_unix.353814
I have several files whose names aren't correct:$ lsdevoirNote1_1_2.R devoirNote1_1_5.R devoirNote1_4_1.RdevoirNote1_1_3.R devoirNote1_1.R devoirNote1.RdevoirNote1_1_4.R devoirNote1_2_1.R example140.RI want to change all devoirNote1_i_j.R with the i and j integers except devoirNote1_4_1.R to devoirNote1_{i+1}_j.R (only devoirNote1_4_1.R is left unchanged).I thought of using the command mvlike mv devoirNote1_*_2.R devoirNote1_2_2.R but when several files match (for example if both devoirNote1_1_2.R and devoirNote1_3_2.R are present), it creates an issue.Therefore, how to create a script or a command line that renames my files, by incrementing one of the variables in the filenames, but not all of them?
How to create a script or a command line that increment the variable part of the name of my files but some of them?
command line;scripting;rename;filenames;variable
null
_codereview.169830
I wrote a function to create one of those CSS triangle blocks and insert it right after one of the already created blocks. function createArrow() { var arrowDown = { parent: document.querySelector('.landingItem'), div: document.createElement('div'), initDiv: function() { this.div.classList.add('arrow-down'); this.div.style.borderLeftWidth = parseInt(document.documentElement.clientWidth)/2 + 'px'; this.div.style.borderRightWidth = parseInt(document.documentElement.clientWidth)/2 + 'px'; this.parent.appendChild(this.div); }, checkDiv: function () { if(this.parent.querySelector('.arrow-down')) { this.parent.removeChild(this.parent.querySelector('.arrow-down')); } this.initDiv(); } }; arrowDown.checkDiv();}createArrow();window.addEventListener('resize', createArrow);.arrow-down { margin-top: -2px; border-top: 60px solid #501a70; border-left: 160px solid transparent; border-right: 160px solid transparent;}<div class=landingItem></div>What can I improve?
Create a triangle arrow block dynamically
javascript;css
null
_unix.87543
Currently I'm running a FreeBSD 9.1 and the default gateway is already configured in the rc.conf.rc.conf:defaultrouter = 10.0.0.1But now I want to change the default gateway without rebooting the system, is this possible?
How can I change the default gateway?
routing;freebsd
route del defaultroute add default 1.2.3.4Where 1.2.3.4 is the new gateway. You can even concatenate them onto the same line with a ;Edit: This is FreeBSD, not Linux. The command is different. Please do not edit this Answer if you haven't read the Question carefully enough to determine the operating system being used.
_unix.175993
I have to compare two files, file1 and file2. Each file has 56 columns separated by |.First column is the employee number in the file, I will check whether same employee number is present in the second file or not. If not we will write the whole row to the output file. If same employee number is present in the file2, I need to compare value of each column. If data doesn't match, we have to write it to the output file. If values of each column match then we need to omit that record.Sample FileFile 12620|256034|131021|Mission Quality and Wipro Way|||2622|256034|131021|Mission Quality and Wipro Way|||2623|256034|131021|Mission Quality and Wipro Way|||File 22620|256034|234567|Mission Quality and Wipro Way|||2621|256034|131021|Mission Quality and Wipro Way|||2622|256034|131021|Mission Quality|||2623|256034|131021|Mission Quality and Wipro Way|||Sample Output:2620|256034|131021|Mission Quality and Wipro Way|||2621|256034|131021|Mission Quality and Wipro Way|||2622|256034|131021|Mission Quality|||
Comparing two files in unix and awk
awk;diff;file comparison
null
_unix.312384
I bought an USBASP 2.0 programmer and hooked it up, I cannot see any port created by the programmer. What I expect is USBtty0 in /devTo fix it I have restarted UDEV and tried other UDEV configurations but it doesn't show.unameLinux Puc 4.4.0-21-generic #37-Ubuntu SMP Mon Apr 18 18:33:37 UTC 2016 x86_64 x86_64 x86_64 GNU/LinuxlsusbBus 003 Device 092: ID 16c0:05dc Van Ooijen Technische Informatica shared ID for use with libusbdmesg[181622.326920] usb 3-5: new low-speed USB device number 92 using xhci_hcd[181622.460268] usb 3-5: New USB device found, idVendor=16c0, idProduct=05dc[181622.460270] usb 3-5: New USB device strings: Mfr=1, Product=2, SerialNumber=0[181622.460271] usb 3-5: Product: USBasp[181622.460272] usb 3-5: Manufacturer: www.fischl.deudev ruleSUBSYSTEMS==usb, ENV{DEVTYPE}==usb_device, ATTRS{idVendor}==16c0, ATTRS{idProduct}==05dc, MODE=0666this device: http://www.fischl.de/usbasp/[EDIT] Using this command from the arduino/hardware/tools/avr directory, the connection works, just not from within the Arduino IDE../bin/avrdude -C etc/avrdude.conf -c usbasp -P usb -p m328pavrdude: warning: cannot set sck period. please check for usbasp firmware update.avrdude: AVR device initialized and ready to accept instructionsReading | ################################################## | 100% 0.00savrdude: Device signature = 0x1e950favrdude: safemode: Fuses OK (H:05, E:DF, L:FF)avrdude done. Thank you.
USBasp not creating ttyUSB0
udev;ttyusb
I don't think it's supposed to.If I remember correctly, USBasp works with custom control transfers, and e.g. avrdude looks it up from /dev/bus/usb by the vendor and product IDs and ID strings.With avrdude, something like this should work, or complain that it can't find a USB device with the correct IDs:avrdude -P usb -c usbasp -p $UCAlso, since USBasp works with software-implemented USB, it's limited to low-speed operation, which in principle means that it can't work as a serial port:The USB CDC class is intended for modems and other communication devices. [...] CDC requires bulk endpoints which are forbidden for low speed devices by the USB specification. (quote from the V-USB wiki)
_webapps.43386
I am trying In Google Drive, how can you link directly to Download a zip file and not view the contents? but it does not work. I am not sure on how to repeat the question. It downloads a 'file is too big to be antivirus scanned' warning HTML and when I try https://drive.google.com/uc?export=download&confirm=no_antivirus&id= it still downloads that.Edit: I tried to wget --save-cookies /tmp/cookie.txt --load-cookies /tmp/cookie.txt and repeat it, still no dice.
Google Drive direct download for big files
google drive
A cookie must match the confirm url parameter, and it is changed on each call.Here's a perl script to download these files in an unattended way.With the url from the antivirus scan warning page (https://drive.google.com/uc?export=download&confirm=s5vl&id=XXX) this code should be enough:#!/usr/bin/perluse strict;my $TEMP='/tmp';my $COMMAND;my $confirm;sub execute_command();my $URL=shift;my $FILENAME=shift;$FILENAME='gdown' if $FILENAME eq '';execute_command();if (-s $FILENAME < 100000) { # only if file isn't the download yet open fFILENAME, '<', $FILENAME; foreach (<fFILENAME>) { if (/confirm=([^;&]+)/) { $confirm=$1; last; } } close fFILENAME; $URL=~s/confirm=([^;&]+)/confirm=$confirm/; execute_command(); }sub execute_command() { $COMMAND=wget --no-check-certificate --load-cookie $TEMP/cookie.txt --save-cookie $TEMP/cookie.txt \$URL\; $COMMAND.= -O \$FILENAME\ if $FILENAME ne ''; `$COMMAND`; return 1; }
_unix.219991
I have parent folder and inside this folder I have 4 files ParentFolder File1.txt File2.txt File3.txt File4.txtI wanted to create subfolders inside the parent folder and carry the name of the files then move every file inside the folder that carry it is name like:ParentFolder File1 File1.txt File2 File2.txt File3 File3.txt File4 File4.txtHow can I do that in batch or tsch script?I tried this script:#!/bin/bashin=path_to_my_parentFolderfor i in $(cat ${in}/all.txt); docd ${in}/${i} ls > files.txtfor ii in $(cat files.txt); domkdir ${ii}mv ${ii} ${in}/${i}/${ii} done done
How do I create a directory for every file in a parent directory
bash;shell script;files;tcsh
You're overcomplicating this. I don't understand what you're trying to do with all.txt. To enumerate the files in a directory, don't call ls: that's more complex and doesn't work reliably anyway. Use a wildcard pattern.To strip the extension (.txt) at the end of the file name, use the suffix stripping feature of variable substitution.Always put double quotes around variable substitutions.cd ParentFolderfor x in ./*.txt; do mkdir ${x%.*} && mv $x ${x%.*}done
_softwareengineering.345694
I'm trying to build a Java application that connects to a remote database that stores and retrieves video files that can be over 200MB. I could store/retrieve these files in MySQL directly as LONGBLOBs, yet I read again and again how that's bad practice for various reasons. One solution commonly offered is to store the files on the filesystem and have the database store the location file and serve it up from the server directly.My problem is, I'm very new to storage and am completely unsure of how to go about doing that. Should I make an FTP connection to the front end once a video file has been requested, then deliver that video over that connection? Or are people usually talking about something else when they say to pull it from the filesystem?I'm using Java and JDBC to make calls to MySQL.
How to properly serve large video files stored outside a MySQL database
java;database;sql;jdbc
null
_softwareengineering.343939
I am working on a networking project. Where I am creating a dashboard to view real time status (CPU/memory usage, up/down traffic and few others) of multiple routers by calling API request to server which will call another API request to the routers ( Mikrotik Routers, they offer api to do configuration and get statuses ).Problem: In testing each request surge my VPS CPU usage up to 20%. This is only one user viewing the dashboard and doing request. What if I have multiple customers and each one of them viewing the dashboard and doing multiple request to the servers. It is going to go down for sure, right?Here is part of back end code:$routers = //Get all the routers belong to that usersforeach($routers as $router){ $api = connectRouter(); if($api === false){ continue; } $api->write('/ip/hotspot/user/getall'); $users = $api->read(); $api->write('/ip/hotspot/active/getall'); $actives = $api->read(); $resources = $api->comm('/system/resource/print'); $resources = $resources[0]; $api->write('/interface/getall'); $router->interfaces = $api->read();} Question: What option do I have to reduce the CPU usage and be able to provide this services to multiple customers?Up to what I had researched:I should try Node.js ? Change ways I am calling from front end: instead of calling API to getting all routers data at once, change it to get one by one?NOTE1. Those values in routers change every second (if not millisecond). I want to get value in real time as much as possible. So caching is not a solution here I think.Every users have their own set of routers. They don't share routers. So doing some duplicate router query check won't be a benefit I think. ( Yeah can be useful if the same logged in user trying to view on multiple devices or browser tabs. ) But I am trying to optimize for multiple users.
Realtime frontend dashboard, calling api every 3 seconds, reduce cpu loads
design patterns;web development;api;api design;node.js
null
_softwareengineering.327763
Programming is complex. And throughout the years new technologies emerge that lay/depend upon older technologies, resulting in the need for deeper knowledge in a broad set of technologies in order to achieve a single goal.One example of that affirmation could be the web development scenario. Once only what was needed was HTML marking. Nowadays a single web application may depend on many languages, technologies and frameworks.So, considering the tendency it is presumable that the traditional way of programming computers will reach a bottleneck on the next few decades.How is this problem supposed to be worked out if (or when) binary computers hit the bottleneck?
How are academics planning to solve the bottlenecks of binary computer's programming in the upcoming years?
future proof
HTML still works just as well as it did before. Nothing requires you to get fancy except competition to make the best stuff.HTML is a domain specific language. It solves structural problems well. It doesn't solve behavioral problems well. If it did it would look a lot different and likely be harder to use.General purpose languages like c# can do either but with that power comes a wide vocabulary and syntax to master.Adding more domain specific languages, CSS, Xml, Json, SQL, does not send us to a bottleneck. It puts more easy to use tools in your toolbox. If you'd rather stick with one general purpose tool you can but since it was designed to be suitable for every job it's more like a Swiss Army knife. It can do every job. It's just equally difficult to use for every job.The downside of the domain specific language approach is you need to master an ever growing number of disparate tools. The downside of the general purpose language approach is while you can stick to one complex language you need to master an ever growing number of library's, which are also just tools.Neither approach leads to a bottleneck. As we develop more tools we'll discard less useful tools.
_webmaster.54645
So we wish to host some pages on a new server with apache2, and embed some of our old content & functionality from another server with lighttpd in an iframe. I'm looking at this configuration from the apache docs (http://httpd.apache.org/docs/2.2/vhosts/examples.html#page-header) under Using Virtual_host and mod_proxy together.<VirtualHost *:*> ProxyPreserveHost On ProxyPass / http://192.168.111.2/ ProxyPassReverse / http://192.168.111.2/ ServerName hostname.example.com</VirtualHost>The only issue is that I want to proxy only on a subdomain, or even better, if I can keep the top domain and proxy only if the url contains a particular path ie. /myprocess.php. So in essence the DNS will point to the apache2 as the master router.
Serve most of a domain with Apache, but use mod_proxy to serve some URLs from Lighttpd
apache;apache2;iframe;lighttpd
null
_unix.147730
From my understanding, all IP addresses of the form 127.x.y.z are loopback addresses. Now that seems to be quite a waste to me; indeed, already more than one address seems like a waste.Is there any use in having so many loopback addresses?
Why are there so many loopback addresses?
networking
Some reasons I've found:Historical limitation: there is no MASK in the first implementation of tcpip, that means network nodes use the first number to distinguish network size and host ID. moreover, since class A is determined by its first octet, the higher-order bit is 0, so 127.x.x.x (01111111.x.x.x) is the latest segement of class A addresses. people often use all zero or all one numbers for special usages, reserving a class A segment is for maximum flexibility.Easy implementation: as what i say above, there was no MASK concept in early days, segment address 01111111.00000000.00000000.00000000 is easy to be determined by AND/XOR operations quickly and easily. even nowadays, such pattern is still easy for matching subnets by applying XOR operation.Reserved for future use: class A has 1,677,216 hosts, so it allows people have more space to divide it into a lot of reasonable zones for specific usages, different devices, systems and applications.Extracted from here
_unix.330370
Both LFS and CLFS apply patches to the GCC source before building.The CLFS patches are a bit more involved than the LFS patches, but what they have in common is the changing of the path used to find the dynamic linker. In this case its moved to the location where a new version of glibc is going to be built.Since, at least in the case of CLFS, you are building a cross toolchain and presumably you cannot run anything built with this chain on your build machine, what difference does it make where GCC has programs look for the dynamic linker. Isn't that a runtime operation which is never going to happen anyway? Also, if you built a binary with this GCC, one which required shared libraries, and attempted to run it on your target wouldn't the path to the dyanmic linker now be wrong?Additionally (C)LFS has you modify the STANDARD_STARTFILE_PREFIX_X to point to $INSTALL_PATH/tools/lib/. Wouldn't those paths presumably be checked when/if you specifiy --with-sysroot? After building GCC with --with-sysroot if I check --preint-search-dirs I don't see it looking in any paths besides ones referenced to either prefix or --with-sysroot.
Why LFS and CLFS change the path used to find the dynamic linker?
gcc;lfs
null
_unix.108589
There's a neat Control-L hotkey in Emacs that repetitively moves the cursor to the top/middle/bottom of the screen. I'm quite sure there's a vim equivalent for that, but I couldn't find it.
Emacs's vim equivalent
vim;keyboard shortcuts
null
_reverseengineering.13011
In the following code, I injected my own instructions to modify third param of sprintf() function, but the process stopped at EXC_BAD_INSTRUCTION. Can anybody tell me what happened in my code?0x144502 <+6>: movw r0, #0xc70 ; injected code start here0x144506 <+10>: movt r0, #0x8bb30x14450a <+14>: movw r3, #0x5760x14450e <+18>: ldr r1, [r7]0x144510 <+20>: movs r5, #0x1a0x144512 <+22>: add r5, pc ; next instruction will jump over 9 instructions0x144514 <+24>: bx r5 ; pc = 0x00144514 ; r5 = 0x001445300x144516 <+26>: ldr r1, [r0]0x144518 <+28>: ldr r0, [r2]0x14451a <+30>: blx 0x29111c0x14451e <+34>: movw r1, #0x64420x144522 <+38>: movt r1, #0x180x144526 <+42>: add r1, pc0x144528 <+44>: ldr r1, [r1]0x14452a <+46>: blx 0x29111c0x14452e <+50>: mov r3, r10x144530 <+52>: movw r1, #0x66a4 ; bx r5 landed here. But r1 has not been loaded0x144534 <+56>: movt r1, #0x15 ; with new value. Why?0x144538 <+60>: mov r2, r00x14453a <+62>: add r1, pc ; this instruction never get called0x14453c <+64>: mov r0, r4 ; EXC_BAD_INSTRUCTION raised here0x14453e <+66>: blx __sprintf
Injected instructions hit `bad instruction` exception
assembly;arm
Looks like you forgot to set bit 0 of the destination address so the CPU switched to ARM mode and tried to execute Thumb instructions as ARM.
_codereview.145220
I wrote a node script to traverse a folder of hour-long mp3s and upload them to Mixcloud via their API. It works, but I suspect it's fairly inefficient - the computer it's going to run on at our radio station is an old white Macbook. Would appreciate any insight for how to improve it. const restler = require('restler'); const fs = require('fs'); const readDir = require('readdir'); const powerOff = require('power-off'); const options = { folder: 'files', completefolder: 'complete', accesstoken: 'xxxxxxxxx' } // shut down computer const shutDown = () => {powerOff((err, stderr, stdout) => { if(!err && !stderr) { console.log(stdout); } }) }; // uploadFile uploads file with restler to mixcloud, if api returns rate limiting object, try again in x seconds const uploadFile = (folder, filename) => { const filepath = `./${folder}/${filename}` fs.stat(`./${folder}/${filename}`, function(err, stats) { const size = stats.size; restler.post(`https://api.mixcloud.com/upload/?access_token=${options.accesstoken}`, { multipart: true, data: { mp3: restler.file(`./${folder}/${filename}`, null, size, null, 'audio/mpeg'), name: filename, // unlisted: true // more data can be added here depending on changes in workflow, automate images etc } }).on(complete, function(data) { const returned = JSON.parse(data); if (returned.error) { if (returned.error.type == RateLimitException) { // try again in x seconds console.log(`uploading too fast, retrying upload of ${filename}after ${returned.error.retry_after} seconds`); setTimeout(() => uploadFile(folder, filename), returned.error.retry_after*1000); } else { console.log('non-rate-limiting error'); console.log(returned); } } else { console.log('Success!'); console.log(returned); // move uploaded files into completed folder fs.rename(`./${folder}/${filename}`, `./${options.completefolder}/${filename}`, (err) => { if (err) { console.log(err) } else { counter += 1; console.log(counter); if (counter === files.length) { console.log('done'); shutDown(); } } }) } }); }); }; // get all mp3s and upload all of them const files = readDir.readSync(`./${options.folder}`, ['**.mp3'] ); let counter = 0; for (var i = 0; i < files.length; i++) { uploadFile(options.folder, files[i]) };
Uploading series of large files to API via Node
javascript;node.js;api;ecmascript 6;network file transfer
null
_cs.47799
I am stuck by analyzing the time complexity of the following algorithm:def fun (r, k, d, p): if d > p: return r if d = 0 and p = 0: r <- r + k return r if d > 0: fun (r, k + 1, d - 1, p) if p > 0: fun (r, k - 1, d, p - 1)The root call will be fun (0, 0, n, n), and n is the size of the problem. I guess that: The recurrence relation is $ T(n, n) = T(n-1, n) + T(n, n-1)$, which is equivalent to $T(2n) = 2T(2n-1) \iff T(m) = 2T(m - 1)$, and so $O(2^m) \iff O(4^n)$.Is my analysis correct (I know it's not very complete and exact)? If it does have serious flaw, please point it out or show me a correct and complete proof on the time complexity of this algorithm.
What's the time complexity of this algorithm? And Why?
algorithm analysis;runtime analysis
The only two arguments relevant to asymptotic analysis are $d$ and $p$. These arguments (virtually) satisfy $d,p \geq 0$ and $d \leq p$ (we need to shuffle the logic in the function slightly to get this). At each point in the execution, you take the current pair $(d,p)$ and then recursively call the function with the pairs $(d-1,p),(d,p-1)$, avoiding pairs which invalidate the constraints stated above.We can picture the resulting call tree as a path starting at $(0,0)$. Each time you decrease $p$, add a / step. Each time you decrease $d$, add a \ step. The condition $d \leq p$ guarantees that you never go below the X axis. Moreover, you have a budget of $n$ of each step. The total number of leaves in this call tree is exactly the Catalan number $\binom{2n}{n}/(n+1) = \Theta(4^n/n^{3/2})$, and this gives us a lower bound on the running time of the function.To get an upper bound, note that on the way to each leaf we pass through $2n$ nodes, and this gives an upper bound $2n$ larger than the lower bound, i.e., $\Theta(4^n/\sqrt{n})$.We have a lower bound of $\Omega(4^n/n^{3/2})$ and an upper bound on $O(4^n/\sqrt{n})$. What are the exact asymptotics? They grow like the total number of paths not crossing the X axis which have at most $n$ steps in each direction. Using Bertrand's ballot theorem we can get an exact expression for this:$$\sum_{0 \leq d \leq p \leq n} \frac{p-d+1}{p+1} \binom{p+d}{p}.$$It thus remains to estimate this sum asymptotically:$$\sum_{0 \leq d \leq p \leq n} \binom{p+d}{p} - \sum_{0 \leq d \leq p \leq n} \frac{d}{p+1} \binom{p+d}{d} = \\\sum_{0 \leq d \leq p \leq n} \binom{p+d}{p} - \sum_{0 \leq d \leq p \leq n} \binom{p+d}{p+1} = \\\sum_{p=0}^n \binom{2p+1}{p+1} - \sum_{p=0}^n \binom{2p+1}{p+2} = \\\sum_{p=0}^n \frac{1}{p+1} \binom{2p+2}{p} = \Theta\left(\sum_{p=0}^n \frac{4^p}{p^{3/2}}\right) =\Theta\left(\frac{4^n}{n^{3/2}}\right).$$
_vi.8893
Let's say I have a text file opened in vim. I'd like to be able to edit this file from bash, let's say with the command echo text >> file while the file is already opened in vim. Ideally, vim would just refresh the new content and wouldn't bother with a .swp file, asking for what version I want to restore. Any idea how to do this?
How to allow editing of a file from other sources while it's already open in vim?
swap file
null
_webapps.69778
Is it possible to write an Array Formula which calculates the running average of the Amount column for each of the Name groups in the following sheet? The rows are sorted by Name. In Column C, I have an Array Formula:(=ArrayFormula(IF(LEN(B2:B),SUMIF(ROW(B2:B),<=&ROW(B2:B),B2:B)/COUNTIF(ROW(B2:B),<=&ROW(B2:B)),))) which calculates a running average of the entire Amount column regardless of Name group but I would like a formula which would restart the running average each time the Name changes. The results of my formula (many thanks to prior answers from AdamL) are in column C and the desired result is shown in column D:NAME AMOUNT RUN AVE DESIREDTom 3 3 3Tom 7 5 5Tom 8 6 6Tom 2 5 5Bill 10 6 10Bill 0 5 5Thank you for any suggestions.
ArrayFormula to compute Running Average for groups of rows
google spreadsheets;formulas
For a conditional running average, assuming all entries in A2:A are grouped:=ArrayFormula(IFERROR((SUMIF(ROW(A2:A),<=&ROW(A2:A),B2:B)-HLOOKUP(0,SUMIF(ROW(A2:A),<&ROW(A2:A),B2:B),MATCH(A2:A,A2:A,0),0))/(ROW(A2:A)-MATCH(A2:A,A2:A,0)-ROW(A2)+2)))Before the update to the newest version of Sheets a number of months ago, it would have generally been advised to use MMULT for these sort of conditional running total problems:=ArrayFormula(IF(LEN(A2:A),MMULT((ROW(A2:A)>=TRANSPOSE(ROW(A2:A)))*(A2:A=TRANSPOSE(A2:A)),--B2:B)/MMULT((ROW(A2:A)>=TRANSPOSE(ROW(A2:A)))*(A2:A=TRANSPOSE(A2:A)),SIGN(ROW(A2:A))),))This solution also has the added benefit that the A2:A column needn't be grouped, nor sorted. However, in the newest version, the MMULT solution will break when the referenced range reaches 3163 rows. It appears to be because the 2D array formed by MMULT will tip over 10 million elements (square root of 10 million = 3162.278...).The first solution shouldn't suffer this limitation, however it will probably still get very slow when referencing a few thousand rows.
_cs.55237
Let $R = \{1, \ldots, n\}$ and $S = \{S_1, \ldots, S_m\}$ a collection of subsets of $R$ such that $R = \bigcup_{i = 1}^m S_i$ and, for $n > 3$, $$3 \leq \vert S_i \vert \leq 4 \, , \enspace i \in \{1, \ldots, m\} \, .$$Then, I want to know the subsetor subsets, since there may be more than one valid solution$T$ with minimum cardinality such that every $S_i$ has at least one element in $T$. I suspect this is an NP-hard problem (or NP-complete in its decision version), but I don't know if it's one that has a name.As an example, consider $R = \{1, 2, 3, 4, 5\}$ and $S = \{S_1, \ldots, S_9\}$, where$S_1 = \{1, 2, 3\} \, , \enspace S_4 = \{1, 4, 5\} \, , \enspace S_7 = \{1, 2, 3, 4\} \, ,$$S_2 = \{1, 2, 4\} \, , \enspace S_5 = \{2, 3, 5\} \, , \enspace S_8 = \{1, 3, 4, 5\} \, ,$$S_3 = \{1, 2, 5\} \, , \enspace S_6 = \{3, 4, 5\} \, , \enspace S_9 = \{2, 3, 4, 5\} \, .$Here, the solutions are $T = \{\{1, 3\}, \{1, 5\}, \{2, 4\}, \{2, 5\}\}$. (I'd be happy even if I knew just one of them.)Note that I'm not asking for an algorithm to solve the problem. I just want to know where this is or reduces to a well-known problem.
Is this a well-known NP-hard problem?
algorithms;complexity theory;optimization;np complete;reductions
3-Hitting Set problem is known in parameterized complexity theory. The requirement $\cup S_i=R$ can always be assumed without loss of generality. See e.g. An efficient fixed-parameter algorithm for 3-Hitting Set. According to this link it is NP-hard in its usual (not parameterized) form. Proving NP-completeness of your problem we give reduction FROM 3-Hitting Set to your problem not vica versa. Therefore your problem is NP-complete (in its decision form).
_unix.352635
Building a server on minimal boot storage borrowing idea #3 removing any kernel modules not needed to run your system (from /usr/lib/modules/...) from How do I minimize disk space usage, I have removed a bunch of kernel drivers rand added those paths as NoExtract rules in pacman.conf.After that mkinitcpio displays error messages like:cp: cannot stat '/lib/modules/4.10.3-1-ARCH/kernel/drivers/cdrom/cdrom.ko.gz': No such file or directorygzip: /tmp/mkinitcpio.SAJmKZ/root/lib/modules/4.10.3-1-ARCH/kernel/cdrom.ko.gz: No such file or directoryI think I can fix by running depmod.Now the mkinitcpio error messages have become:==> ERROR: module not found: `cdrom'How to nicely fix/hide these mkinitcpio ERROR: module not found: like messages too?Note: adding the kernel modules again is not an option.
After removing kernel modules and running depmod, how to fix mkinitcpio ERROR: module not found:?
arch linux;kernel modules;mkinitcpio
null
_unix.352664
I have my DHCP server which I specifically set the ip range to be between: 10.53.70.100 -- 10.53.70.200 but there are sometimes I get IPs outside from this range. For example, the last server I created got the IP 10.53.70.245, so I just wanted to know why my ip range setting is not working.Just to note I'm using dnsmasq instead of dhcpd service for this. Heres the log from the DHCP server:Mar 20 10:32:46 dhcp dnsmasq-dhcp[7657]: 1927259932 available DHCP range: 10.53.70.100 -- 10.53.70.200Mar 20 10:32:46 dhcp dnsmasq-dhcp[7657]: 1927259932 client provides name: dnstestMar 20 10:32:49 dhcp dnsmasq-dhcp[7657]: 1927259932 DHCPDISCOVER(ens192) 10.53.70.245 00:50:56:8f:d4:6fMar 20 10:32:49 dhcp dnsmasq-dhcp[7657]: 1927259932 tags: ens192Mar 20 10:32:49 dhcp dnsmasq-dhcp[7657]: 1927259932 DHCPOFFER(ens192) 10.53.70.177 00:50:56:8f:d4:6fMar 20 10:32:49 dhcp dnsmasq-dhcp[7657]: 1927259932 requested options: 1:netmask, 28:broadcast, 2:time-offset, 121:classless-static-route,Mar 20 10:32:49 dhcp dnsmasq-dhcp[7657]: 1927259932 requested options: 15:domain-name, 6:dns-server, 12:hostname,Mar 20 10:32:49 dhcp dnsmasq-dhcp[7657]: 1927259932 requested options: 40:nis-domain, 41:nis-server, 42:ntp-server,Mar 20 10:32:49 dhcp dnsmasq-dhcp[7657]: 1927259932 requested options: 26:mtu, 119:domain-search, 3:router, 121:classless-static-route,Mar 20 10:32:49 dhcp dnsmasq-dhcp[7657]: 1927259932 requested options: 249, 33:static-route, 252, 42:ntp-serverMar 20 10:32:49 dhcp dnsmasq-dhcp[7657]: 1927259932 next server: 10.53.70.5Mar 20 10:32:49 dhcp dnsmasq-dhcp[7657]: 1927259932 sent size: 1 option: 53 message-type 2Mar 20 10:32:49 dhcp dnsmasq-dhcp[7657]: 1927259932 sent size: 4 option: 54 server-identifier 10.53.70.5Mar 20 10:32:49 dhcp dnsmasq-dhcp[7657]: 1927259932 sent size: 4 option: 51 lease-time 12hMar 20 10:32:49 dhcp dnsmasq-dhcp[7657]: 1927259932 sent size: 4 option: 58 T1 6hMar 20 10:32:49 dhcp dnsmasq-dhcp[7657]: 1927259932 sent size: 4 option: 59 T2 10h30mMar 20 10:32:49 dhcp dnsmasq-dhcp[7657]: 1927259932 sent size: 4 option: 1 netmask 255.255.255.0Mar 20 10:32:49 dhcp dnsmasq-dhcp[7657]: 1927259932 sent size: 4 option: 28 broadcast 10.53.70.255Mar 20 10:32:49 dhcp dnsmasq-dhcp[7657]: 1927259932 sent size: 4 option: 6 dns-server 10.53.70.5Mar 20 10:32:49 dhcp dnsmasq-dhcp[7657]: 1927259932 sent size: 9 option: 15 domain-name example.ioMar 20 10:32:49 dhcp dnsmasq-dhcp[7657]: 1927259932 sent size: 4 option: 3 router 10.53.70.1Mar 20 10:32:49 dhcp dnsmasq-dhcp[7657]: 1927259932 available DHCP range: 10.53.70.100 -- 10.53.70.200Mar 20 10:32:49 dhcp dnsmasq-dhcp[7657]: 1927259932 client provides name: dnstestMar 20 10:32:52 dhcp dnsmasq-dhcp[7657]: 2099714365 available DHCP range: 10.53.70.100 -- 10.53.70.200Mar 20 10:32:52 dhcp dnsmasq-dhcp[7657]: 2099714365 client provides name: dnstestAs you can see there's the line where it says:DHCPOFFER(ens192) 10.53.70.177 00:50:56:8f:d4:6fWhich it will be a correct Ip since it's inside of the range. However I see the line where it says:DHCPDISCOVER(ens192) 10.53.70.245 00:50:56:8f:d4:6fSo, at the end the server takes this IP ending in .245, so my question is why it takes an IP that's outside of the allowed range?Thanks.
dnsmasq DHCP server is not selecting IPs inside of the specified range after being offered the right ones
ip;dhcp;dnsmasq
null
_unix.345788
I need to sum numbers like this Input 1 5 6 8 9 11Output 1 6 12 20 29 40That is:1 1+5 1+5+6 1+5+6+8 1+5+6+8+9 1+5+6+8+9+11
Create a running total of a list of numbers in awk?
awk
In awk:{ for (i = 1; i <= NF; ++i) { printf(%d , s += $i); } printf(\n);}The loop goes over all input fields and prints the running total (s) of the numbers. The variable s doesn't need to be initialized as its value will taken as zero on the first iteration. The result of the assignment to s is the value of s, which is then printed with a trailing space character.With the example input:$ echo 1 5 6 8 9 11 | awk -f script.awk1 6 12 20 29 40
_softwareengineering.199367
This seems to happen every time I create any sort of GUI. I have trouble figuring out how child classes should communicate to their siblings.It's a general problem, but it's probably easier to use a concrete example (hopefully that's still okay for this forum? I know it's different from StackOverflow): I have a window that contains 4 panels. Right now, I simply have the children as member objects of the parent.Keypresses change all 4 panels, so I have the child objects throw the event back to their parent, which does the logic, then makes the appropriate calls for each panel.However, mouse events are different. They change the position of a camera (owned by the parent), which every panel uses to render itself. So I must recompute a few matrices, in order to render each panel. The matrices are different for each panel. The problem I'm having is: when do I give the children the matrices?I think I have three possibilities:When reading a mouse event, compute the matrices and call setter methods for each panel. However, sometimes the matrix will be replaced before the window renders.Give the child panel a reference to the parent, and during the render call, request the matrix from the parent (either by method or member variable).Modify child.render() so that it accepts two matrix parameters, and make parent.render() call them appropriately.#2 seems good, because I'm not unnecessarily setting the matrix in the child window. But it also requires me to mess with forward declarations for member objects, which seems like bad practice. And #3 I'm not quite sure how to implement, because render is called by many things other than my code (un-minimizing, for example), and I can't touch them. So I suppose it is #1?Is there a design pattern people usually follow for this? Am I just overthinking, and #1 is actually completely OK?
What should the relation between parent and child GUI components be?
design patterns;gui
If I got your right, during the render call, the child needs a service which provides some matrixes, right? It does not really matter that it is the parent which provides that matrixes. So create an interface like IMatrixProvider, give a reference to an object of type IMatrixProvider during construction time to your panels and call that service when you need it within the rendermethod. Your parent object can implement that interface, if the matrixes are provided from there.If you use a functional language or a language with functional elements, you may not even need a full interface object, a simpler call back or delegate function may be enough.This is mostly what you described under #2, but not with a reference to the full parent object - so the panels stay decoupled from the parent type.
_codereview.138083
This program starts with initial balance and the individual book balances which must match the initial balance to proceed. The user then enters the selections for the day along with stake, odds etc., then the program calculates the new balance with the new book balances.def main(): def balances(msg): while True: try: x = float(raw_input(msg)) return x except ValueError: printThat's not a number continue while True: balance = balances('Balance:') print bfair_balance = balances('bfair:') wh_balance = balances('wh:') freds_balance = balances('freds:') sky_balance = balances('sky:') pp_balance = balances('pp:') balance_sum = pp_balance + bfair_balance + sky_balance + freds_balance + wh_balance if balance == balance_sum: # balance is correct -> stop the loop break else: print Balances do not match print print Balance: %s %balance print Bfair: %d, Sky: %d, pp: %d, freds: %d, wh: %d %(bfair_balance, sky_balance, pp_balance, freds_balance, wh_balance) books = [bfair_balance, wh_balance, sky_balance,freds_balance,pp_balance] #print books print inputs = [] new_books = [] def looks_good(inputs): for i in inputs: print i while True: add_selection =raw_input(Would you like to add a selection? ) if add_selection == Yes: print selection = raw_input('Horse: ') stake = float(raw_input('Stake: ')) while stake <=0: print Please enter a stake greater than 0 stake = float(raw_input('Stake: ')) while stake > bfair_balance: print You do not have sufficient funds stake = float(raw_input('Stake: ')) while stake > pp_balance: print You do not have sufficient funds stake = float(raw_input('Stake: ')) while stake > freds_balance: print You do not have sufficient funds stake = float(raw_input('Stake: ')) while stake > sky_balance: print You do not have sufficient funds stake = float(raw_input('Stake: ')) while stake > wh_balance: print You do not have sufficient funds stake = float(raw_input('Stake: ')) odds = float(raw_input('Odds: ')) while odds <=0: print Please enter odds greater than 0 odds = float(raw_input('Odds: ')) result = (raw_input('Result: ')) if result == Win: result = stake * odds print Returns:%d%result elif result == Lose: result = 0 * odds print Returns:%d%result book = raw_input('Book: ') while book not in['bfair','sky','wh','freds','pp']: print That's not valid book = raw_input('Book: ') if result == 0 and book == bfair: bfair_balance = bfair_balance - stake new_books.append(bfair_balance) elif result == (stake * odds) and book == bfair: bfair_balance = bfair_balance - stake + (stake * odds) new_books.append(bfair_balance) if result == 0 and book == freds: freds_balance = freds_balance - stake new_books.append(freds_balance) elif result == (stake * odds) and book == freds: freds_balance = freds_balance - stake + (stake * odds) new_books.append(freds_balance) if result == 0 and book == pp: pp_balance = pp_balance - stake new_books.append(pp_balance) elif result == (stake * odds) and book == pp: pp_balance = pp_balance - stake + (stake * odds) new_books.append(pp_balance) if result == 0 and book == wh: wh_balance = wh_balance - stake print wh_balance - stake new_books.append(wh_balance) elif result == (stake * odds) and book == wh: wh_balance = wh_balance - stake + (stake * odds) new_books.append(wh_balance) if result == 0 and book == sky: sky_balance = sky_balance - stake new_books.append(sky_balance) elif result == (stake * odds) and book == sky: sky_balance = sky_balance - stake + (stake * odds) new_books.append(sky_balance) my_list=[selection,stake,odds,result,book] inputs.append(my_list) print total_stake=[] for my_list in inputs: total_stake.append(my_list[1]) print Total Stake: %d %sum(total_stake) total_winnings = [] for my_list in inputs: total_winnings.append(my_list[3]) print Total Winnings: %d %sum(total_winnings) print new_balance = balance - sum(total_stake) + sum(total_winnings) print New Balance:%d %new_balance print Bfair: %d, Sky: %d, pp: %d, freds: %d, wh: %d %(bfair_balance, sky_balance, pp_balance, freds_balance, wh_balance) print elif add_selection == No: break looks_good(inputs) import os os.system(pause)if __name__ == '__main__': main()
Calculate total profit/loss
python;finance
Use loops to avoid repetitionFor example you have:while stake > bfair_balance: print You do not have sufficient funds stake = float(raw_input('Stake: '))# many very similar blocksYou should use a loop to avoid repetition:for balance in [bfair_balance, ...]: while stake > balance: print You do not have sufficient funds stake = float(raw_input('Stake: '))
_softwareengineering.161861
Google's Dart language is not supported by any Web Browsers other than a special build of Chromium known as Dartium. To use Dart for production code you need to run it through a Dart->JavaScript compiler/translator and then use the outputted JavaScript in your web application.Because JavaScript is an interpreted language everyone who receives the binary(Aka, the .js file) has also received the source code.Now, the GNU General Public License v3.0 states that:The source code for a work means the preferred form of the work for making modifications to it.Which would imply that the original Dart code in addition to the JavaScript code must also be provided to the end user. Does this mean that any web applications written in Dart must also provide the original Dart code to all visitors of their website even though a copy of the source code has already been provided in a human readable/writable/modifiable form?
How does the GPL work in regards to languages like Dart which compile to other languages?
javascript;licensing;web applications;gpl;dart
null
_codereview.106598
Please review the codepackage com.gmail.practice;import java.util.Arrays;public class StacksForTwo { int size; int[] stack; int top1; int top2; public StacksForTwo(int arraysize) { size = arraysize; stack = new int[size]; top1 = -1; top2 = size; } public void push1(int x) { if(top1 < top2-1) { top1++; stack[top1] = x; }else{ System.out.println(stackoverflow); } } public void push2(int y) { if(top1 < top2-1) { top2--; stack[top2] = y; }else{ System.out.println(stack overflow); } } public void pop1() { if(top1 >= 0) { top1--; System.out.println(The popped out number is+ +stack[top1+1]); }else{ System.out.println(stack underflow); } } public void pop2() { if(top2 < size) { top2++; System.out.println(The popped out number is+ +stack[top2+1]); }else{ System.out.println(stack underflow); } } public void display() { System.out.println(Arrays.toString(stack)); } public static void main(String[] args) { StacksForTwo sft = new StacksForTwo(10); sft.push1(4); sft.push1(5); sft.push1(3); sft.push1(2); sft.push2(6); sft.push2(4); sft.display(); sft.push2(8); sft.push1(2); sft.push2(6); sft.push2(4); sft.push2(8); sft.display(); }}
Implementing two stacks using single array in java
java;array;stack
null
_softwareengineering.315857
I'm in the process of redesigning a portion of my ASP.NET MVC application. I'm currently using Entity Framework 6.1 code first approach.I've been reading as of late that (Correct me if I'm wrong, I don't know much about DBs): Joins are expensive; we should keep our database normalized and with the least queries executed as possible. Entity Framework does a join each time we virtual a property and try to retrieve it (Eager/Lazy Loading). We should avoid an Entity-Attribute-Value approach (EAV), unless denormalization becomes desirable (Correct me). Code First approach allows us to write the DB schema using C# OOP code (POCO). Which means that we should adhere to OOP's SOLID Principles (Correct me). The first one is Single Responsibility, which means a class should do only one thing (again, correct me if I'm wrong). Now here comes the problem (this is the first time it happens to me). I have a class with around 30 properties. Before thinking in anti-EAV, I went and separated the model accordingly: As you can see I have many virtual properties without the List<> type, this means that it is a one-to-one relationship. I have read in a previous stack-overflow post that a good rule of thumb is that one-to-one relationships should be avoided in favor of having them in a same table. That is, of course, if that one-to-one is not called from other tables. We prevent EAV and therefore, Joins. Following SOLID principles, I have extracted some properties to external classes. They will get their own table. So, the question will be, should I favor a fully normalized design over a OOP Approach when modeling in Entity Framework?
Entity Framework Code First, C# class separation and EAV
database design;entity framework;codefirst;poco
(Late to the party, but I couldn't resist)Let's straighten out some misconceptions.Joins are expensiveAs compared to what? Of course, reading one flat table is cheaper than joining tables, but any mature RDBMS is highly optimized for executing joins because they are inevitably part of sound database designs. Joins over foreign key constraints (the most common ones) are especially optimized. And of course, proper indexing is indispensable.we should keep our database normalized and with the least queries executed as possibleThe way you pose this, it seems to be a consequence of preventing these expensive joins. The reverse is true. Normalization will always result in more tables and, hence, more joins to query the same data as from a denormalized data schema. (Well, to be fair to you, later on you say We prevent EAV and therefore, Joins.).We should avoid an Entity-Attribute-Value approach (EAV), unless denormalization becomes desirableEAV is all but denormalization. I'm under the impression that you don't fully understand what EAV is.In an EAV design, attributes of a relation (aka fields, or columns, of a database table) are taken out of a relation and stored as records in an Attributes tables. The values are stored in yet another table that has foreign keys to the Attributes table and an Entity table. A record in the Attributes tables expresses one fact: this is value X of attribute Y in entity Z.So with EAV, when applied rigorously, if you want to know the start date, end date, and cost of a tournament, you'll have to query the PGTournament table and join to Attribute and Value (with a WHERE condition for the attributes). That's two joins instead of zero without EAV!Nearly always, EAV is bad design. It's to be used when there's no alternative (for instance in lab applications where new analyses for samples can be invented every day -- a fixed set of fields in a Sample table won't suffice).In your case, I don't see any reason to introduce EAV -- I don't even understand why you bring it up. I think it is because you confuse EAV with 1:1 associations. Read on.Which means that we should adhere to OOP's SOLID PrinciplesThe EF class model is part of a data access layer. It's not a domain model! At least, it's not its first responsibility to be that. The class properties should facilitate data access. That means that there will be bidirectional relationships and Id properties, to mention two OOP anti-patterns. And the real OOP bummer: the classes tend to be highly anemic. Whenever the EF classes can be used as domain classes, this is a mere bonus.virtual properties without the List<> typeSuch properties are known as navigation properties because the navigate to other entities. Lists are collection navigation properties and entity-type properties (without the List<> type) are reference navigation properties. They don't have to be virtual. When they're virtual, EF may be able to lazily load the properties.this means that it is a one-to-one relationshipWhy? Reference navigation properties are often the 1 part of a 1:n association. I think most of your reference properties are like that. For example, GameGenre. I think there are many tournaments having the same GameGenre. It's a 1 (genre) to n (tournament) association, even if GameGenre doesn't have a Tournaments collection. Maybe only TournamentSettings and MainImage are actual 1:1 associations.1:1 Associations distribute data belonging to one entity over multiple tables. There can be very good reasons to do that. One of them is to facilitate querying light-weight data without the heavy payload of some blob, like MainImage. Another one is separating sensitive data from public data. Or common data (often queried) from specialized data (queried sometimes), maybe your TournamentSettings.Now, finally, your question:should I favor a fully normalized design over a OOP Approach when modeling in Entity Framework?You're comparing apples and oranges. Normalized design is database, OOP is class model. But if there is anything to favor, it's normalized design. A well-wrought database design is pivotal to any data-based application. Everything else follows. The EF class model will necessarily closely reflect the database structure. As I said above: it must be seen as a data access layer.But whenever you model business logic, of course, try to do it as SOLID as possible. That means that sometimes you'll have to populate a specialized domain model out of the entities queried by EF, and sometimes the EF classes can be extended to encapsulate behavior and data (which is what OOP is all about).
_unix.80192
I am using tcpdump to log traffic outbound on a network. I would like to be able to log traffic on a host or IP-only basis but then I would like to be able to log large numbers of potentially blacklisted IPs. I have read about tcpdump -F in the man page that explains that I can load tcpdump configuration from a file, however, I cannot seem to find much in the way of documentation of how to structure this file or how to load large numbers of IPs into the filtering as I constantly get syntax errors. How would I easily implement IP address lists with tcpdump?
Using tcpdump to log blacklisted IPs
linux;scripting;tcpdump
null